diff --git a/.gitmodules b/.gitmodules index 0a247d2967..3f914fd0b9 100644 --- a/.gitmodules +++ b/.gitmodules @@ -10,3 +10,9 @@ [submodule "tests/cpp-tests/Resources/ccs-res"] path = tests/cpp-tests/Resources/ccs-res url = git://github.com/dumganhar/ccs-res.git +[submodule "cocos/scripting/js-bindings"] + path = cocos/scripting/js-bindings + url = git://github.com/cocos2d/js-bindings.git +[submodule "web"] + path = web + url = git://github.com/cocos2d/cocos2d-html5.git diff --git a/CMakeLists.txt b/CMakeLists.txt index df9edc856d..4359b7c059 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -58,11 +58,15 @@ endif() set(BUILD_CPP_TESTS_DEFAULT ON) set(BUILD_LUA_LIBS_DEFAULT ON) set(BUILD_LUA_TESTS_DEFAULT ON) +set(BUILD_JS_LIBS_DEFAULT OFF) +set(BUILD_JS_TESTS_DEFAULT OFF) # TODO: fix test samples for MSVC if(MSVC) set(BUILD_CPP_TESTS_DEFAULT OFF) set(BUILD_LUA_LIBS_DEFAULT OFF) set(BUILD_LUA_TESTS_DEFAULT OFF) + set(BUILD_JS_LIBS_DEFAULT OFF) + set(BUILD_JS_TESTS_DEFAULT OFF) endif() option(USE_CHIPMUNK "Use chipmunk for physics library" ON) @@ -77,6 +81,8 @@ option(BUILD_EDITOR_COCOSBUILDER "Build editor support for cocosbuilder" ON) option(BUILD_CPP_TESTS "Build TestCpp samples" ${BUILD_CPP_TESTS_DEFAULT}) option(BUILD_LUA_LIBS "Build lua libraries" ${BUILD_LUA_LIBS_DEFAULT}) option(BUILD_LUA_TESTS "Build TestLua samples" ${BUILD_LUA_TESTS_DEFAULT}) +option(BUILD_JS_LIBS "Build js libraries" ${BUILD_JS_LIBS_DEFAULT}) +option(BUILD_JS_TESTS "Build TestJS samples" ${BUILD_JS_TESTS_DEFAULT}) option(USE_PREBUILT_LIBS "Use prebuilt libraries in external directory" ${USE_PREBUILT_LIBS_DEFAULT}) if(USE_PREBUILT_LIBS AND MINGW) @@ -314,3 +320,18 @@ if(BUILD_LUA_LIBS) endif(BUILD_LUA_TESTS) endif(BUILD_LUA_LIBS) + +## JS +if(BUILD_JS_LIBS) + link_directories( + ${CMAKE_CURRENT_SOURCE_DIR}/external/spidermonkey/prebuilt/${PLATFORM_FOLDER}/${ARCH_DIR} + ) + + add_subdirectory(cocos/scripting/js-bindings) + + # build js tests + if(BUILD_JS_TESTS) + add_subdirectory(tests/js-tests/project) + endif(BUILD_JS_TESTS) + +endif(BUILD_JS_LIBS) diff --git a/build/cocos2d-js-win32.vc2012.sln b/build/cocos2d-js-win32.vc2012.sln new file mode 100644 index 0000000000..6a83fb188a --- /dev/null +++ b/build/cocos2d-js-win32.vc2012.sln @@ -0,0 +1,69 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2013 +VisualStudioVersion = 12.0.31101.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d", "..\cocos\2d\libcocos2d.vcxproj", "{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "External", "External", "{92D54E36-7916-48EF-A951-224DD3B25442}" +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}") = "libbox2d", "..\external\Box2D\proj.win32\libbox2d.vcxproj", "{929480E7-23C0-4DF6-8456-096D71547116}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libjscocos2d", "..\cocos\scripting\js-bindings\proj.win32\libjscocos2d.vcxproj", "{39379840-825A-45A0-B363-C09FFEF864BD}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "js-tests", "..\tests\js-tests\project\proj.win32\js-tests.vcxproj", "{D0F06A44-A245-4D13-A498-0120C203B539}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|ARM = Debug|ARM + Debug|Win32 = Debug|Win32 + Release|ARM = Release|ARM + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Debug|ARM.ActiveCfg = Debug|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|ARM.ActiveCfg = Release|Win32 + {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Release|Win32.ActiveCfg = Release|Win32 + {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}.Release|Win32.Build.0 = Release|Win32 + {B7C2A162-DEC9-4418-972E-240AB3CBFCAE}.Debug|ARM.ActiveCfg = Debug|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|ARM.ActiveCfg = Release|Win32 + {B7C2A162-DEC9-4418-972E-240AB3CBFCAE}.Release|Win32.ActiveCfg = Release|Win32 + {B7C2A162-DEC9-4418-972E-240AB3CBFCAE}.Release|Win32.Build.0 = Release|Win32 + {929480E7-23C0-4DF6-8456-096D71547116}.Debug|ARM.ActiveCfg = Debug|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|ARM.ActiveCfg = Release|Win32 + {929480E7-23C0-4DF6-8456-096D71547116}.Release|Win32.ActiveCfg = Release|Win32 + {929480E7-23C0-4DF6-8456-096D71547116}.Release|Win32.Build.0 = Release|Win32 + {39379840-825A-45A0-B363-C09FFEF864BD}.Debug|ARM.ActiveCfg = Debug|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|ARM.ActiveCfg = Release|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|ARM.ActiveCfg = Debug|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|ARM.ActiveCfg = Release|Win32 + {D0F06A44-A245-4D13-A498-0120C203B539}.Release|Win32.ActiveCfg = Release|Win32 + {D0F06A44-A245-4D13-A498-0120C203B539}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {B7C2A162-DEC9-4418-972E-240AB3CBFCAE} = {92D54E36-7916-48EF-A951-224DD3B25442} + {929480E7-23C0-4DF6-8456-096D71547116} = {92D54E36-7916-48EF-A951-224DD3B25442} + EndGlobalSection + GlobalSection(DPCodeReviewSolutionGUID) = preSolution + DPCodeReviewSolutionGUID = {00000000-0000-0000-0000-000000000000} + EndGlobalSection + GlobalSection(DPCodeReviewSolutionGUID) = preSolution + DPCodeReviewSolutionGUID = {00000000-0000-0000-0000-000000000000} + EndGlobalSection +EndGlobal diff --git a/build/cocos2d-js-win8.1-universal.sln b/build/cocos2d-js-win8.1-universal.sln new file mode 100644 index 0000000000..60f8817bf9 --- /dev/null +++ b/build/cocos2d-js-win8.1-universal.sln @@ -0,0 +1,310 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2013 +VisualStudioVersion = 12.0.31101.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "libcocos2d", "libcocos2d", "{B3F299D4-B4CA-4F0B-8BE2-FB328483BC13}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d_8_1.Shared", "..\cocos\2d\libcocos2d_8_1\libcocos2d_8_1\libcocos2d_8_1.Shared\libcocos2d_8_1.Shared.vcxitems", "{5D6F020F-7E72-4494-90A0-2DF11D235DF9}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d_8_1.Windows", "..\cocos\2d\libcocos2d_8_1\libcocos2d_8_1\libcocos2d_8_1.Windows\libcocos2d_8_1.Windows.vcxproj", "{9335005F-678E-4E8E-9B84-50037216AEC8}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d_8_1.WindowsPhone", "..\cocos\2d\libcocos2d_8_1\libcocos2d_8_1\libcocos2d_8_1.WindowsPhone\libcocos2d_8_1.WindowsPhone.vcxproj", "{22F3B9DF-1209-4574-8331-003966F562BF}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "cpp-tests", "cpp-tests", "{572742C5-9322-4548-AB8B-96C3750A1B5D}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cpp-tests.Shared", "..\tests\cpp-tests\proj.win8.1-universal\cpp-tests.Shared\cpp-tests.Shared.vcxitems", "{BE3A1791-5BCE-4CEA-92CD-0E2D86DDE27A}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cpp-tests.Windows", "..\tests\cpp-tests\proj.win8.1-universal\cpp-tests.Windows\cpp-tests.Windows.vcxproj", "{F2BAE06B-CAAE-43EE-B21B-57FA48DB04FA}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cpp-tests.WindowsPhone", "..\tests\cpp-tests\proj.win8.1-universal\cpp-tests.WindowsPhone\cpp-tests.WindowsPhone.vcxproj", "{15247C71-5289-4913-B88F-E253CC353720}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "External", "External", "{85630454-74EA-4B5B-9B62-0E459B4476CB}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "libbox2d", "libbox2d", "{B3D1A3D5-9F54-43AF-9322-230B53242B78}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libbox2d.Shared", "..\external\Box2D\proj.win8.1-universal\libbox2d.Shared\libbox2d.Shared.vcxitems", "{4A3C6BA8-C227-498B-AA21-40BDA27B461F}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libbox2d.Windows", "..\external\Box2D\proj.win8.1-universal\libbox2d.Windows\libbox2d.Windows.vcxproj", "{3B26A12D-3A44-47EA-82D2-282660FC844D}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libbox2d.WindowsPhone", "..\external\Box2D\proj.win8.1-universal\libbox2d.WindowsPhone\libbox2d.WindowsPhone.vcxproj", "{22F798D8-BFFF-4754-996F-A5395343D5EC}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "libSpine", "libSpine", "{6FEB795C-C98C-4C8C-A88B-A35DEE205348}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libSpine.Shared", "..\cocos\editor-support\spine\proj.win8.1-universal\libSpine.Shared\libSpine.Shared.vcxitems", "{ADAFD00D-A0D6-46EF-9F0B-EA2880BFE1DE}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libSpine.Windows", "..\cocos\editor-support\spine\proj.win8.1-universal\libSpine.Windows\libSpine.Windows.vcxproj", "{F3550FE0-C795-44F6-8FEB-093EB68143AE}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libSpine.WindowsPhone", "..\cocos\editor-support\spine\proj.win8.1-universal\libSpine.WindowsPhone\libSpine.WindowsPhone.vcxproj", "{CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "cpp-empty-test", "cpp-empty-test", "{B70EF25E-E352-4020-BCDF-388973E44637}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloCpp.Shared", "..\tests\cpp-empty-test\proj.win8.1-universal\HelloCpp.Shared\HelloCpp.Shared.vcxitems", "{A3AD93E4-0B2F-4C58-9181-69BED2E42E3E}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloCpp.Windows", "..\tests\cpp-empty-test\proj.win8.1-universal\HelloCpp.Windows\HelloCpp.Windows.vcxproj", "{79A8FCDA-4B12-4DD1-B676-FF148D651638}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloCpp.WindowsPhone", "..\tests\cpp-empty-test\proj.win8.1-universal\HelloCpp.WindowsPhone\HelloCpp.WindowsPhone.vcxproj", "{396FE85E-BB05-4B92-BCCB-F89AED4EA41A}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "js-tests", "js-tests", "{8E24A044-D83D-476D-886D-F40E3CC621DF}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "js-tests.Shared", "..\tests\js-tests\project\proj.win8.1-universal\App.Shared\js-tests.Shared.vcxitems", "{AE6763F6-1549-441E-AFB5-377BE1C776DC}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "js-tests.Windows", "..\tests\js-tests\project\proj.win8.1-universal\App.Windows\js-tests.Windows.vcxproj", "{70914FC8-7709-4CD6-B86B-C63FDE5478DB}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "js-tests.WindowsPhone", "..\tests\js-tests\project\proj.win8.1-universal\App.WindowsPhone\js-tests.WindowsPhone.vcxproj", "{94874B5B-398F-448A-A366-35A35DC1DB9C}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "libcocos2d-jsb", "libcocos2d-jsb", "{60DCAEA9-E344-40C0-B90C-82FB8E671BD5}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libjscocos2d.Shared", "..\cocos\scripting\js-bindings\proj.win8.1-universal\libjscocos2d\libjscocos2d.Shared\libjscocos2d.Shared.vcxitems", "{BEA66276-51DD-4C53-92A8-F3D1FEA50892}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libjscocos2d.Windows", "..\cocos\scripting\js-bindings\proj.win8.1-universal\libjscocos2d\libjscocos2d.Windows\libjscocos2d.Windows.vcxproj", "{BCF5546D-66A0-4998-AFD6-C5514F618930}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libjscocos2d.WindowsPhone", "..\cocos\scripting\js-bindings\proj.win8.1-universal\libjscocos2d\libjscocos2d.WindowsPhone\libjscocos2d.WindowsPhone.vcxproj", "{CA082EC4-17CE-430B-8207-D1E947A5D1E9}" +EndProject +Global + GlobalSection(SharedMSBuildProjectFiles) = preSolution + ..\tests\js-tests\project\proj.win8.1-universal\App.Shared\js-tests.Shared.vcxitems*{ae6763f6-1549-441e-afb5-377be1c776dc}*SharedItemsImports = 9 + ..\tests\js-tests\project\proj.win8.1-universal\App.Shared\js-tests.Shared.vcxitems*{94874b5b-398f-448a-a366-35a35dc1db9c}*SharedItemsImports = 4 + ..\cocos\2d\libcocos2d_8_1\libcocos2d_8_1\libcocos2d_8_1.Shared\libcocos2d_8_1.Shared.vcxitems*{9335005f-678e-4e8e-9b84-50037216aec8}*SharedItemsImports = 4 + ..\tests\cpp-tests\proj.win8.1-universal\cpp-tests.Shared\cpp-tests.Shared.vcxitems*{15247c71-5289-4913-b88f-e253cc353720}*SharedItemsImports = 4 + ..\tests\cpp-empty-test\proj.win8.1-universal\HelloCpp.Shared\HelloCpp.Shared.vcxitems*{a3ad93e4-0b2f-4c58-9181-69bed2e42e3e}*SharedItemsImports = 9 + ..\tests\js-tests\project\proj.win8.1-universal\App.Shared\js-tests.Shared.vcxitems*{70914fc8-7709-4cd6-b86b-c63fde5478db}*SharedItemsImports = 4 + ..\cocos\editor-support\spine\proj.win8.1-universal\libSpine.Shared\libSpine.Shared.vcxitems*{cc1da216-a80d-4be4-b309-acb6af313aff}*SharedItemsImports = 4 + ..\external\Box2D\proj.win8.1-universal\libbox2d.Shared\libbox2d.Shared.vcxitems*{4a3c6ba8-c227-498b-aa21-40bda27b461f}*SharedItemsImports = 9 + ..\tests\cpp-empty-test\proj.win8.1-universal\HelloCpp.Shared\HelloCpp.Shared.vcxitems*{79a8fcda-4b12-4dd1-b676-ff148d651638}*SharedItemsImports = 4 + ..\cocos\editor-support\spine\proj.win8.1-universal\libSpine.Shared\libSpine.Shared.vcxitems*{adafd00d-a0d6-46ef-9f0b-ea2880bfe1de}*SharedItemsImports = 9 + ..\tests\cpp-tests\proj.win8.1-universal\cpp-tests.Shared\cpp-tests.Shared.vcxitems*{be3a1791-5bce-4cea-92cd-0e2d86dde27a}*SharedItemsImports = 9 + ..\cocos\scripting\js-bindings\proj.win8.1-universal\libjscocos2d\libjscocos2d.Shared\libjscocos2d.Shared.vcxitems*{ca082ec4-17ce-430b-8207-d1e947a5d1e9}*SharedItemsImports = 4 + ..\cocos\2d\libcocos2d_8_1\libcocos2d_8_1\libcocos2d_8_1.Shared\libcocos2d_8_1.Shared.vcxitems*{5d6f020f-7e72-4494-90a0-2df11d235df9}*SharedItemsImports = 9 + ..\cocos\scripting\js-bindings\proj.win8.1-universal\libjscocos2d\libjscocos2d.Shared\libjscocos2d.Shared.vcxitems*{bea66276-51dd-4c53-92a8-f3d1fea50892}*SharedItemsImports = 9 + ..\cocos\scripting\js-bindings\proj.win8.1-universal\libjscocos2d\libjscocos2d.Shared\libjscocos2d.Shared.vcxitems*{bcf5546d-66a0-4998-afd6-c5514f618930}*SharedItemsImports = 4 + ..\external\Box2D\proj.win8.1-universal\libbox2d.Shared\libbox2d.Shared.vcxitems*{3b26a12d-3a44-47ea-82d2-282660fc844d}*SharedItemsImports = 4 + ..\cocos\2d\libcocos2d_8_1\libcocos2d_8_1\libcocos2d_8_1.Shared\libcocos2d_8_1.Shared.vcxitems*{22f3b9df-1209-4574-8331-003966f562bf}*SharedItemsImports = 4 + ..\external\Box2D\proj.win8.1-universal\libbox2d.Shared\libbox2d.Shared.vcxitems*{22f798d8-bfff-4754-996f-a5395343d5ec}*SharedItemsImports = 4 + ..\cocos\editor-support\spine\proj.win8.1-universal\libSpine.Shared\libSpine.Shared.vcxitems*{f3550fe0-c795-44f6-8feb-093eb68143ae}*SharedItemsImports = 4 + ..\tests\cpp-tests\proj.win8.1-universal\cpp-tests.Shared\cpp-tests.Shared.vcxitems*{f2bae06b-caae-43ee-b21b-57fa48db04fa}*SharedItemsImports = 4 + ..\tests\cpp-empty-test\proj.win8.1-universal\HelloCpp.Shared\HelloCpp.Shared.vcxitems*{396fe85e-bb05-4b92-bccb-f89aed4ea41a}*SharedItemsImports = 4 + EndGlobalSection + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|ARM = Debug|ARM + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|ARM = Release|ARM + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {9335005F-678E-4E8E-9B84-50037216AEC8}.Debug|ARM.ActiveCfg = Debug|ARM + {9335005F-678E-4E8E-9B84-50037216AEC8}.Debug|ARM.Build.0 = Debug|ARM + {9335005F-678E-4E8E-9B84-50037216AEC8}.Debug|Win32.ActiveCfg = Debug|Win32 + {9335005F-678E-4E8E-9B84-50037216AEC8}.Debug|Win32.Build.0 = Debug|Win32 + {9335005F-678E-4E8E-9B84-50037216AEC8}.Debug|x64.ActiveCfg = Debug|x64 + {9335005F-678E-4E8E-9B84-50037216AEC8}.Debug|x64.Build.0 = Debug|x64 + {9335005F-678E-4E8E-9B84-50037216AEC8}.Release|ARM.ActiveCfg = Release|ARM + {9335005F-678E-4E8E-9B84-50037216AEC8}.Release|ARM.Build.0 = Release|ARM + {9335005F-678E-4E8E-9B84-50037216AEC8}.Release|Win32.ActiveCfg = Release|Win32 + {9335005F-678E-4E8E-9B84-50037216AEC8}.Release|Win32.Build.0 = Release|Win32 + {9335005F-678E-4E8E-9B84-50037216AEC8}.Release|x64.ActiveCfg = Release|x64 + {9335005F-678E-4E8E-9B84-50037216AEC8}.Release|x64.Build.0 = Release|x64 + {22F3B9DF-1209-4574-8331-003966F562BF}.Debug|ARM.ActiveCfg = Debug|ARM + {22F3B9DF-1209-4574-8331-003966F562BF}.Debug|ARM.Build.0 = Debug|ARM + {22F3B9DF-1209-4574-8331-003966F562BF}.Debug|Win32.ActiveCfg = Debug|Win32 + {22F3B9DF-1209-4574-8331-003966F562BF}.Debug|Win32.Build.0 = Debug|Win32 + {22F3B9DF-1209-4574-8331-003966F562BF}.Debug|x64.ActiveCfg = Debug|Win32 + {22F3B9DF-1209-4574-8331-003966F562BF}.Release|ARM.ActiveCfg = Release|ARM + {22F3B9DF-1209-4574-8331-003966F562BF}.Release|ARM.Build.0 = Release|ARM + {22F3B9DF-1209-4574-8331-003966F562BF}.Release|Win32.ActiveCfg = Release|Win32 + {22F3B9DF-1209-4574-8331-003966F562BF}.Release|Win32.Build.0 = Release|Win32 + {22F3B9DF-1209-4574-8331-003966F562BF}.Release|x64.ActiveCfg = Release|Win32 + {F2BAE06B-CAAE-43EE-B21B-57FA48DB04FA}.Debug|ARM.ActiveCfg = Debug|ARM + {F2BAE06B-CAAE-43EE-B21B-57FA48DB04FA}.Debug|ARM.Build.0 = Debug|ARM + {F2BAE06B-CAAE-43EE-B21B-57FA48DB04FA}.Debug|ARM.Deploy.0 = Debug|ARM + {F2BAE06B-CAAE-43EE-B21B-57FA48DB04FA}.Debug|Win32.ActiveCfg = Debug|Win32 + {F2BAE06B-CAAE-43EE-B21B-57FA48DB04FA}.Debug|Win32.Build.0 = Debug|Win32 + {F2BAE06B-CAAE-43EE-B21B-57FA48DB04FA}.Debug|Win32.Deploy.0 = Debug|Win32 + {F2BAE06B-CAAE-43EE-B21B-57FA48DB04FA}.Debug|x64.ActiveCfg = Debug|x64 + {F2BAE06B-CAAE-43EE-B21B-57FA48DB04FA}.Debug|x64.Build.0 = Debug|x64 + {F2BAE06B-CAAE-43EE-B21B-57FA48DB04FA}.Debug|x64.Deploy.0 = Debug|x64 + {F2BAE06B-CAAE-43EE-B21B-57FA48DB04FA}.Release|ARM.ActiveCfg = Release|ARM + {F2BAE06B-CAAE-43EE-B21B-57FA48DB04FA}.Release|ARM.Build.0 = Release|ARM + {F2BAE06B-CAAE-43EE-B21B-57FA48DB04FA}.Release|ARM.Deploy.0 = Release|ARM + {F2BAE06B-CAAE-43EE-B21B-57FA48DB04FA}.Release|Win32.ActiveCfg = Release|Win32 + {F2BAE06B-CAAE-43EE-B21B-57FA48DB04FA}.Release|Win32.Build.0 = Release|Win32 + {F2BAE06B-CAAE-43EE-B21B-57FA48DB04FA}.Release|Win32.Deploy.0 = Release|Win32 + {F2BAE06B-CAAE-43EE-B21B-57FA48DB04FA}.Release|x64.ActiveCfg = Release|x64 + {F2BAE06B-CAAE-43EE-B21B-57FA48DB04FA}.Release|x64.Build.0 = Release|x64 + {F2BAE06B-CAAE-43EE-B21B-57FA48DB04FA}.Release|x64.Deploy.0 = Release|x64 + {15247C71-5289-4913-B88F-E253CC353720}.Debug|ARM.ActiveCfg = Debug|ARM + {15247C71-5289-4913-B88F-E253CC353720}.Debug|ARM.Build.0 = Debug|ARM + {15247C71-5289-4913-B88F-E253CC353720}.Debug|ARM.Deploy.0 = Debug|ARM + {15247C71-5289-4913-B88F-E253CC353720}.Debug|Win32.ActiveCfg = Debug|Win32 + {15247C71-5289-4913-B88F-E253CC353720}.Debug|Win32.Build.0 = Debug|Win32 + {15247C71-5289-4913-B88F-E253CC353720}.Debug|Win32.Deploy.0 = Debug|Win32 + {15247C71-5289-4913-B88F-E253CC353720}.Debug|x64.ActiveCfg = Debug|Win32 + {15247C71-5289-4913-B88F-E253CC353720}.Release|ARM.ActiveCfg = Release|ARM + {15247C71-5289-4913-B88F-E253CC353720}.Release|ARM.Build.0 = Release|ARM + {15247C71-5289-4913-B88F-E253CC353720}.Release|ARM.Deploy.0 = Release|ARM + {15247C71-5289-4913-B88F-E253CC353720}.Release|Win32.ActiveCfg = Release|Win32 + {15247C71-5289-4913-B88F-E253CC353720}.Release|Win32.Build.0 = Release|Win32 + {15247C71-5289-4913-B88F-E253CC353720}.Release|Win32.Deploy.0 = Release|Win32 + {15247C71-5289-4913-B88F-E253CC353720}.Release|x64.ActiveCfg = Release|Win32 + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Debug|ARM.ActiveCfg = Debug|ARM + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Debug|ARM.Build.0 = Debug|ARM + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Debug|Win32.ActiveCfg = Debug|Win32 + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Debug|Win32.Build.0 = Debug|Win32 + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Debug|x64.ActiveCfg = Debug|x64 + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Debug|x64.Build.0 = Debug|x64 + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Release|ARM.ActiveCfg = Release|ARM + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Release|ARM.Build.0 = Release|ARM + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Release|Win32.ActiveCfg = Release|Win32 + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Release|Win32.Build.0 = Release|Win32 + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Release|x64.ActiveCfg = Release|x64 + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Release|x64.Build.0 = Release|x64 + {22F798D8-BFFF-4754-996F-A5395343D5EC}.Debug|ARM.ActiveCfg = Debug|ARM + {22F798D8-BFFF-4754-996F-A5395343D5EC}.Debug|ARM.Build.0 = Debug|ARM + {22F798D8-BFFF-4754-996F-A5395343D5EC}.Debug|Win32.ActiveCfg = Debug|Win32 + {22F798D8-BFFF-4754-996F-A5395343D5EC}.Debug|Win32.Build.0 = Debug|Win32 + {22F798D8-BFFF-4754-996F-A5395343D5EC}.Debug|x64.ActiveCfg = Debug|Win32 + {22F798D8-BFFF-4754-996F-A5395343D5EC}.Release|ARM.ActiveCfg = Release|ARM + {22F798D8-BFFF-4754-996F-A5395343D5EC}.Release|ARM.Build.0 = Release|ARM + {22F798D8-BFFF-4754-996F-A5395343D5EC}.Release|Win32.ActiveCfg = Release|Win32 + {22F798D8-BFFF-4754-996F-A5395343D5EC}.Release|Win32.Build.0 = Release|Win32 + {22F798D8-BFFF-4754-996F-A5395343D5EC}.Release|x64.ActiveCfg = Release|Win32 + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Debug|ARM.ActiveCfg = Debug|ARM + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Debug|ARM.Build.0 = Debug|ARM + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Debug|Win32.ActiveCfg = Debug|Win32 + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Debug|Win32.Build.0 = Debug|Win32 + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Debug|x64.ActiveCfg = Debug|x64 + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Debug|x64.Build.0 = Debug|x64 + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Release|ARM.ActiveCfg = Release|ARM + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Release|ARM.Build.0 = Release|ARM + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Release|Win32.ActiveCfg = Release|Win32 + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Release|Win32.Build.0 = Release|Win32 + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Release|x64.ActiveCfg = Release|x64 + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Release|x64.Build.0 = Release|x64 + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}.Debug|ARM.ActiveCfg = Debug|ARM + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}.Debug|ARM.Build.0 = Debug|ARM + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}.Debug|Win32.ActiveCfg = Debug|Win32 + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}.Debug|Win32.Build.0 = Debug|Win32 + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}.Debug|x64.ActiveCfg = Debug|Win32 + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}.Release|ARM.ActiveCfg = Release|ARM + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}.Release|ARM.Build.0 = Release|ARM + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}.Release|Win32.ActiveCfg = Release|Win32 + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}.Release|Win32.Build.0 = Release|Win32 + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}.Release|x64.ActiveCfg = Release|Win32 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Debug|ARM.ActiveCfg = Debug|ARM + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Debug|ARM.Build.0 = Debug|ARM + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Debug|ARM.Deploy.0 = Debug|ARM + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Debug|Win32.ActiveCfg = Debug|Win32 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Debug|Win32.Build.0 = Debug|Win32 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Debug|Win32.Deploy.0 = Debug|Win32 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Debug|x64.ActiveCfg = Debug|x64 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Debug|x64.Build.0 = Debug|x64 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Debug|x64.Deploy.0 = Debug|x64 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Release|ARM.ActiveCfg = Release|ARM + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Release|ARM.Build.0 = Release|ARM + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Release|ARM.Deploy.0 = Release|ARM + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Release|Win32.ActiveCfg = Release|Win32 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Release|Win32.Build.0 = Release|Win32 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Release|Win32.Deploy.0 = Release|Win32 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Release|x64.ActiveCfg = Release|x64 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Release|x64.Build.0 = Release|x64 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Release|x64.Deploy.0 = Release|x64 + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Debug|ARM.ActiveCfg = Debug|ARM + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Debug|ARM.Build.0 = Debug|ARM + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Debug|ARM.Deploy.0 = Debug|ARM + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Debug|Win32.ActiveCfg = Debug|Win32 + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Debug|Win32.Build.0 = Debug|Win32 + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Debug|Win32.Deploy.0 = Debug|Win32 + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Debug|x64.ActiveCfg = Debug|Win32 + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Release|ARM.ActiveCfg = Release|ARM + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Release|ARM.Build.0 = Release|ARM + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Release|ARM.Deploy.0 = Release|ARM + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Release|Win32.ActiveCfg = Release|Win32 + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Release|Win32.Build.0 = Release|Win32 + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Release|Win32.Deploy.0 = Release|Win32 + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Release|x64.ActiveCfg = Release|Win32 + {70914FC8-7709-4CD6-B86B-C63FDE5478DB}.Debug|ARM.ActiveCfg = Debug|ARM + {70914FC8-7709-4CD6-B86B-C63FDE5478DB}.Debug|ARM.Build.0 = Debug|ARM + {70914FC8-7709-4CD6-B86B-C63FDE5478DB}.Debug|ARM.Deploy.0 = Debug|ARM + {70914FC8-7709-4CD6-B86B-C63FDE5478DB}.Debug|Win32.ActiveCfg = Debug|Win32 + {70914FC8-7709-4CD6-B86B-C63FDE5478DB}.Debug|Win32.Build.0 = Debug|Win32 + {70914FC8-7709-4CD6-B86B-C63FDE5478DB}.Debug|Win32.Deploy.0 = Debug|Win32 + {70914FC8-7709-4CD6-B86B-C63FDE5478DB}.Debug|x64.ActiveCfg = Debug|x64 + {70914FC8-7709-4CD6-B86B-C63FDE5478DB}.Debug|x64.Build.0 = Debug|x64 + {70914FC8-7709-4CD6-B86B-C63FDE5478DB}.Debug|x64.Deploy.0 = Debug|x64 + {70914FC8-7709-4CD6-B86B-C63FDE5478DB}.Release|ARM.ActiveCfg = Release|ARM + {70914FC8-7709-4CD6-B86B-C63FDE5478DB}.Release|ARM.Build.0 = Release|ARM + {70914FC8-7709-4CD6-B86B-C63FDE5478DB}.Release|ARM.Deploy.0 = Release|ARM + {70914FC8-7709-4CD6-B86B-C63FDE5478DB}.Release|Win32.ActiveCfg = Release|Win32 + {70914FC8-7709-4CD6-B86B-C63FDE5478DB}.Release|Win32.Build.0 = Release|Win32 + {70914FC8-7709-4CD6-B86B-C63FDE5478DB}.Release|Win32.Deploy.0 = Release|Win32 + {70914FC8-7709-4CD6-B86B-C63FDE5478DB}.Release|x64.ActiveCfg = Release|x64 + {70914FC8-7709-4CD6-B86B-C63FDE5478DB}.Release|x64.Build.0 = Release|x64 + {70914FC8-7709-4CD6-B86B-C63FDE5478DB}.Release|x64.Deploy.0 = Release|x64 + {94874B5B-398F-448A-A366-35A35DC1DB9C}.Debug|ARM.ActiveCfg = Debug|ARM + {94874B5B-398F-448A-A366-35A35DC1DB9C}.Debug|ARM.Build.0 = Debug|ARM + {94874B5B-398F-448A-A366-35A35DC1DB9C}.Debug|ARM.Deploy.0 = Debug|ARM + {94874B5B-398F-448A-A366-35A35DC1DB9C}.Debug|Win32.ActiveCfg = Debug|Win32 + {94874B5B-398F-448A-A366-35A35DC1DB9C}.Debug|Win32.Build.0 = Debug|Win32 + {94874B5B-398F-448A-A366-35A35DC1DB9C}.Debug|Win32.Deploy.0 = Debug|Win32 + {94874B5B-398F-448A-A366-35A35DC1DB9C}.Debug|x64.ActiveCfg = Debug|Win32 + {94874B5B-398F-448A-A366-35A35DC1DB9C}.Release|ARM.ActiveCfg = Release|ARM + {94874B5B-398F-448A-A366-35A35DC1DB9C}.Release|ARM.Build.0 = Release|ARM + {94874B5B-398F-448A-A366-35A35DC1DB9C}.Release|ARM.Deploy.0 = Release|ARM + {94874B5B-398F-448A-A366-35A35DC1DB9C}.Release|Win32.ActiveCfg = Release|Win32 + {94874B5B-398F-448A-A366-35A35DC1DB9C}.Release|Win32.Build.0 = Release|Win32 + {94874B5B-398F-448A-A366-35A35DC1DB9C}.Release|Win32.Deploy.0 = Release|Win32 + {94874B5B-398F-448A-A366-35A35DC1DB9C}.Release|x64.ActiveCfg = Release|Win32 + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Debug|ARM.ActiveCfg = Debug|ARM + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Debug|ARM.Build.0 = Debug|ARM + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Debug|Win32.ActiveCfg = Debug|Win32 + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Debug|Win32.Build.0 = Debug|Win32 + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Debug|x64.ActiveCfg = Debug|x64 + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Debug|x64.Build.0 = Debug|x64 + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Release|ARM.ActiveCfg = Release|ARM + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Release|ARM.Build.0 = Release|ARM + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Release|Win32.ActiveCfg = Release|Win32 + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Release|Win32.Build.0 = Release|Win32 + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Release|x64.ActiveCfg = Release|x64 + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Release|x64.Build.0 = Release|x64 + {CA082EC4-17CE-430B-8207-D1E947A5D1E9}.Debug|ARM.ActiveCfg = Debug|ARM + {CA082EC4-17CE-430B-8207-D1E947A5D1E9}.Debug|ARM.Build.0 = Debug|ARM + {CA082EC4-17CE-430B-8207-D1E947A5D1E9}.Debug|Win32.ActiveCfg = Debug|Win32 + {CA082EC4-17CE-430B-8207-D1E947A5D1E9}.Debug|Win32.Build.0 = Debug|Win32 + {CA082EC4-17CE-430B-8207-D1E947A5D1E9}.Debug|x64.ActiveCfg = Debug|Win32 + {CA082EC4-17CE-430B-8207-D1E947A5D1E9}.Release|ARM.ActiveCfg = Release|ARM + {CA082EC4-17CE-430B-8207-D1E947A5D1E9}.Release|ARM.Build.0 = Release|ARM + {CA082EC4-17CE-430B-8207-D1E947A5D1E9}.Release|Win32.ActiveCfg = Release|Win32 + {CA082EC4-17CE-430B-8207-D1E947A5D1E9}.Release|Win32.Build.0 = Release|Win32 + {CA082EC4-17CE-430B-8207-D1E947A5D1E9}.Release|x64.ActiveCfg = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {5D6F020F-7E72-4494-90A0-2DF11D235DF9} = {B3F299D4-B4CA-4F0B-8BE2-FB328483BC13} + {9335005F-678E-4E8E-9B84-50037216AEC8} = {B3F299D4-B4CA-4F0B-8BE2-FB328483BC13} + {22F3B9DF-1209-4574-8331-003966F562BF} = {B3F299D4-B4CA-4F0B-8BE2-FB328483BC13} + {BE3A1791-5BCE-4CEA-92CD-0E2D86DDE27A} = {572742C5-9322-4548-AB8B-96C3750A1B5D} + {F2BAE06B-CAAE-43EE-B21B-57FA48DB04FA} = {572742C5-9322-4548-AB8B-96C3750A1B5D} + {15247C71-5289-4913-B88F-E253CC353720} = {572742C5-9322-4548-AB8B-96C3750A1B5D} + {B3D1A3D5-9F54-43AF-9322-230B53242B78} = {85630454-74EA-4B5B-9B62-0E459B4476CB} + {4A3C6BA8-C227-498B-AA21-40BDA27B461F} = {B3D1A3D5-9F54-43AF-9322-230B53242B78} + {3B26A12D-3A44-47EA-82D2-282660FC844D} = {B3D1A3D5-9F54-43AF-9322-230B53242B78} + {22F798D8-BFFF-4754-996F-A5395343D5EC} = {B3D1A3D5-9F54-43AF-9322-230B53242B78} + {6FEB795C-C98C-4C8C-A88B-A35DEE205348} = {85630454-74EA-4B5B-9B62-0E459B4476CB} + {ADAFD00D-A0D6-46EF-9F0B-EA2880BFE1DE} = {6FEB795C-C98C-4C8C-A88B-A35DEE205348} + {F3550FE0-C795-44F6-8FEB-093EB68143AE} = {6FEB795C-C98C-4C8C-A88B-A35DEE205348} + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF} = {6FEB795C-C98C-4C8C-A88B-A35DEE205348} + {A3AD93E4-0B2F-4C58-9181-69BED2E42E3E} = {B70EF25E-E352-4020-BCDF-388973E44637} + {79A8FCDA-4B12-4DD1-B676-FF148D651638} = {B70EF25E-E352-4020-BCDF-388973E44637} + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A} = {B70EF25E-E352-4020-BCDF-388973E44637} + {AE6763F6-1549-441E-AFB5-377BE1C776DC} = {8E24A044-D83D-476D-886D-F40E3CC621DF} + {70914FC8-7709-4CD6-B86B-C63FDE5478DB} = {8E24A044-D83D-476D-886D-F40E3CC621DF} + {94874B5B-398F-448A-A366-35A35DC1DB9C} = {8E24A044-D83D-476D-886D-F40E3CC621DF} + {BEA66276-51DD-4C53-92A8-F3D1FEA50892} = {60DCAEA9-E344-40C0-B90C-82FB8E671BD5} + {BCF5546D-66A0-4998-AFD6-C5514F618930} = {60DCAEA9-E344-40C0-B90C-82FB8E671BD5} + {CA082EC4-17CE-430B-8207-D1E947A5D1E9} = {60DCAEA9-E344-40C0-B90C-82FB8E671BD5} + EndGlobalSection +EndGlobal diff --git a/build/cocos2d_js_tests.xcodeproj/project.pbxproj b/build/cocos2d_js_tests.xcodeproj/project.pbxproj new file mode 100644 index 0000000000..8f218bf00a --- /dev/null +++ b/build/cocos2d_js_tests.xcodeproj/project.pbxproj @@ -0,0 +1,845 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 0541A76319738D8C00E45470 /* NativeOcClass.m in Sources */ = {isa = PBXBuildFile; fileRef = 0541A75D19738D5A00E45470 /* NativeOcClass.m */; }; + 0541A77819750DE700E45470 /* NativeOcClass.m in Sources */ = {isa = PBXBuildFile; fileRef = 0541A75D19738D5A00E45470 /* NativeOcClass.m */; }; + 0541A77A19750F7A00E45470 /* AppKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0541A77919750F7A00E45470 /* AppKit.framework */; }; + 1A604F3418BF1D4900CC9A93 /* src in Resources */ = {isa = PBXBuildFile; fileRef = 1A604F3118BF1D4900CC9A93 /* src */; }; + 1A604F3518BF1D4900CC9A93 /* src in Resources */ = {isa = PBXBuildFile; fileRef = 1A604F3118BF1D4900CC9A93 /* src */; }; + 1A604F3918BF1D5600CC9A93 /* AppDelegate.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A604F3718BF1D5600CC9A93 /* AppDelegate.cpp */; }; + 1A604F3A18BF1D5600CC9A93 /* AppDelegate.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A604F3718BF1D5600CC9A93 /* AppDelegate.cpp */; }; + 1A604F4D18BF1D6000CC9A93 /* AppController.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1A604F3D18BF1D6000CC9A93 /* AppController.mm */; }; + 1A604F4E18BF1D6000CC9A93 /* Default-568h@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 1A604F3E18BF1D6000CC9A93 /* Default-568h@2x.png */; }; + 1A604F4F18BF1D6000CC9A93 /* Default.png in Resources */ = {isa = PBXBuildFile; fileRef = 1A604F3F18BF1D6000CC9A93 /* Default.png */; }; + 1A604F5018BF1D6000CC9A93 /* Default@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 1A604F4018BF1D6000CC9A93 /* Default@2x.png */; }; + 1A604F5118BF1D6000CC9A93 /* Icon-114.png in Resources */ = {isa = PBXBuildFile; fileRef = 1A604F4118BF1D6000CC9A93 /* Icon-114.png */; }; + 1A604F5218BF1D6000CC9A93 /* Icon-120.png in Resources */ = {isa = PBXBuildFile; fileRef = 1A604F4218BF1D6000CC9A93 /* Icon-120.png */; }; + 1A604F5318BF1D6000CC9A93 /* Icon-144.png in Resources */ = {isa = PBXBuildFile; fileRef = 1A604F4318BF1D6000CC9A93 /* Icon-144.png */; }; + 1A604F5418BF1D6000CC9A93 /* Icon-152.png in Resources */ = {isa = PBXBuildFile; fileRef = 1A604F4418BF1D6000CC9A93 /* Icon-152.png */; }; + 1A604F5518BF1D6000CC9A93 /* Icon-57.png in Resources */ = {isa = PBXBuildFile; fileRef = 1A604F4518BF1D6000CC9A93 /* Icon-57.png */; }; + 1A604F5618BF1D6000CC9A93 /* Icon-72.png in Resources */ = {isa = PBXBuildFile; fileRef = 1A604F4618BF1D6000CC9A93 /* Icon-72.png */; }; + 1A604F5718BF1D6000CC9A93 /* Icon-76.png in Resources */ = {isa = PBXBuildFile; fileRef = 1A604F4718BF1D6000CC9A93 /* Icon-76.png */; }; + 1A604F5918BF1D6000CC9A93 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 1A604F4918BF1D6000CC9A93 /* main.m */; }; + 1A604F5A18BF1D6000CC9A93 /* RootViewController.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1A604F4C18BF1D6000CC9A93 /* RootViewController.mm */; }; + 1A604F6418BF1D6600CC9A93 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 1A604F5C18BF1D6600CC9A93 /* InfoPlist.strings */; }; + 1A604F6518BF1D6600CC9A93 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 1A604F5E18BF1D6600CC9A93 /* MainMenu.xib */; }; + 1A604F6618BF1D6600CC9A93 /* Icon.icns in Resources */ = {isa = PBXBuildFile; fileRef = 1A604F6018BF1D6600CC9A93 /* Icon.icns */; }; + 1A604F6718BF1D6600CC9A93 /* main.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1A604F6118BF1D6600CC9A93 /* main.cpp */; }; + 420BBD111AA8840E00493976 /* js_DrawNode3D_bindings.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 420BBD0F1AA8840E00493976 /* js_DrawNode3D_bindings.cpp */; }; + 420BBD121AA8840E00493976 /* js_DrawNode3D_bindings.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 420BBD0F1AA8840E00493976 /* js_DrawNode3D_bindings.cpp */; }; + 42BCD4A31AAF3BF500D035E5 /* js_Effect3D_bindings.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 42BCD4A11AAF3BF500D035E5 /* js_Effect3D_bindings.cpp */; }; + 42BCD4A41AAF3BF500D035E5 /* js_Effect3D_bindings.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 42BCD4A11AAF3BF500D035E5 /* js_Effect3D_bindings.cpp */; }; + A01E18F81784C59400B0CA4A /* libsqlite3.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = A035A71117822E9E00987F6C /* libsqlite3.dylib */; }; + A035A5E01782290400987F6C /* libcurl.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A9F808C177E98A600D9A1CB /* libcurl.dylib */; }; + A035A71217822E9E00987F6C /* libsqlite3.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = A035A71117822E9E00987F6C /* libsqlite3.dylib */; }; + BA0613B51AC23B2D003118D6 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BA0613B41AC23B2D003118D6 /* Security.framework */; }; + BA2350551948262700E17B2A /* script in Resources */ = {isa = PBXBuildFile; fileRef = BA2350541948262700E17B2A /* script */; }; + BA2350561948262700E17B2A /* script in Resources */ = {isa = PBXBuildFile; fileRef = BA2350541948262700E17B2A /* script */; }; + BAA7DEE418C84F5000D9A10E /* main.js in Resources */ = {isa = PBXBuildFile; fileRef = BAA7DEE218C84F5000D9A10E /* main.js */; }; + BAA7DEE518C84F5000D9A10E /* main.js in Resources */ = {isa = PBXBuildFile; fileRef = BAA7DEE218C84F5000D9A10E /* main.js */; }; + BAA7DEE618C84F5000D9A10E /* project.json in Resources */ = {isa = PBXBuildFile; fileRef = BAA7DEE318C84F5000D9A10E /* project.json */; }; + BAA7DEE718C84F5000D9A10E /* project.json in Resources */ = {isa = PBXBuildFile; fileRef = BAA7DEE318C84F5000D9A10E /* project.json */; }; + ED2719A21AE4F4F000C17085 /* GameController.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719A11AE4F4F000C17085 /* GameController.framework */; }; + ED2719A41AE4F51F00C17085 /* StoreKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719A31AE4F51F00C17085 /* StoreKit.framework */; }; + ED2719A61AE4F52F00C17085 /* CoreTelephony.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719A51AE4F52E00C17085 /* CoreTelephony.framework */; }; + ED2719A81AE4F53B00C17085 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719A71AE4F53B00C17085 /* Security.framework */; }; + ED2719AA1AE4F54500C17085 /* MediaPlayer.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719A91AE4F54500C17085 /* MediaPlayer.framework */; }; + ED2719AC1AE4F55000C17085 /* MessageUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719AB1AE4F55000C17085 /* MessageUI.framework */; }; + ED2719AE1AE4F55800C17085 /* AdSupport.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719AD1AE4F55800C17085 /* AdSupport.framework */; }; + ED2719B01AE4F56500C17085 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719AF1AE4F56500C17085 /* SystemConfiguration.framework */; }; + ED2719B21AE4F57200C17085 /* CoreMotion.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719B11AE4F57100C17085 /* CoreMotion.framework */; }; + ED2719B41AE4F57E00C17085 /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719B31AE4F57E00C17085 /* libz.dylib */; }; + ED2719B61AE4F59500C17085 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719B51AE4F59500C17085 /* Foundation.framework */; }; + ED2719B81AE4F5A100C17085 /* AudioToolbox.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719B71AE4F5A100C17085 /* AudioToolbox.framework */; }; + ED2719BA1AE4F5A900C17085 /* OpenAL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719B91AE4F5A900C17085 /* OpenAL.framework */; }; + ED2719BC1AE4F5B500C17085 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719BB1AE4F5B500C17085 /* QuartzCore.framework */; }; + ED2719BE1AE4F5BE00C17085 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719BD1AE4F5BE00C17085 /* CoreGraphics.framework */; }; + ED2719C01AE4F5C500C17085 /* OpenGLES.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719BF1AE4F5C500C17085 /* OpenGLES.framework */; }; + ED2719C21AE4F5CC00C17085 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719C11AE4F5CC00C17085 /* UIKit.framework */; }; + ED2719C41AE4F5D300C17085 /* AVFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719C31AE4F5D300C17085 /* AVFoundation.framework */; }; + ED2719C61AE4F60C00C17085 /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719C51AE4F60C00C17085 /* libz.dylib */; }; + ED2719C81AE4F61600C17085 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719C71AE4F61500C17085 /* Foundation.framework */; }; + ED2719CA1AE4F61D00C17085 /* AudioToolbox.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719C91AE4F61D00C17085 /* AudioToolbox.framework */; }; + ED2719CC1AE4F62A00C17085 /* ApplicationServices.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719CB1AE4F62A00C17085 /* ApplicationServices.framework */; }; + ED2719CE1AE4F63200C17085 /* OpenAL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719CD1AE4F63200C17085 /* OpenAL.framework */; }; + ED2719D01AE4F63D00C17085 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719CF1AE4F63D00C17085 /* QuartzCore.framework */; }; + ED2719D21AE4F64600C17085 /* OpenGL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719D11AE4F64600C17085 /* OpenGL.framework */; }; + ED2719D41AE4F64D00C17085 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719D31AE4F64D00C17085 /* Cocoa.framework */; }; + ED2719D51AE4F86500C17085 /* libjscocos2d iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719611AE4E69800C17085 /* libjscocos2d iOS.a */; }; + ED2719DA1AE4F8EB00C17085 /* libcocos2d iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719591AE4E68200C17085 /* libcocos2d iOS.a */; }; + ED2719DB1AE4FA1200C17085 /* libcocos2d Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = ED2719571AE4E68200C17085 /* libcocos2d Mac.a */; }; + ED2719DC1AE4FA1600C17085 /* libjscocos2d Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = ED27195F1AE4E69800C17085 /* libjscocos2d Mac.a */; }; + ED743D1717D099F10004076B /* IOKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EDCC747E17C455FD007B692C /* IOKit.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + ED2719561AE4E68200C17085 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1A604F0218BF1D1C00CC9A93 /* cocos2d_libs.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 1551A33F158F2AB200E66CFE; + remoteInfo = "libcocos2d Mac"; + }; + ED2719581AE4E68200C17085 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1A604F0218BF1D1C00CC9A93 /* cocos2d_libs.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = A07A4D641783777C0073F6A7; + remoteInfo = "libcocos2d iOS"; + }; + ED27195E1AE4E69800C17085 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1A604F2518BF1D2000CC9A93 /* cocos2d_js_bindings.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 1A5410A418B785A10016A3AF; + remoteInfo = "libjscocos2d Mac"; + }; + ED2719601AE4E69800C17085 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1A604F2518BF1D2000CC9A93 /* cocos2d_js_bindings.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 1A5410A518B785A10016A3AF; + remoteInfo = "libjscocos2d iOS"; + }; + ED2719941AE4F14A00C17085 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1A604F2518BF1D2000CC9A93 /* cocos2d_js_bindings.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = A07A4FB5178387750073F6A7; + remoteInfo = "libjscocos2d iOS"; + }; + ED2719961AE4F15100C17085 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1A604F0218BF1D1C00CC9A93 /* cocos2d_libs.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = 1551A33E158F2AB200E66CFE; + remoteInfo = "libcocos2d Mac"; + }; + ED2719981AE4F15800C17085 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1A604F2518BF1D2000CC9A93 /* cocos2d_js_bindings.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = A03F31E81781479B006731B9; + remoteInfo = "libjscocos2d Mac"; + }; + ED27199E1AE4F48800C17085 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1A604F0218BF1D1C00CC9A93 /* cocos2d_libs.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = A07A4C241783777C0073F6A7; + remoteInfo = "libcocos2d iOS"; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 0541A75C19738D5A00E45470 /* NativeOcClass.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = NativeOcClass.h; path = ../proj.ios/NativeOcClass.h; sourceTree = ""; }; + 0541A75D19738D5A00E45470 /* NativeOcClass.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = NativeOcClass.m; path = ../proj.ios/NativeOcClass.m; sourceTree = ""; }; + 0541A77919750F7A00E45470 /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = System/Library/Frameworks/AppKit.framework; sourceTree = SDKROOT; }; + 1A604F0218BF1D1C00CC9A93 /* cocos2d_libs.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = cocos2d_libs.xcodeproj; sourceTree = ""; }; + 1A604F2518BF1D2000CC9A93 /* cocos2d_js_bindings.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = cocos2d_js_bindings.xcodeproj; path = "../cocos/scripting/js-bindings/proj.ios_mac/cocos2d_js_bindings.xcodeproj"; sourceTree = ""; }; + 1A604F3118BF1D4900CC9A93 /* src */ = {isa = PBXFileReference; lastKnownFileType = folder; name = src; path = "../tests/js-tests/src"; sourceTree = ""; }; + 1A604F3718BF1D5600CC9A93 /* AppDelegate.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AppDelegate.cpp; sourceTree = ""; }; + 1A604F3818BF1D5600CC9A93 /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; + 1A604F3C18BF1D6000CC9A93 /* AppController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppController.h; sourceTree = ""; }; + 1A604F3D18BF1D6000CC9A93 /* AppController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = AppController.mm; sourceTree = ""; }; + 1A604F3E18BF1D6000CC9A93 /* Default-568h@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568h@2x.png"; sourceTree = ""; }; + 1A604F3F18BF1D6000CC9A93 /* Default.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Default.png; sourceTree = ""; }; + 1A604F4018BF1D6000CC9A93 /* Default@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default@2x.png"; sourceTree = ""; }; + 1A604F4118BF1D6000CC9A93 /* Icon-114.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Icon-114.png"; sourceTree = ""; }; + 1A604F4218BF1D6000CC9A93 /* Icon-120.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Icon-120.png"; sourceTree = ""; }; + 1A604F4318BF1D6000CC9A93 /* Icon-144.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Icon-144.png"; sourceTree = ""; }; + 1A604F4418BF1D6000CC9A93 /* Icon-152.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Icon-152.png"; sourceTree = ""; }; + 1A604F4518BF1D6000CC9A93 /* Icon-57.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Icon-57.png"; sourceTree = ""; }; + 1A604F4618BF1D6000CC9A93 /* Icon-72.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Icon-72.png"; sourceTree = ""; }; + 1A604F4718BF1D6000CC9A93 /* Icon-76.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Icon-76.png"; sourceTree = ""; }; + 1A604F4818BF1D6000CC9A93 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 1A604F4918BF1D6000CC9A93 /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; + 1A604F4A18BF1D6000CC9A93 /* Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Prefix.pch; sourceTree = ""; }; + 1A604F4B18BF1D6000CC9A93 /* RootViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RootViewController.h; sourceTree = ""; }; + 1A604F4C18BF1D6000CC9A93 /* RootViewController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = RootViewController.mm; sourceTree = ""; }; + 1A604F5D18BF1D6600CC9A93 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = ""; }; + 1A604F5F18BF1D6600CC9A93 /* en */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = en; path = en.lproj/MainMenu.xib; sourceTree = ""; }; + 1A604F6018BF1D6600CC9A93 /* Icon.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; path = Icon.icns; sourceTree = ""; }; + 1A604F6118BF1D6600CC9A93 /* main.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = main.cpp; sourceTree = ""; }; + 1A604F6218BF1D6600CC9A93 /* Test_Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Test_Info.plist; sourceTree = ""; }; + 1A604F6318BF1D6600CC9A93 /* Test_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Test_Prefix.pch; sourceTree = ""; }; + 1A9F808C177E98A600D9A1CB /* libcurl.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libcurl.dylib; path = usr/lib/libcurl.dylib; sourceTree = SDKROOT; }; + 420BBD0F1AA8840E00493976 /* js_DrawNode3D_bindings.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = js_DrawNode3D_bindings.cpp; sourceTree = ""; }; + 420BBD101AA8840E00493976 /* js_DrawNode3D_bindings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = js_DrawNode3D_bindings.h; sourceTree = ""; }; + 42BCD4A11AAF3BF500D035E5 /* js_Effect3D_bindings.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = js_Effect3D_bindings.cpp; sourceTree = ""; }; + 42BCD4A21AAF3BF500D035E5 /* js_Effect3D_bindings.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = js_Effect3D_bindings.h; sourceTree = ""; }; + A01E17721784C06E00B0CA4A /* js-tests iOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "js-tests iOS.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + A035A5EC1782290400987F6C /* js-tests Mac.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "js-tests Mac.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + A035A71117822E9E00987F6C /* libsqlite3.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsqlite3.dylib; path = usr/lib/libsqlite3.dylib; sourceTree = SDKROOT; }; + BA0613B41AC23B2D003118D6 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; }; + BA2350541948262700E17B2A /* script */ = {isa = PBXFileReference; lastKnownFileType = text; name = script; path = "../cocos/scripting/js-bindings/script"; sourceTree = ""; }; + BAA7DEE218C84F5000D9A10E /* main.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = main.js; path = "../tests/js-tests/main.js"; sourceTree = ""; }; + BAA7DEE318C84F5000D9A10E /* project.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; name = project.json; path = "../tests/js-tests/project.json"; sourceTree = ""; }; + ED2719A11AE4F4F000C17085 /* GameController.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GameController.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/GameController.framework; sourceTree = DEVELOPER_DIR; }; + ED2719A31AE4F51F00C17085 /* StoreKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = StoreKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/StoreKit.framework; sourceTree = DEVELOPER_DIR; }; + ED2719A51AE4F52E00C17085 /* CoreTelephony.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreTelephony.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/CoreTelephony.framework; sourceTree = DEVELOPER_DIR; }; + ED2719A71AE4F53B00C17085 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/Security.framework; sourceTree = DEVELOPER_DIR; }; + ED2719A91AE4F54500C17085 /* MediaPlayer.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MediaPlayer.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/MediaPlayer.framework; sourceTree = DEVELOPER_DIR; }; + ED2719AB1AE4F55000C17085 /* MessageUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MessageUI.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/MessageUI.framework; sourceTree = DEVELOPER_DIR; }; + ED2719AD1AE4F55800C17085 /* AdSupport.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AdSupport.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/AdSupport.framework; sourceTree = DEVELOPER_DIR; }; + ED2719AF1AE4F56500C17085 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/SystemConfiguration.framework; sourceTree = DEVELOPER_DIR; }; + ED2719B11AE4F57100C17085 /* CoreMotion.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreMotion.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/CoreMotion.framework; sourceTree = DEVELOPER_DIR; }; + ED2719B31AE4F57E00C17085 /* libz.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libz.dylib; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/usr/lib/libz.dylib; sourceTree = DEVELOPER_DIR; }; + ED2719B51AE4F59500C17085 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + ED2719B71AE4F5A100C17085 /* AudioToolbox.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AudioToolbox.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/AudioToolbox.framework; sourceTree = DEVELOPER_DIR; }; + ED2719B91AE4F5A900C17085 /* OpenAL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenAL.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/OpenAL.framework; sourceTree = DEVELOPER_DIR; }; + ED2719BB1AE4F5B500C17085 /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/QuartzCore.framework; sourceTree = DEVELOPER_DIR; }; + ED2719BD1AE4F5BE00C17085 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/CoreGraphics.framework; sourceTree = DEVELOPER_DIR; }; + ED2719BF1AE4F5C500C17085 /* OpenGLES.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGLES.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/OpenGLES.framework; sourceTree = DEVELOPER_DIR; }; + ED2719C11AE4F5CC00C17085 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; + ED2719C31AE4F5D300C17085 /* AVFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AVFoundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/AVFoundation.framework; sourceTree = DEVELOPER_DIR; }; + ED2719C51AE4F60C00C17085 /* libz.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libz.dylib; path = usr/lib/libz.dylib; sourceTree = SDKROOT; }; + ED2719C71AE4F61500C17085 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; + ED2719C91AE4F61D00C17085 /* AudioToolbox.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AudioToolbox.framework; path = System/Library/Frameworks/AudioToolbox.framework; sourceTree = SDKROOT; }; + ED2719CB1AE4F62A00C17085 /* ApplicationServices.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = ApplicationServices.framework; path = System/Library/Frameworks/ApplicationServices.framework; sourceTree = SDKROOT; }; + ED2719CD1AE4F63200C17085 /* OpenAL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenAL.framework; path = System/Library/Frameworks/OpenAL.framework; sourceTree = SDKROOT; }; + ED2719CF1AE4F63D00C17085 /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; }; + ED2719D11AE4F64600C17085 /* OpenGL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGL.framework; path = System/Library/Frameworks/OpenGL.framework; sourceTree = SDKROOT; }; + ED2719D31AE4F64D00C17085 /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = System/Library/Frameworks/Cocoa.framework; sourceTree = SDKROOT; }; + EDCC747E17C455FD007B692C /* IOKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = IOKit.framework; path = System/Library/Frameworks/IOKit.framework; sourceTree = SDKROOT; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + A01E17601784C06E00B0CA4A /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ED2719DA1AE4F8EB00C17085 /* libcocos2d iOS.a in Frameworks */, + ED2719D51AE4F86500C17085 /* libjscocos2d iOS.a in Frameworks */, + ED2719C41AE4F5D300C17085 /* AVFoundation.framework in Frameworks */, + ED2719C21AE4F5CC00C17085 /* UIKit.framework in Frameworks */, + ED2719C01AE4F5C500C17085 /* OpenGLES.framework in Frameworks */, + ED2719BE1AE4F5BE00C17085 /* CoreGraphics.framework in Frameworks */, + ED2719BC1AE4F5B500C17085 /* QuartzCore.framework in Frameworks */, + ED2719BA1AE4F5A900C17085 /* OpenAL.framework in Frameworks */, + ED2719B81AE4F5A100C17085 /* AudioToolbox.framework in Frameworks */, + ED2719B61AE4F59500C17085 /* Foundation.framework in Frameworks */, + ED2719B41AE4F57E00C17085 /* libz.dylib in Frameworks */, + ED2719B21AE4F57200C17085 /* CoreMotion.framework in Frameworks */, + ED2719B01AE4F56500C17085 /* SystemConfiguration.framework in Frameworks */, + ED2719AE1AE4F55800C17085 /* AdSupport.framework in Frameworks */, + ED2719AC1AE4F55000C17085 /* MessageUI.framework in Frameworks */, + ED2719AA1AE4F54500C17085 /* MediaPlayer.framework in Frameworks */, + ED2719A81AE4F53B00C17085 /* Security.framework in Frameworks */, + ED2719A61AE4F52F00C17085 /* CoreTelephony.framework in Frameworks */, + ED2719A41AE4F51F00C17085 /* StoreKit.framework in Frameworks */, + ED2719A21AE4F4F000C17085 /* GameController.framework in Frameworks */, + A01E18F81784C59400B0CA4A /* libsqlite3.dylib in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A035A5DA1782290400987F6C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ED2719DC1AE4FA1600C17085 /* libjscocos2d Mac.a in Frameworks */, + ED2719DB1AE4FA1200C17085 /* libcocos2d Mac.a in Frameworks */, + ED2719D41AE4F64D00C17085 /* Cocoa.framework in Frameworks */, + ED2719D21AE4F64600C17085 /* OpenGL.framework in Frameworks */, + ED2719D01AE4F63D00C17085 /* QuartzCore.framework in Frameworks */, + ED2719CE1AE4F63200C17085 /* OpenAL.framework in Frameworks */, + ED2719CC1AE4F62A00C17085 /* ApplicationServices.framework in Frameworks */, + ED2719CA1AE4F61D00C17085 /* AudioToolbox.framework in Frameworks */, + ED2719C81AE4F61600C17085 /* Foundation.framework in Frameworks */, + ED2719C61AE4F60C00C17085 /* libz.dylib in Frameworks */, + BA0613B51AC23B2D003118D6 /* Security.framework in Frameworks */, + 0541A77A19750F7A00E45470 /* AppKit.framework in Frameworks */, + A035A71217822E9E00987F6C /* libsqlite3.dylib in Frameworks */, + A035A5E01782290400987F6C /* libcurl.dylib in Frameworks */, + ED743D1717D099F10004076B /* IOKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 19C28FACFE9D520D11CA2CBB /* Products */ = { + isa = PBXGroup; + children = ( + A035A5EC1782290400987F6C /* js-tests Mac.app */, + A01E17721784C06E00B0CA4A /* js-tests iOS.app */, + ); + name = Products; + sourceTree = ""; + }; + 1A2B72DA18D294AE00ED9E74 /* project */ = { + isa = PBXGroup; + children = ( + 1A604F3618BF1D5600CC9A93 /* Classes */, + 1A604F3B18BF1D6000CC9A93 /* proj.ios */, + 1A604F5B18BF1D6600CC9A93 /* proj.mac */, + ); + name = project; + sourceTree = ""; + }; + 1A604F2E18BF1D3300CC9A93 /* js-tests */ = { + isa = PBXGroup; + children = ( + BAA7DEE218C84F5000D9A10E /* main.js */, + 1A2B72DA18D294AE00ED9E74 /* project */, + BAA7DEE318C84F5000D9A10E /* project.json */, + 1A604F3118BF1D4900CC9A93 /* src */, + ); + name = "js-tests"; + sourceTree = ""; + }; + 1A604F3618BF1D5600CC9A93 /* Classes */ = { + isa = PBXGroup; + children = ( + 42BCD4A11AAF3BF500D035E5 /* js_Effect3D_bindings.cpp */, + 42BCD4A21AAF3BF500D035E5 /* js_Effect3D_bindings.h */, + 420BBD0F1AA8840E00493976 /* js_DrawNode3D_bindings.cpp */, + 420BBD101AA8840E00493976 /* js_DrawNode3D_bindings.h */, + 0541A75C19738D5A00E45470 /* NativeOcClass.h */, + 0541A75D19738D5A00E45470 /* NativeOcClass.m */, + 1A604F3718BF1D5600CC9A93 /* AppDelegate.cpp */, + 1A604F3818BF1D5600CC9A93 /* AppDelegate.h */, + ); + name = Classes; + path = "../tests/js-tests/project/Classes"; + sourceTree = ""; + }; + 1A604F3B18BF1D6000CC9A93 /* proj.ios */ = { + isa = PBXGroup; + children = ( + 1A604F3C18BF1D6000CC9A93 /* AppController.h */, + 1A604F3D18BF1D6000CC9A93 /* AppController.mm */, + 1A604F3E18BF1D6000CC9A93 /* Default-568h@2x.png */, + 1A604F3F18BF1D6000CC9A93 /* Default.png */, + 1A604F4018BF1D6000CC9A93 /* Default@2x.png */, + 1A604F4118BF1D6000CC9A93 /* Icon-114.png */, + 1A604F4218BF1D6000CC9A93 /* Icon-120.png */, + 1A604F4318BF1D6000CC9A93 /* Icon-144.png */, + 1A604F4418BF1D6000CC9A93 /* Icon-152.png */, + 1A604F4518BF1D6000CC9A93 /* Icon-57.png */, + 1A604F4618BF1D6000CC9A93 /* Icon-72.png */, + 1A604F4718BF1D6000CC9A93 /* Icon-76.png */, + 1A604F4818BF1D6000CC9A93 /* Info.plist */, + 1A604F4918BF1D6000CC9A93 /* main.m */, + 1A604F4A18BF1D6000CC9A93 /* Prefix.pch */, + 1A604F4B18BF1D6000CC9A93 /* RootViewController.h */, + 1A604F4C18BF1D6000CC9A93 /* RootViewController.mm */, + ); + name = proj.ios; + path = "../tests/js-tests/project/proj.ios"; + sourceTree = ""; + }; + 1A604F5B18BF1D6600CC9A93 /* proj.mac */ = { + isa = PBXGroup; + children = ( + 1A604F5C18BF1D6600CC9A93 /* InfoPlist.strings */, + 1A604F5E18BF1D6600CC9A93 /* MainMenu.xib */, + 1A604F6018BF1D6600CC9A93 /* Icon.icns */, + 1A604F6118BF1D6600CC9A93 /* main.cpp */, + 1A604F6218BF1D6600CC9A93 /* Test_Info.plist */, + 1A604F6318BF1D6600CC9A93 /* Test_Prefix.pch */, + ); + name = proj.mac; + path = "../tests/js-tests/project/proj.mac"; + sourceTree = ""; + }; + 29B97314FDCFA39411CA2CEA /* CustomTemplate */ = { + isa = PBXGroup; + children = ( + 1A604F2518BF1D2000CC9A93 /* cocos2d_js_bindings.xcodeproj */, + 1A604F0218BF1D1C00CC9A93 /* cocos2d_libs.xcodeproj */, + 29B97323FDCFA39411CA2CEA /* Frameworks */, + BAC9055D195C2D2500307000 /* script */, + 1A604F2E18BF1D3300CC9A93 /* js-tests */, + 19C28FACFE9D520D11CA2CBB /* Products */, + ); + name = CustomTemplate; + sourceTree = ""; + }; + 29B97323FDCFA39411CA2CEA /* Frameworks */ = { + isa = PBXGroup; + children = ( + ED2719D31AE4F64D00C17085 /* Cocoa.framework */, + ED2719D11AE4F64600C17085 /* OpenGL.framework */, + ED2719CF1AE4F63D00C17085 /* QuartzCore.framework */, + ED2719CD1AE4F63200C17085 /* OpenAL.framework */, + ED2719CB1AE4F62A00C17085 /* ApplicationServices.framework */, + ED2719C91AE4F61D00C17085 /* AudioToolbox.framework */, + ED2719C71AE4F61500C17085 /* Foundation.framework */, + ED2719C51AE4F60C00C17085 /* libz.dylib */, + ED2719C31AE4F5D300C17085 /* AVFoundation.framework */, + ED2719C11AE4F5CC00C17085 /* UIKit.framework */, + ED2719BF1AE4F5C500C17085 /* OpenGLES.framework */, + ED2719BD1AE4F5BE00C17085 /* CoreGraphics.framework */, + ED2719BB1AE4F5B500C17085 /* QuartzCore.framework */, + ED2719B91AE4F5A900C17085 /* OpenAL.framework */, + ED2719B71AE4F5A100C17085 /* AudioToolbox.framework */, + ED2719B51AE4F59500C17085 /* Foundation.framework */, + ED2719B31AE4F57E00C17085 /* libz.dylib */, + ED2719B11AE4F57100C17085 /* CoreMotion.framework */, + ED2719AF1AE4F56500C17085 /* SystemConfiguration.framework */, + ED2719AD1AE4F55800C17085 /* AdSupport.framework */, + ED2719AB1AE4F55000C17085 /* MessageUI.framework */, + ED2719A91AE4F54500C17085 /* MediaPlayer.framework */, + ED2719A71AE4F53B00C17085 /* Security.framework */, + ED2719A51AE4F52E00C17085 /* CoreTelephony.framework */, + ED2719A31AE4F51F00C17085 /* StoreKit.framework */, + ED2719A11AE4F4F000C17085 /* GameController.framework */, + BA0613B41AC23B2D003118D6 /* Security.framework */, + 0541A77919750F7A00E45470 /* AppKit.framework */, + A035A71117822E9E00987F6C /* libsqlite3.dylib */, + 1A9F808C177E98A600D9A1CB /* libcurl.dylib */, + EDCC747E17C455FD007B692C /* IOKit.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + BAC9055D195C2D2500307000 /* script */ = { + isa = PBXGroup; + children = ( + BA2350541948262700E17B2A /* script */, + ); + name = script; + sourceTree = ""; + }; + ED2719521AE4E68200C17085 /* Products */ = { + isa = PBXGroup; + children = ( + ED2719571AE4E68200C17085 /* libcocos2d Mac.a */, + ED2719591AE4E68200C17085 /* libcocos2d iOS.a */, + ); + name = Products; + sourceTree = ""; + }; + ED27195A1AE4E69800C17085 /* Products */ = { + isa = PBXGroup; + children = ( + ED27195F1AE4E69800C17085 /* libjscocos2d Mac.a */, + ED2719611AE4E69800C17085 /* libjscocos2d iOS.a */, + ); + name = Products; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + A01E16C01784C06E00B0CA4A /* js-tests iOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = A01E176F1784C06E00B0CA4A /* Build configuration list for PBXNativeTarget "js-tests iOS" */; + buildPhases = ( + A01E16CB1784C06E00B0CA4A /* Resources */, + A01E16F51784C06E00B0CA4A /* Sources */, + A01E17601784C06E00B0CA4A /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ED2719951AE4F14A00C17085 /* PBXTargetDependency */, + ED27199F1AE4F48800C17085 /* PBXTargetDependency */, + ); + name = "js-tests iOS"; + productName = iphone; + productReference = A01E17721784C06E00B0CA4A /* js-tests iOS.app */; + productType = "com.apple.product-type.application"; + }; + A035A5441782290400987F6C /* js-tests Mac */ = { + isa = PBXNativeTarget; + buildConfigurationList = A035A5E91782290400987F6C /* Build configuration list for PBXNativeTarget "js-tests Mac" */; + buildPhases = ( + A035A54F1782290400987F6C /* Resources */, + A035A5701782290400987F6C /* Sources */, + A035A5DA1782290400987F6C /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ED2719991AE4F15800C17085 /* PBXTargetDependency */, + ED2719971AE4F15100C17085 /* PBXTargetDependency */, + ); + name = "js-tests Mac"; + productName = iphone; + productReference = A035A5EC1782290400987F6C /* js-tests Mac.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 29B97313FDCFA39411CA2CEA /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0510; + }; + buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "cocos2d_jsb_samples" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 1; + knownRegions = ( + English, + Japanese, + French, + German, + en, + ); + mainGroup = 29B97314FDCFA39411CA2CEA /* CustomTemplate */; + projectDirPath = ""; + projectReferences = ( + { + ProductGroup = ED27195A1AE4E69800C17085 /* Products */; + ProjectRef = 1A604F2518BF1D2000CC9A93 /* cocos2d_js_bindings.xcodeproj */; + }, + { + ProductGroup = ED2719521AE4E68200C17085 /* Products */; + ProjectRef = 1A604F0218BF1D1C00CC9A93 /* cocos2d_libs.xcodeproj */; + }, + ); + projectRoot = ""; + targets = ( + A035A5441782290400987F6C /* js-tests Mac */, + A01E16C01784C06E00B0CA4A /* js-tests iOS */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXReferenceProxy section */ + ED2719571AE4E68200C17085 /* libcocos2d Mac.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libcocos2d Mac.a"; + remoteRef = ED2719561AE4E68200C17085 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + ED2719591AE4E68200C17085 /* libcocos2d iOS.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libcocos2d iOS.a"; + remoteRef = ED2719581AE4E68200C17085 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + ED27195F1AE4E69800C17085 /* libjscocos2d Mac.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libjscocos2d Mac.a"; + remoteRef = ED27195E1AE4E69800C17085 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + ED2719611AE4E69800C17085 /* libjscocos2d iOS.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libjscocos2d iOS.a"; + remoteRef = ED2719601AE4E69800C17085 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; +/* End PBXReferenceProxy section */ + +/* Begin PBXResourcesBuildPhase section */ + A01E16CB1784C06E00B0CA4A /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + BA2350561948262700E17B2A /* script in Resources */, + BAA7DEE718C84F5000D9A10E /* project.json in Resources */, + 1A604F5518BF1D6000CC9A93 /* Icon-57.png in Resources */, + 1A604F5218BF1D6000CC9A93 /* Icon-120.png in Resources */, + 1A604F5618BF1D6000CC9A93 /* Icon-72.png in Resources */, + 1A604F5118BF1D6000CC9A93 /* Icon-114.png in Resources */, + 1A604F5718BF1D6000CC9A93 /* Icon-76.png in Resources */, + 1A604F3518BF1D4900CC9A93 /* src in Resources */, + 1A604F5018BF1D6000CC9A93 /* Default@2x.png in Resources */, + 1A604F4E18BF1D6000CC9A93 /* Default-568h@2x.png in Resources */, + 1A604F5318BF1D6000CC9A93 /* Icon-144.png in Resources */, + 1A604F5418BF1D6000CC9A93 /* Icon-152.png in Resources */, + 1A604F4F18BF1D6000CC9A93 /* Default.png in Resources */, + BAA7DEE518C84F5000D9A10E /* main.js in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A035A54F1782290400987F6C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + BAA7DEE618C84F5000D9A10E /* project.json in Resources */, + 1A604F6418BF1D6600CC9A93 /* InfoPlist.strings in Resources */, + BA2350551948262700E17B2A /* script in Resources */, + 1A604F6618BF1D6600CC9A93 /* Icon.icns in Resources */, + 1A604F3418BF1D4900CC9A93 /* src in Resources */, + 1A604F6518BF1D6600CC9A93 /* MainMenu.xib in Resources */, + BAA7DEE418C84F5000D9A10E /* main.js in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + A01E16F51784C06E00B0CA4A /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 0541A76319738D8C00E45470 /* NativeOcClass.m in Sources */, + 1A604F5A18BF1D6000CC9A93 /* RootViewController.mm in Sources */, + 42BCD4A41AAF3BF500D035E5 /* js_Effect3D_bindings.cpp in Sources */, + 420BBD121AA8840E00493976 /* js_DrawNode3D_bindings.cpp in Sources */, + 1A604F3A18BF1D5600CC9A93 /* AppDelegate.cpp in Sources */, + 1A604F5918BF1D6000CC9A93 /* main.m in Sources */, + 1A604F4D18BF1D6000CC9A93 /* AppController.mm in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A035A5701782290400987F6C /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 0541A77819750DE700E45470 /* NativeOcClass.m in Sources */, + 1A604F6718BF1D6600CC9A93 /* main.cpp in Sources */, + 42BCD4A31AAF3BF500D035E5 /* js_Effect3D_bindings.cpp in Sources */, + 420BBD111AA8840E00493976 /* js_DrawNode3D_bindings.cpp in Sources */, + 1A604F3918BF1D5600CC9A93 /* AppDelegate.cpp in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + ED2719951AE4F14A00C17085 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "libjscocos2d iOS"; + targetProxy = ED2719941AE4F14A00C17085 /* PBXContainerItemProxy */; + }; + ED2719971AE4F15100C17085 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "libcocos2d Mac"; + targetProxy = ED2719961AE4F15100C17085 /* PBXContainerItemProxy */; + }; + ED2719991AE4F15800C17085 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "libjscocos2d Mac"; + targetProxy = ED2719981AE4F15800C17085 /* PBXContainerItemProxy */; + }; + ED27199F1AE4F48800C17085 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "libcocos2d iOS"; + targetProxy = ED27199E1AE4F48800C17085 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 1A604F5C18BF1D6600CC9A93 /* InfoPlist.strings */ = { + isa = PBXVariantGroup; + children = ( + 1A604F5D18BF1D6600CC9A93 /* en */, + ); + name = InfoPlist.strings; + sourceTree = ""; + }; + 1A604F5E18BF1D6600CC9A93 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 1A604F5F18BF1D6600CC9A93 /* en */, + ); + name = MainMenu.xib; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + A01E17701784C06E00B0CA4A /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COMPRESS_PNG_FILES = NO; + COPY_PHASE_STRIP = NO; + FRAMEWORK_SEARCH_PATHS = "$(inherited)"; + GCC_DYNAMIC_NO_PIC = NO; + GCC_INLINES_ARE_PRIVATE_EXTERN = NO; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREPROCESSOR_DEFINITIONS = ( + "$(inherited)", + CC_TARGET_OS_IPHONE, + COCOS2D_JAVASCRIPT, + ); + GCC_SYMBOLS_PRIVATE_EXTERN = YES; + HEADER_SEARCH_PATHS = ""; + INFOPLIST_FILE = "$(SRCROOT)/../tests/js-tests/project/proj.ios/Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 5.1.1; + OTHER_LDFLAGS = "-ObjC"; + PROVISIONING_PROFILE = ""; + SCAN_ALL_SOURCE_FILES_FOR_INCLUDES = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + USER_HEADER_SEARCH_PATHS = "$(inherited) $(SRCROOT)/../cocos/platform/ios $(SRCROOT)/../external/spidermonkey/include/ios"; + VALID_ARCHS = "arm64 armv7"; + }; + name = Debug; + }; + A01E17711784C06E00B0CA4A /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COMPRESS_PNG_FILES = NO; + FRAMEWORK_SEARCH_PATHS = "$(inherited)"; + GCC_GENERATE_DEBUGGING_SYMBOLS = NO; + GCC_INLINES_ARE_PRIVATE_EXTERN = NO; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREPROCESSOR_DEFINITIONS = ( + "$(inherited)", + CC_TARGET_OS_IPHONE, + COCOS2D_JAVASCRIPT, + ); + GCC_SYMBOLS_PRIVATE_EXTERN = YES; + HEADER_SEARCH_PATHS = ""; + INFOPLIST_FILE = "$(SRCROOT)/../tests/js-tests/project/proj.ios/Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 5.1.1; + OTHER_LDFLAGS = "-ObjC"; + PROVISIONING_PROFILE = ""; + SCAN_ALL_SOURCE_FILES_FOR_INCLUDES = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + USER_HEADER_SEARCH_PATHS = "$(inherited) $(SRCROOT)/../cocos/platform/ios $(SRCROOT)/../external/spidermonkey/include/ios"; + VALIDATE_PRODUCT = YES; + VALID_ARCHS = "arm64 armv7"; + }; + name = Release; + }; + A035A5EA1782290400987F6C /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = YES; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)", + ); + GCC_DYNAMIC_NO_PIC = NO; + GCC_INLINES_ARE_PRIVATE_EXTERN = NO; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREPROCESSOR_DEFINITIONS = ( + "$(inherited)", + COCOS2D_JAVASCRIPT, + CC_TARGET_OS_MAC, + CC_KEYBOARD_SUPPORT, + ); + GCC_SYMBOLS_PRIVATE_EXTERN = YES; + HEADER_SEARCH_PATHS = ""; + INFOPLIST_FILE = "$(SRCROOT)/../tests/js-tests/project/proj.mac/Test_Info.plist"; + SCAN_ALL_SOURCE_FILES_FOR_INCLUDES = YES; + USER_HEADER_SEARCH_PATHS = "$(inherited) $(SRCROOT)/../cocos/platform/mac $(SRCROOT)/../external/glfw3/include/mac $(SRCROOT)/../external/spidermonkey/include/mac"; + }; + name = Debug; + }; + A035A5EB1782290400987F6C /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = YES; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)", + ); + GCC_GENERATE_DEBUGGING_SYMBOLS = NO; + GCC_INLINES_ARE_PRIVATE_EXTERN = NO; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREPROCESSOR_DEFINITIONS = ( + "$(inherited)", + COCOS2D_JAVASCRIPT, + CC_TARGET_OS_MAC, + CC_KEYBOARD_SUPPORT, + ); + GCC_SYMBOLS_PRIVATE_EXTERN = YES; + HEADER_SEARCH_PATHS = ""; + INFOPLIST_FILE = "$(SRCROOT)/../tests/js-tests/project/proj.mac/Test_Info.plist"; + SCAN_ALL_SOURCE_FILES_FOR_INCLUDES = YES; + USER_HEADER_SEARCH_PATHS = "$(inherited) $(SRCROOT)/../cocos/platform/mac $(SRCROOT)/../external/glfw3/include/mac $(SRCROOT)/../external/spidermonkey/include/mac"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + C01FCF4F08A954540054247B /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "c++0x"; + CLANG_CXX_LIBRARY = "libc++"; + COMBINE_HIDPI_IMAGES = YES; + COPY_PHASE_STRIP = NO; + GCC_C_LANGUAGE_STANDARD = c99; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "COCOS2D_DEBUG=1", + USE_FILE32API, + "CC_ENABLE_CHIPMUNK_INTEGRATION=1", + ); + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = ""; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = macosx; + USER_HEADER_SEARCH_PATHS = "$(SRCROOT)/.. $(SRCROOT)/../cocos $(SRCROOT)/../cocos/base $(SRCROOT)/../cocos/physics $(SRCROOT)/../cocos/math/kazmath $(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 $(SRCROOT)/../cocos/scripting/js-bindings/auto $(SRCROOT)/../cocos/scripting/js-bindings/manual"; + }; + name = Debug; + }; + C01FCF5008A954540054247B /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "c++0x"; + CLANG_CXX_LIBRARY = "libc++"; + COMBINE_HIDPI_IMAGES = YES; + GCC_C_LANGUAGE_STANDARD = c99; + GCC_PREPROCESSOR_DEFINITIONS = ( + NDEBUG, + USE_FILE32API, + "CC_ENABLE_CHIPMUNK_INTEGRATION=1", + ); + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = ""; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = macosx; + USER_HEADER_SEARCH_PATHS = "$(SRCROOT)/.. $(SRCROOT)/../cocos $(SRCROOT)/../cocos/base $(SRCROOT)/../cocos/physics $(SRCROOT)/../cocos/math/kazmath $(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 $(SRCROOT)/../cocos/scripting/js-bindings/auto $(SRCROOT)/../cocos/scripting/js-bindings/manual"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + A01E176F1784C06E00B0CA4A /* Build configuration list for PBXNativeTarget "js-tests iOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A01E17701784C06E00B0CA4A /* Debug */, + A01E17711784C06E00B0CA4A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Debug; + }; + A035A5E91782290400987F6C /* Build configuration list for PBXNativeTarget "js-tests Mac" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A035A5EA1782290400987F6C /* Debug */, + A035A5EB1782290400987F6C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Debug; + }; + C01FCF4E08A954540054247B /* Build configuration list for PBXProject "cocos2d_jsb_samples" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C01FCF4F08A954540054247B /* Debug */, + C01FCF5008A954540054247B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Debug; + }; +/* End XCConfigurationList section */ + }; + rootObject = 29B97313FDCFA39411CA2CEA /* Project object */; +} diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxJavascriptJavaBridge.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxJavascriptJavaBridge.java new file mode 100644 index 0000000000..996bda03c2 --- /dev/null +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxJavascriptJavaBridge.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2013-2014 Chukong Technologies 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. + */ + +package org.cocos2dx.lib; + +public class Cocos2dxJavascriptJavaBridge { + public static native int evalString(String value); +} diff --git a/cocos/scripting/js-bindings b/cocos/scripting/js-bindings new file mode 160000 index 0000000000..9b5067b881 --- /dev/null +++ b/cocos/scripting/js-bindings @@ -0,0 +1 @@ +Subproject commit 9b5067b88161e4e040330fb58f19d6229c3a442d diff --git a/external/config.json b/external/config.json index 0d89768e8c..393bb8e5af 100644 --- a/external/config.json +++ b/external/config.json @@ -1,6 +1,6 @@ { - "version":"v3-deps-44", - "zip_file_size":"74127526", + "version":"v3-deps-45", + "zip_file_size":"117286481", "repo_name":"cocos2d-x-3rd-party-libs-bin", "repo_parent":"https://github.com/cocos2d/", "move_dirs":{ diff --git a/templates/cocos2dx_files.json b/templates/cocos2dx_files.json index 4a7deb61de..4641606d5a 100644 --- a/templates/cocos2dx_files.json +++ b/templates/cocos2dx_files.json @@ -859,6 +859,7 @@ "cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHandler.java", "cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java", "cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHttpURLConnection.java", + "cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxJavascriptJavaBridge.java", "cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxLocalStorage.java", "cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxLuaJavaBridge.java", "cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxMusic.java", @@ -4510,6 +4511,1234 @@ "tools/simulator/libsimulator/proj.win32/stdafx.h", "tools/simulator/libsimulator/proj.win32/targetver.h" ], + "js": [ + "cocos/scripting/js-bindings/CMakeLists.txt", + "cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_3d_auto_api.js", + "cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_3d_extension_auto_api.js", + "cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js", + "cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_builder_auto_api.js", + "cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_extension_auto_api.js", + "cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_spine_auto_api.js", + "cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_studio_auto_api.js", + "cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_ui_auto_api.js", + "cocos/scripting/js-bindings/auto/jsb_cocos2dx_3d_auto.cpp", + "cocos/scripting/js-bindings/auto/jsb_cocos2dx_3d_auto.hpp", + "cocos/scripting/js-bindings/auto/jsb_cocos2dx_3d_extension_auto.cpp", + "cocos/scripting/js-bindings/auto/jsb_cocos2dx_3d_extension_auto.hpp", + "cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp", + "cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp", + "cocos/scripting/js-bindings/auto/jsb_cocos2dx_builder_auto.cpp", + "cocos/scripting/js-bindings/auto/jsb_cocos2dx_builder_auto.hpp", + "cocos/scripting/js-bindings/auto/jsb_cocos2dx_extension_auto.cpp", + "cocos/scripting/js-bindings/auto/jsb_cocos2dx_extension_auto.hpp", + "cocos/scripting/js-bindings/auto/jsb_cocos2dx_spine_auto.cpp", + "cocos/scripting/js-bindings/auto/jsb_cocos2dx_spine_auto.hpp", + "cocos/scripting/js-bindings/auto/jsb_cocos2dx_studio_auto.cpp", + "cocos/scripting/js-bindings/auto/jsb_cocos2dx_studio_auto.hpp", + "cocos/scripting/js-bindings/auto/jsb_cocos2dx_ui_auto.cpp", + "cocos/scripting/js-bindings/auto/jsb_cocos2dx_ui_auto.hpp", + "cocos/scripting/js-bindings/manual/3d/jsb_cocos2dx_3d_manual.cpp", + "cocos/scripting/js-bindings/manual/3d/jsb_cocos2dx_3d_manual.h", + "cocos/scripting/js-bindings/manual/ScriptingCore.cpp", + "cocos/scripting/js-bindings/manual/ScriptingCore.h", + "cocos/scripting/js-bindings/manual/chipmunk/js_bindings_chipmunk_auto_classes.cpp", + "cocos/scripting/js-bindings/manual/chipmunk/js_bindings_chipmunk_auto_classes.h", + "cocos/scripting/js-bindings/manual/chipmunk/js_bindings_chipmunk_auto_classes_registration.h", + "cocos/scripting/js-bindings/manual/chipmunk/js_bindings_chipmunk_functions.cpp", + "cocos/scripting/js-bindings/manual/chipmunk/js_bindings_chipmunk_functions.h", + "cocos/scripting/js-bindings/manual/chipmunk/js_bindings_chipmunk_functions_registration.h", + "cocos/scripting/js-bindings/manual/chipmunk/js_bindings_chipmunk_manual.cpp", + "cocos/scripting/js-bindings/manual/chipmunk/js_bindings_chipmunk_manual.h", + "cocos/scripting/js-bindings/manual/chipmunk/js_bindings_chipmunk_registration.cpp", + "cocos/scripting/js-bindings/manual/chipmunk/js_bindings_chipmunk_registration.h", + "cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp", + "cocos/scripting/js-bindings/manual/cocos2d_specifics.hpp", + "cocos/scripting/js-bindings/manual/cocosbuilder/cocosbuilder_specifics.hpp", + "cocos/scripting/js-bindings/manual/cocosbuilder/js_bindings_ccbreader.cpp", + "cocos/scripting/js-bindings/manual/cocosbuilder/js_bindings_ccbreader.h", + "cocos/scripting/js-bindings/manual/cocostudio/jsb_cocos2dx_studio_conversions.cpp", + "cocos/scripting/js-bindings/manual/cocostudio/jsb_cocos2dx_studio_conversions.h", + "cocos/scripting/js-bindings/manual/cocostudio/jsb_cocos2dx_studio_manual.cpp", + "cocos/scripting/js-bindings/manual/cocostudio/jsb_cocos2dx_studio_manual.h", + "cocos/scripting/js-bindings/manual/extension/jsb_cocos2dx_extension_manual.cpp", + "cocos/scripting/js-bindings/manual/extension/jsb_cocos2dx_extension_manual.h", + "cocos/scripting/js-bindings/manual/js_bindings_config.h", + "cocos/scripting/js-bindings/manual/js_bindings_core.cpp", + "cocos/scripting/js-bindings/manual/js_bindings_core.h", + "cocos/scripting/js-bindings/manual/js_bindings_opengl.cpp", + "cocos/scripting/js-bindings/manual/js_bindings_opengl.h", + "cocos/scripting/js-bindings/manual/js_manual_conversions.cpp", + "cocos/scripting/js-bindings/manual/js_manual_conversions.h", + "cocos/scripting/js-bindings/manual/jsb_event_dispatcher_manual.cpp", + "cocos/scripting/js-bindings/manual/jsb_event_dispatcher_manual.h", + "cocos/scripting/js-bindings/manual/jsb_helper.h", + "cocos/scripting/js-bindings/manual/jsb_opengl_functions.cpp", + "cocos/scripting/js-bindings/manual/jsb_opengl_functions.h", + "cocos/scripting/js-bindings/manual/jsb_opengl_manual.cpp", + "cocos/scripting/js-bindings/manual/jsb_opengl_manual.h", + "cocos/scripting/js-bindings/manual/jsb_opengl_registration.cpp", + "cocos/scripting/js-bindings/manual/jsb_opengl_registration.h", + "cocos/scripting/js-bindings/manual/localstorage/js_bindings_system_functions.cpp", + "cocos/scripting/js-bindings/manual/localstorage/js_bindings_system_functions.h", + "cocos/scripting/js-bindings/manual/localstorage/js_bindings_system_functions_registration.h", + "cocos/scripting/js-bindings/manual/localstorage/js_bindings_system_registration.cpp", + "cocos/scripting/js-bindings/manual/localstorage/js_bindings_system_registration.h", + "cocos/scripting/js-bindings/manual/network/XMLHTTPRequest.cpp", + "cocos/scripting/js-bindings/manual/network/XMLHTTPRequest.h", + "cocos/scripting/js-bindings/manual/network/jsb_socketio.cpp", + "cocos/scripting/js-bindings/manual/network/jsb_socketio.h", + "cocos/scripting/js-bindings/manual/network/jsb_websocket.cpp", + "cocos/scripting/js-bindings/manual/network/jsb_websocket.h", + "cocos/scripting/js-bindings/manual/platform/android/CCJavascriptJavaBridge.cpp", + "cocos/scripting/js-bindings/manual/platform/android/CCJavascriptJavaBridge.h", + "cocos/scripting/js-bindings/manual/platform/ios/JavaScriptObjCBridge.h", + "cocos/scripting/js-bindings/manual/platform/ios/JavaScriptObjCBridge.mm", + "cocos/scripting/js-bindings/manual/spidermonkey_specifics.h", + "cocos/scripting/js-bindings/manual/spine/jsb_cocos2dx_spine_manual.cpp", + "cocos/scripting/js-bindings/manual/spine/jsb_cocos2dx_spine_manual.h", + "cocos/scripting/js-bindings/manual/ui/jsb_cocos2dx_ui_manual.cpp", + "cocos/scripting/js-bindings/manual/ui/jsb_cocos2dx_ui_manual.h", + "cocos/scripting/js-bindings/proj.android/Android.mk", + "cocos/scripting/js-bindings/proj.ios_mac/cocos2d_js_bindings.xcodeproj/project.pbxproj", + "cocos/scripting/js-bindings/proj.win32/libjscocos2d.vcxproj", + "cocos/scripting/js-bindings/proj.win32/libjscocos2d.vcxproj.filters", + "cocos/scripting/js-bindings/proj.win8.1-universal/libjscocos2d/libjscocos2d.Shared/libjscocos2d.Shared.vcxitems", + "cocos/scripting/js-bindings/proj.win8.1-universal/libjscocos2d/libjscocos2d.Shared/libjscocos2d.Shared.vcxitems.filters", + "cocos/scripting/js-bindings/proj.win8.1-universal/libjscocos2d/libjscocos2d.Shared/targetver.h", + "cocos/scripting/js-bindings/proj.win8.1-universal/libjscocos2d/libjscocos2d.Windows/libjscocos2d.Windows.vcxproj", + "cocos/scripting/js-bindings/proj.win8.1-universal/libjscocos2d/libjscocos2d.Windows/libjscocos2d.Windows.vcxproj.filters", + "cocos/scripting/js-bindings/proj.win8.1-universal/libjscocos2d/libjscocos2d.WindowsPhone/libjscocos2d.WindowsPhone.vcxproj", + "cocos/scripting/js-bindings/proj.win8.1-universal/libjscocos2d/libjscocos2d.WindowsPhone/libjscocos2d.WindowsPhone.vcxproj.filters", + "cocos/scripting/js-bindings/proj.wp8/libjscocos2d.user", + "cocos/scripting/js-bindings/proj.wp8/libjscocos2d.vcxproj", + "cocos/scripting/js-bindings/proj.wp8/libjscocos2d.vcxproj.filters", + "cocos/scripting/js-bindings/script/3d/jsb_cocos2d_3d.js", + "cocos/scripting/js-bindings/script/3d/jsb_cocos2d_3d_ext.js", + "cocos/scripting/js-bindings/script/ccui/jsb_ccui_create_apis.js", + "cocos/scripting/js-bindings/script/ccui/jsb_ccui_deprecated.js", + "cocos/scripting/js-bindings/script/ccui/jsb_ccui_property_apis.js", + "cocos/scripting/js-bindings/script/ccui/jsb_ccui_property_impls.js", + "cocos/scripting/js-bindings/script/ccui/jsb_cocos2d_ui.js", + "cocos/scripting/js-bindings/script/chipmunk/jsb_chipmunk.js", + "cocos/scripting/js-bindings/script/chipmunk/jsb_chipmunk_constants.js", + "cocos/scripting/js-bindings/script/debugger/DevToolsUtils.js", + "cocos/scripting/js-bindings/script/debugger/README.md", + "cocos/scripting/js-bindings/script/debugger/actors/root.js", + "cocos/scripting/js-bindings/script/debugger/actors/script.js", + "cocos/scripting/js-bindings/script/debugger/core/promise.js", + "cocos/scripting/js-bindings/script/debugger/main.js", + "cocos/scripting/js-bindings/script/debugger/transport.js", + "cocos/scripting/js-bindings/script/extension/jsb_cocos2d_extension.js", + "cocos/scripting/js-bindings/script/extension/jsb_ext_create_apis.js", + "cocos/scripting/js-bindings/script/extension/jsb_ext_property_apis.js", + "cocos/scripting/js-bindings/script/jsb.js", + "cocos/scripting/js-bindings/script/jsb_boot.js", + "cocos/scripting/js-bindings/script/jsb_cocos2d.js", + "cocos/scripting/js-bindings/script/jsb_cocos2d_constants.js", + "cocos/scripting/js-bindings/script/jsb_cocosbuilder.js", + "cocos/scripting/js-bindings/script/jsb_common.js", + "cocos/scripting/js-bindings/script/jsb_create_apis.js", + "cocos/scripting/js-bindings/script/jsb_debugger.js", + "cocos/scripting/js-bindings/script/jsb_deprecated.js", + "cocos/scripting/js-bindings/script/jsb_loaders.js", + "cocos/scripting/js-bindings/script/jsb_opengl.js", + "cocos/scripting/js-bindings/script/jsb_opengl_constants.js", + "cocos/scripting/js-bindings/script/jsb_pool.js", + "cocos/scripting/js-bindings/script/jsb_property_apis.js", + "cocos/scripting/js-bindings/script/jsb_property_impls.js", + "cocos/scripting/js-bindings/script/jsb_spine.js", + "cocos/scripting/js-bindings/script/physicsSprite/jsb_physicsSprite.js", + "cocos/scripting/js-bindings/script/studio/jsb_cocos2d_studio.js", + "cocos/scripting/js-bindings/script/studio/jsb_studio_boot.js", + "cocos/scripting/js-bindings/script/studio/jsb_studio_create_apis.js", + "cocos/scripting/js-bindings/script/studio/jsb_studio_load.js", + "cocos/scripting/js-bindings/script/studio/jsb_studio_property_apis.js", + "cocos/scripting/js-bindings/script/studio/parsers/action-1.x.js", + "cocos/scripting/js-bindings/script/studio/parsers/action-2.x.js", + "cocos/scripting/js-bindings/script/studio/parsers/compatible.js", + "cocos/scripting/js-bindings/script/studio/parsers/scene-1.x.js", + "cocos/scripting/js-bindings/script/studio/parsers/timelineParser-1.x.js", + "cocos/scripting/js-bindings/script/studio/parsers/timelineParser-2.x.js", + "cocos/scripting/js-bindings/script/studio/parsers/uiParser-1.x.js", + "external/spidermonkey/README.md", + "external/spidermonkey/include/android/js-config.h", + "external/spidermonkey/include/android/js.msg", + "external/spidermonkey/include/android/js/Anchor.h", + "external/spidermonkey/include/android/js/CallArgs.h", + "external/spidermonkey/include/android/js/CallNonGenericMethod.h", + "external/spidermonkey/include/android/js/CharacterEncoding.h", + "external/spidermonkey/include/android/js/Class.h", + "external/spidermonkey/include/android/js/Date.h", + "external/spidermonkey/include/android/js/GCAPI.h", + "external/spidermonkey/include/android/js/HashTable.h", + "external/spidermonkey/include/android/js/HeapAPI.h", + "external/spidermonkey/include/android/js/Id.h", + "external/spidermonkey/include/android/js/LegacyIntTypes.h", + "external/spidermonkey/include/android/js/MemoryMetrics.h", + "external/spidermonkey/include/android/js/OldDebugAPI.h", + "external/spidermonkey/include/android/js/Principals.h", + "external/spidermonkey/include/android/js/ProfilingStack.h", + "external/spidermonkey/include/android/js/PropertyKey.h", + "external/spidermonkey/include/android/js/RequiredDefines.h", + "external/spidermonkey/include/android/js/RootingAPI.h", + "external/spidermonkey/include/android/js/SliceBudget.h", + "external/spidermonkey/include/android/js/StructuredClone.h", + "external/spidermonkey/include/android/js/TracingAPI.h", + "external/spidermonkey/include/android/js/TypeDecls.h", + "external/spidermonkey/include/android/js/UbiNode.h", + "external/spidermonkey/include/android/js/UbiNodeTraverse.h", + "external/spidermonkey/include/android/js/Utility.h", + "external/spidermonkey/include/android/js/Value.h", + "external/spidermonkey/include/android/js/Vector.h", + "external/spidermonkey/include/android/js/WeakMapPtr.h", + "external/spidermonkey/include/android/jsalloc.h", + "external/spidermonkey/include/android/jsapi.h", + "external/spidermonkey/include/android/jsbytecode.h", + "external/spidermonkey/include/android/jsclist.h", + "external/spidermonkey/include/android/jscpucfg.h", + "external/spidermonkey/include/android/jsfriendapi.h", + "external/spidermonkey/include/android/jsperf.h", + "external/spidermonkey/include/android/jsprf.h", + "external/spidermonkey/include/android/jsprototypes.h", + "external/spidermonkey/include/android/jsproxy.h", + "external/spidermonkey/include/android/jspubtd.h", + "external/spidermonkey/include/android/jstypes.h", + "external/spidermonkey/include/android/jsversion.h", + "external/spidermonkey/include/android/jswrapper.h", + "external/spidermonkey/include/android/mozilla/Alignment.h", + "external/spidermonkey/include/android/mozilla/AllocPolicy.h", + "external/spidermonkey/include/android/mozilla/Array.h", + "external/spidermonkey/include/android/mozilla/ArrayUtils.h", + "external/spidermonkey/include/android/mozilla/Assertions.h", + "external/spidermonkey/include/android/mozilla/Atomics.h", + "external/spidermonkey/include/android/mozilla/Attributes.h", + "external/spidermonkey/include/android/mozilla/BinarySearch.h", + "external/spidermonkey/include/android/mozilla/BloomFilter.h", + "external/spidermonkey/include/android/mozilla/Casting.h", + "external/spidermonkey/include/android/mozilla/ChaosMode.h", + "external/spidermonkey/include/android/mozilla/Char16.h", + "external/spidermonkey/include/android/mozilla/CheckedInt.h", + "external/spidermonkey/include/android/mozilla/Compiler.h", + "external/spidermonkey/include/android/mozilla/Compression.h", + "external/spidermonkey/include/android/mozilla/Constants.h", + "external/spidermonkey/include/android/mozilla/DebugOnly.h", + "external/spidermonkey/include/android/mozilla/Decimal.h", + "external/spidermonkey/include/android/mozilla/Endian.h", + "external/spidermonkey/include/android/mozilla/EnumSet.h", + "external/spidermonkey/include/android/mozilla/EnumeratedArray.h", + "external/spidermonkey/include/android/mozilla/FloatingPoint.h", + "external/spidermonkey/include/android/mozilla/GuardObjects.h", + "external/spidermonkey/include/android/mozilla/HashFunctions.h", + "external/spidermonkey/include/android/mozilla/IntegerPrintfMacros.h", + "external/spidermonkey/include/android/mozilla/IntegerTypeTraits.h", + "external/spidermonkey/include/android/mozilla/Likely.h", + "external/spidermonkey/include/android/mozilla/LinkedList.h", + "external/spidermonkey/include/android/mozilla/LinuxSignal.h", + "external/spidermonkey/include/android/mozilla/MSIntTypes.h", + "external/spidermonkey/include/android/mozilla/MacroArgs.h", + "external/spidermonkey/include/android/mozilla/MacroForEach.h", + "external/spidermonkey/include/android/mozilla/MathAlgorithms.h", + "external/spidermonkey/include/android/mozilla/Maybe.h", + "external/spidermonkey/include/android/mozilla/MaybeOneOf.h", + "external/spidermonkey/include/android/mozilla/MemoryChecking.h", + "external/spidermonkey/include/android/mozilla/MemoryReporting.h", + "external/spidermonkey/include/android/mozilla/Move.h", + "external/spidermonkey/include/android/mozilla/NullPtr.h", + "external/spidermonkey/include/android/mozilla/NumericLimits.h", + "external/spidermonkey/include/android/mozilla/Pair.h", + "external/spidermonkey/include/android/mozilla/PodOperations.h", + "external/spidermonkey/include/android/mozilla/Poison.h", + "external/spidermonkey/include/android/mozilla/Range.h", + "external/spidermonkey/include/android/mozilla/RangedPtr.h", + "external/spidermonkey/include/android/mozilla/ReentrancyGuard.h", + "external/spidermonkey/include/android/mozilla/RefCountType.h", + "external/spidermonkey/include/android/mozilla/RefPtr.h", + "external/spidermonkey/include/android/mozilla/RollingMean.h", + "external/spidermonkey/include/android/mozilla/SHA1.h", + "external/spidermonkey/include/android/mozilla/Scoped.h", + "external/spidermonkey/include/android/mozilla/SplayTree.h", + "external/spidermonkey/include/android/mozilla/TaggedAnonymousMemory.h", + "external/spidermonkey/include/android/mozilla/TemplateLib.h", + "external/spidermonkey/include/android/mozilla/ThreadLocal.h", + "external/spidermonkey/include/android/mozilla/ToString.h", + "external/spidermonkey/include/android/mozilla/TypeTraits.h", + "external/spidermonkey/include/android/mozilla/TypedEnum.h", + "external/spidermonkey/include/android/mozilla/TypedEnumBits.h", + "external/spidermonkey/include/android/mozilla/TypedEnumInternal.h", + "external/spidermonkey/include/android/mozilla/Types.h", + "external/spidermonkey/include/android/mozilla/UniquePtr.h", + "external/spidermonkey/include/android/mozilla/Vector.h", + "external/spidermonkey/include/android/mozilla/WeakPtr.h", + "external/spidermonkey/include/ios/js-config-32.h", + "external/spidermonkey/include/ios/js-config-64.h", + "external/spidermonkey/include/ios/js-config.h", + "external/spidermonkey/include/ios/js.msg", + "external/spidermonkey/include/ios/js/Anchor.h", + "external/spidermonkey/include/ios/js/CallArgs.h", + "external/spidermonkey/include/ios/js/CallNonGenericMethod.h", + "external/spidermonkey/include/ios/js/CharacterEncoding.h", + "external/spidermonkey/include/ios/js/Class.h", + "external/spidermonkey/include/ios/js/Date.h", + "external/spidermonkey/include/ios/js/GCAPI.h", + "external/spidermonkey/include/ios/js/HashTable.h", + "external/spidermonkey/include/ios/js/HeapAPI.h", + "external/spidermonkey/include/ios/js/Id.h", + "external/spidermonkey/include/ios/js/LegacyIntTypes.h", + "external/spidermonkey/include/ios/js/MemoryMetrics.h", + "external/spidermonkey/include/ios/js/OldDebugAPI.h", + "external/spidermonkey/include/ios/js/Principals.h", + "external/spidermonkey/include/ios/js/ProfilingStack.h", + "external/spidermonkey/include/ios/js/PropertyKey.h", + "external/spidermonkey/include/ios/js/RequiredDefines.h", + "external/spidermonkey/include/ios/js/RootingAPI.h", + "external/spidermonkey/include/ios/js/SliceBudget.h", + "external/spidermonkey/include/ios/js/StructuredClone.h", + "external/spidermonkey/include/ios/js/TracingAPI.h", + "external/spidermonkey/include/ios/js/TypeDecls.h", + "external/spidermonkey/include/ios/js/UbiNode.h", + "external/spidermonkey/include/ios/js/UbiNodeTraverse.h", + "external/spidermonkey/include/ios/js/Utility.h", + "external/spidermonkey/include/ios/js/Value.h", + "external/spidermonkey/include/ios/js/Vector.h", + "external/spidermonkey/include/ios/js/WeakMapPtr.h", + "external/spidermonkey/include/ios/jsalloc.h", + "external/spidermonkey/include/ios/jsapi.h", + "external/spidermonkey/include/ios/jsbytecode.h", + "external/spidermonkey/include/ios/jsclist.h", + "external/spidermonkey/include/ios/jscpucfg.h", + "external/spidermonkey/include/ios/jsfriendapi.h", + "external/spidermonkey/include/ios/jsperf.h", + "external/spidermonkey/include/ios/jsprf.h", + "external/spidermonkey/include/ios/jsprototypes.h", + "external/spidermonkey/include/ios/jsproxy.h", + "external/spidermonkey/include/ios/jspubtd.h", + "external/spidermonkey/include/ios/jstypes.h", + "external/spidermonkey/include/ios/jsversion.h", + "external/spidermonkey/include/ios/jswrapper.h", + "external/spidermonkey/include/ios/mozilla/Alignment.h", + "external/spidermonkey/include/ios/mozilla/AllocPolicy.h", + "external/spidermonkey/include/ios/mozilla/Array.h", + "external/spidermonkey/include/ios/mozilla/ArrayUtils.h", + "external/spidermonkey/include/ios/mozilla/Assertions.h", + "external/spidermonkey/include/ios/mozilla/Atomics.h", + "external/spidermonkey/include/ios/mozilla/Attributes.h", + "external/spidermonkey/include/ios/mozilla/BinarySearch.h", + "external/spidermonkey/include/ios/mozilla/BloomFilter.h", + "external/spidermonkey/include/ios/mozilla/Casting.h", + "external/spidermonkey/include/ios/mozilla/ChaosMode.h", + "external/spidermonkey/include/ios/mozilla/Char16.h", + "external/spidermonkey/include/ios/mozilla/CheckedInt.h", + "external/spidermonkey/include/ios/mozilla/Compiler.h", + "external/spidermonkey/include/ios/mozilla/Compression.h", + "external/spidermonkey/include/ios/mozilla/Constants.h", + "external/spidermonkey/include/ios/mozilla/DebugOnly.h", + "external/spidermonkey/include/ios/mozilla/Decimal.h", + "external/spidermonkey/include/ios/mozilla/Endian.h", + "external/spidermonkey/include/ios/mozilla/EnumSet.h", + "external/spidermonkey/include/ios/mozilla/EnumeratedArray.h", + "external/spidermonkey/include/ios/mozilla/FloatingPoint.h", + "external/spidermonkey/include/ios/mozilla/GuardObjects.h", + "external/spidermonkey/include/ios/mozilla/HashFunctions.h", + "external/spidermonkey/include/ios/mozilla/IntegerPrintfMacros.h", + "external/spidermonkey/include/ios/mozilla/IntegerTypeTraits.h", + "external/spidermonkey/include/ios/mozilla/Likely.h", + "external/spidermonkey/include/ios/mozilla/LinkedList.h", + "external/spidermonkey/include/ios/mozilla/MSIntTypes.h", + "external/spidermonkey/include/ios/mozilla/MacroArgs.h", + "external/spidermonkey/include/ios/mozilla/MacroForEach.h", + "external/spidermonkey/include/ios/mozilla/MathAlgorithms.h", + "external/spidermonkey/include/ios/mozilla/Maybe.h", + "external/spidermonkey/include/ios/mozilla/MaybeOneOf.h", + "external/spidermonkey/include/ios/mozilla/MemoryChecking.h", + "external/spidermonkey/include/ios/mozilla/MemoryReporting.h", + "external/spidermonkey/include/ios/mozilla/Move.h", + "external/spidermonkey/include/ios/mozilla/NullPtr.h", + "external/spidermonkey/include/ios/mozilla/NumericLimits.h", + "external/spidermonkey/include/ios/mozilla/Pair.h", + "external/spidermonkey/include/ios/mozilla/PodOperations.h", + "external/spidermonkey/include/ios/mozilla/Poison.h", + "external/spidermonkey/include/ios/mozilla/Range.h", + "external/spidermonkey/include/ios/mozilla/RangedPtr.h", + "external/spidermonkey/include/ios/mozilla/ReentrancyGuard.h", + "external/spidermonkey/include/ios/mozilla/RefCountType.h", + "external/spidermonkey/include/ios/mozilla/RefPtr.h", + "external/spidermonkey/include/ios/mozilla/RollingMean.h", + "external/spidermonkey/include/ios/mozilla/SHA1.h", + "external/spidermonkey/include/ios/mozilla/Scoped.h", + "external/spidermonkey/include/ios/mozilla/SplayTree.h", + "external/spidermonkey/include/ios/mozilla/TaggedAnonymousMemory.h", + "external/spidermonkey/include/ios/mozilla/TemplateLib.h", + "external/spidermonkey/include/ios/mozilla/ThreadLocal.h", + "external/spidermonkey/include/ios/mozilla/ToString.h", + "external/spidermonkey/include/ios/mozilla/TypeTraits.h", + "external/spidermonkey/include/ios/mozilla/TypedEnum.h", + "external/spidermonkey/include/ios/mozilla/TypedEnumBits.h", + "external/spidermonkey/include/ios/mozilla/TypedEnumInternal.h", + "external/spidermonkey/include/ios/mozilla/Types.h", + "external/spidermonkey/include/ios/mozilla/UniquePtr.h", + "external/spidermonkey/include/ios/mozilla/Vector.h", + "external/spidermonkey/include/ios/mozilla/WeakPtr.h", + "external/spidermonkey/include/linux/js-config.h", + "external/spidermonkey/include/linux/js.msg", + "external/spidermonkey/include/linux/js/Anchor.h", + "external/spidermonkey/include/linux/js/CallArgs.h", + "external/spidermonkey/include/linux/js/CallNonGenericMethod.h", + "external/spidermonkey/include/linux/js/CharacterEncoding.h", + "external/spidermonkey/include/linux/js/Class.h", + "external/spidermonkey/include/linux/js/Date.h", + "external/spidermonkey/include/linux/js/GCAPI.h", + "external/spidermonkey/include/linux/js/HashTable.h", + "external/spidermonkey/include/linux/js/HeapAPI.h", + "external/spidermonkey/include/linux/js/Id.h", + "external/spidermonkey/include/linux/js/LegacyIntTypes.h", + "external/spidermonkey/include/linux/js/MemoryMetrics.h", + "external/spidermonkey/include/linux/js/OldDebugAPI.h", + "external/spidermonkey/include/linux/js/Principals.h", + "external/spidermonkey/include/linux/js/ProfilingStack.h", + "external/spidermonkey/include/linux/js/PropertyKey.h", + "external/spidermonkey/include/linux/js/RequiredDefines.h", + "external/spidermonkey/include/linux/js/RootingAPI.h", + "external/spidermonkey/include/linux/js/SliceBudget.h", + "external/spidermonkey/include/linux/js/StructuredClone.h", + "external/spidermonkey/include/linux/js/TracingAPI.h", + "external/spidermonkey/include/linux/js/TypeDecls.h", + "external/spidermonkey/include/linux/js/UbiNode.h", + "external/spidermonkey/include/linux/js/UbiNodeTraverse.h", + "external/spidermonkey/include/linux/js/Utility.h", + "external/spidermonkey/include/linux/js/Value.h", + "external/spidermonkey/include/linux/js/Vector.h", + "external/spidermonkey/include/linux/js/WeakMapPtr.h", + "external/spidermonkey/include/linux/jsalloc.h", + "external/spidermonkey/include/linux/jsapi.h", + "external/spidermonkey/include/linux/jsbytecode.h", + "external/spidermonkey/include/linux/jsclist.h", + "external/spidermonkey/include/linux/jscpucfg.h", + "external/spidermonkey/include/linux/jsfriendapi.h", + "external/spidermonkey/include/linux/jsperf.h", + "external/spidermonkey/include/linux/jsprf.h", + "external/spidermonkey/include/linux/jsprototypes.h", + "external/spidermonkey/include/linux/jsproxy.h", + "external/spidermonkey/include/linux/jspubtd.h", + "external/spidermonkey/include/linux/jstypes.h", + "external/spidermonkey/include/linux/jsversion.h", + "external/spidermonkey/include/linux/jswrapper.h", + "external/spidermonkey/include/linux/mozilla/Alignment.h", + "external/spidermonkey/include/linux/mozilla/AllocPolicy.h", + "external/spidermonkey/include/linux/mozilla/Array.h", + "external/spidermonkey/include/linux/mozilla/ArrayUtils.h", + "external/spidermonkey/include/linux/mozilla/Assertions.h", + "external/spidermonkey/include/linux/mozilla/Atomics.h", + "external/spidermonkey/include/linux/mozilla/Attributes.h", + "external/spidermonkey/include/linux/mozilla/BinarySearch.h", + "external/spidermonkey/include/linux/mozilla/BloomFilter.h", + "external/spidermonkey/include/linux/mozilla/Casting.h", + "external/spidermonkey/include/linux/mozilla/ChaosMode.h", + "external/spidermonkey/include/linux/mozilla/Char16.h", + "external/spidermonkey/include/linux/mozilla/CheckedInt.h", + "external/spidermonkey/include/linux/mozilla/Compiler.h", + "external/spidermonkey/include/linux/mozilla/Compression.h", + "external/spidermonkey/include/linux/mozilla/Constants.h", + "external/spidermonkey/include/linux/mozilla/DebugOnly.h", + "external/spidermonkey/include/linux/mozilla/Decimal.h", + "external/spidermonkey/include/linux/mozilla/Endian.h", + "external/spidermonkey/include/linux/mozilla/EnumSet.h", + "external/spidermonkey/include/linux/mozilla/EnumeratedArray.h", + "external/spidermonkey/include/linux/mozilla/FloatingPoint.h", + "external/spidermonkey/include/linux/mozilla/GuardObjects.h", + "external/spidermonkey/include/linux/mozilla/HashFunctions.h", + "external/spidermonkey/include/linux/mozilla/IntegerPrintfMacros.h", + "external/spidermonkey/include/linux/mozilla/IntegerTypeTraits.h", + "external/spidermonkey/include/linux/mozilla/Likely.h", + "external/spidermonkey/include/linux/mozilla/LinkedList.h", + "external/spidermonkey/include/linux/mozilla/LinuxSignal.h", + "external/spidermonkey/include/linux/mozilla/MSIntTypes.h", + "external/spidermonkey/include/linux/mozilla/MacroArgs.h", + "external/spidermonkey/include/linux/mozilla/MacroForEach.h", + "external/spidermonkey/include/linux/mozilla/MathAlgorithms.h", + "external/spidermonkey/include/linux/mozilla/Maybe.h", + "external/spidermonkey/include/linux/mozilla/MaybeOneOf.h", + "external/spidermonkey/include/linux/mozilla/MemoryChecking.h", + "external/spidermonkey/include/linux/mozilla/MemoryReporting.h", + "external/spidermonkey/include/linux/mozilla/Move.h", + "external/spidermonkey/include/linux/mozilla/NullPtr.h", + "external/spidermonkey/include/linux/mozilla/NumericLimits.h", + "external/spidermonkey/include/linux/mozilla/Pair.h", + "external/spidermonkey/include/linux/mozilla/PodOperations.h", + "external/spidermonkey/include/linux/mozilla/Poison.h", + "external/spidermonkey/include/linux/mozilla/Range.h", + "external/spidermonkey/include/linux/mozilla/RangedPtr.h", + "external/spidermonkey/include/linux/mozilla/ReentrancyGuard.h", + "external/spidermonkey/include/linux/mozilla/RefCountType.h", + "external/spidermonkey/include/linux/mozilla/RefPtr.h", + "external/spidermonkey/include/linux/mozilla/RollingMean.h", + "external/spidermonkey/include/linux/mozilla/SHA1.h", + "external/spidermonkey/include/linux/mozilla/Scoped.h", + "external/spidermonkey/include/linux/mozilla/SplayTree.h", + "external/spidermonkey/include/linux/mozilla/TaggedAnonymousMemory.h", + "external/spidermonkey/include/linux/mozilla/TemplateLib.h", + "external/spidermonkey/include/linux/mozilla/ThreadLocal.h", + "external/spidermonkey/include/linux/mozilla/ToString.h", + "external/spidermonkey/include/linux/mozilla/TypeTraits.h", + "external/spidermonkey/include/linux/mozilla/TypedEnum.h", + "external/spidermonkey/include/linux/mozilla/TypedEnumBits.h", + "external/spidermonkey/include/linux/mozilla/TypedEnumInternal.h", + "external/spidermonkey/include/linux/mozilla/Types.h", + "external/spidermonkey/include/linux/mozilla/UniquePtr.h", + "external/spidermonkey/include/linux/mozilla/Vector.h", + "external/spidermonkey/include/linux/mozilla/WeakPtr.h", + "external/spidermonkey/include/mac/js-config.h", + "external/spidermonkey/include/mac/js.msg", + "external/spidermonkey/include/mac/js/Anchor.h", + "external/spidermonkey/include/mac/js/CallArgs.h", + "external/spidermonkey/include/mac/js/CallNonGenericMethod.h", + "external/spidermonkey/include/mac/js/CharacterEncoding.h", + "external/spidermonkey/include/mac/js/Class.h", + "external/spidermonkey/include/mac/js/Date.h", + "external/spidermonkey/include/mac/js/GCAPI.h", + "external/spidermonkey/include/mac/js/HashTable.h", + "external/spidermonkey/include/mac/js/HeapAPI.h", + "external/spidermonkey/include/mac/js/Id.h", + "external/spidermonkey/include/mac/js/LegacyIntTypes.h", + "external/spidermonkey/include/mac/js/MemoryMetrics.h", + "external/spidermonkey/include/mac/js/OldDebugAPI.h", + "external/spidermonkey/include/mac/js/Principals.h", + "external/spidermonkey/include/mac/js/ProfilingStack.h", + "external/spidermonkey/include/mac/js/PropertyKey.h", + "external/spidermonkey/include/mac/js/RequiredDefines.h", + "external/spidermonkey/include/mac/js/RootingAPI.h", + "external/spidermonkey/include/mac/js/SliceBudget.h", + "external/spidermonkey/include/mac/js/StructuredClone.h", + "external/spidermonkey/include/mac/js/TracingAPI.h", + "external/spidermonkey/include/mac/js/TypeDecls.h", + "external/spidermonkey/include/mac/js/UbiNode.h", + "external/spidermonkey/include/mac/js/UbiNodeTraverse.h", + "external/spidermonkey/include/mac/js/Utility.h", + "external/spidermonkey/include/mac/js/Value.h", + "external/spidermonkey/include/mac/js/Vector.h", + "external/spidermonkey/include/mac/js/WeakMapPtr.h", + "external/spidermonkey/include/mac/jsalloc.h", + "external/spidermonkey/include/mac/jsapi.h", + "external/spidermonkey/include/mac/jsbytecode.h", + "external/spidermonkey/include/mac/jsclist.h", + "external/spidermonkey/include/mac/jscpucfg.h", + "external/spidermonkey/include/mac/jsfriendapi.h", + "external/spidermonkey/include/mac/jsperf.h", + "external/spidermonkey/include/mac/jsprf.h", + "external/spidermonkey/include/mac/jsprototypes.h", + "external/spidermonkey/include/mac/jsproxy.h", + "external/spidermonkey/include/mac/jspubtd.h", + "external/spidermonkey/include/mac/jstypes.h", + "external/spidermonkey/include/mac/jsversion.h", + "external/spidermonkey/include/mac/jswrapper.h", + "external/spidermonkey/include/mac/mozilla/Alignment.h", + "external/spidermonkey/include/mac/mozilla/AllocPolicy.h", + "external/spidermonkey/include/mac/mozilla/Array.h", + "external/spidermonkey/include/mac/mozilla/ArrayUtils.h", + "external/spidermonkey/include/mac/mozilla/Assertions.h", + "external/spidermonkey/include/mac/mozilla/Atomics.h", + "external/spidermonkey/include/mac/mozilla/Attributes.h", + "external/spidermonkey/include/mac/mozilla/BinarySearch.h", + "external/spidermonkey/include/mac/mozilla/BloomFilter.h", + "external/spidermonkey/include/mac/mozilla/Casting.h", + "external/spidermonkey/include/mac/mozilla/ChaosMode.h", + "external/spidermonkey/include/mac/mozilla/Char16.h", + "external/spidermonkey/include/mac/mozilla/CheckedInt.h", + "external/spidermonkey/include/mac/mozilla/Compiler.h", + "external/spidermonkey/include/mac/mozilla/Compression.h", + "external/spidermonkey/include/mac/mozilla/Constants.h", + "external/spidermonkey/include/mac/mozilla/DebugOnly.h", + "external/spidermonkey/include/mac/mozilla/Decimal.h", + "external/spidermonkey/include/mac/mozilla/Endian.h", + "external/spidermonkey/include/mac/mozilla/EnumSet.h", + "external/spidermonkey/include/mac/mozilla/EnumeratedArray.h", + "external/spidermonkey/include/mac/mozilla/FloatingPoint.h", + "external/spidermonkey/include/mac/mozilla/GuardObjects.h", + "external/spidermonkey/include/mac/mozilla/HashFunctions.h", + "external/spidermonkey/include/mac/mozilla/IntegerPrintfMacros.h", + "external/spidermonkey/include/mac/mozilla/IntegerTypeTraits.h", + "external/spidermonkey/include/mac/mozilla/Likely.h", + "external/spidermonkey/include/mac/mozilla/LinkedList.h", + "external/spidermonkey/include/mac/mozilla/MSIntTypes.h", + "external/spidermonkey/include/mac/mozilla/MacroArgs.h", + "external/spidermonkey/include/mac/mozilla/MacroForEach.h", + "external/spidermonkey/include/mac/mozilla/MathAlgorithms.h", + "external/spidermonkey/include/mac/mozilla/Maybe.h", + "external/spidermonkey/include/mac/mozilla/MaybeOneOf.h", + "external/spidermonkey/include/mac/mozilla/MemoryChecking.h", + "external/spidermonkey/include/mac/mozilla/MemoryReporting.h", + "external/spidermonkey/include/mac/mozilla/Move.h", + "external/spidermonkey/include/mac/mozilla/NullPtr.h", + "external/spidermonkey/include/mac/mozilla/NumericLimits.h", + "external/spidermonkey/include/mac/mozilla/Pair.h", + "external/spidermonkey/include/mac/mozilla/PodOperations.h", + "external/spidermonkey/include/mac/mozilla/Poison.h", + "external/spidermonkey/include/mac/mozilla/Range.h", + "external/spidermonkey/include/mac/mozilla/RangedPtr.h", + "external/spidermonkey/include/mac/mozilla/ReentrancyGuard.h", + "external/spidermonkey/include/mac/mozilla/RefCountType.h", + "external/spidermonkey/include/mac/mozilla/RefPtr.h", + "external/spidermonkey/include/mac/mozilla/RollingMean.h", + "external/spidermonkey/include/mac/mozilla/SHA1.h", + "external/spidermonkey/include/mac/mozilla/Scoped.h", + "external/spidermonkey/include/mac/mozilla/SplayTree.h", + "external/spidermonkey/include/mac/mozilla/TaggedAnonymousMemory.h", + "external/spidermonkey/include/mac/mozilla/TemplateLib.h", + "external/spidermonkey/include/mac/mozilla/ThreadLocal.h", + "external/spidermonkey/include/mac/mozilla/ToString.h", + "external/spidermonkey/include/mac/mozilla/TypeTraits.h", + "external/spidermonkey/include/mac/mozilla/TypedEnum.h", + "external/spidermonkey/include/mac/mozilla/TypedEnumBits.h", + "external/spidermonkey/include/mac/mozilla/TypedEnumInternal.h", + "external/spidermonkey/include/mac/mozilla/Types.h", + "external/spidermonkey/include/mac/mozilla/UniquePtr.h", + "external/spidermonkey/include/mac/mozilla/Vector.h", + "external/spidermonkey/include/mac/mozilla/WeakPtr.h", + "external/spidermonkey/include/win32/js-config.h", + "external/spidermonkey/include/win32/js.msg", + "external/spidermonkey/include/win32/js/Anchor.h", + "external/spidermonkey/include/win32/js/CallArgs.h", + "external/spidermonkey/include/win32/js/CallNonGenericMethod.h", + "external/spidermonkey/include/win32/js/CharacterEncoding.h", + "external/spidermonkey/include/win32/js/Class.h", + "external/spidermonkey/include/win32/js/Date.h", + "external/spidermonkey/include/win32/js/GCAPI.h", + "external/spidermonkey/include/win32/js/HashTable.h", + "external/spidermonkey/include/win32/js/HeapAPI.h", + "external/spidermonkey/include/win32/js/Id.h", + "external/spidermonkey/include/win32/js/LegacyIntTypes.h", + "external/spidermonkey/include/win32/js/MemoryMetrics.h", + "external/spidermonkey/include/win32/js/OldDebugAPI.h", + "external/spidermonkey/include/win32/js/Principals.h", + "external/spidermonkey/include/win32/js/ProfilingStack.h", + "external/spidermonkey/include/win32/js/PropertyKey.h", + "external/spidermonkey/include/win32/js/RequiredDefines.h", + "external/spidermonkey/include/win32/js/RootingAPI.h", + "external/spidermonkey/include/win32/js/SliceBudget.h", + "external/spidermonkey/include/win32/js/StructuredClone.h", + "external/spidermonkey/include/win32/js/TracingAPI.h", + "external/spidermonkey/include/win32/js/TypeDecls.h", + "external/spidermonkey/include/win32/js/UbiNode.h", + "external/spidermonkey/include/win32/js/UbiNodeTraverse.h", + "external/spidermonkey/include/win32/js/Utility.h", + "external/spidermonkey/include/win32/js/Value.h", + "external/spidermonkey/include/win32/js/Vector.h", + "external/spidermonkey/include/win32/js/WeakMapPtr.h", + "external/spidermonkey/include/win32/jsalloc.h", + "external/spidermonkey/include/win32/jsapi.h", + "external/spidermonkey/include/win32/jsbytecode.h", + "external/spidermonkey/include/win32/jsclist.h", + "external/spidermonkey/include/win32/jscpucfg.h", + "external/spidermonkey/include/win32/jsfriendapi.h", + "external/spidermonkey/include/win32/jsperf.h", + "external/spidermonkey/include/win32/jsprf.h", + "external/spidermonkey/include/win32/jsprototypes.h", + "external/spidermonkey/include/win32/jsproxy.h", + "external/spidermonkey/include/win32/jspubtd.h", + "external/spidermonkey/include/win32/jstypes.h", + "external/spidermonkey/include/win32/jsversion.h", + "external/spidermonkey/include/win32/jswrapper.h", + "external/spidermonkey/include/win32/mozilla/Alignment.h", + "external/spidermonkey/include/win32/mozilla/AllocPolicy.h", + "external/spidermonkey/include/win32/mozilla/Array.h", + "external/spidermonkey/include/win32/mozilla/ArrayUtils.h", + "external/spidermonkey/include/win32/mozilla/Assertions.h", + "external/spidermonkey/include/win32/mozilla/Atomics.h", + "external/spidermonkey/include/win32/mozilla/Attributes.h", + "external/spidermonkey/include/win32/mozilla/BinarySearch.h", + "external/spidermonkey/include/win32/mozilla/BloomFilter.h", + "external/spidermonkey/include/win32/mozilla/Casting.h", + "external/spidermonkey/include/win32/mozilla/ChaosMode.h", + "external/spidermonkey/include/win32/mozilla/Char16.h", + "external/spidermonkey/include/win32/mozilla/CheckedInt.h", + "external/spidermonkey/include/win32/mozilla/Compiler.h", + "external/spidermonkey/include/win32/mozilla/Compression.h", + "external/spidermonkey/include/win32/mozilla/Constants.h", + "external/spidermonkey/include/win32/mozilla/DebugOnly.h", + "external/spidermonkey/include/win32/mozilla/Decimal.h", + "external/spidermonkey/include/win32/mozilla/Endian.h", + "external/spidermonkey/include/win32/mozilla/EnumSet.h", + "external/spidermonkey/include/win32/mozilla/EnumeratedArray.h", + "external/spidermonkey/include/win32/mozilla/FloatingPoint.h", + "external/spidermonkey/include/win32/mozilla/GuardObjects.h", + "external/spidermonkey/include/win32/mozilla/HashFunctions.h", + "external/spidermonkey/include/win32/mozilla/IntegerPrintfMacros.h", + "external/spidermonkey/include/win32/mozilla/IntegerTypeTraits.h", + "external/spidermonkey/include/win32/mozilla/Likely.h", + "external/spidermonkey/include/win32/mozilla/LinkedList.h", + "external/spidermonkey/include/win32/mozilla/MSIntTypes.h", + "external/spidermonkey/include/win32/mozilla/MacroArgs.h", + "external/spidermonkey/include/win32/mozilla/MacroForEach.h", + "external/spidermonkey/include/win32/mozilla/MathAlgorithms.h", + "external/spidermonkey/include/win32/mozilla/Maybe.h", + "external/spidermonkey/include/win32/mozilla/MaybeOneOf.h", + "external/spidermonkey/include/win32/mozilla/MemoryChecking.h", + "external/spidermonkey/include/win32/mozilla/MemoryReporting.h", + "external/spidermonkey/include/win32/mozilla/Move.h", + "external/spidermonkey/include/win32/mozilla/NullPtr.h", + "external/spidermonkey/include/win32/mozilla/NumericLimits.h", + "external/spidermonkey/include/win32/mozilla/Pair.h", + "external/spidermonkey/include/win32/mozilla/PodOperations.h", + "external/spidermonkey/include/win32/mozilla/Poison.h", + "external/spidermonkey/include/win32/mozilla/Range.h", + "external/spidermonkey/include/win32/mozilla/RangedPtr.h", + "external/spidermonkey/include/win32/mozilla/ReentrancyGuard.h", + "external/spidermonkey/include/win32/mozilla/RefCountType.h", + "external/spidermonkey/include/win32/mozilla/RefPtr.h", + "external/spidermonkey/include/win32/mozilla/RollingMean.h", + "external/spidermonkey/include/win32/mozilla/SHA1.h", + "external/spidermonkey/include/win32/mozilla/Scoped.h", + "external/spidermonkey/include/win32/mozilla/SplayTree.h", + "external/spidermonkey/include/win32/mozilla/TaggedAnonymousMemory.h", + "external/spidermonkey/include/win32/mozilla/TemplateLib.h", + "external/spidermonkey/include/win32/mozilla/ThreadLocal.h", + "external/spidermonkey/include/win32/mozilla/ToString.h", + "external/spidermonkey/include/win32/mozilla/TypeTraits.h", + "external/spidermonkey/include/win32/mozilla/TypedEnum.h", + "external/spidermonkey/include/win32/mozilla/TypedEnumBits.h", + "external/spidermonkey/include/win32/mozilla/TypedEnumInternal.h", + "external/spidermonkey/include/win32/mozilla/Types.h", + "external/spidermonkey/include/win32/mozilla/UniquePtr.h", + "external/spidermonkey/include/win32/mozilla/Vector.h", + "external/spidermonkey/include/win32/mozilla/WeakPtr.h", + "external/spidermonkey/include/win32/mozilla/WindowsVersion.h", + "external/spidermonkey/include/win32/mozzconf.h", + "external/spidermonkey/include/win32/zconf.h", + "external/spidermonkey/include/win32/zlib.h", + "external/spidermonkey/include/winrt_8.1/js-config.h", + "external/spidermonkey/include/winrt_8.1/js.msg", + "external/spidermonkey/include/winrt_8.1/js/Anchor.h", + "external/spidermonkey/include/winrt_8.1/js/CallArgs.h", + "external/spidermonkey/include/winrt_8.1/js/CallNonGenericMethod.h", + "external/spidermonkey/include/winrt_8.1/js/CharacterEncoding.h", + "external/spidermonkey/include/winrt_8.1/js/Class.h", + "external/spidermonkey/include/winrt_8.1/js/Date.h", + "external/spidermonkey/include/winrt_8.1/js/GCAPI.h", + "external/spidermonkey/include/winrt_8.1/js/HashTable.h", + "external/spidermonkey/include/winrt_8.1/js/HeapAPI.h", + "external/spidermonkey/include/winrt_8.1/js/Id.h", + "external/spidermonkey/include/winrt_8.1/js/LegacyIntTypes.h", + "external/spidermonkey/include/winrt_8.1/js/MemoryMetrics.h", + "external/spidermonkey/include/winrt_8.1/js/OldDebugAPI.h", + "external/spidermonkey/include/winrt_8.1/js/Principals.h", + "external/spidermonkey/include/winrt_8.1/js/ProfilingStack.h", + "external/spidermonkey/include/winrt_8.1/js/PropertyKey.h", + "external/spidermonkey/include/winrt_8.1/js/RequiredDefines.h", + "external/spidermonkey/include/winrt_8.1/js/RootingAPI.h", + "external/spidermonkey/include/winrt_8.1/js/SliceBudget.h", + "external/spidermonkey/include/winrt_8.1/js/StructuredClone.h", + "external/spidermonkey/include/winrt_8.1/js/TracingAPI.h", + "external/spidermonkey/include/winrt_8.1/js/TypeDecls.h", + "external/spidermonkey/include/winrt_8.1/js/Utility.h", + "external/spidermonkey/include/winrt_8.1/js/Value.h", + "external/spidermonkey/include/winrt_8.1/js/Vector.h", + "external/spidermonkey/include/winrt_8.1/jsalloc.h", + "external/spidermonkey/include/winrt_8.1/jsapi.h", + "external/spidermonkey/include/winrt_8.1/jsbytecode.h", + "external/spidermonkey/include/winrt_8.1/jsclist.h", + "external/spidermonkey/include/winrt_8.1/jscpucfg.h", + "external/spidermonkey/include/winrt_8.1/jsfriendapi.h", + "external/spidermonkey/include/winrt_8.1/jsprf.h", + "external/spidermonkey/include/winrt_8.1/jsprototypes.h", + "external/spidermonkey/include/winrt_8.1/jsproxy.h", + "external/spidermonkey/include/winrt_8.1/jspubtd.h", + "external/spidermonkey/include/winrt_8.1/jstypes.h", + "external/spidermonkey/include/winrt_8.1/jsversion.h", + "external/spidermonkey/include/winrt_8.1/jswrapper.h", + "external/spidermonkey/include/winrt_8.1/mozilla/Alignment.h", + "external/spidermonkey/include/winrt_8.1/mozilla/AllocPolicy.h", + "external/spidermonkey/include/winrt_8.1/mozilla/Array.h", + "external/spidermonkey/include/winrt_8.1/mozilla/ArrayUtils.h", + "external/spidermonkey/include/winrt_8.1/mozilla/Assertions.h", + "external/spidermonkey/include/winrt_8.1/mozilla/Atomics.h", + "external/spidermonkey/include/winrt_8.1/mozilla/Attributes.h", + "external/spidermonkey/include/winrt_8.1/mozilla/BloomFilter.h", + "external/spidermonkey/include/winrt_8.1/mozilla/Casting.h", + "external/spidermonkey/include/winrt_8.1/mozilla/Char16.h", + "external/spidermonkey/include/winrt_8.1/mozilla/CheckedInt.h", + "external/spidermonkey/include/winrt_8.1/mozilla/Compiler.h", + "external/spidermonkey/include/winrt_8.1/mozilla/Compression.h", + "external/spidermonkey/include/winrt_8.1/mozilla/Constants.h", + "external/spidermonkey/include/winrt_8.1/mozilla/DebugOnly.h", + "external/spidermonkey/include/winrt_8.1/mozilla/Endian.h", + "external/spidermonkey/include/winrt_8.1/mozilla/EnumSet.h", + "external/spidermonkey/include/winrt_8.1/mozilla/FloatingPoint.h", + "external/spidermonkey/include/winrt_8.1/mozilla/GuardObjects.h", + "external/spidermonkey/include/winrt_8.1/mozilla/HashFunctions.h", + "external/spidermonkey/include/winrt_8.1/mozilla/IntegerPrintfMacros.h", + "external/spidermonkey/include/winrt_8.1/mozilla/Likely.h", + "external/spidermonkey/include/winrt_8.1/mozilla/LinkedList.h", + "external/spidermonkey/include/winrt_8.1/mozilla/MSIntTypes.h", + "external/spidermonkey/include/winrt_8.1/mozilla/MacroArgs.h", + "external/spidermonkey/include/winrt_8.1/mozilla/MathAlgorithms.h", + "external/spidermonkey/include/winrt_8.1/mozilla/Maybe.h", + "external/spidermonkey/include/winrt_8.1/mozilla/MemoryChecking.h", + "external/spidermonkey/include/winrt_8.1/mozilla/MemoryReporting.h", + "external/spidermonkey/include/winrt_8.1/mozilla/Move.h", + "external/spidermonkey/include/winrt_8.1/mozilla/NullPtr.h", + "external/spidermonkey/include/winrt_8.1/mozilla/NumericLimits.h", + "external/spidermonkey/include/winrt_8.1/mozilla/Pair.h", + "external/spidermonkey/include/winrt_8.1/mozilla/PodOperations.h", + "external/spidermonkey/include/winrt_8.1/mozilla/Poison.h", + "external/spidermonkey/include/winrt_8.1/mozilla/Range.h", + "external/spidermonkey/include/winrt_8.1/mozilla/RangedPtr.h", + "external/spidermonkey/include/winrt_8.1/mozilla/ReentrancyGuard.h", + "external/spidermonkey/include/winrt_8.1/mozilla/RefPtr.h", + "external/spidermonkey/include/winrt_8.1/mozilla/RollingMean.h", + "external/spidermonkey/include/winrt_8.1/mozilla/SHA1.h", + "external/spidermonkey/include/winrt_8.1/mozilla/Scoped.h", + "external/spidermonkey/include/winrt_8.1/mozilla/SplayTree.h", + "external/spidermonkey/include/winrt_8.1/mozilla/TemplateLib.h", + "external/spidermonkey/include/winrt_8.1/mozilla/ThreadLocal.h", + "external/spidermonkey/include/winrt_8.1/mozilla/TypeTraits.h", + "external/spidermonkey/include/winrt_8.1/mozilla/TypedEnum.h", + "external/spidermonkey/include/winrt_8.1/mozilla/TypedEnumInternal.h", + "external/spidermonkey/include/winrt_8.1/mozilla/Types.h", + "external/spidermonkey/include/winrt_8.1/mozilla/UniquePtr.h", + "external/spidermonkey/include/winrt_8.1/mozilla/Vector.h", + "external/spidermonkey/include/winrt_8.1/mozilla/WeakPtr.h", + "external/spidermonkey/include/wp_8.1/js-config.h", + "external/spidermonkey/include/wp_8.1/js.msg", + "external/spidermonkey/include/wp_8.1/js/Anchor.h", + "external/spidermonkey/include/wp_8.1/js/CallArgs.h", + "external/spidermonkey/include/wp_8.1/js/CallNonGenericMethod.h", + "external/spidermonkey/include/wp_8.1/js/CharacterEncoding.h", + "external/spidermonkey/include/wp_8.1/js/Class.h", + "external/spidermonkey/include/wp_8.1/js/Date.h", + "external/spidermonkey/include/wp_8.1/js/GCAPI.h", + "external/spidermonkey/include/wp_8.1/js/HashTable.h", + "external/spidermonkey/include/wp_8.1/js/HeapAPI.h", + "external/spidermonkey/include/wp_8.1/js/Id.h", + "external/spidermonkey/include/wp_8.1/js/LegacyIntTypes.h", + "external/spidermonkey/include/wp_8.1/js/MemoryMetrics.h", + "external/spidermonkey/include/wp_8.1/js/OldDebugAPI.h", + "external/spidermonkey/include/wp_8.1/js/Principals.h", + "external/spidermonkey/include/wp_8.1/js/ProfilingStack.h", + "external/spidermonkey/include/wp_8.1/js/PropertyKey.h", + "external/spidermonkey/include/wp_8.1/js/RequiredDefines.h", + "external/spidermonkey/include/wp_8.1/js/RootingAPI.h", + "external/spidermonkey/include/wp_8.1/js/SliceBudget.h", + "external/spidermonkey/include/wp_8.1/js/StructuredClone.h", + "external/spidermonkey/include/wp_8.1/js/TracingAPI.h", + "external/spidermonkey/include/wp_8.1/js/TypeDecls.h", + "external/spidermonkey/include/wp_8.1/js/Utility.h", + "external/spidermonkey/include/wp_8.1/js/Value.h", + "external/spidermonkey/include/wp_8.1/js/Vector.h", + "external/spidermonkey/include/wp_8.1/jsalloc.h", + "external/spidermonkey/include/wp_8.1/jsapi.h", + "external/spidermonkey/include/wp_8.1/jsbytecode.h", + "external/spidermonkey/include/wp_8.1/jsclist.h", + "external/spidermonkey/include/wp_8.1/jscpucfg.h", + "external/spidermonkey/include/wp_8.1/jsfriendapi.h", + "external/spidermonkey/include/wp_8.1/jsprf.h", + "external/spidermonkey/include/wp_8.1/jsprototypes.h", + "external/spidermonkey/include/wp_8.1/jsproxy.h", + "external/spidermonkey/include/wp_8.1/jspubtd.h", + "external/spidermonkey/include/wp_8.1/jstypes.h", + "external/spidermonkey/include/wp_8.1/jsversion.h", + "external/spidermonkey/include/wp_8.1/jswrapper.h", + "external/spidermonkey/include/wp_8.1/mozilla/Alignment.h", + "external/spidermonkey/include/wp_8.1/mozilla/AllocPolicy.h", + "external/spidermonkey/include/wp_8.1/mozilla/Array.h", + "external/spidermonkey/include/wp_8.1/mozilla/ArrayUtils.h", + "external/spidermonkey/include/wp_8.1/mozilla/Assertions.h", + "external/spidermonkey/include/wp_8.1/mozilla/Atomics.h", + "external/spidermonkey/include/wp_8.1/mozilla/Attributes.h", + "external/spidermonkey/include/wp_8.1/mozilla/BloomFilter.h", + "external/spidermonkey/include/wp_8.1/mozilla/Casting.h", + "external/spidermonkey/include/wp_8.1/mozilla/Char16.h", + "external/spidermonkey/include/wp_8.1/mozilla/CheckedInt.h", + "external/spidermonkey/include/wp_8.1/mozilla/Compiler.h", + "external/spidermonkey/include/wp_8.1/mozilla/Compression.h", + "external/spidermonkey/include/wp_8.1/mozilla/Constants.h", + "external/spidermonkey/include/wp_8.1/mozilla/DebugOnly.h", + "external/spidermonkey/include/wp_8.1/mozilla/Endian.h", + "external/spidermonkey/include/wp_8.1/mozilla/EnumSet.h", + "external/spidermonkey/include/wp_8.1/mozilla/FloatingPoint.h", + "external/spidermonkey/include/wp_8.1/mozilla/GuardObjects.h", + "external/spidermonkey/include/wp_8.1/mozilla/HashFunctions.h", + "external/spidermonkey/include/wp_8.1/mozilla/IntegerPrintfMacros.h", + "external/spidermonkey/include/wp_8.1/mozilla/Likely.h", + "external/spidermonkey/include/wp_8.1/mozilla/LinkedList.h", + "external/spidermonkey/include/wp_8.1/mozilla/MSIntTypes.h", + "external/spidermonkey/include/wp_8.1/mozilla/MacroArgs.h", + "external/spidermonkey/include/wp_8.1/mozilla/MathAlgorithms.h", + "external/spidermonkey/include/wp_8.1/mozilla/Maybe.h", + "external/spidermonkey/include/wp_8.1/mozilla/MemoryChecking.h", + "external/spidermonkey/include/wp_8.1/mozilla/MemoryReporting.h", + "external/spidermonkey/include/wp_8.1/mozilla/Move.h", + "external/spidermonkey/include/wp_8.1/mozilla/NullPtr.h", + "external/spidermonkey/include/wp_8.1/mozilla/NumericLimits.h", + "external/spidermonkey/include/wp_8.1/mozilla/Pair.h", + "external/spidermonkey/include/wp_8.1/mozilla/PodOperations.h", + "external/spidermonkey/include/wp_8.1/mozilla/Poison.h", + "external/spidermonkey/include/wp_8.1/mozilla/Range.h", + "external/spidermonkey/include/wp_8.1/mozilla/RangedPtr.h", + "external/spidermonkey/include/wp_8.1/mozilla/ReentrancyGuard.h", + "external/spidermonkey/include/wp_8.1/mozilla/RefPtr.h", + "external/spidermonkey/include/wp_8.1/mozilla/RollingMean.h", + "external/spidermonkey/include/wp_8.1/mozilla/SHA1.h", + "external/spidermonkey/include/wp_8.1/mozilla/Scoped.h", + "external/spidermonkey/include/wp_8.1/mozilla/SplayTree.h", + "external/spidermonkey/include/wp_8.1/mozilla/TemplateLib.h", + "external/spidermonkey/include/wp_8.1/mozilla/ThreadLocal.h", + "external/spidermonkey/include/wp_8.1/mozilla/TypeTraits.h", + "external/spidermonkey/include/wp_8.1/mozilla/TypedEnum.h", + "external/spidermonkey/include/wp_8.1/mozilla/TypedEnumInternal.h", + "external/spidermonkey/include/wp_8.1/mozilla/Types.h", + "external/spidermonkey/include/wp_8.1/mozilla/UniquePtr.h", + "external/spidermonkey/include/wp_8.1/mozilla/Vector.h", + "external/spidermonkey/include/wp_8.1/mozilla/WeakPtr.h", + "external/spidermonkey/prebuilt/android/Android.mk", + "external/spidermonkey/prebuilt/android/armeabi-v7a/libjs_static.a", + "external/spidermonkey/prebuilt/android/armeabi/libjs_static.a", + "external/spidermonkey/prebuilt/android/x86/libjs_static.a", + "external/spidermonkey/prebuilt/ios/libjs_static.a", + "external/spidermonkey/prebuilt/linux/32-bit/libjs_static.a", + "external/spidermonkey/prebuilt/linux/64-bit/libjs_static.a", + "external/spidermonkey/prebuilt/mac/libjs_static.a", + "external/spidermonkey/prebuilt/win32/debug-build/mozjs-33.dll", + "external/spidermonkey/prebuilt/win32/debug-build/mozjs-33.lib", + "external/spidermonkey/prebuilt/win32/release-build/mozjs-33.dll", + "external/spidermonkey/prebuilt/win32/release-build/mozjs-33.lib", + "external/spidermonkey/prebuilt/winrt_8.1/arm/mozjs-33.dll", + "external/spidermonkey/prebuilt/winrt_8.1/arm/mozjs-33.lib", + "external/spidermonkey/prebuilt/winrt_8.1/win32/mozjs-33.dll", + "external/spidermonkey/prebuilt/winrt_8.1/win32/mozjs-33.lib", + "external/spidermonkey/prebuilt/wp_8.1/arm/mozjs-33.dll", + "external/spidermonkey/prebuilt/wp_8.1/arm/mozjs-33.lib", + "external/spidermonkey/prebuilt/wp_8.1/win32/mozjs-33.dll", + "external/spidermonkey/prebuilt/wp_8.1/win32/mozjs-33.lib", + "tools/tojs/README.mdown", + "tools/tojs/cocos2dx.ini", + "tools/tojs/cocos2dx_3d.ini", + "tools/tojs/cocos2dx_3d_ext.ini", + "tools/tojs/cocos2dx_builder.ini", + "tools/tojs/cocos2dx_extension.ini", + "tools/tojs/cocos2dx_spine.ini", + "tools/tojs/cocos2dx_studio.ini", + "tools/tojs/cocos2dx_ui.ini", + "tools/tojs/genbindings.py", + "tools/tojs/userconf.ini", + "web/AUTHORS.txt", + "web/Base64Images.js", + "web/CCBoot.js", + "web/CCDebugger.js", + "web/CHANGELOG.txt", + "web/README.mdown", + "web/bower.json", + "web/cocos2d/actions/CCAction.js", + "web/cocos2d/actions/CCActionCamera.js", + "web/cocos2d/actions/CCActionCatmullRom.js", + "web/cocos2d/actions/CCActionEase.js", + "web/cocos2d/actions/CCActionInstant.js", + "web/cocos2d/actions/CCActionInterval.js", + "web/cocos2d/actions/CCActionTween.js", + "web/cocos2d/actions3d/CCActionGrid.js", + "web/cocos2d/actions3d/CCActionGrid3D.js", + "web/cocos2d/actions3d/CCActionPageTurn3D.js", + "web/cocos2d/actions3d/CCActionTiledGrid.js", + "web/cocos2d/audio/CCAudio.js", + "web/cocos2d/clipping-nodes/CCClippingNode.js", + "web/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js", + "web/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js", + "web/cocos2d/compression/ZipUtils.js", + "web/cocos2d/compression/base64.js", + "web/cocos2d/compression/gzip.js", + "web/cocos2d/compression/zlib.min.js", + "web/cocos2d/core/CCActionManager.js", + "web/cocos2d/core/CCCamera.js", + "web/cocos2d/core/CCConfiguration.js", + "web/cocos2d/core/CCDirector.js", + "web/cocos2d/core/CCDirectorWebGL.js", + "web/cocos2d/core/CCDrawingPrimitivesCanvas.js", + "web/cocos2d/core/CCDrawingPrimitivesWebGL.js", + "web/cocos2d/core/CCScheduler.js", + "web/cocos2d/core/base-nodes/BaseNodesPropertyDefine.js", + "web/cocos2d/core/base-nodes/CCAtlasNode.js", + "web/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js", + "web/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js", + "web/cocos2d/core/base-nodes/CCNode.js", + "web/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js", + "web/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js", + "web/cocos2d/core/cocoa/CCAffineTransform.js", + "web/cocos2d/core/cocoa/CCGeometry.js", + "web/cocos2d/core/cocos2d_externs.js", + "web/cocos2d/core/event-manager/CCEvent.js", + "web/cocos2d/core/event-manager/CCEventExtension.js", + "web/cocos2d/core/event-manager/CCEventListener.js", + "web/cocos2d/core/event-manager/CCEventManager.js", + "web/cocos2d/core/event-manager/CCTouch.js", + "web/cocos2d/core/labelttf/CCLabelTTF.js", + "web/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js", + "web/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js", + "web/cocos2d/core/labelttf/LabelTTFPropertyDefine.js", + "web/cocos2d/core/layers/CCLayer.js", + "web/cocos2d/core/layers/CCLayerCanvasRenderCmd.js", + "web/cocos2d/core/layers/CCLayerWebGLRenderCmd.js", + "web/cocos2d/core/platform/CCClass.js", + "web/cocos2d/core/platform/CCCommon.js", + "web/cocos2d/core/platform/CCConfig.js", + "web/cocos2d/core/platform/CCEGLView.js", + "web/cocos2d/core/platform/CCInputExtension.js", + "web/cocos2d/core/platform/CCInputManager.js", + "web/cocos2d/core/platform/CCLoaders.js", + "web/cocos2d/core/platform/CCMacro.js", + "web/cocos2d/core/platform/CCSAXParser.js", + "web/cocos2d/core/platform/CCScreen.js", + "web/cocos2d/core/platform/CCTypes.js", + "web/cocos2d/core/platform/CCTypesPropertyDefine.js", + "web/cocos2d/core/platform/CCTypesWebGL.js", + "web/cocos2d/core/platform/CCVisibleRect.js", + "web/cocos2d/core/platform/miniFramework.js", + "web/cocos2d/core/renderer/RendererCanvas.js", + "web/cocos2d/core/renderer/RendererWebGL.js", + "web/cocos2d/core/scenes/CCLoaderScene.js", + "web/cocos2d/core/scenes/CCScene.js", + "web/cocos2d/core/sprites/CCAnimation.js", + "web/cocos2d/core/sprites/CCAnimationCache.js", + "web/cocos2d/core/sprites/CCBakeSprite.js", + "web/cocos2d/core/sprites/CCSprite.js", + "web/cocos2d/core/sprites/CCSpriteBatchNode.js", + "web/cocos2d/core/sprites/CCSpriteBatchNodeCanvasRenderCmd.js", + "web/cocos2d/core/sprites/CCSpriteBatchNodeWebGLRenderCmd.js", + "web/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js", + "web/cocos2d/core/sprites/CCSpriteFrame.js", + "web/cocos2d/core/sprites/CCSpriteFrameCache.js", + "web/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js", + "web/cocos2d/core/sprites/SpritesPropertyDefine.js", + "web/cocos2d/core/support/CCPointExtension.js", + "web/cocos2d/core/support/CCVertex.js", + "web/cocos2d/core/support/TransformUtils.js", + "web/cocos2d/core/textures/CCTexture2D.js", + "web/cocos2d/core/textures/CCTextureAtlas.js", + "web/cocos2d/core/textures/CCTextureCache.js", + "web/cocos2d/core/textures/TexturesPropertyDefine.js", + "web/cocos2d/core/textures/TexturesWebGL.js", + "web/cocos2d/core/utils/BinaryLoader.js", + "web/cocos2d/effects/CCGrabber.js", + "web/cocos2d/effects/CCGrid.js", + "web/cocos2d/kazmath/aabb.js", + "web/cocos2d/kazmath/gl/mat4stack.js", + "web/cocos2d/kazmath/gl/matrix.js", + "web/cocos2d/kazmath/mat3.js", + "web/cocos2d/kazmath/mat4.js", + "web/cocos2d/kazmath/plane.js", + "web/cocos2d/kazmath/quaternion.js", + "web/cocos2d/kazmath/ray2.js", + "web/cocos2d/kazmath/utility.js", + "web/cocos2d/kazmath/vec2.js", + "web/cocos2d/kazmath/vec3.js", + "web/cocos2d/kazmath/vec4.js", + "web/cocos2d/labels/CCLabelAtlas.js", + "web/cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js", + "web/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js", + "web/cocos2d/labels/CCLabelBMFont.js", + "web/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js", + "web/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js", + "web/cocos2d/menus/CCMenu.js", + "web/cocos2d/menus/CCMenuItem.js", + "web/cocos2d/motion-streak/CCMotionStreak.js", + "web/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js", + "web/cocos2d/node-grid/CCNodeGrid.js", + "web/cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js", + "web/cocos2d/parallax/CCParallaxNode.js", + "web/cocos2d/parallax/CCParallaxNodeRenderCmd.js", + "web/cocos2d/particle/CCPNGReader.js", + "web/cocos2d/particle/CCParticleBatchNode.js", + "web/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js", + "web/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js", + "web/cocos2d/particle/CCParticleExamples.js", + "web/cocos2d/particle/CCParticleSystem.js", + "web/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js", + "web/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js", + "web/cocos2d/particle/CCTIFFReader.js", + "web/cocos2d/physics/CCPhysicsDebugNode.js", + "web/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js", + "web/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js", + "web/cocos2d/physics/CCPhysicsSprite.js", + "web/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js", + "web/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js", + "web/cocos2d/progress-timer/CCActionProgressTimer.js", + "web/cocos2d/progress-timer/CCProgressTimer.js", + "web/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js", + "web/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js", + "web/cocos2d/render-texture/CCRenderTexture.js", + "web/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js", + "web/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js", + "web/cocos2d/shaders/CCGLProgram.js", + "web/cocos2d/shaders/CCGLStateCache.js", + "web/cocos2d/shaders/CCShaderCache.js", + "web/cocos2d/shaders/CCShaders.js", + "web/cocos2d/shape-nodes/CCDrawNode.js", + "web/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js", + "web/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js", + "web/cocos2d/text-input/CCIMEDispatcher.js", + "web/cocos2d/text-input/CCTextFieldTTF.js", + "web/cocos2d/tilemap/CCTGAlib.js", + "web/cocos2d/tilemap/CCTMXLayer.js", + "web/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js", + "web/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js", + "web/cocos2d/tilemap/CCTMXObjectGroup.js", + "web/cocos2d/tilemap/CCTMXTiledMap.js", + "web/cocos2d/tilemap/CCTMXXMLParser.js", + "web/cocos2d/transitions/CCTransition.js", + "web/cocos2d/transitions/CCTransitionPageTurn.js", + "web/cocos2d/transitions/CCTransitionProgress.js", + "web/extensions/ccb-reader/CCBAnimationManager.js", + "web/extensions/ccb-reader/CCBKeyframe.js", + "web/extensions/ccb-reader/CCBReader.js", + "web/extensions/ccb-reader/CCBReaderUtil.js", + "web/extensions/ccb-reader/CCBRelativePositioning.js", + "web/extensions/ccb-reader/CCBSequence.js", + "web/extensions/ccb-reader/CCBValue.js", + "web/extensions/ccb-reader/CCControlLoader.js", + "web/extensions/ccb-reader/CCNodeLoader.js", + "web/extensions/ccb-reader/CCNodeLoaderLibrary.js", + "web/extensions/ccb-reader/CCSpriteLoader.js", + "web/extensions/ccpool/CCPool.js", + "web/extensions/ccui/base-classes/CCProtectedNode.js", + "web/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js", + "web/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js", + "web/extensions/ccui/base-classes/UIScale9Sprite.js", + "web/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js", + "web/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js", + "web/extensions/ccui/base-classes/UIWidget.js", + "web/extensions/ccui/base-classes/UIWidgetRenderCmd.js", + "web/extensions/ccui/layouts/UIHBox.js", + "web/extensions/ccui/layouts/UILayout.js", + "web/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js", + "web/extensions/ccui/layouts/UILayoutComponent.js", + "web/extensions/ccui/layouts/UILayoutManager.js", + "web/extensions/ccui/layouts/UILayoutParameter.js", + "web/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js", + "web/extensions/ccui/layouts/UIRelativeBox.js", + "web/extensions/ccui/layouts/UIVBox.js", + "web/extensions/ccui/system/CocosGUI.js", + "web/extensions/ccui/system/UIHelper.js", + "web/extensions/ccui/uiwidgets/UIButton.js", + "web/extensions/ccui/uiwidgets/UICheckBox.js", + "web/extensions/ccui/uiwidgets/UIImageView.js", + "web/extensions/ccui/uiwidgets/UILoadingBar.js", + "web/extensions/ccui/uiwidgets/UIRichText.js", + "web/extensions/ccui/uiwidgets/UISlider.js", + "web/extensions/ccui/uiwidgets/UIText.js", + "web/extensions/ccui/uiwidgets/UITextAtlas.js", + "web/extensions/ccui/uiwidgets/UITextBMFont.js", + "web/extensions/ccui/uiwidgets/UITextField.js", + "web/extensions/ccui/uiwidgets/scroll-widget/UIListView.js", + "web/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js", + "web/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js", + "web/extensions/cocostudio/CocoStudio.js", + "web/extensions/cocostudio/action/CCActionFrame.js", + "web/extensions/cocostudio/action/CCActionManager.js", + "web/extensions/cocostudio/action/CCActionNode.js", + "web/extensions/cocostudio/action/CCActionObject.js", + "web/extensions/cocostudio/armature/CCArmature.js", + "web/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js", + "web/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js", + "web/extensions/cocostudio/armature/CCBone.js", + "web/extensions/cocostudio/armature/animation/CCArmatureAnimation.js", + "web/extensions/cocostudio/armature/animation/CCProcessBase.js", + "web/extensions/cocostudio/armature/animation/CCTween.js", + "web/extensions/cocostudio/armature/datas/CCDatas.js", + "web/extensions/cocostudio/armature/display/CCBatchNode.js", + "web/extensions/cocostudio/armature/display/CCDecorativeDisplay.js", + "web/extensions/cocostudio/armature/display/CCDisplayFactory.js", + "web/extensions/cocostudio/armature/display/CCDisplayManager.js", + "web/extensions/cocostudio/armature/display/CCSkin.js", + "web/extensions/cocostudio/armature/display/CCSkinCanvasRenderCmd.js", + "web/extensions/cocostudio/armature/display/CCSkinWebGLRenderCmd.js", + "web/extensions/cocostudio/armature/physics/CCColliderDetector.js", + "web/extensions/cocostudio/armature/utils/CCArmatureDataManager.js", + "web/extensions/cocostudio/armature/utils/CCArmatureDefine.js", + "web/extensions/cocostudio/armature/utils/CCDataReaderHelper.js", + "web/extensions/cocostudio/armature/utils/CCSpriteFrameCacheHelper.js", + "web/extensions/cocostudio/armature/utils/CCTransformHelp.js", + "web/extensions/cocostudio/armature/utils/CCTweenFunction.js", + "web/extensions/cocostudio/armature/utils/CCUtilMath.js", + "web/extensions/cocostudio/components/CCComAttribute.js", + "web/extensions/cocostudio/components/CCComAudio.js", + "web/extensions/cocostudio/components/CCComController.js", + "web/extensions/cocostudio/components/CCComRender.js", + "web/extensions/cocostudio/components/CCComponent.js", + "web/extensions/cocostudio/components/CCComponentContainer.js", + "web/extensions/cocostudio/loader/load.js", + "web/extensions/cocostudio/loader/parsers/action-1.x.js", + "web/extensions/cocostudio/loader/parsers/action-2.x.js", + "web/extensions/cocostudio/loader/parsers/compatible.js", + "web/extensions/cocostudio/loader/parsers/scene-1.x.js", + "web/extensions/cocostudio/loader/parsers/timelineParser-1.x.js", + "web/extensions/cocostudio/loader/parsers/timelineParser-2.x.js", + "web/extensions/cocostudio/loader/parsers/uiParser-1.x.js", + "web/extensions/cocostudio/timeline/ActionTimeline.js", + "web/extensions/cocostudio/timeline/Frame.js", + "web/extensions/cocostudio/timeline/Timeline.js", + "web/extensions/cocostudio/trigger/ObjectFactory.js", + "web/extensions/cocostudio/trigger/TriggerBase.js", + "web/extensions/cocostudio/trigger/TriggerMng.js", + "web/extensions/cocostudio/trigger/TriggerObj.js", + "web/extensions/editbox/CCEditBox.js", + "web/extensions/editbox/CCdomNode.js", + "web/extensions/gui/control-extension/CCControl.js", + "web/extensions/gui/control-extension/CCControlButton.js", + "web/extensions/gui/control-extension/CCControlColourPicker.js", + "web/extensions/gui/control-extension/CCControlHuePicker.js", + "web/extensions/gui/control-extension/CCControlPotentiometer.js", + "web/extensions/gui/control-extension/CCControlSaturationBrightnessPicker.js", + "web/extensions/gui/control-extension/CCControlSlider.js", + "web/extensions/gui/control-extension/CCControlStepper.js", + "web/extensions/gui/control-extension/CCControlSwitch.js", + "web/extensions/gui/control-extension/CCControlUtils.js", + "web/extensions/gui/control-extension/CCInvocation.js", + "web/extensions/gui/control-extension/CCMenuPassive.js", + "web/extensions/gui/control-extension/CCScale9Sprite.js", + "web/extensions/gui/control-extension/CCScale9SpriteCanvasRenderCmd.js", + "web/extensions/gui/control-extension/CCScale9SpriteWebGLRenderCmd.js", + "web/extensions/gui/scrollview/CCScrollView.js", + "web/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js", + "web/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js", + "web/extensions/gui/scrollview/CCSorting.js", + "web/extensions/gui/scrollview/CCTableView.js", + "web/extensions/spine/CCSkeleton.js", + "web/extensions/spine/CCSkeletonAnimation.js", + "web/extensions/spine/CCSkeletonCanvasRenderCmd.js", + "web/extensions/spine/CCSkeletonWebGLRenderCmd.js", + "web/extensions/spine/Spine.js", + "web/external/box2d/box2d.js", + "web/external/chipmunk/chipmunk.js", + "web/external/pluginx/Plugin.js", + "web/external/pluginx/platform/facebook.js", + "web/external/pluginx/platform/facebook_sdk.js", + "web/external/socketio/socket.io.js", + "web/external/socketio/socket.io.min.js", + "web/jsb_apis.js", + "web/licenses/LICENSE_cocos2d-html5.txt", + "web/licenses/LICENSE_cocos2d-x.txt", + "web/licenses/LICENSE_zlib.js.txt", + "web/moduleConfig.json", + "web/template/index.html", + "web/template/main.js", + "web/template/project.json", + "web/template/res/HD/CloseNormal.png", + "web/template/res/HD/CloseSelected.png", + "web/template/res/HD/HelloWorld.jpg", + "web/template/res/Normal/CloseNormal.png", + "web/template/res/Normal/CloseSelected.png", + "web/template/res/Normal/HelloWorld.jpg", + "web/template/res/favicon.ico", + "web/template/res/loading.js", + "web/template/src/myApp.js", + "web/template/src/resource.js", + "web/tools/XmlCheck.js", + "web/tools/build.xml", + "web/tools/compiler/compiler.jar", + "web/tools/core4cc.js", + "web/tools/genBuildXml.js", + "web/tools/jsdoc_toolkit/build.xml", + "web/tools/publish.js", + "web/tools/readme for tools.txt", + "web/tools/template/build.xml" + ], "lua": [ "cocos/scripting/lua-bindings/CMakeLists.txt", "cocos/scripting/lua-bindings/auto/api/Action.lua", diff --git a/templates/cpp-template-default/CMakeLists.txt b/templates/cpp-template-default/CMakeLists.txt index 532b5c0ea7..b6fe8f03d7 100644 --- a/templates/cpp-template-default/CMakeLists.txt +++ b/templates/cpp-template-default/CMakeLists.txt @@ -35,7 +35,8 @@ include(CocosBuildHelpers) # libcocos2d set(BUILD_CPP_TESTS OFF CACHE BOOL "turn off build cpp-tests") -set(BUILD_LUA_LIBS OFF CACHE BOOL "turn off build lua-tests") +set(BUILD_LUA_LIBS OFF CACHE BOOL "turn off build lua related targets") +set(BUILD_JS_LIBS OFF CACHE BOOL "turn off build js related targets") add_subdirectory(${COCOS2D_ROOT}) # Some macro definitions diff --git a/templates/js-template-default/CMakeLists.txt b/templates/js-template-default/CMakeLists.txt new file mode 100644 index 0000000000..fd463d9e7e --- /dev/null +++ b/templates/js-template-default/CMakeLists.txt @@ -0,0 +1,299 @@ +#/**************************************************************************** +# Copyright (c) 2014 Chukong Technologies 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. +# ****************************************************************************/ + +cmake_minimum_required(VERSION 2.8) + +set(APP_NAME MyGame) +project (${APP_NAME}) + +set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/cmake/Modules/") +include(CocosBuildHelpers) + +option(USE_CHIPMUNK "Use chipmunk for physics library" ON) +option(DEBUG_MODE "Debug or release?" 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(USE_PREBUILT_LIBS "Use prebuilt libraries in external directory" 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 "-DCOCOS2D_DEBUG=1") +set(CMAKE_CXX_FLAGS_DEBUG ${CMAKE_C_FLAGS_DEBUG}) + +if(WIN32) + ADD_DEFINITIONS (-D_USRDLL -DCOCOS2DXWIN32_EXPORTS -D_WINDOWS -DWIN32) + + if(MSVC) + ADD_DEFINITIONS(-D_CRT_SECURE_NO_WARNINGS + -D_SCL_SECURE_NO_WARNINGS + -wd4251 -wd4244 -wd4334 + -wd4005 -wd4820 -wd4710 + -wd4514 -wd4056 -wd4996 -wd4099) + else(MSVC)#MINGW + + endif(MSVC) +elseif(APPLE) + + +else()#Linux +ADD_DEFINITIONS(-DLINUX -DCC_RESOURCE_FOLDER_LINUX="/") +endif() + + +if(NOT MSVC)# all gcc +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") +endif() + +if(MINGW) + add_definitions(-DGLEW_STATIC) +endif() + + +if(USE_CHIPMUNK) + message("Using chipmunk ...") + add_definitions(-DCC_ENABLE_CHIPMUNK_INTEGRATION=1) +elseif(USE_BOX2D) + message("Using box2d ...") + add_definitions(-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() + +if(WIN32) # Win32 + set(PLATFORM_FOLDER win32) +elseif(APPLE)# osx or ios + set(PLATFORM_FOLDER mac) +else() # Assume Linux + set(PLATFORM_FOLDER linux) +endif() + +set(COCOS_EXTERNAL_DIR ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/external) + + +include_directories( + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/ + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/cocos + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/cocos/base + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/cocos/2d + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/cocos/ui + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/cocos/audio/include + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/cocos/storage + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/cocos/network + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/cocos/platform + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/cocos/editor-support + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/cocos/editor-support/spine + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/cocos/editor-support/cocosbuilder + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/cocos/editor-support/cocostudio + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/deprecated + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/cocos/platform + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/extensions + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/external + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/external/chipmunk/include/chipmunk + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/external/spidermonkey/include/${PLATFORM_FOLDER} + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/cocos/scripting/js-bindings/auto + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/cocos/scripting/js-bindings/manual +) + +link_directories( + ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/external/spidermonkey/prebuilt/${PLATFORM_FOLDER}/${ARCH_DIR} +) + + +if(USE_PREBUILT_LIBS) + include(CocosUsePrebuiltLibs) +endif() + +# GLFW3 used on Mac, Windows and Linux desktop platforms +if(LINUX OR MACOSX OR WINDOWS) + cocos_find_package(OpenGL OPENGL REQUIRED) + + if(LINUX OR WINDOWS) + cocos_find_package(GLEW GLEW REQUIRED) + endif() + + cocos_find_package(GLFW3 GLFW3 REQUIRED) + include_directories(${GLFW3_INCLUDE_DIRS}) + + if(LINUX) + set(CMAKE_THREAD_PREFER_PTHREAD TRUE) + find_package(Threads REQUIRED) + set(THREADS_LIBRARIES ${CMAKE_THREAD_LIBS_INIT}) + + #cocos_find_package(FMODEX FMODEX REQUIRED) + cocos_find_package(Fontconfig FONTCONFIG REQUIRED) + endif() + + if(WINDOWS) + cocos_find_package(Vorbis VORBIS REQUIRED) + cocos_find_package(MPG123 MPG123 REQUIRED) + cocos_find_package(OpenAL OPENAL REQUIRED) + # because FindOpenAL.cmake set include dir for '#include ' for portability (not for '#include ' + set(OPENAL_DEFINITIONS "-DOPENAL_PLAIN_INCLUDES") + endif() +endif(LINUX OR MACOSX OR WINDOWS) + +# Freetype required on all platforms +cocos_find_package(Freetype FREETYPE REQUIRED) + +# WebP required if used +if(USE_WEBP) + cocos_find_package(WebP WEBP REQUIRED) +endif(USE_WEBP) + +# Chipmunk +if(USE_CHIPMUNK) + cocos_find_package(Chipmunk CHIPMUNK REQUIRED) + add_definitions(-DCC_ENABLE_CHIPMUNK_INTEGRATION=1) + if(IOS OR MACOSX) + # without this chipmunk will try to use apple defined geometry types, that conflicts with cocos + add_definitions(-DCP_USE_CGPOINTS=0) + endif() +else(USE_CHIPMUNK) + add_definitions(-DCC_USE_PHYSICS=0) +endif(USE_CHIPMUNK) + +# Box2d (not prebuilded, exists as source) +if(USE_BOX2D) + if(USE_PREBUILT_LIBS) + add_subdirectory(frameworks/cocos2d-x/external/Box2D) + set(Box2D_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js-bindings/cocos2d-x/external/box2d/include) + set(Box2D_LIBRARIES box2d) + else() + find_package(Box2D REQUIRED CONFIG) + # actually Box2D in next line is not a library, it is target exported from Box2DConfig.cmake + set(Box2D_LIBRARIES Box2D) + endif() + message(STATUS "Box2D include dirs: ${Box2D_INCLUDE_DIRS}") + add_definitions(-DCC_ENABLE_BOX2D_INTEGRATION=1) +else() + add_definitions(-DCC_ENABLE_BOX2D_INTEGRATION=0) +endif(USE_BOX2D) + +# Tinyxml2 (not prebuilded, exists as source) +if(USE_PREBUILT_LIBS) + add_subdirectory(frameworks/cocos2d-x/external/tinyxml2) + set(TinyXML2_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/external/tinyxml2) + set(TinyXML2_LIBRARIES tinyxml2) +else() + cocos_find_package(TinyXML2 TinyXML2 REQUIRED) +endif() +message(STATUS "TinyXML2 include dirs: ${TinyXML2_INCLUDE_DIRS}") + +# libjpeg +cocos_find_package(JPEG JPEG REQUIRED) +cocos_find_package(ZLIB ZLIB REQUIRED) + +# minizip (we try to migrate to minizip from https://github.com/nmoinvaz/minizip) +# only msys2 currently provides package for this variant, all other +# dists have packages from zlib, thats very old for us. +# moreover our embedded version modified to quick provide +# functionality needed by cocos. +if(USE_PREBUILT_LIBS OR NOT MINGW) + add_subdirectory(frameworks/cocos2d-x/external/unzip) + set(MINIZIP_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/external/unzip) + set(MINIZIP_LIBRARIES unzip) + message(STATUS "MINIZIP include dirs: ${MINIZIP_INCLUDE_DIRS}") +else() + cocos_find_package(MINIZIP MINIZIP REQUIRED) + # double check that we have needed functions + include(CheckLibraryExists) + check_library_exists(${MINIZIP_LIBRARIES} "unzGoToFirstFile2" "" MINIZIP_HAS_GOTOFIRSTFILE2) + if(NOT MINIZIP_HAS_GOTOFIRSTFILE2) + message(FATAL_ERROR "Minizip library on you system very old. Please use recent version from https://github.com/nmoinvaz/minizip or enable USE_PREBUILT_LIBS") + endif() + add_definitions(-DMINIZIP_FROM_SYSTEM) +endif() + +cocos_find_package(PNG PNG REQUIRED) +cocos_find_package(TIFF TIFF REQUIRED) +cocos_find_package(WEBSOCKETS WEBSOCKETS REQUIRED) +cocos_find_package(CURL CURL REQUIRED) + + +add_subdirectory(frameworks/cocos2d-x/external/flatbuffers) +set(FLATBUFFERS_INCLUDE_DIRS frameworks/cocos2d-x/external) +message(STATUS "Flatbuffers include dirs: ${FLATBUFFERS_INCLUDE_DIRS}") + + +# build xxhash +add_subdirectory(frameworks/cocos2d-x/external/xxhash) +include_directories(frameworks/cocos2d-x/external/xxhash) + +set(GAME_SRC + frameworks/runtime-src/proj.linux/main.cpp + frameworks/runtime-src/Classes/AppDelegate.cpp +) + +# cocos2d +add_subdirectory(frameworks/cocos2d-x/cocos) + +#jsbindings library +add_subdirectory(frameworks/cocos2d-x/cocos/scripting/js-bindings) + + +# add the executable +add_executable(${APP_NAME} + ${GAME_SRC} +) + +target_link_libraries(${APP_NAME} + jscocos2d + cocos2d +) + +set(APP_BIN_DIR "${CMAKE_BINARY_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}/script + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/res + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/src + COMMAND ${CMAKE_COMMAND} -E remove ${APP_BIN_DIR}/*.js + COMMAND ${CMAKE_COMMAND} -E remove ${APP_BIN_DIR}/*.json + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/res ${APP_BIN_DIR}/res + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/src ${APP_BIN_DIR}/src + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/frameworks/cocos2d-x/cocos/scripting/js-bindings/script ${APP_BIN_DIR}/script + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/main.js ${APP_BIN_DIR}/main.js + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/project.json ${APP_BIN_DIR}/project.json +) + diff --git a/templates/js-template-default/cocos-project-template.json b/templates/js-template-default/cocos-project-template.json new file mode 100644 index 0000000000..a70ca555e5 --- /dev/null +++ b/templates/js-template-default/cocos-project-template.json @@ -0,0 +1,107 @@ +{ + "do_default":{ + "exclude_from_template":[ + "frameworks/runtime-src" + ], + "append_h5_engine":{ + "from":"web", + "to":"frameworks/cocos2d-html5" + }, + "append_file":[ + { + "from":"web/jsb_apis.js", + "to":"frameworks/cocos2d-html5/jsb_apis.js" + } + ] + }, + "do_add_native_support":{ + "append_from_template":{ + "from":"frameworks/runtime-src", + "to":"frameworks/runtime-src", + "exclude":[ + "proj.android/bin", + "proj.android/assets", + "proj.android/libs", + "proj.ios_mac/HelloJavascript.xcodeproj/project.xcworkspace", + "proj.ios_mac/HelloJavascript.xcodeproj/xcuserdata", + "proj.win32/Debug.win32", + "proj.win32/Release.win32", + "proj.win32/HelloJavascript.sdf", + "proj.win8.1-universal/HelloJavascript.sdf", + "proj.win8.1-universal/HelloJavascript.v12.suo", + "proj.win8.1-universal/ipch", + "proj.win8.1-universal/Debug", + "proj.win8.1-universal/Release", + "proj.win8.1-universal/ARM" + ] + }, + "append_x_engine":{ + "from":".", + "to":"frameworks/cocos2d-x" + }, + "project_rename":{ + "src_project_name":"HelloJavascript", + "files":[ + "frameworks/runtime-src/proj.win32/PROJECT_NAME.vcxproj", + "frameworks/runtime-src/proj.win32/PROJECT_NAME.vcxproj.filters", + "frameworks/runtime-src/proj.win32/PROJECT_NAME.vcxproj.user", + "frameworks/runtime-src/proj.win32/PROJECT_NAME.sln", + "frameworks/runtime-src/proj.ios_mac/PROJECT_NAME.xcodeproj", + "frameworks/runtime-src/proj.win8.1-universal/PROJECT_NAME.sln", + "frameworks/runtime-src/proj.win8.1-universal/App.Shared/PROJECT_NAME.Shared.vcxitems", + "frameworks/runtime-src/proj.win8.1-universal/App.Shared/PROJECT_NAME.Shared.vcxitems.filters", + "frameworks/runtime-src/proj.win8.1-universal/App.Windows/PROJECT_NAME.Windows.vcxproj", + "frameworks/runtime-src/proj.win8.1-universal/App.Windows/PROJECT_NAME.Windows.vcxproj.filters", + "frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/PROJECT_NAME.WindowsPhone.vcxproj", + "frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/PROJECT_NAME.WindowsPhone.vcxproj.filters" + ] + }, + "project_replace_project_name":{ + "src_project_name":"HelloJavascript", + "files":[ + "manifest.webapp", + "frameworks/runtime-src/proj.win32/PROJECT_NAME.vcxproj", + "frameworks/runtime-src/proj.win32/PROJECT_NAME.vcxproj.filters", + "frameworks/runtime-src/proj.win32/PROJECT_NAME.vcxproj.user", + "frameworks/runtime-src/proj.win32/PROJECT_NAME.sln", + "frameworks/runtime-src/proj.win32/main.cpp", + "frameworks/runtime-src/proj.android/.project", + "frameworks/runtime-src/proj.android/AndroidManifest.xml", + "frameworks/runtime-src/proj.android/build.xml", + "frameworks/runtime-src/proj.android/res/values/strings.xml", + "frameworks/runtime-src/proj.ios_mac/ios/main.m", + "frameworks/runtime-src/proj.ios_mac/ios/Prefix.pch", + "frameworks/runtime-src/proj.ios_mac/PROJECT_NAME.xcodeproj/project.pbxproj", + "frameworks/runtime-src/proj.win8.1-universal/PROJECT_NAME.sln", + "frameworks/runtime-src/proj.win8.1-universal/App.Shared/PROJECT_NAME.Shared.vcxitems", + "frameworks/runtime-src/proj.win8.1-universal/App.Shared/PROJECT_NAME.Shared.vcxitems.filters", + "frameworks/runtime-src/proj.win8.1-universal/App.Windows/PROJECT_NAME.Windows.vcxproj", + "frameworks/runtime-src/proj.win8.1-universal/App.Windows/PROJECT_NAME.Windows.vcxproj.filters", + "frameworks/runtime-src/proj.win8.1-universal/App.Windows/Package.appxmanifest", + "frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/PROJECT_NAME.WindowsPhone.vcxproj", + "frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/PROJECT_NAME.WindowsPhone.vcxproj.filters", + "frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Package.appxmanifest", + "frameworks/runtime-src/Classes/AppDelegate.cpp" + ] + }, + "project_replace_package_name":{ + "src_package_name":"org.cocos2dx.hellojavascript", + "files":[ + "frameworks/runtime-src/proj.android/AndroidManifest.xml" + ] + }, + "project_replace_mac_bundleid":{ + "src_bundle_id":"org.cocos2dx.hellojavascript", + "files":[ + "frameworks/runtime-src/proj.ios_mac/mac/Info.plist" + ] + }, + "project_replace_ios_bundleid":{ + "src_bundle_id":"org.cocos2dx.hellojavascript", + "files":[ + "frameworks/runtime-src/proj.ios_mac/ios/Info.plist" + ] + } + } +} + diff --git a/templates/js-template-default/frameworks/runtime-src/Classes/AppDelegate.cpp b/templates/js-template-default/frameworks/runtime-src/Classes/AppDelegate.cpp new file mode 100644 index 0000000000..e4bcf44553 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/Classes/AppDelegate.cpp @@ -0,0 +1,143 @@ +#include "AppDelegate.h" + +#include "SimpleAudioEngine.h" +#include "jsb_cocos2dx_auto.hpp" +#include "jsb_cocos2dx_ui_auto.hpp" +#include "jsb_cocos2dx_studio_auto.hpp" +#include "jsb_cocos2dx_builder_auto.hpp" +#include "jsb_cocos2dx_spine_auto.hpp" +#include "jsb_cocos2dx_extension_auto.hpp" +#include "jsb_cocos2dx_3d_auto.hpp" +#include "jsb_cocos2dx_3d_extension_auto.hpp" +#include "3d/jsb_cocos2dx_3d_manual.h" +#include "ui/jsb_cocos2dx_ui_manual.h" +#include "cocostudio/jsb_cocos2dx_studio_manual.h" +#include "cocosbuilder/js_bindings_ccbreader.h" +#include "spine/jsb_cocos2dx_spine_manual.h" +#include "extension/jsb_cocos2dx_extension_manual.h" +#include "localstorage/js_bindings_system_registration.h" +#include "chipmunk/js_bindings_chipmunk_registration.h" +#include "jsb_opengl_registration.h" +#include "network/XMLHTTPRequest.h" +#include "network/jsb_websocket.h" +#include "network/jsb_socketio.h" + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) +#include "platform/android/CCJavascriptJavaBridge.h" +#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) +#include "platform/ios/JavaScriptObjCBridge.h" +#endif + +USING_NS_CC; +using namespace CocosDenshion; + +AppDelegate::AppDelegate() +{ +} + +AppDelegate::~AppDelegate() +{ + ScriptEngineManager::destroyInstance(); +} + +void AppDelegate::initGLContextAttrs() +{ + GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8}; + + GLView::setGLContextAttrs(glContextAttrs); +} + +bool AppDelegate::applicationDidFinishLaunching() +{ + // initialize director + auto director = Director::getInstance(); + auto glview = director->getOpenGLView(); + if(!glview) { +#if(CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) + glview = cocos2d::GLViewImpl::create("HelloJavascript"); +#else + glview = cocos2d::GLViewImpl::createWithRect("HelloJavascript", Rect(0,0,900,640)); +#endif + director->setOpenGLView(glview); +} + + // set FPS. the default value is 1.0/60 if you don't call this + director->setAnimationInterval(1.0 / 60); + + ScriptingCore* sc = ScriptingCore::getInstance(); + sc->addRegisterCallback(register_all_cocos2dx); + sc->addRegisterCallback(register_cocos2dx_js_core); + sc->addRegisterCallback(jsb_register_system); + + // extension can be commented out to reduce the package + sc->addRegisterCallback(register_all_cocos2dx_extension); + sc->addRegisterCallback(register_all_cocos2dx_extension_manual); + + // chipmunk can be commented out to reduce the package + sc->addRegisterCallback(jsb_register_chipmunk); + // opengl can be commented out to reduce the package + sc->addRegisterCallback(JSB_register_opengl); + + // builder can be commented out to reduce the package + sc->addRegisterCallback(register_all_cocos2dx_builder); + sc->addRegisterCallback(register_CCBuilderReader); + + // ui can be commented out to reduce the package, attension studio need ui module + sc->addRegisterCallback(register_all_cocos2dx_ui); + sc->addRegisterCallback(register_all_cocos2dx_ui_manual); + + // studio can be commented out to reduce the package, + sc->addRegisterCallback(register_all_cocos2dx_studio); + sc->addRegisterCallback(register_all_cocos2dx_studio_manual); + + // spine can be commented out to reduce the package + sc->addRegisterCallback(register_all_cocos2dx_spine); + sc->addRegisterCallback(register_all_cocos2dx_spine_manual); + + // XmlHttpRequest can be commented out to reduce the package + sc->addRegisterCallback(MinXmlHttpRequest::_js_register); + // websocket can be commented out to reduce the package + sc->addRegisterCallback(register_jsb_websocket); + // sokcet io can be commented out to reduce the package + sc->addRegisterCallback(register_jsb_socketio); + + // 3d can be commented out to reduce the package + sc->addRegisterCallback(register_all_cocos2dx_3d); + sc->addRegisterCallback(register_all_cocos2dx_3d_manual); + + // 3d extension can be commented out to reduce the package + sc->addRegisterCallback(register_all_cocos2dx_3d_extension); + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) + sc->addRegisterCallback(JavascriptJavaBridge::_js_register); +#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) + sc->addRegisterCallback(JavaScriptObjCBridge::_js_register); +#endif + sc->start(); + sc->runScript("script/jsb_boot.js"); + ScriptEngineProtocol *engine = ScriptingCore::getInstance(); + ScriptEngineManager::getInstance()->setScriptEngine(engine); + ScriptingCore::getInstance()->runScript("main.js"); + + return true; +} + +// This function will be called when the app is inactive. When comes a phone call,it's be invoked too +void AppDelegate::applicationDidEnterBackground() +{ + auto director = Director::getInstance(); + director->stopAnimation(); + director->getEventDispatcher()->dispatchCustomEvent("game_on_hide"); + SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); + SimpleAudioEngine::getInstance()->pauseAllEffects(); +} + +// this function will be called when the app is active again +void AppDelegate::applicationWillEnterForeground() +{ + auto director = Director::getInstance(); + director->startAnimation(); + director->getEventDispatcher()->dispatchCustomEvent("game_on_show"); + SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); + SimpleAudioEngine::getInstance()->resumeAllEffects(); +} diff --git a/templates/js-template-default/frameworks/runtime-src/Classes/AppDelegate.h b/templates/js-template-default/frameworks/runtime-src/Classes/AppDelegate.h new file mode 100644 index 0000000000..fc614c95af --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/Classes/AppDelegate.h @@ -0,0 +1,47 @@ +// +// GCTestAppDelegate.h +// GCTest +// +// Created by Rohan Kuruvilla on 06/08/2012. +// Copyright __MyCompanyName__ 2012. All rights reserved. +// + +#ifndef _APP_DELEGATE_H_ +#define _APP_DELEGATE_H_ + +#include "platform/CCApplication.h" +/** + @brief The cocos2d Application. + + The reason for implement as private inheritance is to hide some interface call by Director. + */ +class AppDelegate : private cocos2d::Application +{ +public: + AppDelegate(); + virtual ~AppDelegate(); + + void initGLContextAttrs() override; + + /** + @brief Implement Director and Scene init code here. + @return true Initialize success, app continue. + @return false Initialize failed, app terminate. + */ + virtual bool applicationDidFinishLaunching(); + + /** + @brief The function be called when the application enter background + @param the pointer of the application + */ + virtual void applicationDidEnterBackground(); + + /** + @brief The function be called when the application enter foreground + @param the pointer of the application + */ + virtual void applicationWillEnterForeground(); +}; + +#endif // _APP_DELEGATE_H_ + diff --git a/templates/js-template-default/frameworks/runtime-src/proj.android/.classpath b/templates/js-template-default/frameworks/runtime-src/proj.android/.classpath new file mode 100644 index 0000000000..d57ec02513 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.android/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/templates/js-template-default/frameworks/runtime-src/proj.android/.project b/templates/js-template-default/frameworks/runtime-src/proj.android/.project new file mode 100644 index 0000000000..2509d6ba53 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.android/.project @@ -0,0 +1,50 @@ + + + HelloJavascript + + + + + + com.android.ide.eclipse.adt.ResourceManagerBuilder + + + + + com.android.ide.eclipse.adt.PreCompilerBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + com.android.ide.eclipse.adt.ApkBuilder + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + com.android.ide.eclipse.adt.AndroidNature + org.eclipse.jdt.core.javanature + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + + + jsjavabridge + 2 + PARENT-2-PROJECT_LOC/js-bindings/bindings/manual/platform/android/java/src + + + diff --git a/templates/js-template-default/frameworks/runtime-src/proj.android/.settings/org.eclipse.jdt.core.prefs b/templates/js-template-default/frameworks/runtime-src/proj.android/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..b080d2ddc8 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.android/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,4 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/templates/js-template-default/frameworks/runtime-src/proj.android/AndroidManifest.xml b/templates/js-template-default/frameworks/runtime-src/proj.android/AndroidManifest.xml new file mode 100644 index 0000000000..0aaa49d85f --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.android/AndroidManifest.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/templates/js-template-default/frameworks/runtime-src/proj.android/README.md b/templates/js-template-default/frameworks/runtime-src/proj.android/README.md new file mode 100644 index 0000000000..2d13175ad0 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.android/README.md @@ -0,0 +1 @@ +Reference:[compilation in eclipse](https://github.com/chukong/cocos-docs/blob/master/manual/framework/html5/v3/compilation-in-eclipse/en.md) \ No newline at end of file diff --git a/templates/js-template-default/frameworks/runtime-src/proj.android/ant.properties b/templates/js-template-default/frameworks/runtime-src/proj.android/ant.properties new file mode 100644 index 0000000000..f8af38bfb4 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.android/ant.properties @@ -0,0 +1 @@ +aapt.ignore.assets="!*.pvr.gz:!*.gz:!.svn:!.git:.*:_*:!CVS:!thumbs.db:!picasa.ini:!*.scc:*~" diff --git a/templates/js-template-default/frameworks/runtime-src/proj.android/build-cfg.json b/templates/js-template-default/frameworks/runtime-src/proj.android/build-cfg.json new file mode 100644 index 0000000000..d427ea47b6 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.android/build-cfg.json @@ -0,0 +1,29 @@ +{ + "ndk_module_path" :[ + "../../cocos2d-x", + "../../cocos2d-x/cocos", + "../../cocos2d-x/external" + ], + "copy_resources": [ + { + "from": "../../../src", + "to": "src" + }, + { + "from": "../../../res", + "to": "res" + }, + { + "from": "../../../main.js", + "to": "" + }, + { + "from": "../../../project.json", + "to": "" + }, + { + "from": "../../cocos2d-x/cocos/scripting/js-bindings/script", + "to": "script" + } + ] +} diff --git a/templates/js-template-default/frameworks/runtime-src/proj.android/build.xml b/templates/js-template-default/frameworks/runtime-src/proj.android/build.xml new file mode 100644 index 0000000000..b46375fda9 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.android/build.xml @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/templates/js-template-default/frameworks/runtime-src/proj.android/build_native.py b/templates/js-template-default/frameworks/runtime-src/proj.android/build_native.py new file mode 100755 index 0000000000..31c3ef4513 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.android/build_native.py @@ -0,0 +1,174 @@ +#!/usr/bin/python + +''' +build_native.py + +This script will copy resources to assets and build native code with NDK. +''' +import sys +import os, os.path +import shutil +from optparse import OptionParser + +def get_num_of_cpu(): + ''' The build process can be accelerated by running multiple concurrent job processes using the -j-option. + ''' + try: + platform = sys.platform + if platform == 'win32': + if 'NUMBER_OF_PROCESSORS' in os.environ: + return int(os.environ['NUMBER_OF_PROCESSORS']) + else: + return 1 + else: + from numpy.distutils import cpuinfo + return cpuinfo.cpu._getNCPUs() + except Exception: + print "Can't know cpuinfo, use default 1 cpu" + return 1 + +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(ndk_root): + ret_version = "4.8" + + version_file_path = os.path.join(ndk_root, "RELEASE.TXT") + try: + versionFile = open(version_file_path) + lines = versionFile.readlines() + versionFile.close() + + version_num = None + version_char = None + pattern = r'^[a-zA-Z]+(\d+)(\w)' + for line in lines: + str_line = line.lstrip() + match = re.match(pattern, str_line) + if match: + version_num = int(match.group(1)) + version_char = match.group(2) + break + + if version_num is None: + print("Parse NDK version from file %s failed." % version_file_path) + else: + version_char = version_char.lower() + if version_num > 10 or (version_num == 10 and cmp(version_char, 'c') >= 0): + ret_version = "4.9" + + except: + print("Parse NDK version from file %s failed." % version_file_path) + + print("NDK_TOOLCHAIN_VERSION: %s" % ret_version) + if ret_version == "4.8": + print( + "Your application may crash when using c++ 11 regular expression with NDK_TOOLCHAIN_VERSION %s" % ret_version) + + return ret_version + +def do_build(cocos_root, ndk_root, app_android_root, ndk_build_param,sdk_root,build_mode): + + ndk_path = os.path.join(ndk_root, "ndk-build") + ndk_toolchain_version = select_toolchain_version(ndk_root) + + # windows should use ";" to seperate module paths + platform = sys.platform + if platform == 'win32': + ndk_module_path = 'NDK_MODULE_PATH=%s/..;%s;%s/external;%s/cocos NDK_TOOLCHAIN_VERSION=%s' % (cocos_root, cocos_root, cocos_root, cocos_root, ndk_toolchain_version) + else: + ndk_module_path = 'NDK_MODULE_PATH=%s/..:%s:%s/external:%s/cocos NDK_TOOLCHAIN_VERSION=%s' % (cocos_root, cocos_root, cocos_root, cocos_root, ndk_toolchain_version) + + num_of_cpu = get_num_of_cpu() + if ndk_build_param == None: + command = '%s -j%d -C %s NDK_DEBUG=%d %s' % (ndk_path, num_of_cpu, app_android_root, build_mode=='debug', ndk_module_path) + else: + command = '%s -j%d -C %s NDK_DEBUG=%d %s %s' % (ndk_path, num_of_cpu, app_android_root, build_mode=='debug', ndk_build_param, ndk_module_path) + print command + if os.system(command) != 0: + raise Exception("Build dynamic library for project [ " + app_android_root + " ] fails!") + +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) + + assets_res_dir = assets_dir + "/res"; + assets_scripts_dir = assets_dir + "/src"; + assets_jsb_dir = assets_dir + "/script"; + os.mkdir(assets_res_dir); + os.mkdir(assets_scripts_dir); + os.mkdir(assets_jsb_dir); + + + shutil.copy(os.path.join(app_android_root, "../../../main.js"), assets_dir) + shutil.copy(os.path.join(app_android_root, "../../../project.json"), assets_dir) + + resources_dir = os.path.join(app_android_root, "../../../res") + copy_files(resources_dir, assets_res_dir) + + resources_dir = os.path.join(app_android_root, "../../../src") + copy_files(resources_dir, assets_scripts_dir) + + resources_dir = os.path.join(app_android_root, "../../../frameworks/js-bindings/bindings/script") + copy_files(resources_dir, assets_jsb_dir) + +def build(targets,ndk_build_param,build_mode): + + ndk_root = check_environment_variables() + sdk_root = None + + project_root = os.path.dirname(os.path.realpath(__file__)) + cocos_root = os.path.join(project_root, "..", "..", "..", "frameworks/js-bindings/cocos2d-x") + + print cocos_root + + if build_mode is None: + build_mode = 'debug' + elif build_mode != 'release': + build_mode = 'debug' + + copy_resources(project_root) + do_build(cocos_root, ndk_root, project_root,ndk_build_param,sdk_root,build_mode) + +# -------------- main -------------- +if __name__ == '__main__': + + parser = OptionParser() + parser.add_option("-n", "--ndk", dest="ndk_build_param", + help='Parameter for ndk-build') + parser.add_option("-b", "--build", dest="build_mode", + help='The build mode for NDK project, debug or release') + (opts, args) = parser.parse_args() + + try: + build(args, opts.ndk_build_param,opts.build_mode) + except Exception as e: + print e + sys.exit(1) diff --git a/templates/js-template-default/frameworks/runtime-src/proj.android/jni/Android.mk b/templates/js-template-default/frameworks/runtime-src/proj.android/jni/Android.mk new file mode 100644 index 0000000000..bf30c1d3c5 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.android/jni/Android.mk @@ -0,0 +1,21 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := cocos2djs_shared + +LOCAL_MODULE_FILENAME := libcocos2djs + +LOCAL_SRC_FILES := hellojavascript/main.cpp \ + ../../Classes/AppDelegate.cpp + +LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes + +LOCAL_STATIC_LIBRARIES := cocos2d_js_static + +LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT + +include $(BUILD_SHARED_LIBRARY) + + +$(call import-module, scripting/js-bindings/proj.android) diff --git a/templates/js-template-default/frameworks/runtime-src/proj.android/jni/Application.mk b/templates/js-template-default/frameworks/runtime-src/proj.android/jni/Application.mk new file mode 100644 index 0000000000..706af60331 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.android/jni/Application.mk @@ -0,0 +1,15 @@ +APP_STL := gnustl_static + +# Uncomment this line to compile to armeabi-v7a, your application will run faster but support less devices +#APP_ABI := armeabi-v7a + +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -std=c++11 -fsigned-char +APP_LDFLAGS := -latomic + +ifeq ($(NDK_DEBUG),1) + APP_CPPFLAGS += -DCOCOS2D_DEBUG=1 + APP_OPTIM := debug +else + APP_CPPFLAGS += -DNDEBUG + APP_OPTIM := release +endif diff --git a/templates/js-template-default/frameworks/runtime-src/proj.android/jni/hellojavascript/main.cpp b/templates/js-template-default/frameworks/runtime-src/proj.android/jni/hellojavascript/main.cpp new file mode 100644 index 0000000000..5199d12ab4 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.android/jni/hellojavascript/main.cpp @@ -0,0 +1,15 @@ +#include "AppDelegate.h" +#include "cocos2d.h" +#include "platform/android/jni/JniHelper.h" +#include +#include + +#define LOG_TAG "main" +#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) + +using namespace cocos2d; + +void cocos_android_app_init (JNIEnv* env, jobject thiz) { + LOGD("cocos_android_app_init"); + AppDelegate *pAppDelegate = new AppDelegate(); +} diff --git a/templates/js-template-default/frameworks/runtime-src/proj.android/proguard-project.txt b/templates/js-template-default/frameworks/runtime-src/proj.android/proguard-project.txt new file mode 100644 index 0000000000..f2fe1559a2 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.android/proguard-project.txt @@ -0,0 +1,20 @@ +# To enable ProGuard in your project, edit project.properties +# to define the proguard.config property as described in that file. +# +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in ${sdk.dir}/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the ProGuard +# include property in project.properties. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/templates/js-template-default/frameworks/runtime-src/proj.android/project.properties b/templates/js-template-default/frameworks/runtime-src/proj.android/project.properties new file mode 100644 index 0000000000..8e5895514b --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.android/project.properties @@ -0,0 +1,13 @@ +# This file is automatically generated by Android Tools. +# Do not modify this file -- YOUR CHANGES WILL BE ERASED! +# +# This file must be checked in Version Control Systems. +# +# To customize properties used by the Ant build system use, +# "ant.properties", and override values to adapt the script to your +# project structure. + +# Project target. +target=android-10 + +android.library.reference.1=../../cocos2d-x/cocos/platform/android/java diff --git a/templates/js-template-default/frameworks/runtime-src/proj.android/res/drawable-hdpi/icon.png b/templates/js-template-default/frameworks/runtime-src/proj.android/res/drawable-hdpi/icon.png new file mode 100644 index 0000000000..8aa4767c2f Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.android/res/drawable-hdpi/icon.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.android/res/drawable-ldpi/icon.png b/templates/js-template-default/frameworks/runtime-src/proj.android/res/drawable-ldpi/icon.png new file mode 100644 index 0000000000..17ce11a085 Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.android/res/drawable-ldpi/icon.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.android/res/drawable-mdpi/icon.png b/templates/js-template-default/frameworks/runtime-src/proj.android/res/drawable-mdpi/icon.png new file mode 100644 index 0000000000..3780aac46c Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.android/res/drawable-mdpi/icon.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.android/res/values/strings.xml b/templates/js-template-default/frameworks/runtime-src/proj.android/res/values/strings.xml new file mode 100644 index 0000000000..c847de2851 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.android/res/values/strings.xml @@ -0,0 +1,4 @@ + + + HelloJavascript + diff --git a/templates/js-template-default/frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java b/templates/js-template-default/frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java new file mode 100644 index 0000000000..7bc1264c83 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java @@ -0,0 +1,42 @@ +/**************************************************************************** +Copyright (c) 2008-2010 Ricardo Quesada +Copyright (c) 2010-2012 cocos2d-x.org +Copyright (c) 2011 Zynga Inc. +Copyright (c) 2013-2014 Chukong Technologies 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. +****************************************************************************/ +package org.cocos2dx.javascript; + +import org.cocos2dx.lib.Cocos2dxActivity; +import org.cocos2dx.lib.Cocos2dxGLSurfaceView; + +public class AppActivity extends Cocos2dxActivity { + + @Override + public Cocos2dxGLSurfaceView onCreateView() { + Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this); + // TestCpp should create stencil buffer + glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8); + + return glSurfaceView; + } +} diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj new file mode 100644 index 0000000000..3d9535e1ef --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj @@ -0,0 +1,966 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 1A67682A180E9C060076BC67 /* libcocos2dx Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FB48180E9ACB004C840B /* libcocos2dx Mac.a */; }; + 1A676839180E9C1E0076BC67 /* libcocos2dx iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1AC6FB56180E9ACB004C840B /* libcocos2dx iOS.a */; }; + 1A82F5FB169AC92500C4B13A /* libsqlite3.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A82F5FA169AC92500C4B13A /* libsqlite3.dylib */; }; + 1AC22EDE18CA0E11007112B9 /* project.json in Resources */ = {isa = PBXBuildFile; fileRef = 1A1A081B18C9DF05005C6854 /* project.json */; }; + 1AD7E0A818C9DB93004817A6 /* main.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6BF21418C9DB5900FB0E1C /* main.js */; }; + 1AD7E0A918C9DBE3004817A6 /* main.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6BF21418C9DB5900FB0E1C /* main.js */; }; + 1AE159EC18C9DF3600FCA372 /* project.json in Resources */ = {isa = PBXBuildFile; fileRef = 1A1A081B18C9DF05005C6854 /* project.json */; }; + 502380DC17EBB88200990C9B /* libcurl.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 502380DB17EBB88200990C9B /* libcurl.dylib */; }; + 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 */; }; + 5091731D17ECDF7A00D62437 /* Icon-58.png in Resources */ = {isa = PBXBuildFile; fileRef = 5091731717ECDF7A00D62437 /* Icon-58.png */; }; + 5091731E17ECDF7A00D62437 /* Icon-80.png in Resources */ = {isa = PBXBuildFile; fileRef = 5091731817ECDF7A00D62437 /* Icon-80.png */; }; + 5091731F17ECDF7A00D62437 /* Icon-100.png in Resources */ = {isa = PBXBuildFile; fileRef = 5091731917ECDF7A00D62437 /* Icon-100.png */; }; + 509D4A8117EBB24E00697056 /* AppDelegate.cpp in Sources */ = {isa = PBXBuildFile; fileRef = D4545215156E28EF00887EB5 /* AppDelegate.cpp */; }; + 509D4A8817EBB24E00697056 /* libsqlite3.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 1A82F5FA169AC92500C4B13A /* libsqlite3.dylib */; }; + 509D4A8917EBB24E00697056 /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = D454520B156E22BD00887EB5 /* libz.dylib */; }; + 509D4A8A17EBB24E00697056 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A92275411517C094001B78AA /* QuartzCore.framework */; }; + 509D4A8C17EBB24E00697056 /* OpenAL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A92275451517C094001B78AA /* OpenAL.framework */; }; + 509D4A8D17EBB24E00697056 /* AudioToolbox.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A92275471517C094001B78AA /* AudioToolbox.framework */; }; + 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 */; }; + 509D4ABC17EBB2AB00697056 /* AppController.mm in Sources */ = {isa = PBXBuildFile; fileRef = 509D4AAC17EBB2AB00697056 /* AppController.mm */; }; + 509D4ABD17EBB2AB00697056 /* Default-568h@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 509D4AAD17EBB2AB00697056 /* Default-568h@2x.png */; }; + 509D4ABE17EBB2AB00697056 /* Default.png in Resources */ = {isa = PBXBuildFile; fileRef = 509D4AAE17EBB2AB00697056 /* Default.png */; }; + 509D4ABF17EBB2AB00697056 /* Default@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 509D4AAF17EBB2AB00697056 /* Default@2x.png */; }; + 509D4AC017EBB2AB00697056 /* Icon-57.png in Resources */ = {isa = PBXBuildFile; fileRef = 509D4AB017EBB2AB00697056 /* Icon-57.png */; }; + 509D4AC117EBB2AB00697056 /* Icon-72.png in Resources */ = {isa = PBXBuildFile; fileRef = 509D4AB117EBB2AB00697056 /* Icon-72.png */; }; + 509D4AC217EBB2AB00697056 /* Icon-76.png in Resources */ = {isa = PBXBuildFile; fileRef = 509D4AB217EBB2AB00697056 /* Icon-76.png */; }; + 509D4AC317EBB2AB00697056 /* Icon-114.png in Resources */ = {isa = PBXBuildFile; fileRef = 509D4AB317EBB2AB00697056 /* Icon-114.png */; }; + 509D4AC417EBB2AB00697056 /* Icon-120.png in Resources */ = {isa = PBXBuildFile; fileRef = 509D4AB417EBB2AB00697056 /* Icon-120.png */; }; + 509D4AC517EBB2AB00697056 /* Icon-144.png in Resources */ = {isa = PBXBuildFile; fileRef = 509D4AB517EBB2AB00697056 /* Icon-144.png */; }; + 509D4AC617EBB2AB00697056 /* Icon-152.png in Resources */ = {isa = PBXBuildFile; fileRef = 509D4AB617EBB2AB00697056 /* Icon-152.png */; }; + 509D4AC817EBB2AB00697056 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 509D4AB817EBB2AB00697056 /* main.m */; }; + 509D4AC917EBB2AB00697056 /* RootViewController.mm in Sources */ = {isa = PBXBuildFile; fileRef = 509D4ABB17EBB2AB00697056 /* RootViewController.mm */; }; + 509D4ACF17EBB2BE00697056 /* Icon.icns in Resources */ = {isa = PBXBuildFile; fileRef = 509D4ACB17EBB2BE00697056 /* Icon.icns */; }; + 509D4AE717EBB81800697056 /* OpenGL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 509D4AE617EBB81800697056 /* OpenGL.framework */; }; + 509D4AE917EBB82000697056 /* AppKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 509D4AE817EBB82000697056 /* AppKit.framework */; }; + 509D4AEB17EBB82600697056 /* IOKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 509D4AEA17EBB82600697056 /* IOKit.framework */; }; + A92275421517C094001B78AA /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A92275411517C094001B78AA /* QuartzCore.framework */; }; + A92275441517C094001B78AA /* OpenGLES.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A92275431517C094001B78AA /* OpenGLES.framework */; }; + A92275461517C094001B78AA /* OpenAL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A92275451517C094001B78AA /* OpenAL.framework */; }; + A92275481517C094001B78AA /* AudioToolbox.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A92275471517C094001B78AA /* AudioToolbox.framework */; }; + A922754A1517C094001B78AA /* AVFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A92275491517C094001B78AA /* AVFoundation.framework */; }; + A922754C1517C094001B78AA /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A922754B1517C094001B78AA /* UIKit.framework */; }; + A922754E1517C094001B78AA /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A922754D1517C094001B78AA /* Foundation.framework */; }; + A92275501517C094001B78AA /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A922754F1517C094001B78AA /* CoreGraphics.framework */; }; + BA3A85EC1A724AE900924D24 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BA3A85EB1A724AE900924D24 /* Security.framework */; }; + BA4E718119EB6E3F00932425 /* MediaPlayer.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BA4E718019EB6E3E00932425 /* MediaPlayer.framework */; }; + BAEE4D841AC40C11003BEB0F /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BAEE4D831AC40C11003BEB0F /* Security.framework */; }; + BAF426FB19484B3E002B22EF /* script in Resources */ = {isa = PBXBuildFile; fileRef = BAF426FA19484B3E002B22EF /* script */; }; + BAF426FC19484B3E002B22EF /* script in Resources */ = {isa = PBXBuildFile; fileRef = BAF426FA19484B3E002B22EF /* script */; }; + C03780EB18BEE0E400FE4F13 /* src in Resources */ = {isa = PBXBuildFile; fileRef = C03780EA18BEE0E400FE4F13 /* src */; }; + C03780EC18BEE0E400FE4F13 /* src in Resources */ = {isa = PBXBuildFile; fileRef = C03780EA18BEE0E400FE4F13 /* src */; }; + C037820C18BF77C500FE4F13 /* libjscocos2d iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = C037820918BF76AF00FE4F13 /* libjscocos2d iOS.a */; }; + C037820F18BF77DE00FE4F13 /* libjscocos2d Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = C037820718BF76AF00FE4F13 /* libjscocos2d Mac.a */; }; + C06E23CC18CEFE680093C81A /* main.cpp in Sources */ = {isa = PBXBuildFile; fileRef = C06E23CB18CEFE680093C81A /* main.cpp */; }; + C0799CB918BAE62000E9C828 /* res in Resources */ = {isa = PBXBuildFile; fileRef = C0799CB518BAE62000E9C828 /* res */; }; + C0799CBA18BAE62000E9C828 /* res in Resources */ = {isa = PBXBuildFile; fileRef = C0799CB518BAE62000E9C828 /* res */; }; + 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 */ + 1A67681F180E9BF70076BC67 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + 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"; + }; + 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"; + }; + 1AC6FB47180E9ACB004C840B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 1551A33F158F2AB200E66CFE; + remoteInfo = "cocos2dx Mac"; + }; + 1AC6FB49180E9ACB004C840B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = A03F2FD617814595006731B9; + remoteInfo = "cocos2dx-extensions Mac"; + }; + 1AC6FB4B180E9ACB004C840B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = A03F2CB81780BD04006731B9; + remoteInfo = "chipmunk Mac"; + }; + 1AC6FB4D180E9ACB004C840B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = A03F2D9B1780BDF7006731B9; + remoteInfo = "box2d Mac"; + }; + 1AC6FB4F180E9ACB004C840B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = A03F2ED617814268006731B9; + remoteInfo = "CocosDenshion Mac"; + }; + 1AC6FB55180E9ACB004C840B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = A07A4D641783777C0073F6A7; + remoteInfo = "cocos2dx iOS"; + }; + 1AC6FB57180E9ACB004C840B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = A07A4EFC1783867C0073F6A7; + remoteInfo = "cocos2dx-extensions iOS"; + }; + 1AC6FB59180E9ACB004C840B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = A07A4F3B178387670073F6A7; + remoteInfo = "chipmunk iOS"; + }; + 1AC6FB5B180E9ACB004C840B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = A07A4F9E1783876B0073F6A7; + remoteInfo = "box2d iOS"; + }; + 1AC6FB5D180E9ACB004C840B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = A07A4FB4178387730073F6A7; + remoteInfo = "CocosDenshion iOS"; + }; + C037820618BF76AF00FE4F13 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = C037820118BF76AF00FE4F13 /* cocos2d_js_bindings.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 1A5410A418B785A10016A3AF; + remoteInfo = "jsbindings Mac"; + }; + C037820818BF76AF00FE4F13 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = C037820118BF76AF00FE4F13 /* cocos2d_js_bindings.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 1A5410A518B785A10016A3AF; + remoteInfo = "jsbindings iOS"; + }; + C037820A18BF77BC00FE4F13 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = C037820118BF76AF00FE4F13 /* cocos2d_js_bindings.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = A07A4FB5178387750073F6A7; + remoteInfo = "jsbindings iOS"; + }; + C037820D18BF77D100FE4F13 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = C037820118BF76AF00FE4F13 /* cocos2d_js_bindings.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = A03F31E81781479B006731B9; + remoteInfo = "jsbindings Mac"; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 1A1A081B18C9DF05005C6854 /* project.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; name = project.json; path = ../../../project.json; sourceTree = ""; }; + 1A6BF21418C9DB5900FB0E1C /* main.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; name = main.js; path = ../../../main.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 = "../../cocos2d-x/cocos2dx/platform/third_party/ios/libraries/libcurl.a"; sourceTree = ""; }; + 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = cocos2d_libs.xcodeproj; path = "../../cocos2d-x/build/cocos2d_libs.xcodeproj"; 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 = ""; }; + 5091731617ECDF7A00D62437 /* Icon-50.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-50.png"; path = "ios/Icon-50.png"; sourceTree = ""; }; + 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 /* HelloJavascript Mac.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; 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 = ""; }; + 509D4AAE17EBB2AB00697056 /* Default.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = Default.png; path = ios/Default.png; sourceTree = ""; }; + 509D4AAF17EBB2AB00697056 /* Default@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Default@2x.png"; path = "ios/Default@2x.png"; sourceTree = ""; }; + 509D4AB017EBB2AB00697056 /* Icon-57.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-57.png"; path = "ios/Icon-57.png"; sourceTree = ""; }; + 509D4AB117EBB2AB00697056 /* Icon-72.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-72.png"; path = "ios/Icon-72.png"; sourceTree = ""; }; + 509D4AB217EBB2AB00697056 /* Icon-76.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-76.png"; path = "ios/Icon-76.png"; sourceTree = ""; }; + 509D4AB317EBB2AB00697056 /* Icon-114.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-114.png"; path = "ios/Icon-114.png"; sourceTree = ""; }; + 509D4AB417EBB2AB00697056 /* Icon-120.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-120.png"; path = "ios/Icon-120.png"; sourceTree = ""; }; + 509D4AB517EBB2AB00697056 /* Icon-144.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-144.png"; path = "ios/Icon-144.png"; sourceTree = ""; }; + 509D4AB617EBB2AB00697056 /* Icon-152.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-152.png"; path = "ios/Icon-152.png"; sourceTree = ""; }; + 509D4AB717EBB2AB00697056 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = ios/Info.plist; sourceTree = ""; }; + 509D4AB817EBB2AB00697056 /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = main.m; path = ios/main.m; sourceTree = ""; }; + 509D4AB917EBB2AB00697056 /* Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Prefix.pch; path = ios/Prefix.pch; sourceTree = ""; }; + 509D4ABA17EBB2AB00697056 /* RootViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RootViewController.h; path = ios/RootViewController.h; sourceTree = ""; }; + 509D4ABB17EBB2AB00697056 /* RootViewController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = RootViewController.mm; path = ios/RootViewController.mm; sourceTree = ""; }; + 509D4ACB17EBB2BE00697056 /* Icon.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; path = Icon.icns; sourceTree = ""; }; + 509D4ACC17EBB2BE00697056 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 509D4ACE17EBB2BE00697056 /* Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Prefix.pch; sourceTree = ""; }; + 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 /* HelloJavascript iOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; 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; }; + A92275471517C094001B78AA /* AudioToolbox.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AudioToolbox.framework; path = System/Library/Frameworks/AudioToolbox.framework; sourceTree = SDKROOT; }; + A92275491517C094001B78AA /* AVFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AVFoundation.framework; path = System/Library/Frameworks/AVFoundation.framework; sourceTree = SDKROOT; }; + A922754B1517C094001B78AA /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; + A922754D1517C094001B78AA /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; + A922754F1517C094001B78AA /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; + BA3A85EB1A724AE900924D24 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk/System/Library/Frameworks/Security.framework; sourceTree = DEVELOPER_DIR; }; + BA4E718019EB6E3E00932425 /* MediaPlayer.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MediaPlayer.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.0.sdk/System/Library/Frameworks/MediaPlayer.framework; sourceTree = DEVELOPER_DIR; }; + BA4E718219EB6E4600932425 /* GameController.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GameController.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.0.sdk/System/Library/Frameworks/GameController.framework; sourceTree = DEVELOPER_DIR; }; + BAEE4D831AC40C11003BEB0F /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; }; + BAF426FA19484B3E002B22EF /* script */ = {isa = PBXFileReference; lastKnownFileType = folder; name = script; path = "../../cocos2d-x/cocos/scripting/js-bindings/script"; sourceTree = ""; }; + C03780EA18BEE0E400FE4F13 /* src */ = {isa = PBXFileReference; lastKnownFileType = folder; name = src; path = ../../../src; sourceTree = ""; }; + C037820118BF76AF00FE4F13 /* cocos2d_js_bindings.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = cocos2d_js_bindings.xcodeproj; path = "../../cocos2d-x/cocos/scripting/js-bindings/proj.ios_mac/cocos2d_js_bindings.xcodeproj"; sourceTree = ""; }; + C06E23CB18CEFE680093C81A /* main.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = main.cpp; sourceTree = ""; }; + C0799CB518BAE62000E9C828 /* res */ = {isa = PBXFileReference; lastKnownFileType = folder; name = res; path = ../../../res; sourceTree = ""; }; + 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 */ + 509D4A8217EBB24E00697056 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + BAEE4D841AC40C11003BEB0F /* Security.framework in Frameworks */, + C037820F18BF77DE00FE4F13 /* libjscocos2d Mac.a in Frameworks */, + 1A67682A180E9C060076BC67 /* libcocos2dx Mac.a in Frameworks */, + 502380DC17EBB88200990C9B /* libcurl.dylib in Frameworks */, + 509D4A8817EBB24E00697056 /* libsqlite3.dylib in Frameworks */, + 509D4A8917EBB24E00697056 /* libz.dylib in Frameworks */, + 509D4AEB17EBB82600697056 /* IOKit.framework in Frameworks */, + 509D4AE917EBB82000697056 /* AppKit.framework in Frameworks */, + 509D4AE717EBB81800697056 /* OpenGL.framework in Frameworks */, + 509D4A8A17EBB24E00697056 /* QuartzCore.framework in Frameworks */, + 509D4A8C17EBB24E00697056 /* OpenAL.framework in Frameworks */, + 509D4A8D17EBB24E00697056 /* AudioToolbox.framework in Frameworks */, + 509D4A8E17EBB24E00697056 /* AVFoundation.framework in Frameworks */, + 509D4A9017EBB24E00697056 /* Foundation.framework in Frameworks */, + 509D4A9117EBB24E00697056 /* CoreGraphics.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A922753A1517C094001B78AA /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + BA3A85EC1A724AE900924D24 /* Security.framework in Frameworks */, + BA4E718119EB6E3F00932425 /* MediaPlayer.framework in Frameworks */, + C037820C18BF77C500FE4F13 /* libjscocos2d iOS.a in Frameworks */, + 1A676839180E9C1E0076BC67 /* libcocos2dx iOS.a in Frameworks */, + D6B061241803AB9F0077942B /* CoreMotion.framework in Frameworks */, + 1A82F5FB169AC92500C4B13A /* libsqlite3.dylib in Frameworks */, + D454520C156E22BD00887EB5 /* libz.dylib in Frameworks */, + A92275421517C094001B78AA /* QuartzCore.framework in Frameworks */, + A92275441517C094001B78AA /* OpenGLES.framework in Frameworks */, + A92275461517C094001B78AA /* OpenAL.framework in Frameworks */, + A92275481517C094001B78AA /* AudioToolbox.framework in Frameworks */, + A922754A1517C094001B78AA /* AVFoundation.framework in Frameworks */, + A922754C1517C094001B78AA /* UIKit.framework in Frameworks */, + A922754E1517C094001B78AA /* Foundation.framework in Frameworks */, + A92275501517C094001B78AA /* CoreGraphics.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 15628F5B15F0F5C2000CF24B /* Resources */ = { + isa = PBXGroup; + children = ( + 1A1A081B18C9DF05005C6854 /* project.json */, + 1A6BF21418C9DB5900FB0E1C /* main.js */, + C0799CB518BAE62000E9C828 /* res */, + C03780EA18BEE0E400FE4F13 /* src */, + ); + name = Resources; + 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 */, + 1AC6FB56180E9ACB004C840B /* libcocos2dx iOS.a */, + 1AC6FB58180E9ACB004C840B /* libcocos2dx-extensions iOS.a */, + 1AC6FB5A180E9ACB004C840B /* libchipmunk iOS.a */, + 1AC6FB5C180E9ACB004C840B /* libbox2d iOS.a */, + 1AC6FB5E180E9ACB004C840B /* libCocosDenshion iOS.a */, + ); + name = Products; + sourceTree = ""; + }; + 5091732E17ECDF8A00D62437 /* Icons */ = { + isa = PBXGroup; + children = ( + 5091731417ECDF7A00D62437 /* Icon-29.png */, + 5091731517ECDF7A00D62437 /* Icon-40.png */, + 5091731617ECDF7A00D62437 /* Icon-50.png */, + 5091731717ECDF7A00D62437 /* Icon-58.png */, + 5091731817ECDF7A00D62437 /* Icon-80.png */, + 5091731917ECDF7A00D62437 /* Icon-100.png */, + 509D4AB017EBB2AB00697056 /* Icon-57.png */, + 509D4AB117EBB2AB00697056 /* Icon-72.png */, + 509D4AB217EBB2AB00697056 /* Icon-76.png */, + 509D4AB317EBB2AB00697056 /* Icon-114.png */, + 509D4AB417EBB2AB00697056 /* Icon-120.png */, + 509D4AB517EBB2AB00697056 /* Icon-144.png */, + 509D4AB617EBB2AB00697056 /* Icon-152.png */, + ); + name = Icons; + sourceTree = ""; + }; + 509D4ACA17EBB2BE00697056 /* mac */ = { + isa = PBXGroup; + children = ( + C06E23CB18CEFE680093C81A /* main.cpp */, + 509D4ACB17EBB2BE00697056 /* Icon.icns */, + 509D4ACC17EBB2BE00697056 /* Info.plist */, + 509D4ACE17EBB2BE00697056 /* Prefix.pch */, + ); + path = mac; + sourceTree = ""; + }; + A92275321517C094001B78AA = { + isa = PBXGroup; + children = ( + C037820118BF76AF00FE4F13 /* cocos2d_js_bindings.xcodeproj */, + 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */, + BAF426FA19484B3E002B22EF /* script */, + D4545214156E28EF00887EB5 /* Classes */, + A92275401517C094001B78AA /* Frameworks */, + D45446CC156DE73F00887EB5 /* ios */, + 509D4ACA17EBB2BE00697056 /* mac */, + A922753E1517C094001B78AA /* Products */, + 15628F5B15F0F5C2000CF24B /* Resources */, + ); + sourceTree = ""; + }; + A922753E1517C094001B78AA /* Products */ = { + isa = PBXGroup; + children = ( + A922753D1517C094001B78AA /* HelloJavascript iOS.app */, + 509D4AAA17EBB24E00697056 /* HelloJavascript Mac.app */, + ); + name = Products; + sourceTree = ""; + }; + A92275401517C094001B78AA /* Frameworks */ = { + isa = PBXGroup; + children = ( + BAEE4D831AC40C11003BEB0F /* Security.framework */, + BA3A85EB1A724AE900924D24 /* Security.framework */, + BA4E718219EB6E4600932425 /* GameController.framework */, + BA4E718019EB6E3E00932425 /* MediaPlayer.framework */, + D6B061231803AB9F0077942B /* CoreMotion.framework */, + 502380DB17EBB88200990C9B /* libcurl.dylib */, + 509D4AEA17EBB82600697056 /* IOKit.framework */, + 509D4AE817EBB82000697056 /* AppKit.framework */, + 509D4AE617EBB81800697056 /* OpenGL.framework */, + 1A96A4F2174A3432008653A9 /* libcurl.a */, + 1A82F5FA169AC92500C4B13A /* libsqlite3.dylib */, + D454520B156E22BD00887EB5 /* libz.dylib */, + A92275411517C094001B78AA /* QuartzCore.framework */, + A92275431517C094001B78AA /* OpenGLES.framework */, + A92275451517C094001B78AA /* OpenAL.framework */, + A92275471517C094001B78AA /* AudioToolbox.framework */, + A92275491517C094001B78AA /* AVFoundation.framework */, + A922754B1517C094001B78AA /* UIKit.framework */, + A922754D1517C094001B78AA /* Foundation.framework */, + A922754F1517C094001B78AA /* CoreGraphics.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + C037820218BF76AF00FE4F13 /* Products */ = { + isa = PBXGroup; + children = ( + C037820718BF76AF00FE4F13 /* libjscocos2d Mac.a */, + C037820918BF76AF00FE4F13 /* libjscocos2d iOS.a */, + ); + name = Products; + sourceTree = ""; + }; + D45446CC156DE73F00887EB5 /* ios */ = { + isa = PBXGroup; + children = ( + 509D4AAB17EBB2AB00697056 /* AppController.h */, + 509D4AAC17EBB2AB00697056 /* AppController.mm */, + 509D4AAD17EBB2AB00697056 /* Default-568h@2x.png */, + 509D4AAE17EBB2AB00697056 /* Default.png */, + 509D4AAF17EBB2AB00697056 /* Default@2x.png */, + 5091732E17ECDF8A00D62437 /* Icons */, + 509D4AB717EBB2AB00697056 /* Info.plist */, + 509D4AB817EBB2AB00697056 /* main.m */, + 509D4AB917EBB2AB00697056 /* Prefix.pch */, + 509D4ABA17EBB2AB00697056 /* RootViewController.h */, + 509D4ABB17EBB2AB00697056 /* RootViewController.mm */, + ); + name = ios; + sourceTree = ""; + }; + D4545214156E28EF00887EB5 /* Classes */ = { + isa = PBXGroup; + children = ( + D4545215156E28EF00887EB5 /* AppDelegate.cpp */, + D4545216156E28EF00887EB5 /* AppDelegate.h */, + ); + name = Classes; + path = ../Classes; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 509D4A7517EBB24E00697056 /* HelloJavascript Mac */ = { + isa = PBXNativeTarget; + buildConfigurationList = 509D4AA717EBB24E00697056 /* Build configuration list for PBXNativeTarget "HelloJavascript Mac" */; + buildPhases = ( + 509D4A8017EBB24E00697056 /* Sources */, + 509D4A9317EBB24E00697056 /* Resources */, + 509D4A8217EBB24E00697056 /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + C037820E18BF77D100FE4F13 /* PBXTargetDependency */, + 1A676820180E9BF70076BC67 /* PBXTargetDependency */, + 1A676822180E9BF70076BC67 /* PBXTargetDependency */, + 1A676824180E9BF70076BC67 /* PBXTargetDependency */, + 1A676826180E9BF70076BC67 /* PBXTargetDependency */, + ); + name = "HelloJavascript Mac"; + productName = HelloJavascript; + productReference = 509D4AAA17EBB24E00697056 /* HelloJavascript Mac.app */; + productType = "com.apple.product-type.application"; + }; + A922753C1517C094001B78AA /* HelloJavascript iOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = A92277001517C097001B78AA /* Build configuration list for PBXNativeTarget "HelloJavascript iOS" */; + buildPhases = ( + A92275391517C094001B78AA /* Sources */, + A922753A1517C094001B78AA /* Frameworks */, + A922753B1517C094001B78AA /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + C037820B18BF77BC00FE4F13 /* PBXTargetDependency */, + 1A67682F180E9C110076BC67 /* PBXTargetDependency */, + 1A676831180E9C110076BC67 /* PBXTargetDependency */, + 1A676833180E9C110076BC67 /* PBXTargetDependency */, + 1A676835180E9C110076BC67 /* PBXTargetDependency */, + ); + name = "HelloJavascript iOS"; + productName = HelloJavascript; + productReference = A922753D1517C094001B78AA /* HelloJavascript iOS.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + A92275341517C094001B78AA /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0500; + TargetAttributes = { + A922753C1517C094001B78AA = { + DevelopmentTeam = MDDB52YB8L; + }; + }; + }; + buildConfigurationList = A92275371517C094001B78AA /* Build configuration list for PBXProject "HelloJavascript" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = A92275321517C094001B78AA; + productRefGroup = A922753E1517C094001B78AA /* Products */; + projectDirPath = ""; + projectReferences = ( + { + ProductGroup = C037820218BF76AF00FE4F13 /* Products */; + ProjectRef = C037820118BF76AF00FE4F13 /* cocos2d_js_bindings.xcodeproj */; + }, + { + ProductGroup = 1AC6FB35180E9ACB004C840B /* Products */; + ProjectRef = 1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */; + }, + ); + projectRoot = ""; + targets = ( + A922753C1517C094001B78AA /* HelloJavascript iOS */, + 509D4A7517EBB24E00697056 /* HelloJavascript Mac */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXReferenceProxy section */ + 1AC6FB48180E9ACB004C840B /* libcocos2dx Mac.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libcocos2dx Mac.a"; + remoteRef = 1AC6FB47180E9ACB004C840B /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 1AC6FB4A180E9ACB004C840B /* libcocos2dx-extensions Mac.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libcocos2dx-extensions Mac.a"; + remoteRef = 1AC6FB49180E9ACB004C840B /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 1AC6FB4C180E9ACB004C840B /* libchipmunk Mac.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libchipmunk Mac.a"; + remoteRef = 1AC6FB4B180E9ACB004C840B /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 1AC6FB4E180E9ACB004C840B /* libbox2d Mac.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libbox2d Mac.a"; + remoteRef = 1AC6FB4D180E9ACB004C840B /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 1AC6FB50180E9ACB004C840B /* libCocosDenshion Mac.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libCocosDenshion Mac.a"; + remoteRef = 1AC6FB4F180E9ACB004C840B /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 1AC6FB56180E9ACB004C840B /* libcocos2dx iOS.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libcocos2dx iOS.a"; + remoteRef = 1AC6FB55180E9ACB004C840B /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 1AC6FB58180E9ACB004C840B /* libcocos2dx-extensions iOS.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libcocos2dx-extensions iOS.a"; + remoteRef = 1AC6FB57180E9ACB004C840B /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 1AC6FB5A180E9ACB004C840B /* libchipmunk iOS.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libchipmunk iOS.a"; + remoteRef = 1AC6FB59180E9ACB004C840B /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 1AC6FB5C180E9ACB004C840B /* libbox2d iOS.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libbox2d iOS.a"; + remoteRef = 1AC6FB5B180E9ACB004C840B /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 1AC6FB5E180E9ACB004C840B /* libCocosDenshion iOS.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libCocosDenshion iOS.a"; + remoteRef = 1AC6FB5D180E9ACB004C840B /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + C037820718BF76AF00FE4F13 /* libjscocos2d Mac.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libjscocos2d Mac.a"; + remoteRef = C037820618BF76AF00FE4F13 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + C037820918BF76AF00FE4F13 /* libjscocos2d iOS.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libjscocos2d iOS.a"; + remoteRef = C037820818BF76AF00FE4F13 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; +/* End PBXReferenceProxy section */ + +/* Begin PBXResourcesBuildPhase section */ + 509D4A9317EBB24E00697056 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 1AC22EDE18CA0E11007112B9 /* project.json in Resources */, + 1AD7E0A918C9DBE3004817A6 /* main.js in Resources */, + C0799CBA18BAE62000E9C828 /* res in Resources */, + BAF426FC19484B3E002B22EF /* script in Resources */, + 509D4ACF17EBB2BE00697056 /* Icon.icns in Resources */, + C03780EC18BEE0E400FE4F13 /* src in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A922753B1517C094001B78AA /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + BAF426FB19484B3E002B22EF /* script in Resources */, + 1AE159EC18C9DF3600FCA372 /* project.json in Resources */, + 1AD7E0A818C9DB93004817A6 /* main.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 */, + 509D4AC017EBB2AB00697056 /* Icon-57.png in Resources */, + 5091731A17ECDF7A00D62437 /* Icon-29.png in Resources */, + C03780EB18BEE0E400FE4F13 /* src in Resources */, + 509D4AC617EBB2AB00697056 /* Icon-152.png in Resources */, + C0799CB918BAE62000E9C828 /* res in Resources */, + 509D4AC517EBB2AB00697056 /* Icon-144.png in Resources */, + 509D4AC317EBB2AB00697056 /* Icon-114.png in Resources */, + 509D4ABD17EBB2AB00697056 /* Default-568h@2x.png in Resources */, + 509D4ABF17EBB2AB00697056 /* Default@2x.png in Resources */, + 509D4AC217EBB2AB00697056 /* Icon-76.png in Resources */, + 5091731B17ECDF7A00D62437 /* Icon-40.png in Resources */, + 5091731C17ECDF7A00D62437 /* Icon-50.png in Resources */, + 509D4AC417EBB2AB00697056 /* Icon-120.png in Resources */, + 5091731D17ECDF7A00D62437 /* Icon-58.png in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 509D4A8017EBB24E00697056 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 509D4A8117EBB24E00697056 /* AppDelegate.cpp in Sources */, + C06E23CC18CEFE680093C81A /* main.cpp in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A92275391517C094001B78AA /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 509D4AC917EBB2AB00697056 /* RootViewController.mm in Sources */, + D4545227156E28EF00887EB5 /* AppDelegate.cpp in Sources */, + 509D4AC817EBB2AB00697056 /* main.m in Sources */, + 509D4ABC17EBB2AB00697056 /* AppController.mm in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 1A676820180E9BF70076BC67 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "cocos2dx Mac"; + targetProxy = 1A67681F180E9BF70076BC67 /* PBXContainerItemProxy */; + }; + 1A676822180E9BF70076BC67 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + 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 */; + }; + 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 */; + }; + C037820B18BF77BC00FE4F13 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "jsbindings iOS"; + targetProxy = C037820A18BF77BC00FE4F13 /* PBXContainerItemProxy */; + }; + C037820E18BF77D100FE4F13 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "jsbindings Mac"; + targetProxy = C037820D18BF77D100FE4F13 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 509D4AA817EBB24E00697056 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = YES; + ARCHS = "$(ARCHS_STANDARD_64_BIT)"; + COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; + GCC_DYNAMIC_NO_PIC = NO; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = mac/Prefix.pch; + GCC_PREPROCESSOR_DEFINITIONS = ( + CC_TARGET_OS_MAC, + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = YES; + HEADER_SEARCH_PATHS = ""; + INFOPLIST_FILE = mac/Info.plist; + LIBRARY_SEARCH_PATHS = ""; + OTHER_LDFLAGS = ""; + SDKROOT = macosx; + USER_HEADER_SEARCH_PATHS = "$(inherited) $(SRCROOT)/../../cocos2d-x/cocos/platform/mac $(SRCROOT)/../../cocos2d-x/external/glfw3/include/mac $(SRCROOT)/../../cocos2d-x/external/spidermonkey/include/mac"; + }; + name = Debug; + }; + 509D4AA917EBB24E00697056 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = YES; + ARCHS = "$(ARCHS_STANDARD_64_BIT)"; + COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; + GCC_GENERATE_DEBUGGING_SYMBOLS = NO; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = mac/Prefix.pch; + GCC_PREPROCESSOR_DEFINITIONS = ( + CC_TARGET_OS_MAC, + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = YES; + HEADER_SEARCH_PATHS = ""; + INFOPLIST_FILE = mac/Info.plist; + LIBRARY_SEARCH_PATHS = ""; + OTHER_LDFLAGS = ""; + SDKROOT = macosx; + USER_HEADER_SEARCH_PATHS = "$(inherited) $(SRCROOT)/../../cocos2d-x/cocos/platform/mac $(SRCROOT)/../../cocos2d-x/external/glfw3/include/mac $(SRCROOT)/../../cocos2d-x/external/spidermonkey/include/mac"; + }; + name = Release; + }; + A92276FE1517C097001B78AA /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_CXX_LANGUAGE_STANDARD = "c++0x"; + CLANG_CXX_LIBRARY = "libc++"; + COPY_PHASE_STRIP = NO; + GCC_C_LANGUAGE_STANDARD = c99; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "COCOS2D_DEBUG=1", + USE_FILE32API, + COCOS2D_JAVASCRIPT, + CC_ENABLE_CHIPMUNK_INTEGRATION, + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = ""; + IPHONEOS_DEPLOYMENT_TARGET = 5.1; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + USER_HEADER_SEARCH_PATHS = "$(SRCROOT)/../../cocos2d-x $(SRCROOT)/../../cocos2d-x/cocos $(SRCROOT)/../../cocos2d-x/cocos/base $(SRCROOT)/../../cocos2d-x/cocos/physics $(SRCROOT)/../../cocos2d-x/cocos/math/kazmath $(SRCROOT)/../../cocos2d-x/cocos/2d $(SRCROOT)/../../cocos2d-x/cocos/gui $(SRCROOT)/../../cocos2d-x/cocos/network $(SRCROOT)/../../cocos2d-x/cocos/audio/include $(SRCROOT)/../../cocos2d-x/cocos/editor-support $(SRCROOT)/../../cocos2d-x/extensions $(SRCROOT)/../../cocos2d-x/external $(SRCROOT)/../../cocos2d-x/external/chipmunk/include/chipmunk $(SRCROOT)/../../cocos2d-x/cocos/scripting/js-bindings/auto $(SRCROOT)/../../cocos2d-x/cocos/scripting/js-bindings/manual"; + }; + name = Debug; + }; + A92276FF1517C097001B78AA /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_CXX_LANGUAGE_STANDARD = "c++0x"; + CLANG_CXX_LIBRARY = "libc++"; + GCC_C_LANGUAGE_STANDARD = c99; + GCC_PREPROCESSOR_DEFINITIONS = ( + NDEBUG, + USE_FILE32API, + COCOS2D_JAVASCRIPT, + CC_ENABLE_CHIPMUNK_INTEGRATION, + ); + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + HEADER_SEARCH_PATHS = ""; + IPHONEOS_DEPLOYMENT_TARGET = 5.1; + OTHER_CFLAGS = "-DNS_BLOCK_ASSERTIONS=1"; + PRODUCT_NAME = "$(TARGET_NAME)"; + USER_HEADER_SEARCH_PATHS = "$(SRCROOT)/../../cocos2d-x $(SRCROOT)/../../cocos2d-x/cocos $(SRCROOT)/../../cocos2d-x/cocos/base $(SRCROOT)/../../cocos2d-x/cocos/physics $(SRCROOT)/../../cocos2d-x/cocos/math/kazmath $(SRCROOT)/../../cocos2d-x/cocos/2d $(SRCROOT)/../../cocos2d-x/cocos/gui $(SRCROOT)/../../cocos2d-x/cocos/network $(SRCROOT)/../../cocos2d-x/cocos/audio/include $(SRCROOT)/../../cocos2d-x/cocos/editor-support $(SRCROOT)/../../cocos2d-x/extensions $(SRCROOT)/../../cocos2d-x/external $(SRCROOT)/../../cocos2d-x/external/chipmunk/include/chipmunk $(SRCROOT)/../../cocos2d-x/cocos/scripting/js-bindings/auto $(SRCROOT)/../../cocos2d-x/cocos/scripting/js-bindings/manual"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + A92277011517C097001B78AA /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COMPRESS_PNG_FILES = NO; + GCC_DYNAMIC_NO_PIC = NO; + GCC_GENERATE_DEBUGGING_SYMBOLS = YES; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = ios/Prefix.pch; + GCC_PREPROCESSOR_DEFINITIONS = ( + CC_TARGET_OS_IPHONE, + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = YES; + HEADER_SEARCH_PATHS = ""; + INFOPLIST_FILE = ios/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 5.0; + LIBRARY_SEARCH_PATHS = ""; + OTHER_LDFLAGS = ""; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + USER_HEADER_SEARCH_PATHS = "$(inherited) $(SRCROOT)/../../cocos2d-x/cocos/platform/ios $(SRCROOT)/../../cocos2d-x/external/spidermonkey/include/ios $(SRCROOT)/../../cocos2d-x/plugin/jsbindings/auto $(SRCROOT)/../../cocos2d-x/plugin/jsbindings/manual"; + VALID_ARCHS = "arm64 armv7"; + }; + name = Debug; + }; + A92277021517C097001B78AA /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COMPRESS_PNG_FILES = NO; + GCC_GENERATE_DEBUGGING_SYMBOLS = NO; + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = ios/Prefix.pch; + GCC_PREPROCESSOR_DEFINITIONS = ( + CC_TARGET_OS_IPHONE, + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = YES; + HEADER_SEARCH_PATHS = ""; + INFOPLIST_FILE = ios/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 5.0; + LIBRARY_SEARCH_PATHS = ""; + OTHER_LDFLAGS = ""; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + USER_HEADER_SEARCH_PATHS = "$(inherited) $(SRCROOT)/../../cocos2d-x/cocos/platform/ios $(SRCROOT)/../../cocos2d-x/external/spidermonkey/include/ios $(SRCROOT)/../../cocos2d-x/plugin/jsbindings/auto $(SRCROOT)/../../cocos2d-x/plugin/jsbindings/manual"; + VALID_ARCHS = "arm64 armv7"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 509D4AA717EBB24E00697056 /* Build configuration list for PBXNativeTarget "HelloJavascript Mac" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 509D4AA817EBB24E00697056 /* Debug */, + 509D4AA917EBB24E00697056 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A92275371517C094001B78AA /* Build configuration list for PBXProject "HelloJavascript" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A92276FE1517C097001B78AA /* Debug */, + A92276FF1517C097001B78AA /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A92277001517C097001B78AA /* Build configuration list for PBXNativeTarget "HelloJavascript iOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A92277011517C097001B78AA /* Debug */, + A92277021517C097001B78AA /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = A92275341517C094001B78AA /* Project object */; +} diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.h b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.h new file mode 100644 index 0000000000..2e8186124e --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.h @@ -0,0 +1,35 @@ +/**************************************************************************** + Copyright (c) 2010-2013 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +@class RootViewController; + +@interface AppController : NSObject +{ + UIWindow *window; + RootViewController *viewController; +} + +@end + diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm new file mode 100644 index 0000000000..81f19ebcdd --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/AppController.mm @@ -0,0 +1,144 @@ +/**************************************************************************** + Copyright (c) 2010-2013 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +#import +#import "cocos2d.h" + +#import "AppController.h" +#import "AppDelegate.h" +#import "RootViewController.h" +#import "platform/ios/CCEAGLView-ios.h" + +@implementation AppController + +#pragma mark - +#pragma mark Application lifecycle + +// cocos2d application instance +static AppDelegate s_sharedApplication; + +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions +{ + + // Override point for customization after application launch. + + // Add the view controller's view to the window and display. + window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; + CCEAGLView *eaglView = [CCEAGLView viewWithFrame: [window bounds] + pixelFormat: kEAGLColorFormatRGBA8 + depthFormat: GL_DEPTH24_STENCIL8_OES + preserveBackbuffer: NO + sharegroup: nil + multiSampling: NO + numberOfSamples: 0 ]; + + [eaglView setMultipleTouchEnabled:YES]; + + // Use RootViewController manage CCEAGLView + viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil]; + viewController.wantsFullScreenLayout = YES; + viewController.view = eaglView; + + // Set RootViewController to window + if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) + { + // warning: addSubView doesn't work on iOS6 + [window addSubview: viewController.view]; + } + else + { + // use this method on ios6 + [window setRootViewController:viewController]; + } + + [window makeKeyAndVisible]; + + [[UIApplication sharedApplication] setStatusBarHidden: YES]; + + // IMPORTANT: Setting the GLView should be done after creating the RootViewController + cocos2d::GLView *glview = cocos2d::GLViewImpl::createWithEAGLView(eaglView); + cocos2d::Director::getInstance()->setOpenGLView(glview); + + cocos2d::Application::getInstance()->run(); + return YES; +} + + +- (void)applicationWillResignActive:(UIApplication *)application { + /* + Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. + */ + cocos2d::Director::getInstance()->pause(); +} + +- (void)applicationDidBecomeActive:(UIApplication *)application { + /* + Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + */ + cocos2d::Director::getInstance()->resume(); +} + +- (void)applicationDidEnterBackground:(UIApplication *)application { + /* + Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + If your application supports background execution, called instead of applicationWillTerminate: when the user quits. + */ + cocos2d::Application::getInstance()->applicationDidEnterBackground(); +} + +- (void)applicationWillEnterForeground:(UIApplication *)application { + /* + Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background. + */ + cocos2d::Application::getInstance()->applicationWillEnterForeground(); +} + +- (void)applicationWillTerminate:(UIApplication *)application { + /* + Called when the application is about to terminate. + See also applicationDidEnterBackground:. + */ +} + + +#pragma mark - +#pragma mark Memory management + +- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { + /* + Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. + */ + cocos2d::Director::getInstance()->purgeCachedData(); +} + + +- (void)dealloc { + [super dealloc]; +} + + +@end + diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Default-568h@2x.png b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Default-568h@2x.png new file mode 100644 index 0000000000..66c6d1cead Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Default-568h@2x.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Default.png b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Default.png new file mode 100644 index 0000000000..dcb80725de Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Default.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Default@2x.png b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Default@2x.png new file mode 100644 index 0000000000..84689888a1 Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Default@2x.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-100.png b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-100.png new file mode 100644 index 0000000000..ef38d4500a Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-100.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-114.png b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-114.png new file mode 100644 index 0000000000..c3807861ad Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-114.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-120.png b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-120.png new file mode 100644 index 0000000000..a5b49ccbb1 Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-120.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-144.png b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-144.png new file mode 100644 index 0000000000..1526615c02 Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-144.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-152.png b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-152.png new file mode 100644 index 0000000000..8aa82506d0 Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-152.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-29.png b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-29.png new file mode 100644 index 0000000000..0500184c86 Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-29.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-40.png b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-40.png new file mode 100644 index 0000000000..775685daca Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-40.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-50.png b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-50.png new file mode 100644 index 0000000000..ac381bc20e Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-50.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-57.png b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-57.png new file mode 100644 index 0000000000..4fcc6fddff Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-57.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-58.png b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-58.png new file mode 100644 index 0000000000..f0f8b7fe98 Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-58.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-72.png b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-72.png new file mode 100644 index 0000000000..2c573c8df4 Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-72.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-76.png b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-76.png new file mode 100644 index 0000000000..8a1fa1850c Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-76.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-80.png b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-80.png new file mode 100644 index 0000000000..d9c7ab446b Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Icon-80.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Info.plist b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Info.plist new file mode 100644 index 0000000000..59405f5dce --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Info.plist @@ -0,0 +1,98 @@ + + + + + CFBundleDevelopmentRegion + English + CFBundleDisplayName + ${PRODUCT_NAME} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIconFiles + + Icon.png + Icon@2x.png + Icon-72.png + Icon-144.png + Icon-57.png + Icon-114.png + + CFBundleIcons + + CFBundlePrimaryIcon + + CFBundleIconFiles + + Icon-80 + Icon-58 + Icon-29 + Icon-120 + Icon-72.png + Icon.png + Icon@2x.png + Icon-57.png + Icon-114.png + Icon-144.png + + UIPrerenderedIcon + + + + CFBundleIcons~ipad + + CFBundlePrimaryIcon + + CFBundleIconFiles + + Icon-58 + Icon-29 + Icon-80 + Icon-40 + Icon-100 + Icon-50 + Icon-152 + Icon-76 + Icon-120 + Icon-72.png + Icon.png + Icon@2x.png + Icon-57.png + Icon-114.png + Icon-144.png + + UIPrerenderedIcon + + + + CFBundleIdentifier + org.cocos2dx.hellojavascript + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + APPL + CFBundleSignature + ???? + CFBundleVersion + 1.0 + LSRequiresIPhoneOS + + UIPrerenderedIcon + + UIRequiredDeviceCapabilities + + accelerometer + + opengles-1 + + + UIStatusBarHidden + + UISupportedInterfaceOrientations + + UIInterfaceOrientationLandscapeRight + UIInterfaceOrientationLandscapeLeft + + + diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Prefix.pch b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Prefix.pch new file mode 100644 index 0000000000..168ddec406 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Prefix.pch @@ -0,0 +1,8 @@ +// +// Prefix header for all source files of the 'HelloJavascript' target in the 'HelloJavascript' project +// + +#ifdef __OBJC__ + #import + #import +#endif diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.h b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.h new file mode 100644 index 0000000000..11dfc4bf88 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.h @@ -0,0 +1,33 @@ +/**************************************************************************** + Copyright (c) 2010-2011 cocos2d-x.org + Copyright (c) 2010 Ricardo Quesada + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#import + + +@interface RootViewController : UIViewController { + +} +- (BOOL)prefersStatusBarHidden; +@end diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.mm b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.mm new file mode 100644 index 0000000000..2074ad8e6e --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/RootViewController.mm @@ -0,0 +1,113 @@ +/**************************************************************************** + Copyright (c) 2010-2011 cocos2d-x.org + Copyright (c) 2010 Ricardo Quesada + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#import "RootViewController.h" +#import "cocos2d.h" +#import "platform/ios/CCEAGLView-ios.h" + +@implementation RootViewController + +/* + // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. +- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { + if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { + // Custom initialization + } + return self; +} +*/ + +/* +// Implement loadView to create a view hierarchy programmatically, without using a nib. +- (void)loadView { +} +*/ + +/* +// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. +- (void)viewDidLoad { + [super viewDidLoad]; +} + +*/ +// Override to allow orientations other than the default portrait orientation. +// This method is deprecated on ios6 +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { + return UIInterfaceOrientationIsLandscape( interfaceOrientation ); +} + +// For ios6, use supportedInterfaceOrientations & shouldAutorotate instead +- (NSUInteger) supportedInterfaceOrientations{ +#ifdef __IPHONE_6_0 + return UIInterfaceOrientationMaskAllButUpsideDown; +#endif +} + +- (BOOL) shouldAutorotate { + return YES; +} + +- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { + [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; + + cocos2d::GLView *glview = cocos2d::Director::getInstance()->getOpenGLView(); + if (glview) + { + cocos2d::CCEGLView *eaglview = (cocos2d::CCEGLView*) glview->getEAGLView(); + + if (eaglview) + { + CGSize s = CGSizeMake([eaglview getWidth], [eaglview getHeight]); + cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height); + } + } +} + +//fix not hide status on ios7 +- (BOOL)prefersStatusBarHidden +{ + return YES; +} + +- (void)didReceiveMemoryWarning { + // Releases the view if it doesn't have a superview. + [super didReceiveMemoryWarning]; + + // Release any cached data, images, etc that aren't in use. +} + +- (void)viewDidUnload { + [super viewDidUnload]; + // Release any retained subviews of the main view. + // e.g. self.myOutlet = nil; +} + + +- (void)dealloc { + [super dealloc]; +} + + +@end diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/main.m b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/main.m new file mode 100644 index 0000000000..b1286e31be --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/main.m @@ -0,0 +1,11 @@ + + +#import + +int main(int argc, char *argv[]) { + + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + int retVal = UIApplicationMain(argc, argv, nil, @"AppController"); + [pool release]; + return retVal; +} diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/mac/Icon.icns b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/mac/Icon.icns new file mode 100644 index 0000000000..2040fc6fe6 Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/mac/Icon.icns differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/mac/Info.plist b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/mac/Info.plist new file mode 100644 index 0000000000..aa22263424 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/mac/Info.plist @@ -0,0 +1,36 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIconFile + Icon + CFBundleIdentifier + org.cocos2dx.hellojavascript + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + LSApplicationCategoryType + public.app-category.games + LSMinimumSystemVersion + ${MACOSX_DEPLOYMENT_TARGET} + NSHumanReadableCopyright + Copyright © 2013. All rights reserved. + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/mac/Prefix.pch b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/mac/Prefix.pch new file mode 100644 index 0000000000..46c36a7e99 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/mac/Prefix.pch @@ -0,0 +1,7 @@ +// +// Prefix header for all source files of the 'Paralaxer' target in the 'Paralaxer' project +// + +#ifdef __OBJC__ + #import +#endif diff --git a/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/mac/main.cpp b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/mac/main.cpp new file mode 100644 index 0000000000..96f027e13d --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/mac/main.cpp @@ -0,0 +1,34 @@ +/**************************************************************************** + 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 "AppDelegate.h" +#include "cocos2d.h" + +USING_NS_CC; + +int main(int argc, char *argv[]) +{ + AppDelegate app; + return Application::getInstance()->run(); +} diff --git a/templates/js-template-default/frameworks/runtime-src/proj.linux/main.cpp b/templates/js-template-default/frameworks/runtime-src/proj.linux/main.cpp new file mode 100644 index 0000000000..e236a953b3 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.linux/main.cpp @@ -0,0 +1,10 @@ +#include "../Classes/AppDelegate.h" + +USING_NS_CC; + +int main(int argc, char **argv) +{ + // create the application instance + AppDelegate app; + return Application::getInstance()->run(); +} diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win32/HelloJavascript.sln b/templates/js-template-default/frameworks/runtime-src/proj.win32/HelloJavascript.sln new file mode 100644 index 0000000000..03074bfac7 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win32/HelloJavascript.sln @@ -0,0 +1,54 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloJavascript", "HelloJavascript.vcxproj", "{3B0B58B1-2734-488E-A542-ECEC11EB2455}" + ProjectSection(ProjectDependencies) = postProject + {39379840-825A-45A0-B363-C09FFEF864BD} = {39379840-825A-45A0-B363-C09FFEF864BD} + {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} = {98A51BA8-FC3A-415B-AC8F-8C7BD464E93E} + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "External", "External", "{8C6B0381-B325-4D7F-B1BB-474ABACE46AC}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libSpine", "..\..\cocos2d-x\cocos\editor-support\spine\proj.win32\libSpine.vcxproj", "{B7C2A162-DEC9-4418-972E-240AB3CBFCAE}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libbox2d", "..\..\cocos2d-x\external\Box2D\proj.win32\libbox2d.vcxproj", "{929480E7-23C0-4DF6-8456-096D71547116}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d", "..\..\cocos2d-x\cocos\2d\libcocos2d.vcxproj", "{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libjscocos2d", "..\..\cocos2d-x\cocos\scripting\js-bindings\proj.win32\libjscocos2d.vcxproj", "{39379840-825A-45A0-B363-C09FFEF864BD}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {3B0B58B1-2734-488E-A542-ECEC11EB2455}.Debug|Win32.ActiveCfg = Debug|Win32 + {3B0B58B1-2734-488E-A542-ECEC11EB2455}.Debug|Win32.Build.0 = Debug|Win32 + {3B0B58B1-2734-488E-A542-ECEC11EB2455}.Release|Win32.ActiveCfg = Release|Win32 + {3B0B58B1-2734-488E-A542-ECEC11EB2455}.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 + {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 + {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 + {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 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {B7C2A162-DEC9-4418-972E-240AB3CBFCAE} = {8C6B0381-B325-4D7F-B1BB-474ABACE46AC} + {929480E7-23C0-4DF6-8456-096D71547116} = {8C6B0381-B325-4D7F-B1BB-474ABACE46AC} + EndGlobalSection +EndGlobal diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win32/HelloJavascript.vcxproj b/templates/js-template-default/frameworks/runtime-src/proj.win32/HelloJavascript.vcxproj new file mode 100644 index 0000000000..3c1e1d1fd1 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win32/HelloJavascript.vcxproj @@ -0,0 +1,202 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + {3B0B58B1-2734-488E-A542-ECEC11EB2455} + HelloJavascript + + + + Application + Unicode + v100 + v110 + v110_xp + v120 + v120_xp + + + Application + Unicode + v100 + v110 + v110_xp + v120 + v120_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) + + + + _DEBUG;%(PreprocessorDefinitions) + false + Win32 + true + $(IntDir)game.tlb + game.h + + + game_i.c + game_p.c + + + Disabled + $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\base;$(EngineRoot)cocos\storage;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\js-bindings\auto;$(EngineRoot)cocos\scripting\js-bindings\manual;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) + WIN32;_WINDOWS;STRICT;_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 + MultiThreadedDebugDLL + + + Level3 + EditAndContinue + 4267;4251;4244;4800;%(DisableSpecificWarnings) + true + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(IntDir);%(AdditionalIncludeDirectories) + + + if not exist "$(OutDir)" mkdir "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\cocos2d-x\external\spidermonkey\prebuilt\win32\debug-build\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\cocos2d-x\external\websockets\prebuilt\win32\*.*" "$(OutDir)" + + + libcurl_imp.lib;mozjs-33.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) + $(OutDir);%(AdditionalLibraryDirectories) + true + Windows + MachineX86 + + + xcopy "$(ProjectDir)..\..\cocos2d-x\cocos\scripting\js-bindings\script" "$(OutDir)\script" /D /E /I /F /Y +xcopy "$(ProjectDir)..\..\..\src" "$(OutDir)\src" /D /E /I /F /Y +xcopy "$(ProjectDir)..\..\..\res" "$(OutDir)\res" /D /E /I /F /Y +copy "$(ProjectDir)..\..\..\main.js" "$(OutDir)\" /Y +copy "$(ProjectDir)..\..\..\project.json" "$(OutDir)\" /Y + + + Copy js and resource files. + + + + + NDEBUG;%(PreprocessorDefinitions) + false + Win32 + true + $(IntDir)game.tlb + game.h + + + game_i.c + game_p.c + + + $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\base;$(EngineRoot)cocos\storage;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\js-bindings\auto;$(EngineRoot)cocos\scripting\js-bindings\manual;$(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) + + + MultiThreadedDLL + + + Level3 + + + 4267;4251;4244;4800;%(DisableSpecificWarnings) + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(IntDir);%(AdditionalIncludeDirectories) + + + if not exist "$(OutDir)" mkdir "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\cocos2d-x\external\spidermonkey\prebuilt\win32\release-build\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\cocos2d-x\external\websockets\prebuilt\win32\*.*" "$(OutDir)" + + + libcurl_imp.lib;mozjs-33.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) + $(OutDir);%(AdditionalLibraryDirectories) + Windows + MachineX86 + true + + + xcopy "$(ProjectDir)..\..\cocos2d-x\cocos\scripting\js-bindings\script" "$(OutDir)\script" /D /E /I /F /Y +xcopy "$(ProjectDir)..\..\..\src" "$(OutDir)\src" /D /E /I /F /Y +xcopy "$(ProjectDir)..\..\..\res" "$(OutDir)\res" /D /E /I /F /Y +copy "$(ProjectDir)..\..\..\main.js" "$(OutDir)\" /Y +copy "$(ProjectDir)..\..\..\project.json" "$(OutDir)\" /Y + Copy js and resource files. + + + + + + + + + + + + + + + + + + + + {39379840-825a-45a0-b363-c09ffef864bd} + + + + + + diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win32/HelloJavascript.vcxproj.filters b/templates/js-template-default/frameworks/runtime-src/proj.win32/HelloJavascript.vcxproj.filters new file mode 100644 index 0000000000..75ce9f53fa --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win32/HelloJavascript.vcxproj.filters @@ -0,0 +1,42 @@ + + + + + {ca9c9e15-d942-43a1-aa7a-5f0b74ca1afd} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;jpg;jpeg;jpe;png;manifest + + + {ccb2323b-1cfa-41ea-bcf4-ba5f07309396} + + + {e93a77e1-af1e-4400-87d3-504b62ebdbb0} + + + + + win32 + + + Classes + + + + + Classes + + + win32 + + + + + + resource + + + + + resource + + + \ No newline at end of file diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win32/HelloJavascript.vcxproj.user b/templates/js-template-default/frameworks/runtime-src/proj.win32/HelloJavascript.vcxproj.user new file mode 100644 index 0000000000..bc2c507e26 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win32/HelloJavascript.vcxproj.user @@ -0,0 +1,11 @@ + + + + $(OutDir) + WindowsLocalDebugger + + + $(OutDir) + WindowsLocalDebugger + + \ No newline at end of file diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win32/build-cfg.json b/templates/js-template-default/frameworks/runtime-src/proj.win32/build-cfg.json new file mode 100644 index 0000000000..3aa9a0268e --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win32/build-cfg.json @@ -0,0 +1,24 @@ +{ + "copy_resources": [ + { + "from": "../../../src", + "to": "src" + }, + { + "from": "../../../res", + "to": "res" + }, + { + "from": "../../../main.js", + "to": "" + }, + { + "from": "../../../project.json", + "to": "" + }, + { + "from": "../../cocos2d-x/cocos/scripting/js-bindings/script", + "to": "script" + } + ] +} diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win32/game.rc b/templates/js-template-default/frameworks/runtime-src/proj.win32/game.rc new file mode 100644 index 0000000000..e2df7906f7 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win32/game.rc @@ -0,0 +1,127 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// Chinese (Simplified, PRC) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHS) +LANGUAGE LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED +#pragma code_page(936) + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + +#endif // Chinese (Simplified, PRC) resources +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +GLFW_ICON ICON "res\\game.ico" + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,0,0,1 + PRODUCTVERSION 1,0,0,1 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904B0" + BEGIN + VALUE "FileDescription", "game Module" + VALUE "FileVersion", "1, 0, 0, 1" + VALUE "InternalName", "game" + VALUE "LegalCopyright", "Copyright " + VALUE "OriginalFilename", "game.exe" + VALUE "ProductName", "game Module" + VALUE "ProductVersion", "1, 0, 0, 1" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win32/main.cpp b/templates/js-template-default/frameworks/runtime-src/proj.win32/main.cpp new file mode 100644 index 0000000000..69c3b8c9bb --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win32/main.cpp @@ -0,0 +1,33 @@ +#include "main.h" +#include "AppDelegate.h" + +USING_NS_CC; + +// uncomment below line, open debug console +// #define USE_WIN32_CONSOLE + +int APIENTRY _tWinMain(HINSTANCE hInstance, + HINSTANCE hPrevInstance, + LPTSTR lpCmdLine, + int nCmdShow) +{ + UNREFERENCED_PARAMETER(hPrevInstance); + UNREFERENCED_PARAMETER(lpCmdLine); + +#ifdef USE_WIN32_CONSOLE + AllocConsole(); + freopen("CONIN$", "r", stdin); + freopen("CONOUT$", "w", stdout); + freopen("CONOUT$", "w", stderr); +#endif + + // create the application instance + AppDelegate app; + int ret = Application::getInstance()->run(); + +#ifdef USE_WIN32_CONSOLE + FreeConsole(); +#endif + + return ret; +} diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win32/main.h b/templates/js-template-default/frameworks/runtime-src/proj.win32/main.h new file mode 100644 index 0000000000..e29aeedb3a --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win32/main.h @@ -0,0 +1,12 @@ +#ifndef __MAIN_H__ +#define __MAIN_H__ + +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers + +// Windows Header Files: +#include + +// C RunTime Header Files +#include "CCStdC.h" + +#endif // __WINMAIN_H__ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win32/res/game.ico b/templates/js-template-default/frameworks/runtime-src/proj.win32/res/game.ico new file mode 100644 index 0000000000..feaf932a74 Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.win32/res/game.ico differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win32/resource.h b/templates/js-template-default/frameworks/runtime-src/proj.win32/resource.h new file mode 100644 index 0000000000..920119022a --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win32/resource.h @@ -0,0 +1,17 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by game.rc +// +#define IDS_PROJNAME 100 +#define IDR_TESTJS 100 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 204 +#define _APS_NEXT_COMMAND_VALUE 32785 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/App.xaml b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/App.xaml new file mode 100644 index 0000000000..2da0ff79d0 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/App.xaml @@ -0,0 +1,13 @@ + + + + + cpp_tests + + + diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/App.xaml.cpp b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/App.xaml.cpp new file mode 100644 index 0000000000..f4365b88c5 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/App.xaml.cpp @@ -0,0 +1,21 @@ +#include "App.xaml.h" +#include "OpenGLESPage.xaml.h" + +using namespace cocos2d; + +App::App() +{ + InitializeComponent(); +} + +void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e) +{ + if (mPage == nullptr) + { + mPage = ref new OpenGLESPage(&mOpenGLES); + } + + // Place the page in the current window and ensure that it is active. + Windows::UI::Xaml::Window::Current->Content = mPage; + Windows::UI::Xaml::Window::Current->Activate(); +} diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/App.xaml.h b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/App.xaml.h new file mode 100644 index 0000000000..1309c610d7 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/App.xaml.h @@ -0,0 +1,19 @@ +#pragma once + +#include "app.g.h" +#include "OpenGLES.h" +#include "openglespage.xaml.h" + +namespace cocos2d +{ + ref class App sealed + { + public: + App(); + virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e) override; + + private: + OpenGLESPage^ mPage; + OpenGLES mOpenGLES; + }; +} diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/Cocos2dRenderer.cpp b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/Cocos2dRenderer.cpp new file mode 100644 index 0000000000..ea6d3b68c9 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/Cocos2dRenderer.cpp @@ -0,0 +1,143 @@ +/* +* cocos2d-x http://www.cocos2d-x.org +* +* Copyright (c) 2010-2014 - cocos2d-x community +* +* Portions Copyright (c) Microsoft Open Technologies, Inc. +* All Rights Reserved +* +* 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 "Cocos2dRenderer.h" +#include "AppDelegate.h" +#include "CCGLViewImpl-winrt.h" +#include "CCApplication.h" +#include "cocos2d.h" +#include "renderer/CCTextureCache.h" + +// These are used by the shader compilation methods. +#include +#include +#include + +using namespace Platform; +using namespace Windows::UI::Core; +using namespace Windows::UI::Xaml::Controls; +using namespace Windows::Graphics::Display; + +USING_NS_CC; + + +Cocos2dRenderer::Cocos2dRenderer(int width, int height, float dpi, DisplayOrientations orientation, CoreDispatcher^ dispatcher, Panel^ panel) + : m_app(nullptr) + , m_width(width) + , m_height(height) + , m_dpi(dpi) + , m_dispatcher(dispatcher) + , m_panel(panel) + , m_orientation(orientation) +{ + m_app = new AppDelegate(); +} + +Cocos2dRenderer::~Cocos2dRenderer() +{ + delete m_app; +} + +void Cocos2dRenderer::Resume() +{ + auto director = cocos2d::Director::getInstance(); + auto glview = director->getOpenGLView(); + + if (!glview) + { + GLViewImpl* glview = GLViewImpl::create("Test Cpp"); + glview->setDispatcher(m_dispatcher.Get()); + glview->setPanel(m_panel.Get()); + glview->Create(static_cast(m_width), static_cast(m_height), m_dpi, m_orientation); + director->setOpenGLView(glview); + CCApplication::getInstance()->run(); + } + else + { + Application::getInstance()->applicationWillEnterForeground(); + } +} + +void Cocos2dRenderer::Pause() +{ + if (Director::getInstance()->getOpenGLView()) { + Application::getInstance()->applicationDidEnterBackground(); + //cocos2d::EventCustom backgroundEvent(EVENT_COME_TO_BACKGROUND); + //cocos2d::Director::getInstance()->getEventDispatcher()->dispatchEvent(&backgroundEvent); + } +} + +void Cocos2dRenderer::DeviceLost() +{ + Pause(); + + auto director = cocos2d::Director::getInstance(); + if (director->getOpenGLView()) { + cocos2d::GL::invalidateStateCache(); + cocos2d::GLProgramCache::getInstance()->reloadDefaultGLPrograms(); + cocos2d::DrawPrimitives::init(); + cocos2d::VolatileTextureMgr::reloadAllTextures(); + + cocos2d::EventCustom recreatedEvent(EVENT_RENDERER_RECREATED); + director->getEventDispatcher()->dispatchEvent(&recreatedEvent); + director->setGLDefaultValues(); + + Application::getInstance()->applicationWillEnterForeground(); + cocos2d::EventCustom foregroundEvent(EVENT_COME_TO_FOREGROUND); + cocos2d::Director::getInstance()->getEventDispatcher()->dispatchEvent(&foregroundEvent); + } +} + + + +void Cocos2dRenderer::Draw(GLsizei width, GLsizei height, float dpi, DisplayOrientations orientation) +{ + if (orientation != m_orientation) + { + m_orientation = orientation; + GLViewImpl::sharedOpenGLView()->UpdateOrientation(orientation); + } + + if (width != m_width || height != m_height) + { + m_width = width; + m_height = height; + GLViewImpl::sharedOpenGLView()->UpdateForWindowSizeChange(static_cast(width), static_cast(height)); + } + + if (dpi != m_dpi) + { + m_dpi = dpi; + GLViewImpl::sharedOpenGLView()->SetDPI(m_dpi); + } + + GLViewImpl::sharedOpenGLView()->ProcessEvents(); + GLViewImpl::sharedOpenGLView()->Render(); +} + +void Cocos2dRenderer::QueuePointerEvent(cocos2d::PointerEventType type, Windows::UI::Core::PointerEventArgs^ args) +{ + GLViewImpl::sharedOpenGLView()->QueuePointerEvent(type, args); +} + +void Cocos2dRenderer::QueueKeyBoardEvent(cocos2d::Cocos2dKeyEvent type, Windows::UI::Core::KeyEventArgs^ e) +{ + //GLViewImpl::sharedOpenGLView()->QueuePointerEvent(type, e); +} + + diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/Cocos2dRenderer.h b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/Cocos2dRenderer.h new file mode 100644 index 0000000000..e38e69ce19 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/Cocos2dRenderer.h @@ -0,0 +1,55 @@ +/* +* cocos2d-x http://www.cocos2d-x.org +* +* Copyright (c) 2010-2014 - cocos2d-x community +* +* Portions Copyright (c) Microsoft Open Technologies, Inc. +* All Rights Reserved +* +* 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. +*/ +#pragma once + +#include + +#include "cocos2d.h" + + +class AppDelegate; + +namespace cocos2d +{ + class Cocos2dRenderer + { + public: + Cocos2dRenderer(int width, int height, float dpi, + Windows::Graphics::Display::DisplayOrientations orientation, + Windows::UI::Core::CoreDispatcher^ dispathcer, Windows::UI::Xaml::Controls::Panel^ panel); + ~Cocos2dRenderer(); + void Draw(GLsizei width, GLsizei height, float dpi, Windows::Graphics::Display::DisplayOrientations orientation); + void QueuePointerEvent(PointerEventType type, Windows::UI::Core::PointerEventArgs^ args); + void QueueKeyBoardEvent(Cocos2dKeyEvent type, Windows::UI::Core::KeyEventArgs^ e); + void Pause(); + void Resume(); + void DeviceLost(); + + private: + + int m_width; + int m_height; + float m_dpi; + + // The AppDelegate for the Cocos2D app + AppDelegate* m_app; + Platform::Agile m_dispatcher; + Platform::Agile m_panel; + Windows::Graphics::Display::DisplayOrientations m_orientation; + }; +} \ No newline at end of file diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/HelloJavascript.Shared.vcxitems b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/HelloJavascript.Shared.vcxitems new file mode 100644 index 0000000000..57fe321d30 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/HelloJavascript.Shared.vcxitems @@ -0,0 +1,59 @@ + + + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + true + e956c24b-f04e-47bf-bf00-746681ae1301 + {a3ad93e4-0b2f-4c58-9181-69bed2e42e3e} + HelloJavascript + + + + %(AdditionalIncludeDirectories);$(MSBuildThisFileDirectory) + + + + + Designer + + + + $(MSBuildThisFileDirectory)App.xaml + + + + + $(MSBuildThisFileDirectory)OpenGLESPage.xaml + + + + $(MSBuildThisFileDirectory)App.xaml + + + Create + + + + $(MSBuildThisFileDirectory)OpenGLESPage.xaml + + + + + + + + <_CustomResource Include="$(MSBuildThisFileDirectory)..\..\Resources\**\*"> + Assets\Resources\%(RecursiveDir)%(FileName)%(Extension) + true + + + + + + + + + + + + \ No newline at end of file diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/HelloJavascript.Shared.vcxitems.filters b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/HelloJavascript.Shared.vcxitems.filters new file mode 100644 index 0000000000..328a801eb8 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/HelloJavascript.Shared.vcxitems.filters @@ -0,0 +1,33 @@ + + + + + + + + + + + + Classes + + + + + + + + {38ad799c-8c3c-44a2-8e41-516c8f62f556} + + + + + + + Classes + + + + + + \ No newline at end of file diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/OpenGLES.cpp b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/OpenGLES.cpp new file mode 100644 index 0000000000..c375a709e7 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/OpenGLES.cpp @@ -0,0 +1,239 @@ +/* +* cocos2d-x http://www.cocos2d-x.org +* +* Copyright (c) 2010-2014 - cocos2d-x community +* +* Portions Copyright (c) Microsoft Open Technologies, Inc. +* All Rights Reserved +* +* 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 "OpenGLES.h" +using namespace Platform; +using namespace Windows::UI::Xaml::Controls; +using namespace Windows::Foundation; +using namespace Windows::Foundation::Collections; + +OpenGLES::OpenGLES() : + mEglConfig(nullptr), + mEglDisplay(EGL_NO_DISPLAY), + mEglContext(EGL_NO_CONTEXT) +{ + Initialize(); +} + +OpenGLES::~OpenGLES() +{ + Cleanup(); +} + +void OpenGLES::Initialize() +{ + const EGLint configAttributes[] = + { + EGL_RED_SIZE, 8, + EGL_GREEN_SIZE, 8, + EGL_BLUE_SIZE, 8, + EGL_ALPHA_SIZE, 8, + EGL_DEPTH_SIZE, 8, + EGL_STENCIL_SIZE, 8, + EGL_NONE + }; + + const EGLint contextAttributes[] = + { + EGL_CONTEXT_CLIENT_VERSION, 2, + EGL_NONE + }; + + const EGLint defaultDisplayAttributes[] = + { + // These are the default display attributes, used to request ANGLE's D3D11 renderer. + // eglInitialize will only succeed with these attributes if the hardware supports D3D11 Feature Level 10_0+. + EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, + + // EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER is an optimization that can have large performance benefits on mobile devices. + // Its syntax is subject to change, though. Please update your Visual Studio templates if you experience compilation issues with it. + EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER, EGL_TRUE, + EGL_NONE, + }; + + const EGLint fl9_3DisplayAttributes[] = + { + // These can be used to request ANGLE's D3D11 renderer, with D3D11 Feature Level 9_3. + // These attributes are used if the call to eglInitialize fails with the default display attributes. + EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, + EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, 9, + EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE, 3, + EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER, EGL_TRUE, + EGL_NONE, + }; + + const EGLint warpDisplayAttributes[] = + { + // These attributes can be used to request D3D11 WARP. + // They are used if eglInitialize fails with both the default display attributes and the 9_3 display attributes. + EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, + EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_DEVICE_TYPE_WARP_ANGLE, + EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER, EGL_TRUE, + EGL_NONE, + }; + + EGLConfig config = NULL; + + // eglGetPlatformDisplayEXT is an alternative to eglGetDisplay. It allows us to pass in display attributes, used to configure D3D11. + PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = reinterpret_cast(eglGetProcAddress("eglGetPlatformDisplayEXT")); + if (!eglGetPlatformDisplayEXT) + { + throw Exception::CreateException(E_FAIL, L"Failed to get function eglGetPlatformDisplayEXT"); + } + + // + // To initialize the display, we make three sets of calls to eglGetPlatformDisplayEXT and eglInitialize, with varying + // parameters passed to eglGetPlatformDisplayEXT: + // 1) The first calls uses "defaultDisplayAttributes" as a parameter. This corresponds to D3D11 Feature Level 10_0+. + // 2) If eglInitialize fails for step 1 (e.g. because 10_0+ isn't supported by the default GPU), then we try again + // using "fl9_3DisplayAttributes". This corresponds to D3D11 Feature Level 9_3. + // 3) If eglInitialize fails for step 2 (e.g. because 9_3+ isn't supported by the default GPU), then we try again + // using "warpDisplayAttributes". This corresponds to D3D11 Feature Level 11_0 on WARP, a D3D11 software rasterizer. + // + // Note: On Windows Phone, we #ifdef out the first set of calls to eglPlatformDisplayEXT and eglInitialize. + // Windows Phones devices only support D3D11 Feature Level 9_3, but the Windows Phone emulator supports 11_0+. + // We use this #ifdef to limit the Phone emulator to Feature Level 9_3, making it behave more like + // real Windows Phone devices. + // If you wish to test Feature Level 10_0+ in the Windows Phone emulator then you should remove this #ifdef. + // + +#if (WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP) + // This tries to initialize EGL to D3D11 Feature Level 10_0+. See above comment for details. + mEglDisplay = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, EGL_DEFAULT_DISPLAY, defaultDisplayAttributes); + if (mEglDisplay == EGL_NO_DISPLAY) + { + throw Exception::CreateException(E_FAIL, L"Failed to get EGL display"); + } + + if (eglInitialize(mEglDisplay, NULL, NULL) == EGL_FALSE) +#endif + { + // This tries to initialize EGL to D3D11 Feature Level 9_3, if 10_0+ is unavailable (e.g. on Windows Phone, or certain Windows tablets). + mEglDisplay = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, EGL_DEFAULT_DISPLAY, fl9_3DisplayAttributes); + if (mEglDisplay == EGL_NO_DISPLAY) + { + throw Exception::CreateException(E_FAIL, L"Failed to get EGL display"); + } + + if (eglInitialize(mEglDisplay, NULL, NULL) == EGL_FALSE) + { + // This initializes EGL to D3D11 Feature Level 11_0 on WARP, if 9_3+ is unavailable on the default GPU (e.g. on Surface RT). + mEglDisplay = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, EGL_DEFAULT_DISPLAY, warpDisplayAttributes); + if (mEglDisplay == EGL_NO_DISPLAY) + { + throw Exception::CreateException(E_FAIL, L"Failed to get EGL display"); + } + + if (eglInitialize(mEglDisplay, NULL, NULL) == EGL_FALSE) + { + // If all of the calls to eglInitialize returned EGL_FALSE then an error has occurred. + throw Exception::CreateException(E_FAIL, L"Failed to initialize EGL"); + } + } + } + + EGLint numConfigs = 0; + if ((eglChooseConfig(mEglDisplay, configAttributes, &mEglConfig, 1, &numConfigs) == EGL_FALSE) || (numConfigs == 0)) + { + throw Exception::CreateException(E_FAIL, L"Failed to choose first EGLConfig"); + } + + mEglContext = eglCreateContext(mEglDisplay, mEglConfig, EGL_NO_CONTEXT, contextAttributes); + if (mEglContext == EGL_NO_CONTEXT) + { + throw Exception::CreateException(E_FAIL, L"Failed to create EGL context"); + } +} + +void OpenGLES::Cleanup() +{ + if (mEglDisplay != EGL_NO_DISPLAY && mEglContext != EGL_NO_CONTEXT) + { + eglDestroyContext(mEglDisplay, mEglContext); + mEglContext = EGL_NO_CONTEXT; + } + + if (mEglDisplay != EGL_NO_DISPLAY) + { + eglTerminate(mEglDisplay); + mEglDisplay = EGL_NO_DISPLAY; + } +} + +void OpenGLES::Reset() +{ + Cleanup(); + Initialize(); +} + +EGLSurface OpenGLES::CreateSurface(SwapChainPanel^ panel, const Size* renderSurfaceSize) +{ + if (!panel) + { + throw Exception::CreateException(E_INVALIDARG, L"SwapChainPanel parameter is invalid"); + } + + EGLSurface surface = EGL_NO_SURFACE; + + const EGLint surfaceAttributes[] = + { + // EGL_ANGLE_SURFACE_RENDER_TO_BACK_BUFFER is part of the same optimization as EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER (see above). + // If you have compilation issues with it then please update your Visual Studio templates. + EGL_ANGLE_SURFACE_RENDER_TO_BACK_BUFFER, EGL_TRUE, + EGL_NONE + }; + + // Create a PropertySet and initialize with the EGLNativeWindowType. + PropertySet^ surfaceCreationProperties = ref new PropertySet(); + surfaceCreationProperties->Insert(ref new String(EGLNativeWindowTypeProperty), panel); + + // If a render surface size is specified, add it to the surface creation properties + if (renderSurfaceSize != nullptr) + { + surfaceCreationProperties->Insert(ref new String(EGLRenderSurfaceSizeProperty), PropertyValue::CreateSize(*renderSurfaceSize)); + } + + surface = eglCreateWindowSurface(mEglDisplay, mEglConfig, reinterpret_cast(surfaceCreationProperties), surfaceAttributes); + if (surface == EGL_NO_SURFACE) + { + throw Exception::CreateException(E_FAIL, L"Failed to create EGL surface"); + } + + return surface; +} + +void OpenGLES::DestroySurface(const EGLSurface surface) +{ + if (mEglDisplay != EGL_NO_DISPLAY && surface != EGL_NO_SURFACE) + { + eglDestroySurface(mEglDisplay, surface); + } +} + +void OpenGLES::MakeCurrent(const EGLSurface surface) +{ + if (eglMakeCurrent(mEglDisplay, surface, surface, mEglContext) == EGL_FALSE) + { + throw Exception::CreateException(E_FAIL, L"Failed to make EGLSurface current"); + } +} + +EGLBoolean OpenGLES::SwapBuffers(const EGLSurface surface) +{ + return (eglSwapBuffers(mEglDisplay, surface)); +} diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/OpenGLES.h b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/OpenGLES.h new file mode 100644 index 0000000000..1a57b68739 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/OpenGLES.h @@ -0,0 +1,51 @@ +/* +* cocos2d-x http://www.cocos2d-x.org +* +* Copyright (c) 2010-2014 - cocos2d-x community +* +* Portions Copyright (c) Microsoft Open Technologies, Inc. +* All Rights Reserved +* +* 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. +*/ + +#pragma once + +// OpenGL ES includes +#include +#include + +// EGL includes +#include +#include +#include +#include + +class OpenGLES +{ +public: + OpenGLES(); + ~OpenGLES(); + + EGLSurface CreateSurface(Windows::UI::Xaml::Controls::SwapChainPanel^ panel, const Windows::Foundation::Size* renderSurfaceSize); + void DestroySurface(const EGLSurface surface); + void MakeCurrent(const EGLSurface surface); + EGLBoolean SwapBuffers(const EGLSurface surface); + void Reset(); + +private: + void Initialize(); + void Cleanup(); + +private: + EGLDisplay mEglDisplay; + EGLContext mEglContext; + EGLConfig mEglConfig; +}; diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/OpenGLESPage.xaml b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/OpenGLESPage.xaml new file mode 100644 index 0000000000..e5b62802a5 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/OpenGLESPage.xaml @@ -0,0 +1,28 @@ + + + + + + + + + + + diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/OpenGLESPage.xaml.cpp b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/OpenGLESPage.xaml.cpp new file mode 100644 index 0000000000..352507ec3e --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/OpenGLESPage.xaml.cpp @@ -0,0 +1,313 @@ +/* +* cocos2d-x http://www.cocos2d-x.org +* +* Copyright (c) 2010-2014 - cocos2d-x community +* +* Portions Copyright (c) Microsoft Open Technologies, Inc. +* All Rights Reserved +* +* 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 "App.xaml.h" +#include "OpenGLESPage.xaml.h" + +using namespace cocos2d; +using namespace Platform; +using namespace Concurrency; +using namespace Windows::Foundation; +using namespace Windows::Foundation::Collections; +using namespace Windows::Graphics::Display; +using namespace Windows::System::Threading; +using namespace Windows::UI::Core; +using namespace Windows::UI::Input; +using namespace Windows::UI::Xaml; +using namespace Windows::UI::Xaml::Controls; +using namespace Windows::UI::Xaml::Controls::Primitives; +using namespace Windows::UI::Xaml::Data; +using namespace Windows::UI::Xaml::Input; +using namespace Windows::UI::Xaml::Media; +using namespace Windows::UI::Xaml::Navigation; + +OpenGLESPage::OpenGLESPage() : + OpenGLESPage(nullptr) +{ + +} + +OpenGLESPage::OpenGLESPage(OpenGLES* openGLES) : + mOpenGLES(openGLES), + mRenderSurface(EGL_NO_SURFACE), + mCustomRenderSurfaceSize(0,0), + mUseCustomRenderSurfaceSize(false), + m_coreInput(nullptr), + m_dpi(0.0f), + m_deviceLost(false), + m_orientation(DisplayOrientations::Landscape) +{ + InitializeComponent(); + + Windows::UI::Core::CoreWindow^ window = Windows::UI::Xaml::Window::Current->CoreWindow; + + window->VisibilityChanged += + ref new Windows::Foundation::TypedEventHandler(this, &OpenGLESPage::OnVisibilityChanged); + + swapChainPanel->SizeChanged += + ref new Windows::UI::Xaml::SizeChangedEventHandler(this, &OpenGLESPage::OnSwapChainPanelSizeChanged); + + DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView(); + + currentDisplayInformation->OrientationChanged += + ref new TypedEventHandler(this, &OpenGLESPage::OnOrientationChanged); + + m_orientation = currentDisplayInformation->CurrentOrientation; + + this->Loaded += + ref new Windows::UI::Xaml::RoutedEventHandler(this, &OpenGLESPage::OnPageLoaded); + + mSwapChainPanelSize = { swapChainPanel->RenderSize.Width, swapChainPanel->RenderSize.Height }; + +#if (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) + Windows::UI::ViewManagement::StatusBar::GetForCurrentView()->HideAsync(); +#else + // Disable all pointer visual feedback for better performance when touching. + // This is not supported on Windows Phone applications. + auto pointerVisualizationSettings = Windows::UI::Input::PointerVisualizationSettings::GetForCurrentView(); + pointerVisualizationSettings->IsContactFeedbackEnabled = false; + pointerVisualizationSettings->IsBarrelButtonFeedbackEnabled = false; +#endif + + // Register our SwapChainPanel to get independent input pointer events + auto workItemHandler = ref new WorkItemHandler([this](IAsyncAction ^) + { + // The CoreIndependentInputSource will raise pointer events for the specified device types on whichever thread it's created on. + m_coreInput = swapChainPanel->CreateCoreIndependentInputSource( + Windows::UI::Core::CoreInputDeviceTypes::Mouse | + Windows::UI::Core::CoreInputDeviceTypes::Touch | + Windows::UI::Core::CoreInputDeviceTypes::Pen + ); + + // Register for pointer events, which will be raised on the background thread. + m_coreInput->PointerPressed += ref new TypedEventHandler(this, &OpenGLESPage::OnPointerPressed); + m_coreInput->PointerMoved += ref new TypedEventHandler(this, &OpenGLESPage::OnPointerMoved); + m_coreInput->PointerReleased += ref new TypedEventHandler(this, &OpenGLESPage::OnPointerReleased); + + // Begin processing input messages as they're delivered. + m_coreInput->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit); + }); + + // Run task on a dedicated high priority background thread. + m_inputLoopWorker = ThreadPool::RunAsync(workItemHandler, WorkItemPriority::High, WorkItemOptions::TimeSliced); + +} + +OpenGLESPage::~OpenGLESPage() +{ + StopRenderLoop(); + DestroyRenderSurface(); +} + +void OpenGLESPage::OnPageLoaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) +{ + // The SwapChainPanel has been created and arranged in the page layout, so EGL can be initialized. + CreateRenderSurface(); + StartRenderLoop(); +} + +void OpenGLESPage::OnPointerPressed(Object^ sender, PointerEventArgs^ e) +{ + if (m_renderer) + { + m_renderer->QueuePointerEvent(PointerEventType::PointerPressed, e); + } +} + +void OpenGLESPage::OnPointerMoved(Object^ sender, PointerEventArgs^ e) +{ + if (m_renderer) + { + m_renderer->QueuePointerEvent(PointerEventType::PointerMoved, e); + } +} + +void OpenGLESPage::OnPointerReleased(Object^ sender, PointerEventArgs^ e) +{ + if (m_renderer) + { + m_renderer->QueuePointerEvent(PointerEventType::PointerReleased, e); + } +} + +void OpenGLESPage::OnOrientationChanged(DisplayInformation^ sender, Object^ args) +{ + critical_section::scoped_lock lock(mSwapChainPanelSizeCriticalSection); + m_orientation = sender->CurrentOrientation; +} + +void OpenGLESPage::OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args) +{ + if (args->Visible && mRenderSurface != EGL_NO_SURFACE) + { + StartRenderLoop(); + } + else + { + StopRenderLoop(); + } +} + +void OpenGLESPage::OnSwapChainPanelSizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e) +{ + // Size change events occur outside of the render thread. A lock is required when updating + // the swapchainpanel size + critical_section::scoped_lock lock(mSwapChainPanelSizeCriticalSection); + mSwapChainPanelSize = { e->NewSize.Width, e->NewSize.Height }; +} + +void OpenGLESPage::GetSwapChainPanelSize(GLsizei* width, GLsizei* height) +{ + critical_section::scoped_lock lock(mSwapChainPanelSizeCriticalSection); + // If a custom render surface size is specified, return its size instead of + // the swapchain panel size. + if (mUseCustomRenderSurfaceSize) + { + *width = static_cast(mCustomRenderSurfaceSize.Width); + *height = static_cast(mCustomRenderSurfaceSize.Height); + } + else + { + *width = static_cast(mSwapChainPanelSize.Width); + *height = static_cast(mSwapChainPanelSize.Height); + } +} + +void OpenGLESPage::CreateRenderSurface() +{ + if (mOpenGLES) + { + // + // A Custom render surface size can be specified by uncommenting the following lines. + // The render surface will be automatically scaled to fit the entire window. Using a + // smaller sized render surface can result in a performance gain. + // + //mCustomRenderSurfaceSize = Size(800, 600); + //mUseCustomRenderSurfaceSize = true; + + mRenderSurface = mOpenGLES->CreateSurface(swapChainPanel, mUseCustomRenderSurfaceSize ? &mCustomRenderSurfaceSize : nullptr); + } +} + +void OpenGLESPage::DestroyRenderSurface() +{ + if (mOpenGLES) + { + mOpenGLES->DestroySurface(mRenderSurface); + } + mRenderSurface = EGL_NO_SURFACE; +} + +void OpenGLESPage::RecoverFromLostDevice() +{ + // Stop the render loop, reset OpenGLES, recreate the render surface + // and start the render loop again to recover from a lost device. + + StopRenderLoop(); + + { + critical_section::scoped_lock lock(mRenderSurfaceCriticalSection); + DestroyRenderSurface(); + mOpenGLES->Reset(); + CreateRenderSurface(); + } + + StartRenderLoop(); +} + +void OpenGLESPage::StartRenderLoop() +{ + // If the render loop is already running then do not start another thread. + if (mRenderLoopWorker != nullptr && mRenderLoopWorker->Status == Windows::Foundation::AsyncStatus::Started) + { + return; + } + + DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView(); + m_dpi = currentDisplayInformation->LogicalDpi; + + auto dispatcher = Windows::UI::Xaml::Window::Current->CoreWindow->Dispatcher; + + // Create a task for rendering that will be run on a background thread. + auto workItemHandler = ref new Windows::System::Threading::WorkItemHandler([this, dispatcher](Windows::Foundation::IAsyncAction ^ action) + { + critical_section::scoped_lock lock(mRenderSurfaceCriticalSection); + + mOpenGLES->MakeCurrent(mRenderSurface); + + GLsizei panelWidth = 0; + GLsizei panelHeight = 0; + GetSwapChainPanelSize(&panelWidth, &panelHeight); + + + + if (m_renderer.get() == nullptr) + { + m_renderer = std::make_shared(panelWidth, panelHeight, m_dpi, m_orientation, dispatcher, swapChainPanel); + } + + if (m_deviceLost) + { + m_deviceLost = false; + m_renderer->DeviceLost(); + } + else + { + m_renderer->Resume(); + } + + + while (action->Status == Windows::Foundation::AsyncStatus::Started && !m_deviceLost) + { + GetSwapChainPanelSize(&panelWidth, &panelHeight); + m_renderer.get()->Draw(panelWidth, panelHeight, m_dpi, m_orientation); + + // The call to eglSwapBuffers might not be successful (i.e. due to Device Lost) + // If the call fails, then we must reinitialize EGL and the GL resources. + if (mOpenGLES->SwapBuffers(mRenderSurface) != GL_TRUE) + { + m_deviceLost = true; + + // XAML objects like the SwapChainPanel must only be manipulated on the UI thread. + swapChainPanel->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([=]() + { + RecoverFromLostDevice(); + }, CallbackContext::Any)); + + return; + } + } + }); + + // Run task on a dedicated high priority background thread. + mRenderLoopWorker = Windows::System::Threading::ThreadPool::RunAsync(workItemHandler, Windows::System::Threading::WorkItemPriority::High, Windows::System::Threading::WorkItemOptions::TimeSliced); +} + +void OpenGLESPage::StopRenderLoop() +{ + if (mRenderLoopWorker) + { + mRenderLoopWorker->Cancel(); + mRenderLoopWorker = nullptr; + } + + if (m_renderer) + { + m_renderer->Pause(); + } +} \ No newline at end of file diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/OpenGLESPage.xaml.h b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/OpenGLESPage.xaml.h new file mode 100644 index 0000000000..7bf8e75cb9 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/OpenGLESPage.xaml.h @@ -0,0 +1,78 @@ +/* +* cocos2d-x http://www.cocos2d-x.org +* +* Copyright (c) 2010-2014 - cocos2d-x community +* +* Portions Copyright (c) Microsoft Open Technologies, Inc. +* All Rights Reserved +* +* 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. +*/ + +#pragma once + +#include "OpenGLES.h" +#include "OpenGLESPage.g.h" +#include + +#include "Cocos2dRenderer.h" + +namespace cocos2d +{ + public ref class OpenGLESPage sealed + { + public: + OpenGLESPage(); + virtual ~OpenGLESPage(); + + internal: + OpenGLESPage(OpenGLES* openGLES); + + private: + void OnPageLoaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); + void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args); + void OnSwapChainPanelSizeChanged(Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e); + void GetSwapChainPanelSize(GLsizei* width, GLsizei* height); + void CreateRenderSurface(); + void DestroyRenderSurface(); + void RecoverFromLostDevice(); + void StartRenderLoop(); + void StopRenderLoop(); + + OpenGLES* mOpenGLES; + std::shared_ptr m_renderer; + + Windows::Foundation::Size mSwapChainPanelSize; + Concurrency::critical_section mSwapChainPanelSizeCriticalSection; + + Windows::Foundation::Size mCustomRenderSurfaceSize; + bool mUseCustomRenderSurfaceSize; + + EGLSurface mRenderSurface; // This surface is associated with a swapChainPanel on the page + Concurrency::critical_section mRenderSurfaceCriticalSection; + Windows::Foundation::IAsyncAction^ mRenderLoopWorker; + + // Track user input on a background worker thread. + Windows::Foundation::IAsyncAction^ m_inputLoopWorker; + Windows::UI::Core::CoreIndependentInputSource^ m_coreInput; + + // Independent input handling functions. + void OnPointerPressed(Platform::Object^ sender, Windows::UI::Core::PointerEventArgs^ e); + void OnPointerMoved(Platform::Object^ sender, Windows::UI::Core::PointerEventArgs^ e); + void OnPointerReleased(Platform::Object^ sender, Windows::UI::Core::PointerEventArgs^ e); + + void OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args); + + float m_dpi; + bool m_deviceLost; + Windows::Graphics::Display::DisplayOrientations m_orientation; + + }; +} diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/pch.cpp b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/pch.cpp new file mode 100644 index 0000000000..bcb5590be1 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/pch.cpp @@ -0,0 +1 @@ +#include "pch.h" diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/pch.h b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/pch.h new file mode 100644 index 0000000000..8c399a075d --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Shared/pch.h @@ -0,0 +1,13 @@ +// +// pch.h +// Header for standard system include files. +// + +#pragma once + +#include "mozilla\Char16.h" +#include "cocos2d.h" +#include "cocos-ext.h" + + + diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/Assets/Logo.scale-100.png b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/Assets/Logo.scale-100.png new file mode 100644 index 0000000000..e26771cb33 Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/Assets/Logo.scale-100.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/Assets/SmallLogo.scale-100.png b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/Assets/SmallLogo.scale-100.png new file mode 100644 index 0000000000..1eb0d9d528 Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/Assets/SmallLogo.scale-100.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/Assets/SplashScreen.scale-100.png b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/Assets/SplashScreen.scale-100.png new file mode 100644 index 0000000000..d8ded7198a Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/Assets/SplashScreen.scale-100.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/Assets/StoreLogo.scale-100.png b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/Assets/StoreLogo.scale-100.png new file mode 100644 index 0000000000..dcb672712c Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/Assets/StoreLogo.scale-100.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/HelloJavascript.Windows.vcxproj b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/HelloJavascript.Windows.vcxproj new file mode 100644 index 0000000000..26f8cbeafb --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/HelloJavascript.Windows.vcxproj @@ -0,0 +1,201 @@ + + + + + Debug + ARM + + + Debug + Win32 + + + Debug + x64 + + + Release + ARM + + + Release + Win32 + + + Release + x64 + + + + {79a8fcda-4b12-4dd1-b676-ff148d651638} + cocos2d + en-US + 12.0 + true + Windows Store + 8.1 + + + + Application + true + v120 + + + Application + true + v120 + + + Application + true + v120 + + + Application + false + true + v120 + + + Application + false + true + v120 + + + Application + false + true + v120 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TemporaryKey.pfx + True + x86 + + + + /bigobj /Zm200 %(AdditionalOptions) + 4453;28204;4756;%(DisableSpecificWarnings) + pch.h + $(ProjectDir)..\..\Classes;%(AdditionalIncludeDirectories) + false + + + + + /bigobj /Zm200 %(AdditionalOptions) + 4453;28204;4756;%(DisableSpecificWarnings) + pch.h + $(ProjectDir)..\..\Classes;%(AdditionalIncludeDirectories) + false + + + + + /bigobj /Zm200 %(AdditionalOptions) + 4453;28204;4756;%(DisableSpecificWarnings) + pch.h + $(ProjectDir)..\..\Classes;%(AdditionalIncludeDirectories) + false + + + + + /bigobj /Zm200 %(AdditionalOptions) + 4453;28204;4756;%(DisableSpecificWarnings) + pch.h + $(ProjectDir)..\..\Classes;%(AdditionalIncludeDirectories) + false + + + + + /bigobj /Zm200 %(AdditionalOptions) + 4453;28204;4756;%(DisableSpecificWarnings) + pch.h + $(ProjectDir)..\..\Classes;%(AdditionalIncludeDirectories) + false + + + + + /bigobj /Zm200 %(AdditionalOptions) + 4453;28204;4756;%(DisableSpecificWarnings) + pch.h + $(ProjectDir)..\..\Classes;%(AdditionalIncludeDirectories) + false + + + + + Designer + + + + + + + + + + + + {bcf5546d-66a0-4998-afd6-c5514f618930} + + + {9335005f-678e-4e8e-9b84-50037216aec8} + + + {f3550fe0-c795-44f6-8feb-093eb68143ae} + + + {3b26a12d-3a44-47ea-82d2-282660fc844d} + + + + + + diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/HelloJavascript.Windows.vcxproj.filters b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/HelloJavascript.Windows.vcxproj.filters new file mode 100644 index 0000000000..bf2fa53b3c --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/HelloJavascript.Windows.vcxproj.filters @@ -0,0 +1,29 @@ + + + + + {1a9fa652-867e-41d2-8588-962f108d2d8f} + bmp;fbx;gif;jpg;jpeg;tga;tiff;tif;png + + + + + + + + + + + Assets + + + Assets + + + Assets + + + Assets + + + \ No newline at end of file diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/Package.appxmanifest b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/Package.appxmanifest new file mode 100644 index 0000000000..e22abcc6f9 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/Package.appxmanifest @@ -0,0 +1,30 @@ + + + + + HelloJavascript.Windows + dalestam + Assets\StoreLogo.png + + + 6.3.0 + 6.3.0 + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/TemporaryKey.pfx b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/TemporaryKey.pfx new file mode 100644 index 0000000000..5ad010651a Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.Windows/TemporaryKey.pfx differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Assets/Logo.scale-240.png b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Assets/Logo.scale-240.png new file mode 100644 index 0000000000..76921ca997 Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Assets/Logo.scale-240.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Assets/SmallLogo.scale-240.png b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Assets/SmallLogo.scale-240.png new file mode 100644 index 0000000000..316630124f Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Assets/SmallLogo.scale-240.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Assets/SplashScreen.scale-240.png b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Assets/SplashScreen.scale-240.png new file mode 100644 index 0000000000..b0b6bc08e5 Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Assets/SplashScreen.scale-240.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Assets/Square71x71Logo.scale-240.png b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Assets/Square71x71Logo.scale-240.png new file mode 100644 index 0000000000..cfa54bee03 Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Assets/Square71x71Logo.scale-240.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Assets/StoreLogo.scale-240.png b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Assets/StoreLogo.scale-240.png new file mode 100644 index 0000000000..47e084b593 Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Assets/StoreLogo.scale-240.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Assets/WideLogo.scale-240.png b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Assets/WideLogo.scale-240.png new file mode 100644 index 0000000000..6249d29db0 Binary files /dev/null and b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Assets/WideLogo.scale-240.png differ diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/HelloJavascript.WindowsPhone.vcxproj b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/HelloJavascript.WindowsPhone.vcxproj new file mode 100644 index 0000000000..d0b374b373 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/HelloJavascript.WindowsPhone.vcxproj @@ -0,0 +1,151 @@ + + + + + Debug + ARM + + + Debug + Win32 + + + Release + ARM + + + Release + Win32 + + + + {396fe85e-bb05-4b92-bccb-f89aed4ea41a} + cocos2d + en-US + 12.0 + true + Windows Phone + 8.1 + + + + Application + true + v120_wp81 + + + Application + true + v120_wp81 + + + Application + false + true + v120_wp81 + + + Application + false + true + v120_wp81 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + True + arm + + + + /bigobj /Zm200 %(AdditionalOptions) + 4453;28204;4756;%(DisableSpecificWarnings) + pch.h + $(ProjectDir)..\..\Classes;%(AdditionalIncludeDirectories) + false + + + + + /bigobj /Zm200 %(AdditionalOptions) + 4453;28204;4756;%(DisableSpecificWarnings) + pch.h + $(ProjectDir)..\..\Classes;%(AdditionalIncludeDirectories) + false + + + + + /bigobj /Zm200 %(AdditionalOptions) + 4453;28204;4756;%(DisableSpecificWarnings) + pch.h + $(ProjectDir)..\..\Classes;%(AdditionalIncludeDirectories) + false + + + + + /bigobj /Zm200 %(AdditionalOptions) + 4453;28204;4756;%(DisableSpecificWarnings) + pch.h + $(ProjectDir)..\..\Classes;%(AdditionalIncludeDirectories) + false + + + + + Designer + + + + + + + + + + + + + {ca082ec4-17ce-430b-8207-d1e947a5d1e9} + + + {22f3b9df-1209-4574-8331-003966f562bf} + + + {cc1da216-a80d-4be4-b309-acb6af313aff} + + + {22f798d8-bfff-4754-996f-a5395343d5ec} + + + + + + diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/HelloJavascript.WindowsPhone.vcxproj.filters b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/HelloJavascript.WindowsPhone.vcxproj.filters new file mode 100644 index 0000000000..eb71f325ca --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/HelloJavascript.WindowsPhone.vcxproj.filters @@ -0,0 +1,30 @@ + + + + + {c8beb60d-689b-4aaa-9749-99bd3e2dcf75} + bmp;fbx;gif;jpg;jpeg;tga;tiff;tif;png + + + Assets + + + Assets + + + Assets + + + Assets + + + Assets + + + Assets + + + + + + \ No newline at end of file diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Package.appxmanifest b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Package.appxmanifest new file mode 100644 index 0000000000..3f0809f393 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/App.WindowsPhone/Package.appxmanifest @@ -0,0 +1,33 @@ + + + + + + HelloJavascript.WindowsPhone + dalestam + Assets\StoreLogo.png + + + 6.3.1 + 6.3.1 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/HelloJavascript.sln b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/HelloJavascript.sln new file mode 100644 index 0000000000..fb1b307993 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/HelloJavascript.sln @@ -0,0 +1,217 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2013 +VisualStudioVersion = 12.0.31101.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "HelloJavascript", "HelloJavascript", "{36AFDE04-D127-4D84-9730-D84E3E51EAA7}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloJavascript.Shared", "App.Shared\HelloJavascript.Shared.vcxitems", "{A3AD93E4-0B2F-4C58-9181-69BED2E42E3E}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloJavascript.Windows", "App.Windows\HelloJavascript.Windows.vcxproj", "{79A8FCDA-4B12-4DD1-B676-FF148D651638}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloJavascript.WindowsPhone", "App.WindowsPhone\HelloJavascript.WindowsPhone.vcxproj", "{396FE85E-BB05-4B92-BCCB-F89AED4EA41A}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "libcocos2d", "libcocos2d", "{80DA05C1-6532-4D2A-8606-EF02079B1373}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "External", "External", "{F13CB4F7-BEE5-4368-A815-A971797387D8}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "libbox2d", "libbox2d", "{626C3EB8-F53B-41D0-BEA8-44EACAA1228C}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "libSpine", "libSpine", "{D0E32B77-3B4F-44F8-AEBC-12EE8BBF1783}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libbox2d.Shared", "..\..\cocos2d-x\external\Box2D\proj.win8.1-universal\libbox2d.Shared\libbox2d.Shared.vcxitems", "{4A3C6BA8-C227-498B-AA21-40BDA27B461F}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libbox2d.Windows", "..\..\cocos2d-x\external\Box2D\proj.win8.1-universal\libbox2d.Windows\libbox2d.Windows.vcxproj", "{3B26A12D-3A44-47EA-82D2-282660FC844D}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libbox2d.WindowsPhone", "..\..\cocos2d-x\external\Box2D\proj.win8.1-universal\libbox2d.WindowsPhone\libbox2d.WindowsPhone.vcxproj", "{22F798D8-BFFF-4754-996F-A5395343D5EC}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libSpine.Shared", "..\..\cocos2d-x\cocos\editor-support\spine\proj.win8.1-universal\libSpine.Shared\libSpine.Shared.vcxitems", "{ADAFD00D-A0D6-46EF-9F0B-EA2880BFE1DE}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libSpine.Windows", "..\..\cocos2d-x\cocos\editor-support\spine\proj.win8.1-universal\libSpine.Windows\libSpine.Windows.vcxproj", "{F3550FE0-C795-44F6-8FEB-093EB68143AE}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libSpine.WindowsPhone", "..\..\cocos2d-x\cocos\editor-support\spine\proj.win8.1-universal\libSpine.WindowsPhone\libSpine.WindowsPhone.vcxproj", "{CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d_8_1.Shared", "..\..\cocos2d-x\cocos\2d\libcocos2d_8_1\libcocos2d_8_1\libcocos2d_8_1.Shared\libcocos2d_8_1.Shared.vcxitems", "{5D6F020F-7E72-4494-90A0-2DF11D235DF9}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d_8_1.Windows", "..\..\cocos2d-x\cocos\2d\libcocos2d_8_1\libcocos2d_8_1\libcocos2d_8_1.Windows\libcocos2d_8_1.Windows.vcxproj", "{9335005F-678E-4E8E-9B84-50037216AEC8}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d_8_1.WindowsPhone", "..\..\cocos2d-x\cocos\2d\libcocos2d_8_1\libcocos2d_8_1\libcocos2d_8_1.WindowsPhone\libcocos2d_8_1.WindowsPhone.vcxproj", "{22F3B9DF-1209-4574-8331-003966F562BF}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "libjscocos2d", "libjscocos2d", "{FCB0EDBB-7A20-48D0-926B-E5617D40E6E5}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libjscocos2d.Shared", "..\..\cocos2d-x\cocos\scripting\js-bindings\proj.win8.1-universal\libjscocos2d\libjscocos2d.Shared\libjscocos2d.Shared.vcxitems", "{BEA66276-51DD-4C53-92A8-F3D1FEA50892}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libjscocos2d.Windows", "..\..\cocos2d-x\cocos\scripting\js-bindings\proj.win8.1-universal\libjscocos2d\libjscocos2d.Windows\libjscocos2d.Windows.vcxproj", "{BCF5546D-66A0-4998-AFD6-C5514F618930}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libjscocos2d.WindowsPhone", "..\..\cocos2d-x\cocos\scripting\js-bindings\proj.win8.1-universal\libjscocos2d\libjscocos2d.WindowsPhone\libjscocos2d.WindowsPhone.vcxproj", "{CA082EC4-17CE-430B-8207-D1E947A5D1E9}" +EndProject +Global + GlobalSection(SharedMSBuildProjectFiles) = preSolution + ..\..\cocos2d-x\cocos\2d\libcocos2d_8_1\libcocos2d_8_1\libcocos2d_8_1.Shared\libcocos2d_8_1.Shared.vcxitems*{9335005f-678e-4e8e-9b84-50037216aec8}*SharedItemsImports = 4 + App.Shared\HelloJavascript.Shared.vcxitems*{a3ad93e4-0b2f-4c58-9181-69bed2e42e3e}*SharedItemsImports = 9 + ..\..\cocos2d-x\cocos\editor-support\spine\proj.win8.1-universal\libSpine.Shared\libSpine.Shared.vcxitems*{cc1da216-a80d-4be4-b309-acb6af313aff}*SharedItemsImports = 4 + ..\..\cocos2d-x\external\Box2D\proj.win8.1-universal\libbox2d.Shared\libbox2d.Shared.vcxitems*{4a3c6ba8-c227-498b-aa21-40bda27b461f}*SharedItemsImports = 9 + App.Shared\HelloJavascript.Shared.vcxitems*{79a8fcda-4b12-4dd1-b676-ff148d651638}*SharedItemsImports = 4 + ..\..\cocos2d-x\cocos\editor-support\spine\proj.win8.1-universal\libSpine.Shared\libSpine.Shared.vcxitems*{adafd00d-a0d6-46ef-9f0b-ea2880bfe1de}*SharedItemsImports = 9 + ..\..\cocos2d-x\cocos\scripting\js-bindings\proj.win8.1-universal\libjscocos2d\libjscocos2d.Shared\libjscocos2d.Shared.vcxitems*{ca082ec4-17ce-430b-8207-d1e947a5d1e9}*SharedItemsImports = 4 + ..\..\cocos2d-x\cocos\2d\libcocos2d_8_1\libcocos2d_8_1\libcocos2d_8_1.Shared\libcocos2d_8_1.Shared.vcxitems*{5d6f020f-7e72-4494-90a0-2df11d235df9}*SharedItemsImports = 9 + ..\..\cocos2d-x\cocos\scripting\js-bindings\proj.win8.1-universal\libjscocos2d\libjscocos2d.Shared\libjscocos2d.Shared.vcxitems*{bea66276-51dd-4c53-92a8-f3d1fea50892}*SharedItemsImports = 9 + ..\..\cocos2d-x\cocos\scripting\js-bindings\proj.win8.1-universal\libjscocos2d\libjscocos2d.Shared\libjscocos2d.Shared.vcxitems*{bcf5546d-66a0-4998-afd6-c5514f618930}*SharedItemsImports = 4 + ..\..\cocos2d-x\external\Box2D\proj.win8.1-universal\libbox2d.Shared\libbox2d.Shared.vcxitems*{3b26a12d-3a44-47ea-82d2-282660fc844d}*SharedItemsImports = 4 + ..\..\cocos2d-x\cocos\2d\libcocos2d_8_1\libcocos2d_8_1\libcocos2d_8_1.Shared\libcocos2d_8_1.Shared.vcxitems*{22f3b9df-1209-4574-8331-003966f562bf}*SharedItemsImports = 4 + ..\..\cocos2d-x\external\Box2D\proj.win8.1-universal\libbox2d.Shared\libbox2d.Shared.vcxitems*{22f798d8-bfff-4754-996f-a5395343d5ec}*SharedItemsImports = 4 + ..\..\cocos2d-x\cocos\editor-support\spine\proj.win8.1-universal\libSpine.Shared\libSpine.Shared.vcxitems*{f3550fe0-c795-44f6-8feb-093eb68143ae}*SharedItemsImports = 4 + App.Shared\HelloJavascript.Shared.vcxitems*{396fe85e-bb05-4b92-bccb-f89aed4ea41a}*SharedItemsImports = 4 + EndGlobalSection + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|ARM = Debug|ARM + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|ARM = Release|ARM + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Debug|ARM.ActiveCfg = Debug|ARM + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Debug|ARM.Build.0 = Debug|ARM + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Debug|ARM.Deploy.0 = Debug|ARM + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Debug|Win32.ActiveCfg = Debug|Win32 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Debug|Win32.Build.0 = Debug|Win32 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Debug|Win32.Deploy.0 = Debug|Win32 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Debug|x64.ActiveCfg = Debug|x64 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Debug|x64.Build.0 = Debug|x64 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Debug|x64.Deploy.0 = Debug|x64 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Release|ARM.ActiveCfg = Release|ARM + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Release|ARM.Build.0 = Release|ARM + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Release|ARM.Deploy.0 = Release|ARM + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Release|Win32.ActiveCfg = Release|Win32 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Release|Win32.Build.0 = Release|Win32 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Release|Win32.Deploy.0 = Release|Win32 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Release|x64.ActiveCfg = Release|x64 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Release|x64.Build.0 = Release|x64 + {79A8FCDA-4B12-4DD1-B676-FF148D651638}.Release|x64.Deploy.0 = Release|x64 + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Debug|ARM.ActiveCfg = Debug|ARM + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Debug|ARM.Build.0 = Debug|ARM + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Debug|ARM.Deploy.0 = Debug|ARM + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Debug|Win32.ActiveCfg = Debug|Win32 + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Debug|Win32.Build.0 = Debug|Win32 + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Debug|Win32.Deploy.0 = Debug|Win32 + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Debug|x64.ActiveCfg = Debug|Win32 + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Release|ARM.ActiveCfg = Release|ARM + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Release|ARM.Build.0 = Release|ARM + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Release|ARM.Deploy.0 = Release|ARM + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Release|Win32.ActiveCfg = Release|Win32 + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Release|Win32.Build.0 = Release|Win32 + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Release|Win32.Deploy.0 = Release|Win32 + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A}.Release|x64.ActiveCfg = Release|Win32 + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Debug|ARM.ActiveCfg = Debug|ARM + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Debug|ARM.Build.0 = Debug|ARM + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Debug|Win32.ActiveCfg = Debug|Win32 + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Debug|Win32.Build.0 = Debug|Win32 + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Debug|x64.ActiveCfg = Debug|x64 + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Debug|x64.Build.0 = Debug|x64 + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Release|ARM.ActiveCfg = Release|ARM + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Release|ARM.Build.0 = Release|ARM + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Release|Win32.ActiveCfg = Release|Win32 + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Release|Win32.Build.0 = Release|Win32 + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Release|x64.ActiveCfg = Release|x64 + {3B26A12D-3A44-47EA-82D2-282660FC844D}.Release|x64.Build.0 = Release|x64 + {22F798D8-BFFF-4754-996F-A5395343D5EC}.Debug|ARM.ActiveCfg = Debug|ARM + {22F798D8-BFFF-4754-996F-A5395343D5EC}.Debug|ARM.Build.0 = Debug|ARM + {22F798D8-BFFF-4754-996F-A5395343D5EC}.Debug|Win32.ActiveCfg = Debug|Win32 + {22F798D8-BFFF-4754-996F-A5395343D5EC}.Debug|Win32.Build.0 = Debug|Win32 + {22F798D8-BFFF-4754-996F-A5395343D5EC}.Debug|x64.ActiveCfg = Debug|Win32 + {22F798D8-BFFF-4754-996F-A5395343D5EC}.Release|ARM.ActiveCfg = Release|ARM + {22F798D8-BFFF-4754-996F-A5395343D5EC}.Release|ARM.Build.0 = Release|ARM + {22F798D8-BFFF-4754-996F-A5395343D5EC}.Release|Win32.ActiveCfg = Release|Win32 + {22F798D8-BFFF-4754-996F-A5395343D5EC}.Release|Win32.Build.0 = Release|Win32 + {22F798D8-BFFF-4754-996F-A5395343D5EC}.Release|x64.ActiveCfg = Release|Win32 + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Debug|ARM.ActiveCfg = Debug|ARM + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Debug|ARM.Build.0 = Debug|ARM + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Debug|Win32.ActiveCfg = Debug|Win32 + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Debug|Win32.Build.0 = Debug|Win32 + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Debug|x64.ActiveCfg = Debug|x64 + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Debug|x64.Build.0 = Debug|x64 + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Release|ARM.ActiveCfg = Release|ARM + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Release|ARM.Build.0 = Release|ARM + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Release|Win32.ActiveCfg = Release|Win32 + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Release|Win32.Build.0 = Release|Win32 + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Release|x64.ActiveCfg = Release|x64 + {F3550FE0-C795-44F6-8FEB-093EB68143AE}.Release|x64.Build.0 = Release|x64 + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}.Debug|ARM.ActiveCfg = Debug|ARM + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}.Debug|ARM.Build.0 = Debug|ARM + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}.Debug|Win32.ActiveCfg = Debug|Win32 + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}.Debug|Win32.Build.0 = Debug|Win32 + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}.Debug|x64.ActiveCfg = Debug|Win32 + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}.Release|ARM.ActiveCfg = Release|ARM + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}.Release|ARM.Build.0 = Release|ARM + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}.Release|Win32.ActiveCfg = Release|Win32 + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}.Release|Win32.Build.0 = Release|Win32 + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF}.Release|x64.ActiveCfg = Release|Win32 + {9335005F-678E-4E8E-9B84-50037216AEC8}.Debug|ARM.ActiveCfg = Debug|ARM + {9335005F-678E-4E8E-9B84-50037216AEC8}.Debug|ARM.Build.0 = Debug|ARM + {9335005F-678E-4E8E-9B84-50037216AEC8}.Debug|Win32.ActiveCfg = Debug|Win32 + {9335005F-678E-4E8E-9B84-50037216AEC8}.Debug|Win32.Build.0 = Debug|Win32 + {9335005F-678E-4E8E-9B84-50037216AEC8}.Debug|x64.ActiveCfg = Debug|x64 + {9335005F-678E-4E8E-9B84-50037216AEC8}.Debug|x64.Build.0 = Debug|x64 + {9335005F-678E-4E8E-9B84-50037216AEC8}.Release|ARM.ActiveCfg = Release|ARM + {9335005F-678E-4E8E-9B84-50037216AEC8}.Release|ARM.Build.0 = Release|ARM + {9335005F-678E-4E8E-9B84-50037216AEC8}.Release|Win32.ActiveCfg = Release|Win32 + {9335005F-678E-4E8E-9B84-50037216AEC8}.Release|Win32.Build.0 = Release|Win32 + {9335005F-678E-4E8E-9B84-50037216AEC8}.Release|x64.ActiveCfg = Release|x64 + {9335005F-678E-4E8E-9B84-50037216AEC8}.Release|x64.Build.0 = Release|x64 + {22F3B9DF-1209-4574-8331-003966F562BF}.Debug|ARM.ActiveCfg = Debug|ARM + {22F3B9DF-1209-4574-8331-003966F562BF}.Debug|ARM.Build.0 = Debug|ARM + {22F3B9DF-1209-4574-8331-003966F562BF}.Debug|Win32.ActiveCfg = Debug|Win32 + {22F3B9DF-1209-4574-8331-003966F562BF}.Debug|Win32.Build.0 = Debug|Win32 + {22F3B9DF-1209-4574-8331-003966F562BF}.Debug|x64.ActiveCfg = Debug|Win32 + {22F3B9DF-1209-4574-8331-003966F562BF}.Release|ARM.ActiveCfg = Release|ARM + {22F3B9DF-1209-4574-8331-003966F562BF}.Release|ARM.Build.0 = Release|ARM + {22F3B9DF-1209-4574-8331-003966F562BF}.Release|Win32.ActiveCfg = Release|Win32 + {22F3B9DF-1209-4574-8331-003966F562BF}.Release|Win32.Build.0 = Release|Win32 + {22F3B9DF-1209-4574-8331-003966F562BF}.Release|x64.ActiveCfg = Release|Win32 + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Debug|ARM.ActiveCfg = Debug|ARM + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Debug|ARM.Build.0 = Debug|ARM + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Debug|Win32.ActiveCfg = Debug|Win32 + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Debug|Win32.Build.0 = Debug|Win32 + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Debug|x64.ActiveCfg = Debug|x64 + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Debug|x64.Build.0 = Debug|x64 + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Release|ARM.ActiveCfg = Release|ARM + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Release|ARM.Build.0 = Release|ARM + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Release|Win32.ActiveCfg = Release|Win32 + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Release|Win32.Build.0 = Release|Win32 + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Release|x64.ActiveCfg = Release|x64 + {BCF5546D-66A0-4998-AFD6-C5514F618930}.Release|x64.Build.0 = Release|x64 + {CA082EC4-17CE-430B-8207-D1E947A5D1E9}.Debug|ARM.ActiveCfg = Debug|ARM + {CA082EC4-17CE-430B-8207-D1E947A5D1E9}.Debug|ARM.Build.0 = Debug|ARM + {CA082EC4-17CE-430B-8207-D1E947A5D1E9}.Debug|Win32.ActiveCfg = Debug|Win32 + {CA082EC4-17CE-430B-8207-D1E947A5D1E9}.Debug|Win32.Build.0 = Debug|Win32 + {CA082EC4-17CE-430B-8207-D1E947A5D1E9}.Debug|x64.ActiveCfg = Debug|Win32 + {CA082EC4-17CE-430B-8207-D1E947A5D1E9}.Release|ARM.ActiveCfg = Release|ARM + {CA082EC4-17CE-430B-8207-D1E947A5D1E9}.Release|ARM.Build.0 = Release|ARM + {CA082EC4-17CE-430B-8207-D1E947A5D1E9}.Release|Win32.ActiveCfg = Release|Win32 + {CA082EC4-17CE-430B-8207-D1E947A5D1E9}.Release|Win32.Build.0 = Release|Win32 + {CA082EC4-17CE-430B-8207-D1E947A5D1E9}.Release|x64.ActiveCfg = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {A3AD93E4-0B2F-4C58-9181-69BED2E42E3E} = {36AFDE04-D127-4D84-9730-D84E3E51EAA7} + {79A8FCDA-4B12-4DD1-B676-FF148D651638} = {36AFDE04-D127-4D84-9730-D84E3E51EAA7} + {396FE85E-BB05-4B92-BCCB-F89AED4EA41A} = {36AFDE04-D127-4D84-9730-D84E3E51EAA7} + {626C3EB8-F53B-41D0-BEA8-44EACAA1228C} = {F13CB4F7-BEE5-4368-A815-A971797387D8} + {D0E32B77-3B4F-44F8-AEBC-12EE8BBF1783} = {F13CB4F7-BEE5-4368-A815-A971797387D8} + {4A3C6BA8-C227-498B-AA21-40BDA27B461F} = {626C3EB8-F53B-41D0-BEA8-44EACAA1228C} + {3B26A12D-3A44-47EA-82D2-282660FC844D} = {626C3EB8-F53B-41D0-BEA8-44EACAA1228C} + {22F798D8-BFFF-4754-996F-A5395343D5EC} = {626C3EB8-F53B-41D0-BEA8-44EACAA1228C} + {ADAFD00D-A0D6-46EF-9F0B-EA2880BFE1DE} = {D0E32B77-3B4F-44F8-AEBC-12EE8BBF1783} + {F3550FE0-C795-44F6-8FEB-093EB68143AE} = {D0E32B77-3B4F-44F8-AEBC-12EE8BBF1783} + {CC1DA216-A80D-4BE4-B309-ACB6AF313AFF} = {D0E32B77-3B4F-44F8-AEBC-12EE8BBF1783} + {5D6F020F-7E72-4494-90A0-2DF11D235DF9} = {80DA05C1-6532-4D2A-8606-EF02079B1373} + {9335005F-678E-4E8E-9B84-50037216AEC8} = {80DA05C1-6532-4D2A-8606-EF02079B1373} + {22F3B9DF-1209-4574-8331-003966F562BF} = {80DA05C1-6532-4D2A-8606-EF02079B1373} + {BEA66276-51DD-4C53-92A8-F3D1FEA50892} = {FCB0EDBB-7A20-48D0-926B-E5617D40E6E5} + {BCF5546D-66A0-4998-AFD6-C5514F618930} = {FCB0EDBB-7A20-48D0-926B-E5617D40E6E5} + {CA082EC4-17CE-430B-8207-D1E947A5D1E9} = {FCB0EDBB-7A20-48D0-926B-E5617D40E6E5} + EndGlobalSection +EndGlobal diff --git a/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/resources.props b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/resources.props new file mode 100644 index 0000000000..adce6f5869 --- /dev/null +++ b/templates/js-template-default/frameworks/runtime-src/proj.win8.1-universal/resources.props @@ -0,0 +1,63 @@ + + + + + + + $(EngineRoot)cocos\scripting\js-bindings\manual;$(EngineRoot)cocos\scripting\js-bindings\auto;$(EngineRoot)external\spidermonkey\include\$(COCOS2D_PLATFORM);$(EngineRoot)cocos\base;%(AdditionalIncludeDirectories); + + + mozjs-33.lib;%(AdditionalDependencies) + $(EngineRoot)external\spidermonkey\prebuilt\$(COCOS2D_PLATFORM)\$(Platform);%(AdditionalLibraryDirectories); + + + + + $(EngineRoot)external\spidermonkey\prebuilt\$(COCOS2D_PLATFORM)\$(Platform)\ + + + + + true + + + + + <_CustomResource Include="..\..\..\..\res\**\*"> + Assets\Resources\res\%(RecursiveDir)%(FileName)%(Extension) + true + + + + <_CustomResource Include="..\..\..\..\src\**\*"> + Assets\Resources\src\%(RecursiveDir)%(FileName)%(Extension) + true + + + + <_CustomResource Include="$(EngineRoot)cocos\scripting\js-bindings\script\**\*"> + Assets\Resources\script\%(RecursiveDir)%(FileName)%(Extension) + true + + + + <_CustomResource Include="..\..\..\..\main.js"> + Assets\Resources\%(RecursiveDir)%(FileName)%(Extension) + true + + + + <_CustomResource Include="..\..\..\..\project.json"> + Assets\Resources\%(RecursiveDir)%(FileName)%(Extension) + true + + + + + + + + + + + diff --git a/templates/js-template-default/index.html b/templates/js-template-default/index.html new file mode 100644 index 0000000000..42074ad179 --- /dev/null +++ b/templates/js-template-default/index.html @@ -0,0 +1,28 @@ + + + + + Cocos2d-html5 Hello World test + + + + + + + + + + + + + + + diff --git a/templates/js-template-default/main.js b/templates/js-template-default/main.js new file mode 100644 index 0000000000..95f14b8224 --- /dev/null +++ b/templates/js-template-default/main.js @@ -0,0 +1,67 @@ +/** + * A brief explanation for "project.json": + * Here is the content of project.json file, this is the global configuration for your game, you can modify it to customize some behavior. + * The detail of each field is under it. + { + "project_type": "javascript", + // "project_type" indicate the program language of your project, you can ignore this field + + "debugMode" : 1, + // "debugMode" possible values : + // 0 - No message will be printed. + // 1 - cc.error, cc.assert, cc.warn, cc.log will print in console. + // 2 - cc.error, cc.assert, cc.warn will print in console. + // 3 - cc.error, cc.assert will print in console. + // 4 - cc.error, cc.assert, cc.warn, cc.log will print on canvas, available only on web. + // 5 - cc.error, cc.assert, cc.warn will print on canvas, available only on web. + // 6 - cc.error, cc.assert will print on canvas, available only on web. + + "showFPS" : true, + // Left bottom corner fps information will show when "showFPS" equals true, otherwise it will be hide. + + "frameRate" : 60, + // "frameRate" set the wanted frame rate for your game, but the real fps depends on your game implementation and the running environment. + + "id" : "gameCanvas", + // "gameCanvas" sets the id of your canvas element on the web page, it's useful only on web. + + "renderMode" : 0, + // "renderMode" sets the renderer type, only useful on web : + // 0 - Automatically chosen by engine + // 1 - Forced to use canvas renderer + // 2 - Forced to use WebGL renderer, but this will be ignored on mobile browsers + + "engineDir" : "frameworks/cocos2d-html5/", + // In debug mode, if you use the whole engine to develop your game, you should specify its relative path with "engineDir", + // but if you are using a single engine file, you can ignore it. + + "modules" : ["cocos2d"], + // "modules" defines which modules you will need in your game, it's useful only on web, + // using this can greatly reduce your game's resource size, and the cocos console tool can package your game with only the modules you set. + // For details about modules definitions, you can refer to "../../frameworks/cocos2d-html5/modulesConfig.json". + + "jsList" : [ + ] + // "jsList" sets the list of js files in your game. + } + * + */ + +cc.game.onStart = function(){ + if(!cc.sys.isNative && document.getElementById("cocosLoading")) //If referenced loading.js, please remove it + document.body.removeChild(document.getElementById("cocosLoading")); + + // Pass true to enable retina display, disabled by default to improve performance + cc.view.enableRetina(false); + // Adjust viewport meta + cc.view.adjustViewPort(true); + // Setup the resolution policy and design resolution size + cc.view.setDesignResolutionSize(800, 450, cc.ResolutionPolicy.SHOW_ALL); + // The game will be resized when browser size change + cc.view.resizeWithBrowserSize(true); + //load resources + cc.LoaderScene.preload(g_resources, function () { + cc.director.runScene(new HelloWorldScene()); + }, this); +}; +cc.game.run(); \ No newline at end of file diff --git a/templates/js-template-default/manifest.webapp b/templates/js-template-default/manifest.webapp new file mode 100644 index 0000000000..e9ecf73f0b --- /dev/null +++ b/templates/js-template-default/manifest.webapp @@ -0,0 +1,19 @@ +{ + "version": "1.0", + "name": "HelloJavascript", + "description": "HelloJavascript", + "launch_path": "/index.html", + "icons": { + "128": "/res/icon.png" + }, + "developer": { + "name": "Cocos2d-html5", + "url": "http://cocos2d-x.org/" + }, + "default_locale": "en", + "installs_allowed_from": [ + "*" + ], + "orientation": "portrait-primary", + "fullscreen": "true" +} diff --git a/templates/js-template-default/project.json b/templates/js-template-default/project.json new file mode 100644 index 0000000000..e54f870660 --- /dev/null +++ b/templates/js-template-default/project.json @@ -0,0 +1,17 @@ +{ + "project_type": "javascript", + + "debugMode" : 1, + "showFPS" : true, + "frameRate" : 60, + "id" : "gameCanvas", + "renderMode" : 0, + "engineDir":"frameworks/cocos2d-html5", + + "modules" : ["cocos2d"], + + "jsList" : [ + "src/resource.js", + "src/app.js" + ] +} diff --git a/templates/js-template-default/res/CloseNormal.png b/templates/js-template-default/res/CloseNormal.png new file mode 100644 index 0000000000..5657a13b58 Binary files /dev/null and b/templates/js-template-default/res/CloseNormal.png differ diff --git a/templates/js-template-default/res/CloseSelected.png b/templates/js-template-default/res/CloseSelected.png new file mode 100644 index 0000000000..e4c82da775 Binary files /dev/null and b/templates/js-template-default/res/CloseSelected.png differ diff --git a/templates/js-template-default/res/HelloWorld.png b/templates/js-template-default/res/HelloWorld.png new file mode 100644 index 0000000000..3a20f2538a Binary files /dev/null and b/templates/js-template-default/res/HelloWorld.png differ diff --git a/templates/js-template-default/res/favicon.ico b/templates/js-template-default/res/favicon.ico new file mode 100644 index 0000000000..1ad6a0907b Binary files /dev/null and b/templates/js-template-default/res/favicon.ico differ diff --git a/templates/js-template-default/res/loading.js b/templates/js-template-default/res/loading.js new file mode 100644 index 0000000000..d17a700344 --- /dev/null +++ b/templates/js-template-default/res/loading.js @@ -0,0 +1 @@ +(function(){var createStyle=function(){return".cocosLoading{position:absolute;margin:-30px -60px;padding:0;top:50%;left:50%}"+".cocosLoading ul{margin:0;padding:0;}"+".cocosLoading span{color:#FFF;text-align:center;display:block;}"+".cocosLoading li{list-style:none;float:left;border-radius:15px;width:15px;height:15px;background:#FFF;margin:5px 0 0 10px}"+".cocosLoading li .ball,.cocosLoading li .unball{background-color:#2187e7;background-image:-moz-linear-gradient(90deg,#2187e7 25%,#a0eaff);background-image:-webkit-linear-gradient(90deg,#2187e7 25%,#a0eaff);width:15px;height:15px;border-radius:50px}"+".cocosLoading li .ball{transform:scale(0);-moz-transform:scale(0);-webkit-transform:scale(0);animation:showDot 1s linear forwards;-moz-animation:showDot 1s linear forwards;-webkit-animation:showDot 1s linear forwards}"+".cocosLoading li .unball{transform:scale(1);-moz-transform:scale(1);-webkit-transform:scale(1);animation:hideDot 1s linear forwards;-moz-animation:hideDot 1s linear forwards;-webkit-animation:hideDot 1s linear forwards}"+"@keyframes showDot{0%{transform:scale(0,0)}100%{transform:scale(1,1)}}"+"@-moz-keyframes showDot{0%{-moz-transform:scale(0,0)}100%{-moz-transform:scale(1,1)}}"+"@-webkit-keyframes showDot{0%{-webkit-transform:scale(0,0)}100%{-webkit-transform:scale(1,1)}}"+"@keyframes hideDot{0%{transform:scale(1,1)}100%{transform:scale(0,0)}}"+"@-moz-keyframes hideDot{0%{-moz-transform:scale(1,1)}100%{-moz-transform:scale(0,0)}}"+"@-webkit-keyframes hideDot{0%{-webkit-transform:scale(1,1)}100%{-webkit-transform:scale(0,0)}}"};var createDom=function(id,num){id=id||"cocosLoading";num=num||5;var i,item;var div=document.createElement("div");div.className="cocosLoading";div.id=id;var bar=document.createElement("ul");var list=[];for(i=0;i=list.length){direction=!direction;index=0;time=1000}else{time=300}animation()},time)};animation()};(function(){var bgColor=document.body.style.background;document.body.style.background="#000";var style=document.createElement("style");style.type="text/css";style.innerHTML=createStyle();document.head.appendChild(style);var list=createDom();startAnimation(list,function(){var div=document.getElementById("cocosLoading");if(!div){document.body.style.background=bgColor}return !!div})})()})(); \ No newline at end of file diff --git a/templates/js-template-default/src/app.js b/templates/js-template-default/src/app.js new file mode 100644 index 0000000000..8df4e42ce8 --- /dev/null +++ b/templates/js-template-default/src/app.js @@ -0,0 +1,78 @@ + +var HelloWorldLayer = cc.Layer.extend({ + sprite:null, + ctor:function () { + ////////////////////////////// + // 1. super init first + this._super(); + + ///////////////////////////// + // 2. add a menu item with "X" image, which is clicked to quit the program + // you may modify it. + // ask the window size + var size = cc.winSize; + + // add a "close" icon to exit the progress. it's an autorelease object + var closeItem = new cc.MenuItemImage( + res.CloseNormal_png, + res.CloseSelected_png, + function () { + cc.log("Menu is clicked!"); + }, this); + closeItem.attr({ + x: size.width - 20, + y: 20, + anchorX: 0.5, + anchorY: 0.5 + }); + + var menu = new cc.Menu(closeItem); + menu.x = 0; + menu.y = 0; + this.addChild(menu, 1); + + ///////////////////////////// + // 3. add your codes below... + // add a label shows "Hello World" + // create and initialize a label + var helloLabel = new cc.LabelTTF("Hello World", "Arial", 38); + // position the label on the center of the screen + helloLabel.x = size.width / 2; + helloLabel.y = 0; + // add the label as a child to this layer + this.addChild(helloLabel, 5); + + // add "HelloWorld" splash screen" + this.sprite = new cc.Sprite(res.HelloWorld_png); + this.sprite.attr({ + x: size.width / 2, + y: size.height / 2, + scale: 0.5, + rotation: 180 + }); + this.addChild(this.sprite, 0); + + this.sprite.runAction( + cc.sequence( + cc.rotateTo(2, 0), + cc.scaleTo(2, 1, 1) + ) + ); + helloLabel.runAction( + cc.spawn( + cc.moveBy(2.5, cc.p(0, size.height - 40)), + cc.tintTo(2.5,255,125,0) + ) + ); + return true; + } +}); + +var HelloWorldScene = cc.Scene.extend({ + onEnter:function () { + this._super(); + var layer = new HelloWorldLayer(); + this.addChild(layer); + } +}); + diff --git a/templates/js-template-default/src/resource.js b/templates/js-template-default/src/resource.js new file mode 100644 index 0000000000..4438ab1b86 --- /dev/null +++ b/templates/js-template-default/src/resource.js @@ -0,0 +1,10 @@ +var res = { + HelloWorld_png : "res/HelloWorld.png", + CloseNormal_png : "res/CloseNormal.png", + CloseSelected_png : "res/CloseSelected.png" +}; + +var g_resources = []; +for (var i in res) { + g_resources.push(res[i]); +} \ No newline at end of file diff --git a/templates/lua-template-default/frameworks/CMakeLists.txt b/templates/lua-template-default/frameworks/CMakeLists.txt index 9f43fc9529..9e0621aba5 100644 --- a/templates/lua-template-default/frameworks/CMakeLists.txt +++ b/templates/lua-template-default/frameworks/CMakeLists.txt @@ -45,6 +45,7 @@ endif(DEBUG_MODE) # libcocos2d set(BUILD_CPP_TESTS OFF CACHE BOOL "turn off build cpp-tests") set(BUILD_LUA_TESTS OFF CACHE BOOL "turn off build lua-tests") +set(BUILD_JS_LIBS OFF CACHE BOOL "turn off build js releated targets") add_subdirectory(${COCOS2D_ROOT}) diff --git a/tests/cpp-empty-test/.cocos-project.json b/tests/cpp-empty-test/.cocos-project.json index 0c934452c6..083f76ad90 100644 --- a/tests/cpp-empty-test/.cocos-project.json +++ b/tests/cpp-empty-test/.cocos-project.json @@ -26,14 +26,6 @@ "android_cfg": { "project_path": "proj.android" }, - "wp8_cfg" : { - "project_path": "../../build", - "sln_file": "cocos2d-wp8.sln", - "project_name": "cpp-empty-test", - "wp8_proj_path" : "proj-wp8-xaml", - "build_folder_path": "cpp-empty-test/Bin/x86", - "manifest_path": "cpp-empty-test/Properties/WMAppManifest.xml" - }, "wp8_1_cfg" : { "project_path": "../../build", "sln_file": "cocos2d-win8.1-universal.sln", diff --git a/tests/cpp-tests/.cocos-project.json b/tests/cpp-tests/.cocos-project.json index e7c71f562f..173028a970 100644 --- a/tests/cpp-tests/.cocos-project.json +++ b/tests/cpp-tests/.cocos-project.json @@ -26,14 +26,6 @@ "android_cfg": { "project_path": "proj.android" }, - "wp8_cfg" : { - "project_path": "../../build", - "sln_file": "cocos2d-wp8.sln", - "project_name": "cpp-tests", - "wp8_proj_path" : "proj.wp8-xaml", - "build_folder_path": "cpp-tests/Bin/x86", - "manifest_path": "cpp-tests/Properties/WMAppManifest.xml" - }, "wp8_1_cfg" : { "project_path": "../../build", "sln_file": "cocos2d-win8.1-universal.sln", diff --git a/tests/js-tests/.cocos-project.json b/tests/js-tests/.cocos-project.json new file mode 100644 index 0000000000..a9cc782214 --- /dev/null +++ b/tests/js-tests/.cocos-project.json @@ -0,0 +1,41 @@ +{ + "project_type": "js", + "has_native": true, + "win32_cfg": { + "project_path": "../../build", + "sln_file": "cocos2d-js-win32.vc2012.sln", + "project_name": "js-tests", + "build_cfg_path": "project/proj.win32" + }, + "ios_cfg": { + "project_path": "../../build", + "project_file": "cocos2d_js_tests.xcodeproj", + "target_name": "js-tests iOS" + }, + "mac_cfg": { + "project_path": "../../build", + "project_file": "cocos2d_js_tests.xcodeproj", + "target_name": "js-tests Mac" + }, + "android_cfg": { + "project_path": "project/proj.android" + }, + "linux_cfg": { + "project_path": "project/proj.linux", + "project_name": "js-tests", + "cmake_path": "../../", + "build_dir": "../../build/linux-build", + "build_result_dir": "js-tests" + }, + "wp8_1_cfg" : { + "project_path": "../../build", + "sln_file": "cocos2d-js-win8.1-universal.sln", + "project_name": "js-tests.WindowsPhone" + }, + "metro_cfg" : { + "project_path": "../../build", + "sln_file": "cocos2d-js-win8.1-universal.sln", + "project_name": "js-tests.Windows" + }, + "engine_dir": "../../" +} diff --git a/tests/js-tests/main.js b/tests/js-tests/main.js new file mode 100644 index 0000000000..50b5724332 --- /dev/null +++ b/tests/js-tests/main.js @@ -0,0 +1,127 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +/** + * A brief explanation for "project.json": + * Here is the content of project.json file, this is the global configuration for your game, you can modify it to customize some behavior. + * The detail of each field is under it. + { + "debugMode" : 1, + // "debugMode" possible values : + // 0 - No message will be printed. + // 1 - cc.error, cc.assert, cc.warn, cc.log will print in console. + // 2 - cc.error, cc.assert, cc.warn will print in console. + // 3 - cc.error, cc.assert will print in console. + // 4 - cc.error, cc.assert, cc.warn, cc.log will print on canvas, available only on web. + // 5 - cc.error, cc.assert, cc.warn will print on canvas, available only on web. + // 6 - cc.error, cc.assert will print on canvas, available only on web. + + "showFPS" : true, + // Left bottom corner fps information will show when "showFPS" equals true, otherwise it will be hide. + + "frameRate" : 60, + // "frameRate" set the wanted frame rate for your game, but the real fps depends on your game implementation and the running environment. + + "id" : "gameCanvas", + // "gameCanvas" sets the id of your canvas element on the web page, it's useful only on web. + + "renderMode" : 0, + // "renderMode" sets the renderer type, only useful on web : + // 0 - Automatically chosen by engine + // 1 - Forced to use canvas renderer + // 2 - Forced to use WebGL renderer, but this will be ignored on mobile browsers + + "engineDir" : "../../frameworks/cocos2d-html5/", + // In debug mode, if you use the whole engine to develop your game, you should specify its relative path with "engineDir", + // but if you are using a single engine file, you can ignore it. + + "modules" : ["cocos2d", "extensions", "external"], + // "modules" defines which modules you will need in your game, it's useful only on web, + // using this can greatly reduce your game's resource size, and the cocos console tool can package your game with only the modules you set. + // For details about modules definitions, you can refer to "../../frameworks/cocos2d-html5/modulesConfig.json". + + "plugin": { + "facebook": { + "appId" : "1426774790893461", + "xfbml" : true, + "version" : "v2.0" + } + }, + // "plugin" is used by plugin-x for its settings, if you don't use it, you can ignore it. + + "jsList" : [ + ] + // "jsList" sets the list of js files in your game. + } + * + */ + +if(cc.sys){ + var scene3SearchPaths = cc.sys.localStorage.getItem("Scene3SearchPaths"); + if (scene3SearchPaths) + jsb.fileUtils.setSearchPaths(JSON.parse(scene3SearchPaths)); +} + +cc.game.onStart = function(){ + cc.view.enableRetina(false); + if (cc.sys.isNative) { + var resolutionPolicy = (cc.sys.os == cc.sys.OS_WP8 || cc.sys.os == cc.sys.OS_WINRT) ? cc.ResolutionPolicy.SHOW_ALL : cc.ResolutionPolicy.FIXED_HEIGHT; + cc.view.setDesignResolutionSize(800, 450, resolutionPolicy); + cc.view.resizeWithBrowserSize(true); + var searchPaths = jsb.fileUtils.getSearchPaths(); + searchPaths.push('script'); + searchPaths.push('src'); + var paths = [ + 'res', + 'res/scenetest', + 'res/scenetest/ArmatureComponentTest', + 'res/scenetest/AttributeComponentTest', + 'res/scenetest/BackgroundComponentTest', + 'res/scenetest/EffectComponentTest', + 'res/scenetest/LoadSceneEdtiorFileTest', + 'res/scenetest/ParticleComponentTest', + 'res/scenetest/SpriteComponentTest', + 'res/scenetest/TmxMapComponentTest', + 'res/scenetest/UIComponentTest', + 'res/scenetest/TriggerTest' + ]; + for (var i = 0; i < paths.length; i++) { + searchPaths.push(paths[i]); + } + jsb.fileUtils.setSearchPaths(searchPaths); + } + cc.LoaderScene.preload(g_resources, function () { + if(window.sideIndexBar && typeof sideIndexBar.start === 'function'){ + sideIndexBar.start(); + }else{ + var scene = new cc.Scene(); + scene.addChild(new TestController()); + cc.director.runScene(scene); + } + }, this); +}; +cc.game.run(); diff --git a/tests/js-tests/project.json b/tests/js-tests/project.json new file mode 100644 index 0000000000..df4c38b167 --- /dev/null +++ b/tests/js-tests/project.json @@ -0,0 +1,186 @@ +{ + "debugMode" : 1, + "showFPS" : true, + "frameRate" : 60, + "id" : "gameCanvas", + "renderMode" : 0, + "engineDir" : "../../frameworks/cocos2d-html5/", + + "modules" : ["cocos2d", "extensions", "external"], + + "plugin": { + "facebook": { + "appId" : "1426774790893461", + "xfbml" : true, + "version" : "v2.0" + } + }, + + "jsList" : [ + "src/BaseTestLayer/BaseTestLayer.js", + + "src/tests_resources.js", + "src/tests-main.js", + + "src/PathTest/PathTest.js", + "src/LoaderTest/LoaderTest.js", + + "src/BakeLayerTest/BakeLayerTest.js", + + "src/TouchesTest/Ball.js", + "src/TouchesTest/Paddle.js", + "src/TouchesTest/TouchesTest.js", + "src/SchedulerTest/SchedulerTest.js", + "src/ClickAndMoveTest/ClickAndMoveTest.js", + "src/MenuTest/MenuTest.js", + "src/ActionsTest/ActionsTest.js", + "src/TileMapTest/TileMapTest.js", + "src/TransitionsTest/TransitionsTest.js", + "src/DrawPrimitivesTest/DrawPrimitivesTest.js", + "src/ParticleTest/ParticleTest.js", + "src/ProgressActionsTest/ProgressActionsTest.js", + "src/LayerTest/LayerTest.js", + "src/SceneTest/SceneTest.js", + "src/SpineTest/SpineTest.js", + "src/SpriteTest/SpriteTest.js", + "src/Sprite3DTest/Sprite3DTest.js", + "src/LightTest/LightTest.js", + "src/BillBoardTest/BillBoardTest.js", + "src/Camera3DTest/Camera3DTest.js", + "src/TextureCacheTest/TextureCacheTest.js", + "src/CocosDenshionTest/CocosDenshionTest.js", + "src/CocosNodeTest/CocosNodeTest.js", + "src/RotateWorldTest/RotateWorldTest.js", + "src/RenderTextureTest/RenderTextureTest.js", + "src/IntervalTest/IntervalTest.js", + "src/ActionManagerTest/ActionManagerTest.js", + "src/EaseActionsTest/EaseActionsTest.js", + "src/ParallaxTest/ParallaxTest.js", + "src/PerformanceTest/PerformanceTest.js", + "src/PerformanceTest/PerformanceSpriteTest.js", + "src/PerformanceTest/PerformanceSpriteTest2.js", + "src/PerformanceTest/PerformanceParticleTest.js", + "src/PerformanceTest/PerformanceNodeChildrenTest.js", + "src/PerformanceTest/PerformanceTextureTest.js", + "src/PerformanceTest/PerformanceAnimationTest.js", + "src/PerformanceTest/PerformanceVirtualMachineTest.js", + "src/PerformanceTest/seedrandom.js", + "src/FontTest/FontTest.js", + "src/PerformanceTest/PerformanceTouchesTest.js", + "src/LabelTest/LabelTest.js", + "src/CurrentLanguageTest/CurrentLanguageTest.js", + "src/TextInputTest/TextInputTest.js", + "src/NewEventManagerTest/NewEventManagerTest.js", + "src/EventTest/EventTest.js", + "src/UnitTest/UnitTest.js", + "src/SysTest/SysTest.js", + "src/SysTest/ScriptTestTempFile.js", + "src/EffectsTest/EffectsTest.js", + "src/EffectsAdvancedTest/EffectsAdvancedTest.js", + "src/MotionStreakTest/MotionStreakTest.js", + "src/ClippingNodeTest/ClippingNodeTest.js", + "src/OpenGLTest/OpenGLTest.js", + + "src/FacebookTest/FacebookTest.js", + "src/FacebookTest/FacebookShareTest.js", + "src/FacebookTest/FacebookUserTest.js", + "src/FacebookTest/FacebookTestsManager.js", + + "src/ExtensionsTest/ExtensionsTest.js", + "src/ExtensionsTest/AssetsManagerTest/AssetsManagerTest.js", + "src/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.js", + "src/ExtensionsTest/ControlExtensionTest/CCControlScene.js", + "src/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.js", + "src/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.js", + "src/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.js", + "src/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.js", + "src/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.js", + "src/ExtensionsTest/ControlExtensionTest/CCControlColourPickerTest/CCControlColourPickerTest.js", + "src/ExtensionsTest/TableViewTest/TableViewTestScene.js", + "src/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.js", + "src/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.js", + "src/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.js", + "src/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.js", + "src/ExtensionsTest/CocosBuilderTest/SpriteTest/SpriteTestLayer.js", + "src/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.js", + "src/ExtensionsTest/CocosBuilderTest/LabelTest/LabelTestLayer.js", + "src/ExtensionsTest/CocosBuilderTest/ParticleSystemTest/ParticleSystemTestLayer.js", + "src/ExtensionsTest/CocosBuilderTest/ScrollViewTest/ScrollViewTestLayer.js", + "src/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.js", + "src/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.js", + "src/ExtensionsTest/CCPoolTest/CCPoolTest.js", + "src/ExtensionsTest/EditBoxTest/EditBoxTest.js", + "src/ExtensionsTest/S9SpriteTest/S9SpriteTest.js", + "src/ExtensionsTest/NetworkTest/WebSocketTest.js", + "src/ExtensionsTest/NetworkTest/SocketIOTest.js", + "src/ExtensionsTest/PluginXTest/PluginXTest.js", + "src/ExtensionsTest/PluginXTest/PluginXTestsManager.js", + "src/ExtensionsTest/PluginXTest/IOSIAPTest.js", + "src/ExtensionsTest/PluginXTest/AnalyticsTest.js", + "src/CocoStudioTest/ArmatureTest/ArmatureTest.js", + "src/CocoStudioTest/ComponentsTest/ComponentsTestScene.js", + "src/CocoStudioTest/ComponentsTest/EnemyController.js", + "src/CocoStudioTest/ComponentsTest/GameOverScene.js", + "src/CocoStudioTest/ComponentsTest/PlayerController.js", + "src/CocoStudioTest/ComponentsTest/ProjectileController.js", + "src/CocoStudioTest/ComponentsTest/SceneController.js", + "src/CocoStudioTest/GUITest/UISceneTest.js", + "src/CocoStudioTest/GUITest/UIBaseLayer.js", + "src/CocoStudioTest/GUITest/UIButtonTest/UIButtonTest.js", + "src/CocoStudioTest/GUITest/UICheckBoxTest/UICheckBoxTest.js", + "src/CocoStudioTest/GUITest/UIImageViewTest/UIImageViewTest.js", + "src/CocoStudioTest/GUITest/UITextTest/UITextTest.js", + "src/CocoStudioTest/GUITest/UITextAtlasTest/UITextAtlasTest.js", + "src/CocoStudioTest/GUITest/UITextBMFontTest/UITextBMFontTest.js", + "src/CocoStudioTest/GUITest/UILoadingBarTest/UILoadingBarTest.js", + "src/CocoStudioTest/GUITest/UISliderTest/UISliderTest.js", + "src/CocoStudioTest/GUITest/UITextFieldTest/UITextFieldTest.js", + "src/CocoStudioTest/GUITest/UINodeContainerTest/UINodeContainerTest.js", + "src/CocoStudioTest/GUITest/UILayoutTest/UILayoutTest.js", + "src/CocoStudioTest/GUITest/UIListViewTest/UIListViewTest.js", + "src/CocoStudioTest/GUITest/UIPageViewTest/UIPageViewTest.js", + "src/CocoStudioTest/GUITest/UIScrollViewTest/UIScrollViewTest.js", + "src/CocoStudioTest/ParserTest/ParserTest.js", + "src/CocoStudioTest/CustomTest/CustomImageView/CustomImageView.js", + "src/CocoStudioTest/CustomTest/CustomImageView/CustomImageViewReader.js", + "src/CocoStudioTest/CustomTest/CustomImageView/CustomParticleWidget.js", + "src/CocoStudioTest/CustomTest/CustomImageView/CustomParticWidgetReader.js", + "src/CocoStudioTest/CustomTest/CustomImageView/CustomReader.js", + "src/CocoStudioTest/CustomTest/CustomParticleWidgetTest/CustomParticleWidgetTest.js", + "src/CocoStudioTest/CustomTest/CustomImageScene/CustomImageScene.js", + "src/CocoStudioTest/CustomTest/CustomGUIScene.js", + "src/GUITest/UIScene.js", + "src/GUITest/UIButtonTest/UIButtonTest.js", + "src/GUITest/UICheckBoxTest/UICheckBoxTest.js", + "src/GUITest/UIFocusTest/UIFocusTest.js", + "src/GUITest/UIImageViewTest/UIImageViewTest.js", + "src/GUITest/UILabelAtlasTest/UILabelAtlasTest.js", + "src/GUITest/UILabelBMFontTest/UILabelBMFontTest.js", + "src/GUITest/UILabelTest/UILabelTest.js", + "src/GUITest/UILayoutTest/UILayoutTest.js", + "src/GUITest/UIListViewTest/UIListViewTest.js", + "src/GUITest/UILoadingBarTest/UILoadingBarTest.js", + "src/GUITest/UINodeContainerTest/UINodeContainerTest.js", + "src/GUITest/UIPageViewTest/UIPageViewTest.js", + "src/GUITest/UISceneManager.js", + "src/GUITest/UIScrollViewTest/UIScrollViewTest.js", + "src/GUITest/UISliderTest/UISliderTest.js", + "src/GUITest/UITextFieldTest/UITextFieldTest.js", + "src/GUITest/UIRichTextTest/UIRichTextTest.js", + "src/GUITest/UITextTest/UITextTest.js", + + "src/CocoStudioTest/SceneTest/TriggerCode/Acts.js", + "src/CocoStudioTest/SceneTest/TriggerCode/Cons.js", + "src/CocoStudioTest/SceneTest/TriggerCode/EventDef.js", + "src/CocoStudioTest/SceneTest/SceneEditorTest.js", + "src/CocoStudioTest/CocoStudioTest.js", + "src/XHRTest/XHRTest.js", + "src/XHRTest/XHRArrayBufferTest.js", + + "src/Box2dTest/Box2dTest.js", + "src/ChipmunkTest/ChipmunkTest.js", + + "src/Presentation/Presentation.js", + "src/ReflectionTest/ReflectionTest.js" + ] +} diff --git a/tests/js-tests/project/CMakeLists.txt b/tests/js-tests/project/CMakeLists.txt new file mode 100644 index 0000000000..0aa7cfacfc --- /dev/null +++ b/tests/js-tests/project/CMakeLists.txt @@ -0,0 +1,79 @@ +#/**************************************************************************** +# Copyright (c) 2015 Chukong Technologies 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. +# ****************************************************************************/ + +set(APP_NAME js-tests) + +if(WIN32) + +else() + set(PLATFORM_SRC + proj.linux/main.cpp + ) +endif() + +set(SAMPLE_SRC + Classes/AppDelegate.cpp + Classes/js_DrawNode3D_bindings.cpp + Classes/js_Effect3D_bindings.cpp + ${PLATFORM_SRC} +) + +include_directories( + Classes + ../../../cocos/scripting/js-bindings/auto + ../../../cocos/scripting/js-bindings/manual + ../../../cocos/base + ../../../cocos/editor-support + ../../../cocos/audio/include + ../../../external/spidermonkey/include/${PLATFORM_FOLDER} + ../../../external/chipmunk/include/chipmunk +) + +# add the executable +add_executable(${APP_NAME} + ${SAMPLE_SRC} +) + +target_link_libraries(${APP_NAME} + jscocos2d + cocos2d +) + +set(APP_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${APP_NAME}") + +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}/script + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/res + COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/src + COMMAND ${CMAKE_COMMAND} -E remove ${APP_BIN_DIR}/*.js + COMMAND ${CMAKE_COMMAND} -E remove ${APP_BIN_DIR}/*.json + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/../../cpp-tests/Resources ${APP_BIN_DIR}/res + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/../src ${APP_BIN_DIR}/src + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/../../../cocos/scripting/js-bindings/script ${APP_BIN_DIR}/script + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/../main.js ${APP_BIN_DIR}/main.js + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/../project.json ${APP_BIN_DIR}/project.json + ) diff --git a/tests/js-tests/project/Classes/AppDelegate.cpp b/tests/js-tests/project/Classes/AppDelegate.cpp new file mode 100644 index 0000000000..053a51c7ee --- /dev/null +++ b/tests/js-tests/project/Classes/AppDelegate.cpp @@ -0,0 +1,151 @@ +#include "AppDelegate.h" + +#include "cocos2d.h" +#include "SimpleAudioEngine.h" +#include "ScriptingCore.h" +#include "jsb_cocos2dx_auto.hpp" +#include "jsb_cocos2dx_extension_auto.hpp" +#include "jsb_cocos2dx_builder_auto.hpp" +#include "jsb_cocos2dx_spine_auto.hpp" +#include "jsb_cocos2dx_3d_auto.hpp" +#include "jsb_cocos2dx_3d_extension_auto.hpp" +#include "3d/jsb_cocos2dx_3d_manual.h" +#include "extension/jsb_cocos2dx_extension_manual.h" +#include "cocostudio/jsb_cocos2dx_studio_manual.h" +#include "jsb_cocos2dx_studio_auto.hpp" +#include "jsb_cocos2dx_ui_auto.hpp" +#include "ui/jsb_cocos2dx_ui_manual.h" +#include "spine/jsb_cocos2dx_spine_manual.h" +#include "cocos2d_specifics.hpp" +#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 "network/XMLHTTPRequest.h" +#include "network/jsb_websocket.h" +#include "network/jsb_socketio.h" +#include "cocosbuilder/js_bindings_ccbreader.h" +#include "js_DrawNode3D_bindings.h" + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) +#include "platform/android/CCJavascriptJavaBridge.h" +#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) +#include "platform/ios/JavaScriptObjCBridge.h" +#endif + +#if(CC_TARGET_PLATFORM != CC_PLATFORM_WP8) +#include "js_Effect3D_bindings.h" +#endif + +USING_NS_CC; +USING_NS_CC_EXT; +using namespace CocosDenshion; + +AppDelegate::AppDelegate() +{ +} + +AppDelegate::~AppDelegate() +{ + ScriptEngineManager::destroyInstance(); +} + +void AppDelegate::initGLContextAttrs() +{ + GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8}; + + GLView::setGLContextAttrs(glContextAttrs); +} + +bool AppDelegate::applicationDidFinishLaunching() +{ + // initialize director + auto director = Director::getInstance(); + auto glview = director->getOpenGLView(); + if(!glview) { +#if(CC_TARGET_PLATFORM == CC_PLATFORM_WP8 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) + glview = cocos2d::GLViewImpl::create("js-tests"); +#else + glview = cocos2d::GLViewImpl::createWithRect("js-tests", Rect(0,0,900,640)); +#endif + director->setOpenGLView(glview); + } + + // set FPS. the default value is 1.0/60 if you don't call this + director->setAnimationInterval(1.0 / 60); + + ScriptingCore* sc = ScriptingCore::getInstance(); + sc->addRegisterCallback(register_all_cocos2dx); + sc->addRegisterCallback(register_cocos2dx_js_core); + sc->addRegisterCallback(jsb_register_system); + + sc->addRegisterCallback(register_all_cocos2dx_extension); + sc->addRegisterCallback(register_all_cocos2dx_extension_manual); + + sc->addRegisterCallback(jsb_register_chipmunk); + sc->addRegisterCallback(JSB_register_opengl); + + sc->addRegisterCallback(MinXmlHttpRequest::_js_register); + sc->addRegisterCallback(register_jsb_websocket); + sc->addRegisterCallback(register_jsb_socketio); + + sc->addRegisterCallback(register_all_cocos2dx_builder); + sc->addRegisterCallback(register_CCBuilderReader); + + sc->addRegisterCallback(register_all_cocos2dx_ui); + sc->addRegisterCallback(register_all_cocos2dx_ui_manual); + sc->addRegisterCallback(register_all_cocos2dx_studio); + sc->addRegisterCallback(register_all_cocos2dx_studio_manual); + + sc->addRegisterCallback(register_all_cocos2dx_spine); + sc->addRegisterCallback(register_all_cocos2dx_spine_manual); + + sc->addRegisterCallback(register_all_cocos2dx_3d); + sc->addRegisterCallback(register_all_cocos2dx_3d_manual); + + sc->addRegisterCallback(register_all_cocos2dx_3d_extension); + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) + sc->addRegisterCallback(JavascriptJavaBridge::_js_register); +#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) + sc->addRegisterCallback(JavaScriptObjCBridge::_js_register); +#endif + + sc->addRegisterCallback(register_DrawNode3D_bindings); +#if(CC_TARGET_PLATFORM != CC_PLATFORM_WP8) + sc->addRegisterCallback(register_Effect3D_bindings); +#endif + + sc->start(); + sc->runScript("script/jsb_boot.js"); +#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) + sc->enableDebugger(); +#endif + + auto pEngine = ScriptingCore::getInstance(); + ScriptEngineManager::getInstance()->setScriptEngine(pEngine); + + ScriptingCore::getInstance()->runScript("main.js"); + + return true; +} + +// This function will be called when the app is inactive. When comes a phone call,it's be invoked too +void AppDelegate::applicationDidEnterBackground() +{ + auto director = Director::getInstance(); + director->stopAnimation(); + director->getEventDispatcher()->dispatchCustomEvent("game_on_hide"); + SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); + SimpleAudioEngine::getInstance()->pauseAllEffects(); +} + +// this function will be called when the app is active again +void AppDelegate::applicationWillEnterForeground() +{ + auto director = Director::getInstance(); + director->startAnimation(); + director->getEventDispatcher()->dispatchCustomEvent("game_on_show"); + SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); + SimpleAudioEngine::getInstance()->resumeAllEffects(); +} diff --git a/tests/js-tests/project/Classes/AppDelegate.h b/tests/js-tests/project/Classes/AppDelegate.h new file mode 100644 index 0000000000..ee146a75d9 --- /dev/null +++ b/tests/js-tests/project/Classes/AppDelegate.h @@ -0,0 +1,39 @@ +#ifndef _APP_DELEGATE_H_ +#define _APP_DELEGATE_H_ + +#include "platform/CCApplication.h" +/** + @brief The cocos2d Application. + + The reason for implement as private inheritance is to hide some interface call by Director. + */ +class AppDelegate : private cocos2d::Application +{ +public: + AppDelegate(); + virtual ~AppDelegate(); + + void initGLContextAttrs() override; + + /** + @brief Implement Director and Scene init code here. + @return true Initialize success, app continue. + @return false Initialize failed, app terminate. + */ + virtual bool applicationDidFinishLaunching(); + + /** + @brief The function be called when the application enter background + @param the pointer of the application + */ + virtual void applicationDidEnterBackground(); + + /** + @brief The function be called when the application enter foreground + @param the pointer of the application + */ + virtual void applicationWillEnterForeground(); +}; + +#endif // _APP_DELEGATE_H_ + diff --git a/tests/js-tests/project/Classes/js_DrawNode3D_bindings.cpp b/tests/js-tests/project/Classes/js_DrawNode3D_bindings.cpp new file mode 100644 index 0000000000..b8cd8a42e4 --- /dev/null +++ b/tests/js-tests/project/Classes/js_DrawNode3D_bindings.cpp @@ -0,0 +1,593 @@ +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies 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 "cocos2d_specifics.hpp" +#include "js_DrawNode3D_bindings.h" + +NS_CC_BEGIN + +/** + * Copy DrawNode for 3D geometry drawing. + */ +class DrawNode3D: public Node +{ +public: + /** creates and initialize a DrawNode3D node */ + static DrawNode3D* create(); + + /** + * Draw 3D Line + */ + void drawLine(const Vec3 &from, const Vec3 &to, const Color4F &color); + + /** + * Draw 3D cube + * @param point to a vertex array who has 8 element. + * vertices[0]:Left-top-front, + * vertices[1]:Left-bottom-front, + * vertices[2]:Right-bottom-front, + * vertices[3]:Right-top-front, + * vertices[4]:Right-top-back, + * vertices[5]:Right-bottom-back, + * vertices[6]:Left-bottom-back, + * vertices[7]:Left-top-back. + * @param color + */ + void drawCube(Vec3* vertices, const Color4F &color); + + /** Clear the geometry in the node's buffer. */ + void clear(); + + /** + * @js NA + * @lua NA + */ + const BlendFunc& getBlendFunc() const; + + /** + * @code + * When this function bound into js or lua,the parameter will be changed + * In js: var setBlendFunc(var src, var dst) + * @endcode + * @lua NA + */ + void setBlendFunc(const BlendFunc &blendFunc); + + void onDraw(const Mat4 &transform, uint32_t flags); + + // Overrides + virtual void draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) override; + +CC_CONSTRUCTOR_ACCESS: + DrawNode3D(); + virtual ~DrawNode3D(); + virtual bool init(); + +protected: + struct V3F_C4B + { + Vec3 vertices; + Color4B colors; + }; + void ensureCapacity(int count); + + GLuint _vao; + GLuint _vbo; + + int _bufferCapacity; + GLsizei _bufferCount; + V3F_C4B* _buffer; + + BlendFunc _blendFunc; + CustomCommand _customCommand; + + bool _dirty; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(DrawNode3D); +}; + + +DrawNode3D::DrawNode3D() +: _vao(0) +, _vbo(0) +, _bufferCapacity(0) +, _bufferCount(0) +, _buffer(nullptr) +, _dirty(false) +{ + _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; +} + +DrawNode3D::~DrawNode3D() +{ + free(_buffer); + _buffer = nullptr; + + glDeleteBuffers(1, &_vbo); + _vbo = 0; + + if (Configuration::getInstance()->supportsShareableVAO()) + { + glDeleteVertexArrays(1, &_vao); + GL::bindVAO(0); + _vao = 0; + } +} + +DrawNode3D* DrawNode3D::create() +{ + DrawNode3D* ret = new (std::nothrow) DrawNode3D(); + if (ret && ret->init()) + { + ret->autorelease(); + } + else + { + CC_SAFE_DELETE(ret); + } + + return ret; +} + +void DrawNode3D::ensureCapacity(int count) +{ + CCASSERT(count>=0, "capacity must be >= 0"); + + if(_bufferCount + count > _bufferCapacity) + { + _bufferCapacity += MAX(_bufferCapacity, count); + _buffer = (V3F_C4B*)realloc(_buffer, _bufferCapacity*sizeof(V3F_C4B)); + } +} + +bool DrawNode3D::init() +{ + _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; + + setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_COLOR)); + + ensureCapacity(512); + + if (Configuration::getInstance()->supportsShareableVAO()) + { + glGenVertexArrays(1, &_vao); + GL::bindVAO(_vao); + } + + glGenBuffers(1, &_vbo); + glBindBuffer(GL_ARRAY_BUFFER, _vbo); + glBufferData(GL_ARRAY_BUFFER, sizeof(V3F_C4B)* _bufferCapacity, _buffer, GL_STREAM_DRAW); + + glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_POSITION); + glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, sizeof(V3F_C4B), (GLvoid *)offsetof(V3F_C4B, vertices)); + + glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_COLOR); + glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(V3F_C4B), (GLvoid *)offsetof(V3F_C4B, colors)); + + glBindBuffer(GL_ARRAY_BUFFER, 0); + + if (Configuration::getInstance()->supportsShareableVAO()) + { + GL::bindVAO(0); + } + + CHECK_GL_ERROR_DEBUG(); + + _dirty = true; + +#if CC_ENABLE_CACHE_TEXTURE_DATA + // Need to listen the event only when not use batchnode, because it will use VBO + auto listener = EventListenerCustom::create(EVENT_COME_TO_FOREGROUND, [this](EventCustom* event){ + /** listen the event that coming to foreground on Android */ + this->init(); + }); + + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); +#endif + + return true; +} + +void DrawNode3D::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) +{ + _customCommand.init(_globalZOrder, transform, flags); + _customCommand.func = CC_CALLBACK_0(DrawNode3D::onDraw, this, transform, flags); + renderer->addCommand(&_customCommand); +} + +void DrawNode3D::onDraw(const Mat4 &transform, uint32_t flags) +{ + auto glProgram = getGLProgram(); + glProgram->use(); + glProgram->setUniformsForBuiltins(transform); + glEnable(GL_DEPTH_TEST); + GL::blendFunc(_blendFunc.src, _blendFunc.dst); + + if (_dirty) + { + glBindBuffer(GL_ARRAY_BUFFER, _vbo); + glBufferData(GL_ARRAY_BUFFER, sizeof(V3F_C4B)*_bufferCapacity, _buffer, GL_STREAM_DRAW); + _dirty = false; + } + if (Configuration::getInstance()->supportsShareableVAO()) + { + GL::bindVAO(_vao); + } + else + { + GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX); + + glBindBuffer(GL_ARRAY_BUFFER, _vbo); + // vertex + glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, sizeof(V3F_C4B), (GLvoid *)offsetof(V3F_C4B, vertices)); + + // color + glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(V3F_C4B), (GLvoid *)offsetof(V3F_C4B, colors)); + } + + glDrawArrays(GL_LINES, 0, _bufferCount); + glBindBuffer(GL_ARRAY_BUFFER, 0); + + CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1,_bufferCount); + glDisable(GL_DEPTH_TEST); + CHECK_GL_ERROR_DEBUG(); +} + +void DrawNode3D::drawLine(const Vec3 &from, const Vec3 &to, const Color4F &color) +{ + unsigned int vertex_count = 2; + ensureCapacity(vertex_count); + + Color4B col = Color4B(color); + V3F_C4B a = {Vec3(from.x, from.y, from.z), col}; + V3F_C4B b = {Vec3(to.x, to.y, to.z), col, }; + + V3F_C4B *lines = (V3F_C4B *)(_buffer + _bufferCount); + lines[0] = a; + lines[1] = b; + + _bufferCount += vertex_count; + _dirty = true; + +} + +void DrawNode3D::drawCube(Vec3* vertices, const Color4F &color) +{ + // front face + drawLine(vertices[0], vertices[1], color); + drawLine(vertices[1], vertices[2], color); + drawLine(vertices[2], vertices[3], color); + drawLine(vertices[3], vertices[0], color); + + // back face + drawLine(vertices[4], vertices[5], color); + drawLine(vertices[5], vertices[6], color); + drawLine(vertices[6], vertices[7], color); + drawLine(vertices[7], vertices[4], color); + + // edge + drawLine(vertices[0], vertices[7], color); + drawLine(vertices[1], vertices[6], color); + drawLine(vertices[2], vertices[5], color); + drawLine(vertices[3], vertices[4], color); +} + +void DrawNode3D::clear() +{ + _bufferCount = 0; + _dirty = true; +} + +const BlendFunc& DrawNode3D::getBlendFunc() const +{ + return _blendFunc; +} + +void DrawNode3D::setBlendFunc(const BlendFunc &blendFunc) +{ + _blendFunc = blendFunc; +} + +NS_CC_END + +/** + * bindings for cc.DrawNode3D + **/ +JSClass *jsb_cocos2d_DrawNode3D_class; +JSObject *jsb_cocos2d_DrawNode3D_prototype; + +bool js_cocos2dx_DrawNode3D_getBlendFunc(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::DrawNode3D* cobj = (cocos2d::DrawNode3D *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_DrawNode3D_getBlendFunc : Invalid Native Object"); + if (argc == 0) { + const cocos2d::BlendFunc& ret = cobj->getBlendFunc(); + jsval jsret = JSVAL_NULL; + jsret = blendfunc_to_jsval(cx, ret); + args.rval().set(jsret); + return true; + } + + JS_ReportError(cx, "js_cocos2dx_DrawNode3D_getBlendFunc : wrong number of arguments: %d, was expecting %d", argc, 0); + return false; +} +bool js_cocos2dx_DrawNode3D_setBlendFunc(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::DrawNode3D* cobj = (cocos2d::DrawNode3D *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_DrawNode3D_setBlendFunc : Invalid Native Object"); + if (argc == 1) { + cocos2d::BlendFunc arg0; + ok &= jsval_to_blendfunc(cx, args.get(0), &arg0); + JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_DrawNode3D_setBlendFunc : Error processing arguments"); + cobj->setBlendFunc(arg0); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_cocos2dx_DrawNode3D_setBlendFunc : wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} +bool js_cocos2dx_DrawNode3D_drawLine(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::DrawNode3D* cobj = (cocos2d::DrawNode3D *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_DrawNode3D_drawLine : Invalid Native Object"); + if (argc == 3) { + cocos2d::Vec3 arg0; + cocos2d::Vec3 arg1; + cocos2d::Color4F arg2; + ok &= jsval_to_vector3(cx, args.get(0), &arg0); + ok &= jsval_to_vector3(cx, args.get(1), &arg1); + ok &= jsval_to_cccolor4f(cx, args.get(2), &arg2); + JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_DrawNode3D_drawLine : Error processing arguments"); + cobj->drawLine(arg0, arg1, arg2); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_cocos2dx_DrawNode3D_drawLine : wrong number of arguments: %d, was expecting %d", argc, 3); + return false; +} +bool js_cocos2dx_DrawNode3D_clear(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::DrawNode3D* cobj = (cocos2d::DrawNode3D *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_DrawNode3D_clear : Invalid Native Object"); + if (argc == 0) { + cobj->clear(); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_cocos2dx_DrawNode3D_clear : wrong number of arguments: %d, was expecting %d", argc, 0); + return false; +} +bool js_cocos2dx_DrawNode3D_onDraw(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::DrawNode3D* cobj = (cocos2d::DrawNode3D *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_DrawNode3D_onDraw : Invalid Native Object"); + if (argc == 2) { + cocos2d::Mat4 arg0; + unsigned int arg1; + ok &= jsval_to_matrix(cx, args.get(0), &arg0); + ok &= jsval_to_uint32(cx, args.get(1), &arg1); + JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_DrawNode3D_onDraw : Error processing arguments"); + cobj->onDraw(arg0, arg1); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_cocos2dx_DrawNode3D_onDraw : wrong number of arguments: %d, was expecting %d", argc, 2); + return false; +} +bool js_cocos2dx_DrawNode3D_init(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::DrawNode3D* cobj = (cocos2d::DrawNode3D *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_DrawNode3D_init : Invalid Native Object"); + if (argc == 0) { + bool ret = cobj->init(); + jsval jsret = JSVAL_NULL; + jsret = BOOLEAN_TO_JSVAL(ret); + args.rval().set(jsret); + return true; + } + + JS_ReportError(cx, "js_cocos2dx_DrawNode3D_init : wrong number of arguments: %d, was expecting %d", argc, 0); + return false; +} +bool js_cocos2dx_DrawNode3D_drawCube(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::DrawNode3D* cobj = (cocos2d::DrawNode3D *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_DrawNode3D_drawCube : Invalid Native Object"); + if (argc == 2) { + cocos2d::Vec3 arg0[8]; + cocos2d::Color4F arg1; + + JS::RootedObject jsVec3Array(cx, args.get(0).toObjectOrNull()); + JSB_PRECONDITION3( jsVec3Array && JS_IsArrayObject( cx, jsVec3Array), cx, false, "augument must be an array"); + uint32_t len = 0; + JS_GetArrayLength(cx, jsVec3Array, &len); + + if (len != 8) + { + JS_ReportError(cx, "array length error: %d, was expecting 8", len); + } + for (uint32_t i=0; i < len; i++) + { + JS::RootedValue value(cx); + if (JS_GetElement(cx, jsVec3Array, i, &value)) + { + ok &= jsval_to_vector3(cx, value, &arg0[i]); + if(!ok) + break; + } + } + + ok &= jsval_to_cccolor4f(cx, args.get(1), &arg1); + + JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_DrawNode3D_drawCube : Error processing arguments"); + cobj->drawCube(arg0, arg1); + + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_cocos2dx_DrawNode3D_drawCube : wrong number of arguments: %d, was expecting %d", argc, 2); + return false; +} + +bool js_cocos2dx_DrawNode3D_constructor(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + cocos2d::DrawNode3D* cobj = new (std::nothrow) cocos2d::DrawNode3D(); + cobj->init(); + cocos2d::Ref *_ccobj = dynamic_cast(cobj); + if (_ccobj) { + _ccobj->autorelease(); + } + TypeTest t; + js_type_class_t *typeClass = nullptr; + std::string typeName = t.s_name(); + auto typeMapIter = _js_global_type_map.find(typeName); + 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::RootedObject proto(cx, typeClass->proto.get()); + JS::RootedObject parent(cx, typeClass->parentProto.get()); + JS::RootedObject obj(cx, JS_NewObject(cx, typeClass->jsclass, proto, parent)); + args.rval().set(OBJECT_TO_JSVAL(obj)); + // link the native object with the javascript object + js_proxy_t* p = jsb_new_proxy(cobj, obj); + AddNamedObjectRoot(cx, &p->obj, "cocos2d::DrawNode3D"); + if (JS_HasProperty(cx, obj, "_ctor", &ok) && ok) + ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(obj), "_ctor", args); + return true; +} + +static bool js_is_native_obj(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + args.rval().setBoolean(true); + return true; +} + +extern JSObject *jsb_cocos2d_Node_prototype; + +void js_cocos2d_DrawNode3D_finalize(JSFreeOp *fop, JSObject *obj) { + CCLOGINFO("jsbindings: finalizing JS object %p (DrawNode3D)", obj); +} + +void js_register_cocos2dx_DrawNode3D(JSContext *cx, JS::HandleObject global) { + jsb_cocos2d_DrawNode3D_class = (JSClass *)calloc(1, sizeof(JSClass)); + jsb_cocos2d_DrawNode3D_class->name = "DrawNode3D"; + jsb_cocos2d_DrawNode3D_class->addProperty = JS_PropertyStub; + jsb_cocos2d_DrawNode3D_class->delProperty = JS_DeletePropertyStub; + jsb_cocos2d_DrawNode3D_class->getProperty = JS_PropertyStub; + jsb_cocos2d_DrawNode3D_class->setProperty = JS_StrictPropertyStub; + jsb_cocos2d_DrawNode3D_class->enumerate = JS_EnumerateStub; + jsb_cocos2d_DrawNode3D_class->resolve = JS_ResolveStub; + jsb_cocos2d_DrawNode3D_class->convert = JS_ConvertStub; + jsb_cocos2d_DrawNode3D_class->finalize = js_cocos2d_DrawNode3D_finalize; + jsb_cocos2d_DrawNode3D_class->flags = JSCLASS_HAS_RESERVED_SLOTS(2); + + static JSPropertySpec properties[] = { + JS_PSG("__nativeObj", js_is_native_obj, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_PS_END + }; + + static JSFunctionSpec funcs[] = { + JS_FN("getBlendFunc", js_cocos2dx_DrawNode3D_getBlendFunc, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("setBlendFunc", js_cocos2dx_DrawNode3D_setBlendFunc, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("drawLine", js_cocos2dx_DrawNode3D_drawLine, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("clear", js_cocos2dx_DrawNode3D_clear, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("onDraw", js_cocos2dx_DrawNode3D_onDraw, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("init", js_cocos2dx_DrawNode3D_init, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("drawCube", js_cocos2dx_DrawNode3D_drawCube, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FS_END + }; + + static JSFunctionSpec st_funcs[] = { + JS_FS_END + }; + + jsb_cocos2d_DrawNode3D_prototype = JS_InitClass( + cx, global, + JS::RootedObject(cx, jsb_cocos2d_Node_prototype), + jsb_cocos2d_DrawNode3D_class, + js_cocos2dx_DrawNode3D_constructor, 0, // constructor + properties, + funcs, + NULL, // no static properties + st_funcs); + // make the class enumerable in the registered namespace +// bool found; +//FIXME: Removed in Firefox v27 +// JS_SetPropertyAttributes(cx, global, "DrawNode3D", JSPROP_ENUMERATE | JSPROP_READONLY, &found); + + // add the proto and JSClass to the type->js info hash table + TypeTest t; + js_type_class_t *p; + std::string typeName = t.s_name(); + if (_js_global_type_map.find(typeName) == _js_global_type_map.end()) + { + p = (js_type_class_t *)malloc(sizeof(js_type_class_t)); + p->jsclass = jsb_cocos2d_DrawNode3D_class; + p->proto = jsb_cocos2d_DrawNode3D_prototype; + p->parentProto = jsb_cocos2d_Node_prototype; + _js_global_type_map.insert(std::make_pair(typeName, p)); + } +} + +void register_DrawNode3D_bindings(JSContext *cx, JS::HandleObject global) +{ + JS::RootedObject ccobj(cx); + get_or_create_js_obj(cx, global, "cc", &ccobj); + js_register_cocos2dx_DrawNode3D(cx, ccobj); +} \ No newline at end of file diff --git a/tests/js-tests/project/Classes/js_DrawNode3D_bindings.h b/tests/js-tests/project/Classes/js_DrawNode3D_bindings.h new file mode 100644 index 0000000000..810e186765 --- /dev/null +++ b/tests/js-tests/project/Classes/js_DrawNode3D_bindings.h @@ -0,0 +1,31 @@ +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies 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 __js_tests_bindings_h__ +#define __js_tests_bindings_h__ + +#include "jsapi.h" + +void register_DrawNode3D_bindings(JSContext *cx, JS::HandleObject global); + +#endif diff --git a/tests/js-tests/project/Classes/js_Effect3D_bindings.cpp b/tests/js-tests/project/Classes/js_Effect3D_bindings.cpp new file mode 100644 index 0000000000..f83aeca744 --- /dev/null +++ b/tests/js-tests/project/Classes/js_Effect3D_bindings.cpp @@ -0,0 +1,777 @@ +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies 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 "js_Effect3D_bindings.h" +#include "cocos2d_specifics.hpp" + +using namespace cocos2d; + +class EffectSprite3D; + +class Effect3D : public Ref +{ +public: + virtual void draw(const Mat4 &transform) = 0; + virtual void setTarget(EffectSprite3D *sprite) = 0; +protected: + Effect3D() : _glProgramState(nullptr) {} + virtual ~Effect3D() + { + CC_SAFE_RELEASE(_glProgramState); + } +protected: + GLProgramState* _glProgramState; +}; + +class Effect3DOutline: public Effect3D +{ +public: + static Effect3DOutline* create(); + + void setOutlineColor(const Vec3& color); + + void setOutlineWidth(float width); + + virtual void draw(const Mat4 &transform) override; + virtual void setTarget(EffectSprite3D *sprite) override; + + + Effect3DOutline(); + virtual ~Effect3DOutline(); + + bool init(); +protected: + Vec3 _outlineColor; + float _outlineWidth; + //weak reference + EffectSprite3D* _sprite; +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WP8 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) + EventListenerCustom* _backToForegroundListener; +#endif + +protected: + static const std::string _vertShaderFile; + static const std::string _fragShaderFile; + static const std::string _keyInGLProgramCache; + + static const std::string _vertSkinnedShaderFile; + static const std::string _fragSkinnedShaderFile; + static const std::string _keySkinnedInGLProgramCache; + + static GLProgram* getOrCreateProgram(bool isSkinned = false); +}; + +class EffectSprite3D : public Sprite3D +{ +public: + static EffectSprite3D* createFromObjFileAndTexture(const std::string& objFilePath, const std::string& textureFilePath); + static EffectSprite3D* create(const std::string& path); + + void setEffect3D(Effect3D* effect); + void addEffect(Effect3DOutline* effect, ssize_t order); + virtual void draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) override; + + EffectSprite3D(); + virtual ~EffectSprite3D(); +protected: + std::vector> _effects; + Effect3D* _defaultEffect; + CustomCommand _command; +}; + + +EffectSprite3D* EffectSprite3D::createFromObjFileAndTexture(const std::string &objFilePath, const std::string &textureFilePath) +{ + auto sprite = new (std::nothrow) EffectSprite3D(); + if (sprite && sprite->initWithFile(objFilePath)) + { + sprite->autorelease(); + if(textureFilePath.size() > 0) + sprite->setTexture(textureFilePath); + return sprite; + } + CC_SAFE_DELETE(sprite); + return nullptr; +} + +EffectSprite3D* EffectSprite3D::create(const std::string &path) +{ + if (path.length() < 4) + CCASSERT(false, "improper name specified when creating Sprite3D"); + + auto sprite = new (std::nothrow) EffectSprite3D(); + if (sprite && sprite->initWithFile(path)) + { + sprite->autorelease(); + return sprite; + } + CC_SAFE_DELETE(sprite); + return nullptr; +} + +EffectSprite3D::EffectSprite3D() +: _defaultEffect(nullptr) +{ + +} + +EffectSprite3D::~EffectSprite3D() +{ + for(auto effect : _effects) + { + CC_SAFE_RELEASE_NULL(std::get<1>(effect)); + } + CC_SAFE_RELEASE(_defaultEffect); +} + +void EffectSprite3D::setEffect3D(Effect3D *effect) +{ + if(_defaultEffect == effect) return; + CC_SAFE_RETAIN(effect); + CC_SAFE_RELEASE(_defaultEffect); + _defaultEffect = effect; +} + +static int tuple_sort( const std::tuple &tuple1, const std::tuple &tuple2 ) +{ + return std::get<0>(tuple1) < std::get<0>(tuple2); +} + +void EffectSprite3D::addEffect(Effect3DOutline* effect, ssize_t order) +{ + if(nullptr == effect) return; + effect->retain(); + effect->setTarget(this); + + _effects.push_back(std::make_tuple(order,effect,CustomCommand())); + + std::sort(std::begin(_effects), std::end(_effects), tuple_sort); +} + +const std::string Effect3DOutline::_vertShaderFile = "Shaders3D/OutLine.vert"; +const std::string Effect3DOutline::_fragShaderFile = "Shaders3D/OutLine.frag"; +const std::string Effect3DOutline::_keyInGLProgramCache = "Effect3DLibrary_Outline"; + +const std::string Effect3DOutline::_vertSkinnedShaderFile = "Shaders3D/SkinnedOutline.vert"; +const std::string Effect3DOutline::_fragSkinnedShaderFile = "Shaders3D/OutLine.frag"; +const std::string Effect3DOutline::_keySkinnedInGLProgramCache = "Effect3DLibrary_Outline"; +GLProgram* Effect3DOutline::getOrCreateProgram(bool isSkinned /* = false */ ) +{ + if(isSkinned) + { + auto program = GLProgramCache::getInstance()->getGLProgram(_keySkinnedInGLProgramCache); + if(program == nullptr) + { + program = GLProgram::createWithFilenames(_vertSkinnedShaderFile, _fragSkinnedShaderFile); + GLProgramCache::getInstance()->addGLProgram(program, _keySkinnedInGLProgramCache); + } + return program; + } + else + { + auto program = GLProgramCache::getInstance()->getGLProgram(_keyInGLProgramCache); + if(program == nullptr) + { + program = GLProgram::createWithFilenames(_vertShaderFile, _fragShaderFile); + GLProgramCache::getInstance()->addGLProgram(program, _keyInGLProgramCache); + } + return program; + } + +} + +Effect3DOutline* Effect3DOutline::create() +{ + Effect3DOutline* effect = new (std::nothrow) Effect3DOutline(); + if(effect && effect->init()) + { + effect->autorelease(); + return effect; + } + else + { + CC_SAFE_DELETE(effect); + return nullptr; + } +} + +bool Effect3DOutline::init() +{ + + return true; +} + +Effect3DOutline::Effect3DOutline() +: _outlineWidth(1.0f) +, _outlineColor(1, 1, 1) +, _sprite(nullptr) +{ +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WP8 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) + _backToForegroundListener = EventListenerCustom::create(EVENT_RENDERER_RECREATED, + [this](EventCustom*) + { + auto glProgram = _glProgramState->getGLProgram(); + glProgram->reset(); + glProgram->initWithFilenames(_vertShaderFile, _fragShaderFile); + glProgram->link(); + glProgram->updateUniforms(); + } + ); + Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(_backToForegroundListener, -1); +#endif +} + +Effect3DOutline::~Effect3DOutline() +{ +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WP8 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) + Director::getInstance()->getEventDispatcher()->removeEventListener(_backToForegroundListener); +#endif +} + +void Effect3DOutline::setOutlineColor(const Vec3& color) +{ + if(_outlineColor != color) + { + _outlineColor = color; + if(_glProgramState) + _glProgramState->setUniformVec3("OutLineColor", _outlineColor); + } +} + +void Effect3DOutline::setOutlineWidth(float width) +{ + if(_outlineWidth != width) + { + _outlineWidth = width; + if(_glProgramState) + _glProgramState->setUniformFloat("OutlineWidth", _outlineWidth); + } +} + +void Effect3DOutline::setTarget(EffectSprite3D *sprite) +{ + CCASSERT(nullptr != sprite && nullptr != sprite->getMesh(),"Error: Setting a null pointer or a null mesh EffectSprite3D to Effect3D"); + + if(sprite != _sprite) + { + GLProgram* glprogram; + if(!sprite->getMesh()->getSkin()) + glprogram = GLProgram::createWithFilenames(_vertShaderFile, _fragShaderFile); + else + glprogram = GLProgram::createWithFilenames(_vertSkinnedShaderFile, _fragSkinnedShaderFile); + + _glProgramState = GLProgramState::create(glprogram); + + _glProgramState->retain(); + _glProgramState->setUniformVec3("OutLineColor", _outlineColor); + _glProgramState->setUniformFloat("OutlineWidth", _outlineWidth); + + + _sprite = sprite; + + auto mesh = sprite->getMesh(); + long offset = 0; + for (auto i = 0; i < mesh->getMeshVertexAttribCount(); i++) + { + auto meshvertexattrib = mesh->getMeshVertexAttribute(i); + + _glProgramState->setVertexAttribPointer(s_attributeNames[meshvertexattrib.vertexAttrib], + meshvertexattrib.size, + meshvertexattrib.type, + GL_FALSE, + mesh->getVertexSizeInBytes(), + (void*)offset); + offset += meshvertexattrib.attribSizeBytes; + } + + Color4F color(_sprite->getDisplayedColor()); + color.a = _sprite->getDisplayedOpacity() / 255.0f; + _glProgramState->setUniformVec4("u_color", Vec4(color.r, color.g, color.b, color.a)); + } + +} + +static void MatrixPalleteCallBack( GLProgram* glProgram, Uniform* uniform, int paletteSize, const float* palette) +{ + glUniform4fv( uniform->location, (GLsizei)paletteSize, (const float*)palette ); +} + +void Effect3DOutline::draw(const Mat4 &transform) +{ + //draw + Color4F color(_sprite->getDisplayedColor()); + color.a = _sprite->getDisplayedOpacity() / 255.0f; + _glProgramState->setUniformVec4("u_color", Vec4(color.r, color.g, color.b, color.a)); + if(_sprite && _sprite->getMesh()) + { + glEnable(GL_CULL_FACE); + glCullFace(GL_FRONT); + glEnable(GL_DEPTH_TEST); + + auto mesh = _sprite->getMesh(); + glBindBuffer(GL_ARRAY_BUFFER, mesh->getVertexBuffer()); + + auto skin = _sprite->getMesh()->getSkin(); + if(_sprite && skin) + { + auto function = std::bind(MatrixPalleteCallBack, std::placeholders::_1, std::placeholders::_2, + skin->getMatrixPaletteSize(), (float*)skin->getMatrixPalette()); + _glProgramState->setUniformCallback("u_matrixPalette", function); + } + + if(_sprite) + _glProgramState->apply(transform); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->getIndexBuffer()); + glDrawElements(mesh->getPrimitiveType(), (GLsizei)mesh->getIndexCount(), mesh->getIndexFormat(), 0); + CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1, mesh->getIndexCount()); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + glBindBuffer(GL_ARRAY_BUFFER, 0); + glDisable(GL_DEPTH_TEST); + glCullFace(GL_BACK); + glDisable(GL_CULL_FACE); + } +} + +void EffectSprite3D::draw(cocos2d::Renderer *renderer, const cocos2d::Mat4 &transform, uint32_t flags) +{ + for(auto &effect : _effects) + { + if(std::get<0>(effect) >=0) + break; + CustomCommand &cc = std::get<2>(effect); + cc.func = CC_CALLBACK_0(Effect3D::draw,std::get<1>(effect),transform); + renderer->addCommand(&cc); + + } + + if(!_defaultEffect) + { + Sprite3D::draw(renderer, transform, flags); + } + else + { + _command.init(_globalZOrder, transform, flags); + _command.func = CC_CALLBACK_0(Effect3D::draw, _defaultEffect, transform); + renderer->addCommand(&_command); + } + + for(auto &effect : _effects) + { + if(std::get<0>(effect) <=0) + continue; + CustomCommand &cc = std::get<2>(effect); + cc.func = CC_CALLBACK_0(Effect3D::draw,std::get<1>(effect),transform); + renderer->addCommand(&cc); + + } +} + +// js bindings + +static bool js_is_native_obj(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + args.rval().setBoolean(true); + return true; +} + +JSClass *jsb_Effect3DOutline_class; +JSObject *jsb_Effect3DOutline_prototype; + +bool js_cocos2dx_Effect3DOutline_setOutlineWidth(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + Effect3DOutline* cobj = (Effect3DOutline *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_Effect3DOutline_setOutlineWidth : Invalid Native Object"); + if (argc == 1) { + double arg0; + ok &= JS::ToNumber( cx, args.get(0), &arg0) && !isnan(arg0); + JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_Effect3DOutline_setOutlineWidth : Error processing arguments"); + cobj->setOutlineWidth(arg0); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_cocos2dx_Effect3DOutline_setOutlineWidth : wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} +bool js_cocos2dx_Effect3DOutline_setOutlineColor(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + Effect3DOutline* cobj = (Effect3DOutline *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_Effect3DOutline_setOutlineColor : Invalid Native Object"); + if (argc == 1) { + cocos2d::Vec3 arg0; + ok &= jsval_to_vector3(cx, args.get(0), &arg0); + JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_Effect3DOutline_setOutlineColor : Error processing arguments"); + cobj->setOutlineColor(arg0); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_cocos2dx_Effect3DOutline_setOutlineColor : wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} +bool js_cocos2dx_Effect3DOutline_create(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + if (argc == 0) { + Effect3DOutline* ret = Effect3DOutline::create(); + jsval jsret = JSVAL_NULL; + do { + if (ret) { + js_proxy_t *jsProxy = js_get_or_create_proxy(cx, (Effect3DOutline*)ret); + jsret = OBJECT_TO_JSVAL(jsProxy->obj); + } else { + jsret = JSVAL_NULL; + } + } while (0); + args.rval().set(jsret); + return true; + } + JS_ReportError(cx, "js_cocos2dx_Effect3DOutline_create : wrong number of arguments"); + return false; +} + + +JSObject *jsb_Effect3D_prototype; + +void js_Effect3DOutline_finalize(JSFreeOp *fop, JSObject *obj) { + CCLOGINFO("jsbindings: finalizing JS object %p (Effect3DOutline)", obj); +} + +bool jsb_Effect3DOutline_constructor(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + Effect3DOutline* cobj = new (std::nothrow) Effect3DOutline(); + cobj->init(); + cobj->autorelease(); + TypeTest t; + js_type_class_t *typeClass = nullptr; + std::string typeName = t.s_name(); + auto typeMapIter = _js_global_type_map.find(typeName); + 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::RootedObject proto(cx, typeClass->proto.get()); + JS::RootedObject parent(cx, typeClass->parentProto.get()); + JS::RootedObject obj(cx, JS_NewObject(cx, typeClass->jsclass, proto, parent)); + args.rval().set(OBJECT_TO_JSVAL(obj)); + // link the native object with the javascript object + js_proxy_t* p = jsb_new_proxy(cobj, obj); + AddNamedObjectRoot(cx, &p->obj, "cocos2d::Effect3DOutline"); + if (JS_HasProperty(cx, obj, "_ctor", &ok) && ok) + ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(obj), "_ctor", args); + return true; +} + +void js_register_cocos2dx_Effect3DOutline(JSContext *cx, JS::HandleObject global) { + jsb_Effect3DOutline_class = (JSClass *)calloc(1, sizeof(JSClass)); + jsb_Effect3DOutline_class->name = "Effect3DOutline"; + jsb_Effect3DOutline_class->addProperty = JS_PropertyStub; + jsb_Effect3DOutline_class->delProperty = JS_DeletePropertyStub; + jsb_Effect3DOutline_class->getProperty = JS_PropertyStub; + jsb_Effect3DOutline_class->setProperty = JS_StrictPropertyStub; + jsb_Effect3DOutline_class->enumerate = JS_EnumerateStub; + jsb_Effect3DOutline_class->resolve = JS_ResolveStub; + jsb_Effect3DOutline_class->convert = JS_ConvertStub; + jsb_Effect3DOutline_class->finalize = js_Effect3DOutline_finalize; + jsb_Effect3DOutline_class->flags = JSCLASS_HAS_RESERVED_SLOTS(2); + + static JSPropertySpec properties[] = { + JS_PSG("__nativeObj", js_is_native_obj, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_PS_END + }; + + static JSFunctionSpec funcs[] = { + JS_FN("setOutlineWidth", js_cocos2dx_Effect3DOutline_setOutlineWidth, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("setOutlineColor", js_cocos2dx_Effect3DOutline_setOutlineColor, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FS_END + }; + + static JSFunctionSpec st_funcs[] = { + JS_FN("create", js_cocos2dx_Effect3DOutline_create, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FS_END + }; + + jsb_Effect3DOutline_prototype = JS_InitClass( + cx, global, + JS::RootedObject(cx, jsb_Effect3D_prototype), + jsb_Effect3DOutline_class, + jsb_Effect3DOutline_constructor, 0, + properties, + funcs, + NULL, // no static properties + st_funcs); + // make the class enumerable in the registered namespace + // bool found; + //FIXME: Removed in Firefox v27 + // JS_SetPropertyAttributes(cx, global, "Effect3DOutline", JSPROP_ENUMERATE | JSPROP_READONLY, &found); + + // add the proto and JSClass to the type->js info hash table + TypeTest t; + js_type_class_t *p; + std::string typeName = t.s_name(); + if (_js_global_type_map.find(typeName) == _js_global_type_map.end()) + { + p = (js_type_class_t *)malloc(sizeof(js_type_class_t)); + p->jsclass = jsb_Effect3DOutline_class; + p->proto = jsb_Effect3DOutline_prototype; + p->parentProto = jsb_Effect3D_prototype; + _js_global_type_map.insert(std::make_pair(typeName, p)); + } +} + + +JSClass *jsb_EffectSprite3D_class; +JSObject *jsb_EffectSprite3D_prototype; + +bool js_cocos2dx_EffectSprite3D_setEffect3D(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + EffectSprite3D* cobj = (EffectSprite3D *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_EffectSprite3D_setEffect3D : Invalid Native Object"); + if (argc == 1) { + Effect3D* arg0; + do { + if (!args.get(0).isObject()) { ok = false; break; } + js_proxy_t *jsProxy; + JSObject *tmpObj = args.get(0).toObjectOrNull(); + jsProxy = jsb_get_js_proxy(tmpObj); + arg0 = (Effect3D*)(jsProxy ? jsProxy->ptr : NULL); + JSB_PRECONDITION2( arg0, cx, false, "Invalid Native Object"); + } while (0); + JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_EffectSprite3D_setEffect3D : Error processing arguments"); + cobj->setEffect3D(arg0); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_cocos2dx_EffectSprite3D_setEffect3D : wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} +bool js_cocos2dx_EffectSprite3D_addEffect(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + EffectSprite3D* cobj = (EffectSprite3D *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_EffectSprite3D_addEffect : Invalid Native Object"); + if (argc == 2) { + Effect3DOutline* arg0; + ssize_t arg1; + do { + if (!args.get(0).isObject()) { ok = false; break; } + js_proxy_t *jsProxy; + JSObject *tmpObj = args.get(0).toObjectOrNull(); + jsProxy = jsb_get_js_proxy(tmpObj); + arg0 = (Effect3DOutline*)(jsProxy ? jsProxy->ptr : NULL); + JSB_PRECONDITION2( arg0, cx, false, "Invalid Native Object"); + } while (0); + ok &= jsval_to_ssize(cx, args.get(1), &arg1); + JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_EffectSprite3D_addEffect : Error processing arguments"); + cobj->addEffect(arg0, arg1); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_cocos2dx_EffectSprite3D_addEffect : wrong number of arguments: %d, was expecting %d", argc, 2); + return false; +} +bool js_cocos2dx_EffectSprite3D_createFromObjFileAndTexture(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + if (argc == 2) { + std::string arg0; + std::string arg1; + ok &= jsval_to_std_string(cx, args.get(0), &arg0); + ok &= jsval_to_std_string(cx, args.get(1), &arg1); + JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_EffectSprite3D_createFromObjFileAndTexture : Error processing arguments"); + EffectSprite3D* ret = EffectSprite3D::createFromObjFileAndTexture(arg0, arg1); + jsval jsret = JSVAL_NULL; + do { + if (ret) { + js_proxy_t *jsProxy = js_get_or_create_proxy(cx, (EffectSprite3D*)ret); + jsret = OBJECT_TO_JSVAL(jsProxy->obj); + } else { + jsret = JSVAL_NULL; + } + } while (0); + args.rval().set(jsret); + return true; + } + JS_ReportError(cx, "js_cocos2dx_EffectSprite3D_createFromObjFileAndTexture : wrong number of arguments"); + return false; +} + +bool js_cocos2dx_EffectSprite3D_create(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + if (argc == 1) { + std::string arg0; + ok &= jsval_to_std_string(cx, args.get(0), &arg0); + JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_EffectSprite3D_create : Error processing arguments"); + EffectSprite3D* ret = EffectSprite3D::create(arg0); + jsval jsret = JSVAL_NULL; + do { + if (ret) { + js_proxy_t *jsProxy = js_get_or_create_proxy(cx, (EffectSprite3D*)ret); + jsret = OBJECT_TO_JSVAL(jsProxy->obj); + } else { + jsret = JSVAL_NULL; + } + } while (0); + args.rval().set(jsret); + return true; + } + JS_ReportError(cx, "js_cocos2dx_EffectSprite3D_create : wrong number of arguments"); + return false; +} + + +extern JSObject *jsb_cocos2d_Sprite3D_prototype; + +void js_EffectSprite3D_finalize(JSFreeOp *fop, JSObject *obj) { + CCLOGINFO("jsbindings: finalizing JS object %p (EffectSprite3D)", obj); +} + +bool jsb_EffectSprite3D_constructor(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + EffectSprite3D* cobj = new (std::nothrow) EffectSprite3D(); + if(argc == 1 || argc == 2) + { + std::string path; + jsval_to_std_string(cx, args.get(0), &path); + cobj->initWithFile(path); + if(argc == 2) + { + std::string texture; + jsval_to_std_string(cx, args.get(1), &texture); + cobj->setTexture(texture); + } + } + cobj->autorelease(); + TypeTest t; + js_type_class_t *typeClass = nullptr; + std::string typeName = t.s_name(); + auto typeMapIter = _js_global_type_map.find(typeName); + 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::RootedObject proto(cx, typeClass->proto.get()); + JS::RootedObject parent(cx, typeClass->parentProto.get()); + JS::RootedObject obj(cx, JS_NewObject(cx, typeClass->jsclass, proto, parent)); + args.rval().set(OBJECT_TO_JSVAL(obj)); + // link the native object with the javascript object + js_proxy_t* p = jsb_new_proxy(cobj, obj); + AddNamedObjectRoot(cx, &p->obj, "cocos2d::EffectSprite3D"); + if (JS_HasProperty(cx, obj, "_ctor", &ok) && ok) + ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(obj), "_ctor", args); + return true; +} + +void js_register_cocos2dx_EffectSprite3D(JSContext *cx, JS::HandleObject global) { + jsb_EffectSprite3D_class = (JSClass *)calloc(1, sizeof(JSClass)); + jsb_EffectSprite3D_class->name = "EffectSprite3D"; + jsb_EffectSprite3D_class->addProperty = JS_PropertyStub; + jsb_EffectSprite3D_class->delProperty = JS_DeletePropertyStub; + jsb_EffectSprite3D_class->getProperty = JS_PropertyStub; + jsb_EffectSprite3D_class->setProperty = JS_StrictPropertyStub; + jsb_EffectSprite3D_class->enumerate = JS_EnumerateStub; + jsb_EffectSprite3D_class->resolve = JS_ResolveStub; + jsb_EffectSprite3D_class->convert = JS_ConvertStub; + jsb_EffectSprite3D_class->finalize = js_EffectSprite3D_finalize; + jsb_EffectSprite3D_class->flags = JSCLASS_HAS_RESERVED_SLOTS(2); + + static JSPropertySpec properties[] = { + JS_PSG("__nativeObj", js_is_native_obj, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_PS_END + }; + + static JSFunctionSpec funcs[] = { + JS_FN("setEffect3D", js_cocos2dx_EffectSprite3D_setEffect3D, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("addEffect", js_cocos2dx_EffectSprite3D_addEffect, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FS_END + }; + + static JSFunctionSpec st_funcs[] = { + JS_FN("createFromObjFileAndTexture", js_cocos2dx_EffectSprite3D_createFromObjFileAndTexture, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("create", js_cocos2dx_EffectSprite3D_create, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FS_END + }; + + jsb_EffectSprite3D_prototype = JS_InitClass( + cx, global, + JS::RootedObject(cx, jsb_cocos2d_Sprite3D_prototype), + jsb_EffectSprite3D_class, + jsb_EffectSprite3D_constructor, 1, + properties, + funcs, + NULL, // no static properties + st_funcs); + // make the class enumerable in the registered namespace + // bool found; + //FIXME: Removed in Firefox v27 + // JS_SetPropertyAttributes(cx, global, "EffectSprite3D", JSPROP_ENUMERATE | JSPROP_READONLY, &found); + + // add the proto and JSClass to the type->js info hash table + TypeTest t; + js_type_class_t *p; + std::string typeName = t.s_name(); + if (_js_global_type_map.find(typeName) == _js_global_type_map.end()) + { + p = (js_type_class_t *)malloc(sizeof(js_type_class_t)); + p->jsclass = jsb_EffectSprite3D_class; + p->proto = jsb_EffectSprite3D_prototype; + p->parentProto = jsb_cocos2d_Sprite3D_prototype; + _js_global_type_map.insert(std::make_pair(typeName, p)); + } +} + +void register_Effect3D_bindings(JSContext *cx, JS::HandleObject global) +{ + JS::RootedObject ccobj(cx); + get_or_create_js_obj(cx, global, "cc", &ccobj); + js_register_cocos2dx_Effect3DOutline(cx, ccobj); + js_register_cocos2dx_EffectSprite3D(cx, ccobj); +} \ No newline at end of file diff --git a/tests/js-tests/project/Classes/js_Effect3D_bindings.h b/tests/js-tests/project/Classes/js_Effect3D_bindings.h new file mode 100644 index 0000000000..b5456d6d3b --- /dev/null +++ b/tests/js-tests/project/Classes/js_Effect3D_bindings.h @@ -0,0 +1,31 @@ +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies 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 __js_effect3d_bindings_h__ +#define __js_effect3d_bindings_h__ + +#include "jsapi.h" + +void register_Effect3D_bindings(JSContext *cx, JS::HandleObject global); + +#endif diff --git a/tests/js-tests/project/proj.android/.classpath b/tests/js-tests/project/proj.android/.classpath new file mode 100644 index 0000000000..3cd35c958e --- /dev/null +++ b/tests/js-tests/project/proj.android/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/js-tests/project/proj.android/.project b/tests/js-tests/project/proj.android/.project new file mode 100644 index 0000000000..0649734c25 --- /dev/null +++ b/tests/js-tests/project/proj.android/.project @@ -0,0 +1,49 @@ + + + JSTests + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + com.android.ide.eclipse.adt.ResourceManagerBuilder + + + + + com.android.ide.eclipse.adt.PreCompilerBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + com.android.ide.eclipse.adt.ApkBuilder + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + com.android.ide.eclipse.adt.AndroidNature + org.eclipse.jdt.core.javanature + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/tests/js-tests/project/proj.android/AndroidManifest.xml b/tests/js-tests/project/proj.android/AndroidManifest.xml new file mode 100644 index 0000000000..0e3fe1e035 --- /dev/null +++ b/tests/js-tests/project/proj.android/AndroidManifest.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/js-tests/project/proj.android/ant.properties b/tests/js-tests/project/proj.android/ant.properties new file mode 100644 index 0000000000..f8af38bfb4 --- /dev/null +++ b/tests/js-tests/project/proj.android/ant.properties @@ -0,0 +1 @@ +aapt.ignore.assets="!*.pvr.gz:!*.gz:!.svn:!.git:.*:_*:!CVS:!thumbs.db:!picasa.ini:!*.scc:*~" diff --git a/tests/js-tests/project/proj.android/build-cfg.json b/tests/js-tests/project/proj.android/build-cfg.json new file mode 100644 index 0000000000..4010cc7cdb --- /dev/null +++ b/tests/js-tests/project/proj.android/build-cfg.json @@ -0,0 +1,29 @@ +{ + "copy_resources": [ + { + "from": "../../src", + "to": "src" + }, + { + "from": "../../../cpp-tests/Resources/", + "to": "res/" + }, + { + "from": "../../main.js", + "to": "" + }, + { + "from": "../../project.json", + "to": "" + }, + { + "from": "../../../../cocos/scripting/js-bindings/script", + "to": "script" + } + ], + "ndk_module_path": [ + "../../../..", + "../../../../cocos", + "../../../../external" + ] +} diff --git a/tests/js-tests/project/proj.android/build.xml b/tests/js-tests/project/proj.android/build.xml new file mode 100644 index 0000000000..2f46f6e914 --- /dev/null +++ b/tests/js-tests/project/proj.android/build.xml @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/js-tests/project/proj.android/jni/Android.mk b/tests/js-tests/project/proj.android/jni/Android.mk new file mode 100644 index 0000000000..4ea163a5bb --- /dev/null +++ b/tests/js-tests/project/proj.android/jni/Android.mk @@ -0,0 +1,23 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := js_tests_shared + +LOCAL_MODULE_FILENAME := libjs_tests + +LOCAL_SRC_FILES := main.cpp \ + ../../Classes/AppDelegate.cpp \ + ../../Classes/js_DrawNode3D_bindings.cpp \ + ../../Classes/js_Effect3D_bindings.cpp + +LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes + +LOCAL_STATIC_LIBRARIES := cocos2d_js_static + + +LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=1 + +include $(BUILD_SHARED_LIBRARY) + +$(call import-module,scripting/js-bindings/proj.android) diff --git a/tests/js-tests/project/proj.android/jni/Application.mk b/tests/js-tests/project/proj.android/jni/Application.mk new file mode 100644 index 0000000000..706af60331 --- /dev/null +++ b/tests/js-tests/project/proj.android/jni/Application.mk @@ -0,0 +1,15 @@ +APP_STL := gnustl_static + +# Uncomment this line to compile to armeabi-v7a, your application will run faster but support less devices +#APP_ABI := armeabi-v7a + +APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -std=c++11 -fsigned-char +APP_LDFLAGS := -latomic + +ifeq ($(NDK_DEBUG),1) + APP_CPPFLAGS += -DCOCOS2D_DEBUG=1 + APP_OPTIM := debug +else + APP_CPPFLAGS += -DNDEBUG + APP_OPTIM := release +endif diff --git a/tests/js-tests/project/proj.android/jni/main.cpp b/tests/js-tests/project/proj.android/jni/main.cpp new file mode 100644 index 0000000000..baf5ca9810 --- /dev/null +++ b/tests/js-tests/project/proj.android/jni/main.cpp @@ -0,0 +1,17 @@ +#include "AppDelegate.h" +#include "cocos2d.h" +#include "platform/android/jni/JniHelper.h" +#include +#include + +#define LOG_TAG "main" +#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) + +using namespace cocos2d; + +void cocos_android_app_init (JNIEnv* env, jobject thiz) { + LOGD("cocos_android_app_init"); + AppDelegate *pAppDelegate = new AppDelegate(); + JavaVM* vm; + env->GetJavaVM(&vm); +} diff --git a/tests/js-tests/project/proj.android/ndkgdb.sh b/tests/js-tests/project/proj.android/ndkgdb.sh new file mode 100644 index 0000000000..b8b83e024f --- /dev/null +++ b/tests/js-tests/project/proj.android/ndkgdb.sh @@ -0,0 +1,47 @@ +APPNAME="JSTests" +APP_ANDROID_NAME="org.cocos2dx.js_tests" + +if [ -z "${SDK_ROOT+aaa}" ]; then +# ... if SDK_ROOT is not set, use "$HOME/bin/android-sdk" + SDK_ROOT="$HOME/bin/android-sdk" +fi + +if [ -z "${NDK_ROOT+aaa}" ]; then +# ... if NDK_ROOT is not set, use "$HOME/bin/android-ndk" + NDK_ROOT="$HOME/bin/android-ndk" +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/$APPNAME" + APP_ANDROID_ROOT="$COCOS2DX_ROOT/samples/$APPNAME/proj.android" +fi + +echo "NDK_ROOT = $NDK_ROOT" +echo "SDK_ROOT = $SDK_ROOT" +echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" +echo "APP_ROOT = $APP_ROOT" +echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" +echo "APP_ANDROID_NAME = $APP_ANDROID_NAME" + +echo +echo "Killing and restarting ${APP_ANDROID_NAME}" +echo + +set -x + +"${SDK_ROOT}"/platform-tools/adb shell am force-stop "${APP_ANDROID_NAME}" + +NDK_MODULE_PATH="${COCOS2DX_ROOT}":"${COCOS2DX_ROOT}"/cocos2dx/platform/third_party/android/prebuilt \ + "${NDK_ROOT}"/ndk-gdb \ + --adb="${SDK_ROOT}"/platform-tools/adb \ + --verbose \ + --start \ + --force diff --git a/tests/js-tests/project/proj.android/proguard-project.txt b/tests/js-tests/project/proj.android/proguard-project.txt new file mode 100644 index 0000000000..f2fe1559a2 --- /dev/null +++ b/tests/js-tests/project/proj.android/proguard-project.txt @@ -0,0 +1,20 @@ +# To enable ProGuard in your project, edit project.properties +# to define the proguard.config property as described in that file. +# +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in ${sdk.dir}/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the ProGuard +# include property in project.properties. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/tests/js-tests/project/proj.android/project.properties b/tests/js-tests/project/proj.android/project.properties new file mode 100644 index 0000000000..4bd7647d63 --- /dev/null +++ b/tests/js-tests/project/proj.android/project.properties @@ -0,0 +1,14 @@ +# This file is automatically generated by Android Tools. +# Do not modify this file -- YOUR CHANGES WILL BE ERASED! +# +# This file must be checked in Version Control Systems. +# +# To customize properties used by the Ant build system use, +# "ant.properties", and override values to adapt the script to your +# project structure. + +# Project target. +target=android-10 + +android.library.reference.1=../../../../cocos/platform/android/java +android.library.reference.2=../../../../plugin/plugins/facebook/proj.android/DependProject diff --git a/tests/js-tests/project/proj.android/res/drawable-hdpi/icon.png b/tests/js-tests/project/proj.android/res/drawable-hdpi/icon.png new file mode 100644 index 0000000000..8aa4767c2f Binary files /dev/null and b/tests/js-tests/project/proj.android/res/drawable-hdpi/icon.png differ diff --git a/tests/js-tests/project/proj.android/res/drawable-ldpi/icon.png b/tests/js-tests/project/proj.android/res/drawable-ldpi/icon.png new file mode 100644 index 0000000000..17ce11a085 Binary files /dev/null and b/tests/js-tests/project/proj.android/res/drawable-ldpi/icon.png differ diff --git a/tests/js-tests/project/proj.android/res/drawable-mdpi/icon.png b/tests/js-tests/project/proj.android/res/drawable-mdpi/icon.png new file mode 100644 index 0000000000..3780aac46c Binary files /dev/null and b/tests/js-tests/project/proj.android/res/drawable-mdpi/icon.png differ diff --git a/tests/js-tests/project/proj.android/res/values/strings.xml b/tests/js-tests/project/proj.android/res/values/strings.xml new file mode 100644 index 0000000000..4717131918 --- /dev/null +++ b/tests/js-tests/project/proj.android/res/values/strings.xml @@ -0,0 +1,5 @@ + + + JSTests + 1426774790893461 + diff --git a/tests/js-tests/project/proj.android/src/org/cocos2dx/js_tests/AppActivity.java b/tests/js-tests/project/proj.android/src/org/cocos2dx/js_tests/AppActivity.java new file mode 100644 index 0000000000..a42c8089d7 --- /dev/null +++ b/tests/js-tests/project/proj.android/src/org/cocos2dx/js_tests/AppActivity.java @@ -0,0 +1,80 @@ +/**************************************************************************** +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. +****************************************************************************/ +package org.cocos2dx.js_tests; + +import org.cocos2dx.js_tests.R; +import org.cocos2dx.lib.Cocos2dxActivity; +import org.cocos2dx.lib.Cocos2dxGLSurfaceView; +import org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge; + +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.content.Intent; +import android.os.Bundle; + +public class AppActivity extends Cocos2dxActivity { + + private static AppActivity app = null; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + app = this; + } + + @Override + public Cocos2dxGLSurfaceView onCreateView() { + Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this); + // TestCpp should create stencil buffer + glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8); + + return glSurfaceView; + } + + public static void showAlertDialog(final String title, final String message) { + app.runOnUiThread(new Runnable() { + @Override + public void run() { + AlertDialog alertDialog = new AlertDialog.Builder(app).create(); + alertDialog.setTitle(title); + alertDialog.setMessage(message); + alertDialog.setCancelable(true); + alertDialog.setIcon(R.drawable.icon); + alertDialog.setButton("OK", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + app.runOnGLThread(new Runnable() { + @Override + public void run() { + + Cocos2dxJavascriptJavaBridge.evalString("cc.log(\"Javascript Java bridge!\")"); + } + }); + } + }); + alertDialog.show(); + } + }); + } + +} diff --git a/tests/js-tests/project/proj.ios/AppController.h b/tests/js-tests/project/proj.ios/AppController.h new file mode 100644 index 0000000000..2e8186124e --- /dev/null +++ b/tests/js-tests/project/proj.ios/AppController.h @@ -0,0 +1,35 @@ +/**************************************************************************** + Copyright (c) 2010-2013 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +@class RootViewController; + +@interface AppController : NSObject +{ + UIWindow *window; + RootViewController *viewController; +} + +@end + diff --git a/tests/js-tests/project/proj.ios/AppController.mm b/tests/js-tests/project/proj.ios/AppController.mm new file mode 100644 index 0000000000..127a2d3c20 --- /dev/null +++ b/tests/js-tests/project/proj.ios/AppController.mm @@ -0,0 +1,144 @@ +/**************************************************************************** + Copyright (c) 2010-2013 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +#import +#import "cocos2d.h" +#import "AppController.h" +#import "AppDelegate.h" +#import "RootViewController.h" +#import "platform/ios/CCEAGLView-ios.h" +//#import +@implementation AppController + +#pragma mark - +#pragma mark Application lifecycle + +// cocos2d application instance +static AppDelegate s_sharedApplication; + +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions +{ + + // Override point for customization after application launch. + + // Add the view controller's view to the window and display. + window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; + CCEAGLView *eaglView = [CCEAGLView viewWithFrame: [window bounds] + pixelFormat: kEAGLColorFormatRGBA8 + depthFormat: GL_DEPTH24_STENCIL8_OES + preserveBackbuffer: NO + sharegroup: nil + multiSampling: NO + numberOfSamples: 0 ]; + + [eaglView setMultipleTouchEnabled:YES]; + + // Use RootViewController manage CCEAGLView + viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil]; + viewController.wantsFullScreenLayout = YES; + viewController.view = eaglView; + + // Set RootViewController to window + if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) + { + // warning: addSubView doesn't work on iOS6 + [window addSubview: viewController.view]; + } + else + { + // use this method on ios6 + [window setRootViewController:viewController]; + } + + [window makeKeyAndVisible]; + + [[UIApplication sharedApplication] setStatusBarHidden: YES]; + + // IMPORTANT: Setting the GLView should be done after creating the RootViewController + cocos2d::GLView *glview = cocos2d::GLViewImpl::createWithEAGLView(eaglView); + cocos2d::Director::getInstance()->setOpenGLView(glview); + + cocos2d::Application::getInstance()->run(); + return YES; +} +- (void)applicationWillResignActive:(UIApplication *)application { + /* + Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. + */ + cocos2d::Director::getInstance()->pause(); +} +//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation +//{ +// return [FBSession.activeSession handleOpenURL:url]; +//} +//- (void)applicationDidBecomeActive:(UIApplication *)application { +// /* +// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. +// */ +// [FBAppCall handleDidBecomeActive]; +// cocos2d::Director::getInstance()->resume(); +//} + +- (void)applicationDidEnterBackground:(UIApplication *)application { + /* + Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + If your application supports background execution, called instead of applicationWillTerminate: when the user quits. + */ + cocos2d::Application::getInstance()->applicationDidEnterBackground(); +} + +- (void)applicationWillEnterForeground:(UIApplication *)application { + /* + Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background. + */ + cocos2d::Application::getInstance()->applicationWillEnterForeground(); +} + +- (void)applicationWillTerminate:(UIApplication *)application { + /* + Called when the application is about to terminate. + See also applicationDidEnterBackground:. + */ +} + + +#pragma mark - +#pragma mark Memory management + +- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { + /* + Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. + */ + cocos2d::Director::getInstance()->purgeCachedData(); +} + + +- (void)dealloc { + [super dealloc]; +} + +@end + diff --git a/tests/js-tests/project/proj.ios/Default-568h@2x.png b/tests/js-tests/project/proj.ios/Default-568h@2x.png new file mode 100644 index 0000000000..66c6d1cead Binary files /dev/null and b/tests/js-tests/project/proj.ios/Default-568h@2x.png differ diff --git a/tests/js-tests/project/proj.ios/Default.png b/tests/js-tests/project/proj.ios/Default.png new file mode 100644 index 0000000000..dcb80725de Binary files /dev/null and b/tests/js-tests/project/proj.ios/Default.png differ diff --git a/tests/js-tests/project/proj.ios/Default@2x.png b/tests/js-tests/project/proj.ios/Default@2x.png new file mode 100644 index 0000000000..84689888a1 Binary files /dev/null and b/tests/js-tests/project/proj.ios/Default@2x.png differ diff --git a/tests/js-tests/project/proj.ios/Icon-114.png b/tests/js-tests/project/proj.ios/Icon-114.png new file mode 100644 index 0000000000..c3807861ad Binary files /dev/null and b/tests/js-tests/project/proj.ios/Icon-114.png differ diff --git a/tests/js-tests/project/proj.ios/Icon-120.png b/tests/js-tests/project/proj.ios/Icon-120.png new file mode 100644 index 0000000000..a5b49ccbb1 Binary files /dev/null and b/tests/js-tests/project/proj.ios/Icon-120.png differ diff --git a/tests/js-tests/project/proj.ios/Icon-144.png b/tests/js-tests/project/proj.ios/Icon-144.png new file mode 100644 index 0000000000..1526615c02 Binary files /dev/null and b/tests/js-tests/project/proj.ios/Icon-144.png differ diff --git a/tests/js-tests/project/proj.ios/Icon-152.png b/tests/js-tests/project/proj.ios/Icon-152.png new file mode 100644 index 0000000000..8aa82506d0 Binary files /dev/null and b/tests/js-tests/project/proj.ios/Icon-152.png differ diff --git a/tests/js-tests/project/proj.ios/Icon-57.png b/tests/js-tests/project/proj.ios/Icon-57.png new file mode 100644 index 0000000000..4fcc6fddff Binary files /dev/null and b/tests/js-tests/project/proj.ios/Icon-57.png differ diff --git a/tests/js-tests/project/proj.ios/Icon-72.png b/tests/js-tests/project/proj.ios/Icon-72.png new file mode 100644 index 0000000000..2c573c8df4 Binary files /dev/null and b/tests/js-tests/project/proj.ios/Icon-72.png differ diff --git a/tests/js-tests/project/proj.ios/Icon-76.png b/tests/js-tests/project/proj.ios/Icon-76.png new file mode 100644 index 0000000000..8a1fa1850c Binary files /dev/null and b/tests/js-tests/project/proj.ios/Icon-76.png differ diff --git a/tests/js-tests/project/proj.ios/Info.plist b/tests/js-tests/project/proj.ios/Info.plist new file mode 100644 index 0000000000..4c9edec354 --- /dev/null +++ b/tests/js-tests/project/proj.ios/Info.plist @@ -0,0 +1,96 @@ + + + + + CFBundleDevelopmentRegion + English + CFBundleDisplayName + ${PRODUCT_NAME} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIconFiles + + Icon-72.png + Icon.png + Icon@2x.png + Icon-57.png + Icon-114.png + Icon-144.png + + CFBundleIcons + + CFBundlePrimaryIcon + + CFBundleIconFiles + + Icon-72.png + Icon.png + Icon@2x.png + Icon-57.png + Icon-114.png + Icon-144.png + + UIPrerenderedIcon + + + + CFBundleIdentifier + org.cocos2d-x.${PRODUCT_NAME:rfc1034identifier} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + APPL + CFBundleSignature + ???? + CFBundleVersion + 1.0 + LSRequiresIPhoneOS + + UIAppFonts + + res/fonts/A Damn Mess.ttf + res/fonts/Abberancy.ttf + res/fonts/Abduction.ttf + res/fonts/American Typewriter.ttf + res/fonts/Courier New.ttf + res/fonts/Marker Felt.ttf + res/fonts/Paint Boy.ttf + res/fonts/Schwarzwald Regular.ttf + res/fonts/Scissor Cuts.ttf + res/fonts/tahoma.ttf + res/fonts/Thonburi.ttf + res/fonts/ThonburiBold.ttf + + UIPrerenderedIcon + + UIRequiredDeviceCapabilities + + accelerometer + + opengles-1 + + + UIStatusBarHidden + + UISupportedInterfaceOrientations + + UIInterfaceOrientationLandscapeRight + UIInterfaceOrientationLandscapeLeft + + FacebookAppID + 1426774790893461 + FacebookDisplayName + myFc + CFBundleURLTypes + + + CFBundleURLSchemes + + fb1426774790893461 + + + + + diff --git a/tests/js-tests/project/proj.ios/NativeOcClass.h b/tests/js-tests/project/proj.ios/NativeOcClass.h new file mode 100644 index 0000000000..f8664c6d63 --- /dev/null +++ b/tests/js-tests/project/proj.ios/NativeOcClass.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2013-2014 Chukong Technologies 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. + */ + + +#import + +@interface NativeOcClass : NSObject + ++(float) callNative:(NSNumber *)a andInt:(NSString *)str; ++(void) callNativeWithParam:(NSString *)str; ++(NSString *)callNativeWithReturnString; ++(BOOL)callNativeUIWithTitle:(NSString *) title andContent:(NSString *)content; ++(int)callNativeWithAdd:(NSNumber *)num1 and:(NSNumber *)num2; +@end diff --git a/tests/js-tests/project/proj.ios/NativeOcClass.m b/tests/js-tests/project/proj.ios/NativeOcClass.m new file mode 100644 index 0000000000..8591fee98a --- /dev/null +++ b/tests/js-tests/project/proj.ios/NativeOcClass.m @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2013-2014 Chukong Technologies 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. + */ + +#import "NativeOcClass.h" +#if TARGET_OS_IPHONE +#import +#elif TARGET_OS_MAC +#import +#endif +@implementation NativeOcClass ++(float) callNative:(NSNumber *)a andInt:(NSString *)str{ + float b = [a floatValue]+111.3333; + NSLog(@"callNative string is %@ and int value is %f",str,b); + return b; +} ++(void)callNativeWithParam:(NSString *)str{ + NSLog(@"callNativeWithParam: str is %@ ",str); +} ++(NSString *)callNativeWithReturnString{ + return @"yes is a return string form objective-c"; +} ++(BOOL)callNativeWithReturnBool{ + return true; +} ++(int)callNativeWithAdd:(NSNumber *)num1 and:(NSNumber *)num2{ + return [num1 intValue]+[num2 intValue]; +} +#if TARGET_OS_IPHONE ++(BOOL)callNativeUIWithTitle:(NSString *) title andContent:(NSString *)content{ + UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:content delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil]; + [alertView show]; + return true; +} +#elif TARGET_OS_MAC + ++(BOOL)callNativeUIWithTitle:(NSString *) title andContent:(NSString *)content{ + NSAlert *alert = [[NSAlert alloc] init]; + [alert addButtonWithTitle:@"OK"]; + [alert addButtonWithTitle:@"Cancel"]; + [alert setMessageText:title]; + [alert setInformativeText:content]; + [alert setAlertStyle:NSWarningAlertStyle]; + [alert runModal]; + return true; +} + +#endif +@end diff --git a/tests/js-tests/project/proj.ios/Prefix.pch b/tests/js-tests/project/proj.ios/Prefix.pch new file mode 100644 index 0000000000..b056d8694a --- /dev/null +++ b/tests/js-tests/project/proj.ios/Prefix.pch @@ -0,0 +1,8 @@ +// +// Prefix header for all source files of the 'testjs' target in the 'testjs' project +// + +#ifdef __OBJC__ + #import + #import +#endif diff --git a/tests/js-tests/project/proj.ios/RootViewController.h b/tests/js-tests/project/proj.ios/RootViewController.h new file mode 100644 index 0000000000..11dfc4bf88 --- /dev/null +++ b/tests/js-tests/project/proj.ios/RootViewController.h @@ -0,0 +1,33 @@ +/**************************************************************************** + Copyright (c) 2010-2011 cocos2d-x.org + Copyright (c) 2010 Ricardo Quesada + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#import + + +@interface RootViewController : UIViewController { + +} +- (BOOL)prefersStatusBarHidden; +@end diff --git a/tests/js-tests/project/proj.ios/RootViewController.mm b/tests/js-tests/project/proj.ios/RootViewController.mm new file mode 100644 index 0000000000..8438d7a420 --- /dev/null +++ b/tests/js-tests/project/proj.ios/RootViewController.mm @@ -0,0 +1,79 @@ +// +// testjsAppController.h +// testjs +// +// Created by Rolando Abarca on 3/19/12. +// Copyright __MyCompanyName__ 2012. All rights reserved. +// + +#import "RootViewController.h" + + +@implementation RootViewController + +/* + // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. +- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { + if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { + // Custom initialization + } + return self; +} +*/ + +/* +// Implement loadView to create a view hierarchy programmatically, without using a nib. +- (void)loadView { +} +*/ + +/* +// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. +- (void)viewDidLoad { + [super viewDidLoad]; +} + +*/ +// Override to allow orientations other than the default portrait orientation. +// This method is deprecated on ios6 +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { + return UIInterfaceOrientationIsLandscape( interfaceOrientation ); +} + +// For ios6, use supportedInterfaceOrientations & shouldAutorotate instead +- (NSUInteger) supportedInterfaceOrientations{ +#ifdef __IPHONE_6_0 + return UIInterfaceOrientationMaskAllButUpsideDown; +#endif +} + +- (BOOL) shouldAutorotate { + return YES; +} + +//fix not hide status on ios7 +- (BOOL)prefersStatusBarHidden +{ + return YES; +} + +- (void)didReceiveMemoryWarning { + // Releases the view if it doesn't have a superview. + [super didReceiveMemoryWarning]; + + // Release any cached data, images, etc that aren't in use. +} + +- (void)viewDidUnload { + [super viewDidUnload]; + // Release any retained subviews of the main view. + // e.g. self.myOutlet = nil; +} + + +- (void)dealloc { + [super dealloc]; +} + + +@end diff --git a/tests/js-tests/project/proj.ios/main.m b/tests/js-tests/project/proj.ios/main.m new file mode 100644 index 0000000000..e3dedca28b --- /dev/null +++ b/tests/js-tests/project/proj.ios/main.m @@ -0,0 +1,17 @@ +// +// main.m +// testjs +// +// Created by Rolando Abarca on 3/19/12. +// Copyright __MyCompanyName__ 2012. All rights reserved. +// + +#import + +int main(int argc, char *argv[]) { + + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + int retVal = UIApplicationMain(argc, argv, nil, @"AppController"); + [pool release]; + return retVal; +} diff --git a/tests/js-tests/project/proj.linux/main.cpp b/tests/js-tests/project/proj.linux/main.cpp new file mode 100644 index 0000000000..e236a953b3 --- /dev/null +++ b/tests/js-tests/project/proj.linux/main.cpp @@ -0,0 +1,10 @@ +#include "../Classes/AppDelegate.h" + +USING_NS_CC; + +int main(int argc, char **argv) +{ + // create the application instance + AppDelegate app; + return Application::getInstance()->run(); +} diff --git a/tests/js-tests/project/proj.mac/Icon.icns b/tests/js-tests/project/proj.mac/Icon.icns new file mode 100644 index 0000000000..3d09e8fb4f Binary files /dev/null and b/tests/js-tests/project/proj.mac/Icon.icns differ diff --git a/tests/js-tests/project/proj.mac/Test_Info.plist b/tests/js-tests/project/proj.mac/Test_Info.plist new file mode 100644 index 0000000000..dfab7c096d --- /dev/null +++ b/tests/js-tests/project/proj.mac/Test_Info.plist @@ -0,0 +1,34 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIconFile + Icon + CFBundleIdentifier + org.cocos2d-x.$(PRODUCT_NAME:rfc1034identifier) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + LSMinimumSystemVersion + ${MACOSX_DEPLOYMENT_TARGET} + NSHumanReadableCopyright + Copyright © 2012. All rights reserved. + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/tests/js-tests/project/proj.mac/Test_Prefix.pch b/tests/js-tests/project/proj.mac/Test_Prefix.pch new file mode 100644 index 0000000000..46c36a7e99 --- /dev/null +++ b/tests/js-tests/project/proj.mac/Test_Prefix.pch @@ -0,0 +1,7 @@ +// +// Prefix header for all source files of the 'Paralaxer' target in the 'Paralaxer' project +// + +#ifdef __OBJC__ + #import +#endif diff --git a/tests/js-tests/project/proj.mac/en.lproj/InfoPlist.strings b/tests/js-tests/project/proj.mac/en.lproj/InfoPlist.strings new file mode 100644 index 0000000000..477b28ff8f --- /dev/null +++ b/tests/js-tests/project/proj.mac/en.lproj/InfoPlist.strings @@ -0,0 +1,2 @@ +/* Localized versions of Info.plist keys */ + diff --git a/tests/js-tests/project/proj.mac/en.lproj/MainMenu.xib b/tests/js-tests/project/proj.mac/en.lproj/MainMenu.xib new file mode 100644 index 0000000000..3dacdedbd0 --- /dev/null +++ b/tests/js-tests/project/proj.mac/en.lproj/MainMenu.xib @@ -0,0 +1,812 @@ + + + + 1060 + 10K549 + 1938 + 1038.36 + 461.00 + + com.apple.InterfaceBuilder.CocoaPlugin + 1938 + + + YES + NSMenuItem + NSCustomObject + NSMenu + + + YES + com.apple.InterfaceBuilder.CocoaPlugin + + + PluginDependencyRecalculationVersion + + + + YES + + NSApplication + + + FirstResponder + + + NSApplication + + + AMainMenu + + YES + + + TestCpp + + 1048576 + 2147483647 + + NSImage + NSMenuCheckmark + + + NSImage + NSMenuMixedState + + submenuAction: + + TestCpp + + YES + + + About TestCpp + + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Preferences… + , + 1048576 + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Services + + 1048576 + 2147483647 + + + submenuAction: + + Services + + YES + + _NSServicesMenu + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Hide TestCpp + h + 1048576 + 2147483647 + + + + + + Hide Others + h + 1572864 + 2147483647 + + + + + + Show All + + 1048576 + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Quit TestCpp + q + 1048576 + 2147483647 + + + + + _NSAppleMenu + + + + + View + + 1048576 + 2147483647 + + + submenuAction: + + View + + YES + + + Toggle Fullscreen + f + 1048576 + 2147483647 + + + + + + + + + Window + + 1048576 + 2147483647 + + + submenuAction: + + Window + + YES + + + Minimize + m + 1048576 + 2147483647 + + + + + + Zoom + + 1048576 + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Bring All to Front + + 1048576 + 2147483647 + + + + + _NSWindowsMenu + + + + + Help + + 2147483647 + + + submenuAction: + + Help + + YES + + + TestCpp Help + ? + 1048576 + 2147483647 + + + + + _NSHelpMenu + + + + _NSMainMenu + + + AppController + + + NSFontManager + + + + + YES + + + terminate: + + + + 449 + + + + orderFrontStandardAboutPanel: + + + + 142 + + + + delegate + + + + 495 + + + + performMiniaturize: + + + + 37 + + + + arrangeInFront: + + + + 39 + + + + performZoom: + + + + 240 + + + + hide: + + + + 367 + + + + hideOtherApplications: + + + + 368 + + + + unhideAllApplications: + + + + 370 + + + + showHelp: + + + + 493 + + + + toggleFullScreen: + + + + 537 + + + + + YES + + 0 + + YES + + + + + + -2 + + + File's Owner + + + -1 + + + First Responder + + + -3 + + + Application + + + 29 + + + YES + + + + + + + + + 19 + + + YES + + + + + + 56 + + + YES + + + + + + 57 + + + YES + + + + + + + + + + + + + + + + 58 + + + + + 134 + + + + + 150 + + + + + 136 + + + + + 144 + + + + + 129 + + + + + 143 + + + + + 236 + + + + + 131 + + + YES + + + + + + 149 + + + + + 145 + + + + + 130 + + + + + 24 + + + YES + + + + + + + + + 92 + + + + + 5 + + + + + 239 + + + + + 23 + + + + + 295 + + + YES + + + + + + 296 + + + YES + + + + + + 420 + + + + + 490 + + + YES + + + + + + 491 + + + YES + + + + + + 492 + + + + + 494 + + + + + 536 + + + + + + + YES + + YES + -1.IBPluginDependency + -2.IBPluginDependency + -3.IBPluginDependency + 129.IBPluginDependency + 130.IBPluginDependency + 131.IBPluginDependency + 134.IBPluginDependency + 136.IBPluginDependency + 143.IBPluginDependency + 144.IBPluginDependency + 145.IBPluginDependency + 149.IBPluginDependency + 150.IBPluginDependency + 19.IBPluginDependency + 23.IBPluginDependency + 236.IBPluginDependency + 239.IBPluginDependency + 24.IBPluginDependency + 29.IBPluginDependency + 295.IBPluginDependency + 296.IBPluginDependency + 420.IBPluginDependency + 490.IBPluginDependency + 491.IBPluginDependency + 492.IBPluginDependency + 494.IBPluginDependency + 5.IBPluginDependency + 536.IBPluginDependency + 56.IBPluginDependency + 57.IBPluginDependency + 58.IBPluginDependency + 92.IBPluginDependency + + + YES + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + + + + YES + + + + + + YES + + + + + 541 + + + + YES + + AppController + NSObject + + YES + + YES + exitFullScreen: + toggleFullScreen: + + + YES + id + id + + + + YES + + YES + exitFullScreen: + toggleFullScreen: + + + YES + + exitFullScreen: + id + + + toggleFullScreen: + id + + + + + YES + + YES + glView + window + + + YES + EAGLView + NSWindow + + + + YES + + YES + glView + window + + + YES + + glView + EAGLView + + + window + NSWindow + + + + + IBProjectSource + ./Classes/AppController.h + + + + EAGLView + NSOpenGLView + + IBProjectSource + ./Classes/EAGLView.h + + + + + 0 + IBCocoaFramework + + com.apple.InterfaceBuilder.CocoaPlugin.InterfaceBuilder3 + + + YES + 3 + + YES + + YES + NSMenuCheckmark + NSMenuMixedState + + + YES + {9, 8} + {7, 2} + + + + diff --git a/tests/js-tests/project/proj.mac/main.cpp b/tests/js-tests/project/proj.mac/main.cpp new file mode 100644 index 0000000000..4b6a1e9021 --- /dev/null +++ b/tests/js-tests/project/proj.mac/main.cpp @@ -0,0 +1,35 @@ +/**************************************************************************** + 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 "AppDelegate.h" +#include "cocos2d.h" + +USING_NS_CC; + +int main(int argc, char *argv[]) +{ + AppDelegate app; + return Application::getInstance()->run(); +} + diff --git a/tests/js-tests/project/proj.win32/build-cfg.json b/tests/js-tests/project/proj.win32/build-cfg.json new file mode 100644 index 0000000000..d1965344bc --- /dev/null +++ b/tests/js-tests/project/proj.win32/build-cfg.json @@ -0,0 +1,24 @@ +{ + "copy_resources": [ + { + "from": "../../src", + "to": "src" + }, + { + "from": "../../../cpp-tests/Resources", + "to": "res" + }, + { + "from": "../../main.js", + "to": "" + }, + { + "from": "../../project.json", + "to": "" + }, + { + "from": "../../../../cocos/scripting/js-bindings/script", + "to": "script" + } + ] +} diff --git a/tests/js-tests/project/proj.win32/js-tests.rc b/tests/js-tests/project/proj.win32/js-tests.rc new file mode 100644 index 0000000000..3d664e8370 --- /dev/null +++ b/tests/js-tests/project/proj.win32/js-tests.rc @@ -0,0 +1,86 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#define APSTUDIO_HIDDEN_SYMBOLS +#include "windows.h" +#undef APSTUDIO_HIDDEN_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +#endif // APSTUDIO_INVOKED + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDR_MAINFRAME ICON "res\\js-tests.ico" + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,0,0,1 + PRODUCTVERSION 1,0,0,1 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904B0" + BEGIN + VALUE "CompanyName", "\0" + VALUE "FileDescription", "js-tests Module\0" + VALUE "FileVersion", "1, 0, 0, 1\0" + VALUE "InternalName", "js-tests\0" + VALUE "LegalCopyright", "Copyright \0" + VALUE "OriginalFilename", "js-tests.exe\0" + VALUE "ProductName", "js-tests Module\0" + VALUE "ProductVersion", "1, 0, 0, 1\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x0409, 0x04B0 + END +END + +///////////////////////////////////////////////////////////////////////////// +#endif // !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) diff --git a/tests/js-tests/project/proj.win32/js-tests.vcxproj b/tests/js-tests/project/proj.win32/js-tests.vcxproj new file mode 100644 index 0000000000..0068693b00 --- /dev/null +++ b/tests/js-tests/project/proj.win32/js-tests.vcxproj @@ -0,0 +1,218 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + {D0F06A44-A245-4D13-A498-0120C203B539} + js-tests + + + + Application + Unicode + v100 + v110 + v110_xp + v120 + v120_xp + + + Application + Unicode + v100 + v110 + v110_xp + v120 + v120_xp + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.40219.1 + $(SolutionDir)$(Configuration).win32\js-tests\ + $(Configuration).win32\ + false + $(SolutionDir)$(Configuration).win32\js-tests\ + $(Configuration).win32\ + false + AllRules.ruleset + + + AllRules.ruleset + + + + + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) + + + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) + + + + _DEBUG;%(PreprocessorDefinitions) + false + Win32 + true + $(IntDir)js-tests.tlb + js-tests.h + + + js-tests_i.c + js-tests_p.c + + + Disabled + $(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\base;$(EngineRoot)cocos\storage;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;$(ProjectDir)..\Classes;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)cocos\scripting\js-bindings\auto;$(EngineRoot)cocos\scripting\js-bindings\manual;%(AdditionalIncludeDirectories) + WIN32;_WINDOWS;STRICT;_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 + MultiThreadedDebugDLL + + + Level3 + EditAndContinue + 4267;4251;4244;%(DisableSpecificWarnings) + true + + + _DEBUG;%(PreprocessorDefinitions) + 0x0409 + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(IntDir);%(AdditionalIncludeDirectories) + + + if not exist "$(OutDir)" mkdir "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\debug-build\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$(OutDir)" + + + libcurl_imp.lib;mozjs-33.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) + $(OutDir);$(SolutionDir)$(Configuration).win32;%(AdditionalLibraryDirectories) + true + Windows + MachineX86 + + + if not exist "$(OutDir)" mkdir "$(OutDir)" + +mkdir "$(OutDir)\script" +mkdir "$(OutDir)\src" +mkdir "$(OutDir)\res" +xcopy "$(OutDir)..\*.dll" "$(OutDir)" /D /Y +xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\js-bindings\script\*" "$(OutDir)\script" /e /Y +xcopy "$(ProjectDir)..\..\src" "$(OutDir)\src\" /e /Y +xcopy "$(ProjectDir)..\..\res" "$(OutDir)\res\" /e /Y +copy "$(ProjectDir)..\..\main.js" "$(OutDir)" +copy "$(ProjectDir)..\..\project.json" "$(OutDir)" + + + Copy js and resource files. + + + + + NDEBUG;%(PreprocessorDefinitions) + false + Win32 + true + $(IntDir)js-tests.tlb + js-tests.h + + + js-tests_i.c + js-tests_p.c + + + $(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\base;$(EngineRoot)cocos\storage;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;$(ProjectDir)..\Classes;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)cocos\scripting\js-bindings\auto;$(EngineRoot)cocos\scripting\js-bindings\manual;%(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) + + + MultiThreadedDLL + + + Level3 + + + 4267;4251;4244;%(DisableSpecificWarnings) + true + + + NDEBUG;%(PreprocessorDefinitions) + 0x0409 + $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(IntDir);%(AdditionalIncludeDirectories) + + + if not exist "$(OutDir)" mkdir "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\release-build\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$(OutDir)" + + + libcurl_imp.lib;mozjs-33.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) + $(OutDir);$(SolutionDir)$(Configuration).win32;%(AdditionalLibraryDirectories) + Windows + MachineX86 + true + + + if not exist "$(OutDir)" mkdir "$(OutDir)" + +mkdir "$(OutDir)\script" +mkdir "$(OutDir)\src" +mkdir "$(OutDir)\res" +xcopy "$(OutDir)..\*.dll" "$(OutDir)" /D /Y +xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\js-bindings\script\*" "$(OutDir)\script" /e /Y +xcopy "$(ProjectDir)..\..\src" "$(OutDir)\src\" /e /Y +xcopy "$(ProjectDir)..\..\..\cpp-tests\Resources" "$(OutDir)\res\" /e /Y +copy "$(ProjectDir)..\..\main.js" "$(OutDir)" +copy "$(ProjectDir)..\..\project.json" "$(OutDir)" + Copy js and resource files. + + + + + + + + + + + + + + + + + + + + + + + + {39379840-825a-45a0-b363-c09ffef864bd} + + + + + + \ No newline at end of file diff --git a/tests/js-tests/project/proj.win32/js-tests.vcxproj.filters b/tests/js-tests/project/proj.win32/js-tests.vcxproj.filters new file mode 100644 index 0000000000..b66e775a2e --- /dev/null +++ b/tests/js-tests/project/proj.win32/js-tests.vcxproj.filters @@ -0,0 +1,55 @@ + + + + + Classes + + + win32 + + + Classes + + + Classes + + + + + Classes + + + win32 + + + win32 + + + Classes + + + Classes + + + + + {73cd069e-e032-4051-8d30-65b08ab4f954} + + + {abaf0468-14d3-43ce-8d1a-8a4a34dba59b} + + + {bbe7342c-1f30-4512-b00a-841aa2d4ca9f} + + + + + resource + + + + + resource + + + \ No newline at end of file diff --git a/tests/js-tests/project/proj.win32/main.cpp b/tests/js-tests/project/proj.win32/main.cpp new file mode 100644 index 0000000000..f5ce0656ed --- /dev/null +++ b/tests/js-tests/project/proj.win32/main.cpp @@ -0,0 +1,34 @@ +#include "main.h" +#include "AppDelegate.h" + +USING_NS_CC; + +// uncomment below line, open debug console +// #define USE_WIN32_CONSOLE + +int APIENTRY _tWinMain(HINSTANCE hInstance, + HINSTANCE hPrevInstance, + LPTSTR lpCmdLine, + int nCmdShow) +{ + UNREFERENCED_PARAMETER(hPrevInstance); + UNREFERENCED_PARAMETER(lpCmdLine); + +#ifdef USE_WIN32_CONSOLE + AllocConsole(); + freopen("CONIN$", "r", stdin); + freopen("CONOUT$", "w", stdout); + freopen("CONOUT$", "w", stderr); +#endif + + // create the application instance + AppDelegate app; + + int ret = Application::getInstance()->run(); + +#ifdef USE_WIN32_CONSOLE + FreeConsole(); +#endif + + return ret; +} diff --git a/tests/js-tests/project/proj.win32/main.h b/tests/js-tests/project/proj.win32/main.h new file mode 100644 index 0000000000..e29aeedb3a --- /dev/null +++ b/tests/js-tests/project/proj.win32/main.h @@ -0,0 +1,12 @@ +#ifndef __MAIN_H__ +#define __MAIN_H__ + +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers + +// Windows Header Files: +#include + +// C RunTime Header Files +#include "CCStdC.h" + +#endif // __WINMAIN_H__ diff --git a/tests/js-tests/project/proj.win32/res/js-tests.ico b/tests/js-tests/project/proj.win32/res/js-tests.ico new file mode 100644 index 0000000000..feaf932a74 Binary files /dev/null and b/tests/js-tests/project/proj.win32/res/js-tests.ico differ diff --git a/tests/js-tests/project/proj.win32/resource.h b/tests/js-tests/project/proj.win32/resource.h new file mode 100644 index 0000000000..3436133bc7 --- /dev/null +++ b/tests/js-tests/project/proj.win32/resource.h @@ -0,0 +1,20 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by js-tests.RC +// + +#define IDS_PROJNAME 100 +#define IDR_TESTJS 100 + +#define ID_FILE_NEW_WINDOW 32771 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 201 +#define _APS_NEXT_CONTROL_VALUE 1000 +#define _APS_NEXT_SYMED_VALUE 101 +#define _APS_NEXT_COMMAND_VALUE 32775 +#endif +#endif diff --git a/tests/js-tests/project/proj.win8.1-universal/App.Shared/App.xaml b/tests/js-tests/project/proj.win8.1-universal/App.Shared/App.xaml new file mode 100644 index 0000000000..2da0ff79d0 --- /dev/null +++ b/tests/js-tests/project/proj.win8.1-universal/App.Shared/App.xaml @@ -0,0 +1,13 @@ + + + + + cpp_tests + + + diff --git a/tests/js-tests/project/proj.win8.1-universal/App.Shared/App.xaml.cpp b/tests/js-tests/project/proj.win8.1-universal/App.Shared/App.xaml.cpp new file mode 100644 index 0000000000..f4365b88c5 --- /dev/null +++ b/tests/js-tests/project/proj.win8.1-universal/App.Shared/App.xaml.cpp @@ -0,0 +1,21 @@ +#include "App.xaml.h" +#include "OpenGLESPage.xaml.h" + +using namespace cocos2d; + +App::App() +{ + InitializeComponent(); +} + +void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e) +{ + if (mPage == nullptr) + { + mPage = ref new OpenGLESPage(&mOpenGLES); + } + + // Place the page in the current window and ensure that it is active. + Windows::UI::Xaml::Window::Current->Content = mPage; + Windows::UI::Xaml::Window::Current->Activate(); +} diff --git a/tests/js-tests/project/proj.win8.1-universal/App.Shared/App.xaml.h b/tests/js-tests/project/proj.win8.1-universal/App.Shared/App.xaml.h new file mode 100644 index 0000000000..1309c610d7 --- /dev/null +++ b/tests/js-tests/project/proj.win8.1-universal/App.Shared/App.xaml.h @@ -0,0 +1,19 @@ +#pragma once + +#include "app.g.h" +#include "OpenGLES.h" +#include "openglespage.xaml.h" + +namespace cocos2d +{ + ref class App sealed + { + public: + App(); + virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e) override; + + private: + OpenGLESPage^ mPage; + OpenGLES mOpenGLES; + }; +} diff --git a/tests/js-tests/project/proj.win8.1-universal/App.Shared/js-tests.Shared.vcxitems b/tests/js-tests/project/proj.win8.1-universal/App.Shared/js-tests.Shared.vcxitems new file mode 100644 index 0000000000..4a353710a9 --- /dev/null +++ b/tests/js-tests/project/proj.win8.1-universal/App.Shared/js-tests.Shared.vcxitems @@ -0,0 +1,64 @@ + + + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + true + e956c24b-f04e-47bf-bf00-746681ae1301 + {AE6763F6-1549-441E-AFB5-377BE1C776DC} + js-tests + + + + %(AdditionalIncludeDirectories);$(MSBuildThisFileDirectory) + + + + + Designer + + + + + $(MSBuildThisFileDirectory)..\..\..\..\..\cocos\platform\win8.1-universal\OpenGLESPage.xaml + + + + + + $(MSBuildThisFileDirectory)App.xaml + + + + + $(MSBuildThisFileDirectory)..\..\..\..\..\cocos\platform\win8.1-universal\OpenGLESPage.xaml + + + + + + $(MSBuildThisFileDirectory)App.xaml + + + Create + + + + + + + + <_CustomResource Include="$(MSBuildThisFileDirectory)..\..\Resources\**\*"> + Assets\Resources\%(RecursiveDir)%(FileName)%(Extension) + true + + + + + + + + + + + + \ No newline at end of file diff --git a/tests/js-tests/project/proj.win8.1-universal/App.Shared/js-tests.Shared.vcxitems.filters b/tests/js-tests/project/proj.win8.1-universal/App.Shared/js-tests.Shared.vcxitems.filters new file mode 100644 index 0000000000..841a3ae6ee --- /dev/null +++ b/tests/js-tests/project/proj.win8.1-universal/App.Shared/js-tests.Shared.vcxitems.filters @@ -0,0 +1,46 @@ + + + + + + + + + Classes + + + Classes + + + Classes + + + + + + + + + + + {38ad799c-8c3c-44a2-8e41-516c8f62f556} + + + + + Classes + + + Classes + + + Classes + + + + + + + + + \ No newline at end of file diff --git a/tests/js-tests/project/proj.win8.1-universal/App.Shared/pch.cpp b/tests/js-tests/project/proj.win8.1-universal/App.Shared/pch.cpp new file mode 100644 index 0000000000..bcb5590be1 --- /dev/null +++ b/tests/js-tests/project/proj.win8.1-universal/App.Shared/pch.cpp @@ -0,0 +1 @@ +#include "pch.h" diff --git a/tests/js-tests/project/proj.win8.1-universal/App.Shared/pch.h b/tests/js-tests/project/proj.win8.1-universal/App.Shared/pch.h new file mode 100644 index 0000000000..087ce3bf18 --- /dev/null +++ b/tests/js-tests/project/proj.win8.1-universal/App.Shared/pch.h @@ -0,0 +1,12 @@ +// +// pch.h +// Header for standard system include files. +// + +#pragma once + +#include "mozilla\Char16.h" +#include "cocos2d.h" +#include "cocos-ext.h" + + diff --git a/tests/js-tests/project/proj.win8.1-universal/App.Windows/Assets/Logo.scale-100.png b/tests/js-tests/project/proj.win8.1-universal/App.Windows/Assets/Logo.scale-100.png new file mode 100644 index 0000000000..e26771cb33 Binary files /dev/null and b/tests/js-tests/project/proj.win8.1-universal/App.Windows/Assets/Logo.scale-100.png differ diff --git a/tests/js-tests/project/proj.win8.1-universal/App.Windows/Assets/SmallLogo.scale-100.png b/tests/js-tests/project/proj.win8.1-universal/App.Windows/Assets/SmallLogo.scale-100.png new file mode 100644 index 0000000000..1eb0d9d528 Binary files /dev/null and b/tests/js-tests/project/proj.win8.1-universal/App.Windows/Assets/SmallLogo.scale-100.png differ diff --git a/tests/js-tests/project/proj.win8.1-universal/App.Windows/Assets/SplashScreen.scale-100.png b/tests/js-tests/project/proj.win8.1-universal/App.Windows/Assets/SplashScreen.scale-100.png new file mode 100644 index 0000000000..d8ded7198a Binary files /dev/null and b/tests/js-tests/project/proj.win8.1-universal/App.Windows/Assets/SplashScreen.scale-100.png differ diff --git a/tests/js-tests/project/proj.win8.1-universal/App.Windows/Assets/StoreLogo.scale-100.png b/tests/js-tests/project/proj.win8.1-universal/App.Windows/Assets/StoreLogo.scale-100.png new file mode 100644 index 0000000000..dcb672712c Binary files /dev/null and b/tests/js-tests/project/proj.win8.1-universal/App.Windows/Assets/StoreLogo.scale-100.png differ diff --git a/tests/js-tests/project/proj.win8.1-universal/App.Windows/Package.appxmanifest b/tests/js-tests/project/proj.win8.1-universal/App.Windows/Package.appxmanifest new file mode 100644 index 0000000000..1eb9e09ad5 --- /dev/null +++ b/tests/js-tests/project/proj.win8.1-universal/App.Windows/Package.appxmanifest @@ -0,0 +1,30 @@ + + + + + js-tests.Windows + msopentech + Assets\StoreLogo.png + + + 6.3.0 + 6.3.0 + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests/js-tests/project/proj.win8.1-universal/App.Windows/js-tests.Windows.vcxproj b/tests/js-tests/project/proj.win8.1-universal/App.Windows/js-tests.Windows.vcxproj new file mode 100644 index 0000000000..14c9ea25f5 --- /dev/null +++ b/tests/js-tests/project/proj.win8.1-universal/App.Windows/js-tests.Windows.vcxproj @@ -0,0 +1,227 @@ + + + + + Debug + ARM + + + Debug + Win32 + + + Debug + x64 + + + Release + ARM + + + Release + Win32 + + + Release + x64 + + + + {70914FC8-7709-4CD6-B86B-C63FDE5478DB} + cocos2d + en-US + 12.0 + true + Windows Store + 8.1 + + + + Application + true + v120 + + + Application + true + v120 + + + Application + true + v120 + + + Application + false + false + v120 + + + Application + false + false + v120 + + + Application + false + false + v120 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + js-tests.Windows_TemporaryKey.pfx + True + x86 + FB58178D2A50D64A72EC25130D072580B999A12E + + + + /bigobj /Zm200 %(AdditionalOptions) + 4800;%(DisableSpecificWarnings) + pch.h + $(ProjectDir)..\..\Classes;$(EngineRoot)cocos\platform\win8.1-universal;%(AdditionalIncludeDirectories) + false + + + + + + + + + /bigobj /Zm200 %(AdditionalOptions) + 4800;%(DisableSpecificWarnings) + pch.h + $(ProjectDir)..\..\Classes;$(EngineRoot)cocos\platform\win8.1-universal;%(AdditionalIncludeDirectories) + false + + + + + + + + + /bigobj /Zm200 %(AdditionalOptions) + 4800;%(DisableSpecificWarnings) + pch.h + $(ProjectDir)..\..\Classes;$(EngineRoot)cocos\platform\win8.1-universal;%(AdditionalIncludeDirectories) + false + + + + + + + + + /bigobj /Zm200 %(AdditionalOptions) + 4800;%(DisableSpecificWarnings) + pch.h + $(ProjectDir)..\..\Classes;$(EngineRoot)cocos\platform\win8.1-universal;%(AdditionalIncludeDirectories) + false + + + + + + + + + /bigobj /Zm200 %(AdditionalOptions) + 4800;%(DisableSpecificWarnings) + pch.h + $(ProjectDir)..\..\Classes;$(EngineRoot)cocos\platform\win8.1-universal;%(AdditionalIncludeDirectories) + false + + + + + + + /bigobj /Zm200 %(AdditionalOptions) + 4800;%(DisableSpecificWarnings) + pch.h + $(ProjectDir)..\..\Classes;$(EngineRoot)cocos\platform\win8.1-universal;%(AdditionalIncludeDirectories) + false + + + echo "Copying Windows 8.1 Universal App CPP template files" +xcopy "$(EngineRoot)external\win8.1-universal\OpenGLESPage.xaml" "$(EngineRoot)templates\js-template-default\frameworks\runtime-src\proj.win8.1-universal\App.Shared\*" /eiycq +xcopy "$(EngineRoot)external\win8.1-universal\OpenGLESPage.xaml.cpp" "$(EngineRoot)templates\js-template-default\frameworks\runtime-src\proj.win8.1-universal\App.Shared\*" /eiycq +xcopy "$(EngineRoot)external\win8.1-universal\OpenGLESPage.xaml.h" "$(EngineRoot)templates\js-template-default\frameworks\runtime-src\proj.win8.1-universal\App.Shared\*" /eiycq + + + + + + Designer + + + + + + + + + + + + {bcf5546d-66a0-4998-afd6-c5514f618930} + + + {9335005f-678e-4e8e-9b84-50037216aec8} + + + {f3550fe0-c795-44f6-8feb-093eb68143ae} + + + {3b26a12d-3a44-47ea-82d2-282660fc844d} + + + + + + \ No newline at end of file diff --git a/tests/js-tests/project/proj.win8.1-universal/App.Windows/js-tests.Windows.vcxproj.filters b/tests/js-tests/project/proj.win8.1-universal/App.Windows/js-tests.Windows.vcxproj.filters new file mode 100644 index 0000000000..0391f8dd5a --- /dev/null +++ b/tests/js-tests/project/proj.win8.1-universal/App.Windows/js-tests.Windows.vcxproj.filters @@ -0,0 +1,29 @@ + + + + + {1a9fa652-867e-41d2-8588-962f108d2d8f} + bmp;fbx;gif;jpg;jpeg;tga;tiff;tif;png + + + + + + + + + + + Assets + + + Assets + + + Assets + + + Assets + + + \ No newline at end of file diff --git a/tests/js-tests/project/proj.win8.1-universal/App.Windows/js-tests.Windows_TemporaryKey.pfx b/tests/js-tests/project/proj.win8.1-universal/App.Windows/js-tests.Windows_TemporaryKey.pfx new file mode 100644 index 0000000000..a5b8824cbb Binary files /dev/null and b/tests/js-tests/project/proj.win8.1-universal/App.Windows/js-tests.Windows_TemporaryKey.pfx differ diff --git a/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Assets/Logo.scale-240.png b/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Assets/Logo.scale-240.png new file mode 100644 index 0000000000..76921ca997 Binary files /dev/null and b/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Assets/Logo.scale-240.png differ diff --git a/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Assets/SmallLogo.scale-240.png b/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Assets/SmallLogo.scale-240.png new file mode 100644 index 0000000000..316630124f Binary files /dev/null and b/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Assets/SmallLogo.scale-240.png differ diff --git a/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Assets/SplashScreen.scale-240.png b/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Assets/SplashScreen.scale-240.png new file mode 100644 index 0000000000..b0b6bc08e5 Binary files /dev/null and b/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Assets/SplashScreen.scale-240.png differ diff --git a/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Assets/Square71x71Logo.scale-240.png b/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Assets/Square71x71Logo.scale-240.png new file mode 100644 index 0000000000..cfa54bee03 Binary files /dev/null and b/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Assets/Square71x71Logo.scale-240.png differ diff --git a/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Assets/StoreLogo.scale-240.png b/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Assets/StoreLogo.scale-240.png new file mode 100644 index 0000000000..47e084b593 Binary files /dev/null and b/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Assets/StoreLogo.scale-240.png differ diff --git a/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Assets/WideLogo.scale-240.png b/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Assets/WideLogo.scale-240.png new file mode 100644 index 0000000000..6249d29db0 Binary files /dev/null and b/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Assets/WideLogo.scale-240.png differ diff --git a/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Package.appxmanifest b/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Package.appxmanifest new file mode 100644 index 0000000000..0568af1b21 --- /dev/null +++ b/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/Package.appxmanifest @@ -0,0 +1,33 @@ + + + + + + js-tests.WindowsPhone + dalestam + Assets\StoreLogo.png + + + 6.3.1 + 6.3.1 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/js-tests.WindowsPhone.vcxproj b/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/js-tests.WindowsPhone.vcxproj new file mode 100644 index 0000000000..b9b5a08fcb --- /dev/null +++ b/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/js-tests.WindowsPhone.vcxproj @@ -0,0 +1,151 @@ + + + + + Debug + ARM + + + Debug + Win32 + + + Release + ARM + + + Release + Win32 + + + + {94874B5B-398F-448A-A366-35A35DC1DB9C} + cocos2d + en-US + 12.0 + true + Windows Phone + 8.1 + + + + Application + true + v120_wp81 + + + Application + true + v120_wp81 + + + Application + false + false + v120_wp81 + + + Application + false + false + v120_wp81 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + True + arm + + + + /bigobj /Zm200 %(AdditionalOptions) + 4800;%(DisableSpecificWarnings) + pch.h + $(ProjectDir)..\..\Classes;$(EngineRoot)cocos\platform\win8.1-universal;%(AdditionalIncludeDirectories) + false + + + + + /bigobj /Zm200 %(AdditionalOptions) + 4800;%(DisableSpecificWarnings) + pch.h + $(ProjectDir)..\..\Classes;$(EngineRoot)cocos\platform\win8.1-universal;%(AdditionalIncludeDirectories) + false + + + + + /bigobj /Zm200 %(AdditionalOptions) + 4800;%(DisableSpecificWarnings) + pch.h + $(ProjectDir)..\..\Classes;$(EngineRoot)cocos\platform\win8.1-universal;%(AdditionalIncludeDirectories) + false + + + + + /bigobj /Zm200 %(AdditionalOptions) + 4800;%(DisableSpecificWarnings) + pch.h + $(ProjectDir)..\..\Classes;$(EngineRoot)cocos\platform\win8.1-universal;%(AdditionalIncludeDirectories) + false + + + + + Designer + + + + + + + + + + + + + {ca082ec4-17ce-430b-8207-d1e947a5d1e9} + + + {22f3b9df-1209-4574-8331-003966f562bf} + + + {cc1da216-a80d-4be4-b309-acb6af313aff} + + + {22f798d8-bfff-4754-996f-a5395343d5ec} + + + + + + \ No newline at end of file diff --git a/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/js-tests.WindowsPhone.vcxproj.filters b/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/js-tests.WindowsPhone.vcxproj.filters new file mode 100644 index 0000000000..eb71f325ca --- /dev/null +++ b/tests/js-tests/project/proj.win8.1-universal/App.WindowsPhone/js-tests.WindowsPhone.vcxproj.filters @@ -0,0 +1,30 @@ + + + + + {c8beb60d-689b-4aaa-9749-99bd3e2dcf75} + bmp;fbx;gif;jpg;jpeg;tga;tiff;tif;png + + + Assets + + + Assets + + + Assets + + + Assets + + + Assets + + + Assets + + + + + + \ No newline at end of file diff --git a/tests/js-tests/project/proj.win8.1-universal/resources.props b/tests/js-tests/project/proj.win8.1-universal/resources.props new file mode 100644 index 0000000000..753a816029 --- /dev/null +++ b/tests/js-tests/project/proj.win8.1-universal/resources.props @@ -0,0 +1,63 @@ + + + + + + + $(EngineRoot)cocos\scripting\js-bindings\manual;$(EngineRoot)cocos\scripting\js-bindings\auto;$(EngineRoot)external\spidermonkey\include\$(COCOS2D_PLATFORM);$(EngineRoot)cocos\base;%(AdditionalIncludeDirectories); + + + mozjs-33.lib;%(AdditionalDependencies) + $(EngineRoot)external\spidermonkey\prebuilt\$(COCOS2D_PLATFORM)\$(Platform);%(AdditionalLibraryDirectories); + + + + + $(EngineRoot)external\spidermonkey\prebuilt\$(COCOS2D_PLATFORM)\$(Platform)\ + + + + + true + + + + + <_CustomResource Include="..\..\..\res\**\*"> + Assets\Resources\res\%(RecursiveDir)%(FileName)%(Extension) + true + + + + <_CustomResource Include="..\..\..\src\**\*"> + Assets\Resources\src\%(RecursiveDir)%(FileName)%(Extension) + true + + + + <_CustomResource Include="..\..\..\..\..\cocos\scripting\js-bindings\script\**\*"> + Assets\Resources\script\%(RecursiveDir)%(FileName)%(Extension) + true + + + + <_CustomResource Include="..\..\..\main.js"> + Assets\Resources\%(RecursiveDir)%(FileName)%(Extension) + true + + + + <_CustomResource Include="..\..\..\project.json"> + Assets\Resources\%(RecursiveDir)%(FileName)%(Extension) + true + + + + + + + + + + + diff --git a/tests/js-tests/src/ActionManagerTest/ActionManagerTest.js b/tests/js-tests/src/ActionManagerTest/ActionManagerTest.js new file mode 100644 index 0000000000..7bb29f3a1c --- /dev/null +++ b/tests/js-tests/src/ActionManagerTest/ActionManagerTest.js @@ -0,0 +1,428 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var TAG_NODE = 5560; +var TAG_GROSSINI = 5561; +var TAG_SEQUENCE = 5562; + +var ActionMgrTestIdx = -1; +var NOT_CRASHED_CONST = "NOT_CRASHED"; + + +//------------------------------------------------------------------ +// +// ActionManagerTest +// +//------------------------------------------------------------------ +var ActionManagerTest = BaseTestLayer.extend({ + _atlas:null, + _title:"", + + title:function () { + return "No title"; + }, + + subtitle:function () { + return ""; + }, + + onBackCallback:function (sender) { + var s = new ActionManagerTestScene(); + s.addChild(previousActionMgrTest()); + director.runScene(s); + }, + onRestartCallback:function (sender) { + var s = new ActionManagerTestScene(); + s.addChild(restartActionMgrTest()); + director.runScene(s); + }, + onNextCallback:function (sender) { + var s = new ActionManagerTestScene(); + s.addChild(nextActionMgrTest()); + director.runScene(s); + }, + // automation + numberOfPendingTests:function() { + return ( (arrayOfActionMgrTest.length-1) - ActionMgrTestIdx ); + }, + + getTestNumber:function() { + return ActionMgrTestIdx; + } +}); + +//------------------------------------------------------------------ +// +// Test1 +// +//------------------------------------------------------------------ +var CrashTest = ActionManagerTest.extend({ + title:function () { + return "Test 1. Should not crash"; + }, + onEnter:function () { + //----start0----onEnter + this._super(); + + var child = new cc.Sprite(s_pathGrossini); + child.x = 200; + child.y = 200; + this.addChild(child, 1); + + //Sum of all action's duration is 1.5 second. + child.runAction(cc.rotateBy(1.5, 90)); + child.runAction(cc.sequence( + cc.delayTime(1.4), + cc.fadeOut(1.1)) + ); + + //After 1.5 second, self will be removed. + //this.runAction(cc.sequence( + // cc.delayTime(1.4), + // cc.callFunc(this.onRemoveThis, this)) + //); + //----end0---- + }, + + onRemoveThis:function () { + //----start0----onRemoveThis + this.parent.removeChild(this); + this.onNextCallback(this); + //----end0---- + }, + + // + // Automation + // + getExpectedResult:function() { + return NOT_CRASHED_CONST; + }, + getCurrentResult:function() { + return NOT_CRASHED_CONST; + } +}); + +//------------------------------------------------------------------ +// +// Test2 +// +//------------------------------------------------------------------ +var LogicTest = ActionManagerTest.extend({ + title:function () { + return "Logic test"; + }, + onEnter:function () { + //----start1----onEnter + this._super(); + + var grossini = new cc.Sprite(s_pathGrossini); + this.addChild(grossini, 0, 2); + grossini.x = 200; + grossini.y = 200; + + grossini.runAction(cc.sequence( + cc.moveBy(1, cc.p(150, 0)), + cc.callFunc(this.onBugMe, this)) + ); + + + // + // only for automation + // + if ( autoTestEnabled ) { + this._grossini = grossini; + } + //----end1---- + }, + onBugMe:function (node) { + //----start1----onBugMe + node.stopAllActions(); //After this stop next action not working, if remove this stop everything is working + node.runAction(cc.scaleTo(2, 2)); + //----end1---- + }, + + // + // Automation + // + testDuration: 4.0, + getExpectedResult:function() { + var ret = [ {"scaleX":2, "scaleY":2} ]; + return JSON.stringify(ret); + }, + getCurrentResult:function() { + var ret = [ {"scaleX":this._grossini.scaleX, "scaleY":this._grossini.scaleY} ]; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// PauseTest +// +//------------------------------------------------------------------ +var PauseTest = ActionManagerTest.extend({ + title:function () { + return "Pause Test"; + }, + onEnter:function () { + //----start2----onEnter + // + // This test MUST be done in 'onEnter' and not on 'init' + // otherwise the paused action will be resumed at 'onEnter' time + // + this._super(); + + var s = director.getWinSize(); + var l = new cc.LabelTTF("After 3 seconds grossini should move", "Thonburi", 16); + this.addChild(l); + l.x = s.width / 2; + l.y = 245; + + // + // Also, this test MUST be done, after [super onEnter] + // + var grossini = new cc.Sprite(s_pathGrossini); + this.addChild(grossini, 0, TAG_GROSSINI); + grossini.x = 200; + grossini.y = 200; + + + var action = cc.moveBy(1, cc.p(150, 0)); + + director.getActionManager().addAction(action, grossini, true); + + this.schedule(this.onUnpause, 3); + + // + // only for automation + // + if ( autoTestEnabled ) { + this.scheduleOnce(this.checkControl1, 2.0); + this.scheduleOnce(this.checkControl2, 4.5); + this._grossini = grossini; + } + //----end2---- + }, + + onUnpause:function (dt) { + //----start2----onUnpause + this.unschedule(this.onUnpause); + var node = this.getChildByTag(TAG_GROSSINI); + director.getActionManager().resumeTarget(node); + //----end2---- + }, + + // + // Automation + // + testDuration:5.5, + checkControl1:function(dt) { + this.control1 = cc.p(this._grossini.x, this._grossini.y); + }, + checkControl2:function(dt) { + this.control2 = cc.p(this._grossini.x, this._grossini.y); + }, + getExpectedResult:function() { + var ret = [ {"x":200, "y":200}, {"x":350, "y":200} ]; + return JSON.stringify(ret); + }, + getCurrentResult:function() { + var ret = [ {"x":this.control1.x, "y":this.control1.y}, {"x":this.control2.x, "y":this.control2.y} ]; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// RemoveTest +// +//------------------------------------------------------------------ +var RemoveTest = ActionManagerTest.extend({ + title:function () { + return "Remove Test"; + }, + onEnter:function () { + //----start3----onEnter + this._super(); + + var s = director.getWinSize(); + var l = new cc.LabelTTF("Should not crash", "Thonburi", 16); + this.addChild(l); + l.x = s.width / 2; + l.y = 245; + + var move = cc.moveBy(2, cc.p(200, 0)); + var callback = cc.callFunc(this.stopAction, this); + var sequence = cc.sequence(move, callback); + sequence.tag = TAG_SEQUENCE; + + var child = new cc.Sprite(s_pathGrossini); + child.x = 200; + child.y = 200; + + this.addChild(child, 1, TAG_GROSSINI); + child.runAction(sequence); + //----end3---- + }, + + stopAction:function () { + //----start3----onEnter + var sprite = this.getChildByTag(TAG_GROSSINI); + sprite.stopActionByTag(TAG_SEQUENCE); + //----end3---- + }, + + // + // Automation + // + testDuration:3.5, + getExpectedResult:function() { + return NOT_CRASHED_CONST; + }, + getCurrentResult:function() { + return NOT_CRASHED_CONST; + } +}); + +//------------------------------------------------------------------ +// +// ResumeTest +// +//------------------------------------------------------------------ +var ResumeTest = ActionManagerTest.extend({ + title:function () { + return "Resume Test"; + }, + onEnter:function () { + //----start4----onEnter + this._super(); + + var s = director.getWinSize(); + var l = new cc.LabelTTF("Grossini only rotate/scale in 3 seconds", "Thonburi", 16); + this.addChild(l); + l.x = s.width / 2; + l.y = 245; + + var grossini = new cc.Sprite(s_pathGrossini); + this._grossini = grossini; + this.addChild(grossini, 0, TAG_GROSSINI); + grossini.x = s.width / 2; + grossini.y = s.height / 2; + + grossini.runAction(cc.scaleBy(2, 2)); + + director.getActionManager().pauseTarget(grossini); + grossini.runAction(cc.rotateBy(2, 360)); + + this.schedule(this.resumeGrossini, 3.0); + //----end4---- + + }, + resumeGrossini:function (time) { + //----start4----resumeGrossini + this.unschedule(this.resumeGrossini); + + var grossini = this.getChildByTag(TAG_GROSSINI); + director.getActionManager().resumeTarget(grossini); + //----end4---- + }, + + // + // Automation + // + testDuration:6.0, + setupAutomation:function() { + this.scheduleOnce(this.checkControl1, 1.0); + this.scheduleOnce(this.checkControl2, 5.5); + }, + checkControl1:function(dt) { + this.control1ScaleX = this._grossini.scaleX; + this.control1ScaleY = this._grossini.scaleY; + this.control1Rotation = this._grossini.rotation; + }, + checkControl2:function(dt) { + this.control2ScaleX = this._grossini.scaleX; + this.control2ScaleY = this._grossini.scaleY; + this.control2Rotation = this._grossini.rotation; + }, + getExpectedResult:function() { + var ret = [ {"Rot":0 }, {"sX":1, "sY":1}, {"Rot":360 }, {"sX":2, "sY":2} ]; + return JSON.stringify(ret); + }, + getCurrentResult:function() { + var ret = [ {"Rot": this.control1Rotation }, {"sX": this.control1ScaleX, "sY": this.control1ScaleY}, {"Rot": this.control2Rotation }, {"sX": this.control2ScaleX, "sY": this.control2ScaleY} ]; + return JSON.stringify(ret); + } +}); + +var ActionManagerTestScene = TestScene.extend({ + runThisTest:function (num) { + ActionMgrTestIdx = (num || 0) - 1; + this.addChild(nextActionMgrTest()); + director.runScene(this); + } +}); + + +//- +// +// Flow control +// +var arrayOfActionMgrTest = [ + CrashTest, + LogicTest, + PauseTest, + RemoveTest, + ResumeTest +]; + +var nextActionMgrTest = function (num) { + + ActionMgrTestIdx = num ? num - 1 : ActionMgrTestIdx; + + ActionMgrTestIdx++; + ActionMgrTestIdx = ActionMgrTestIdx % arrayOfActionMgrTest.length; + + if(window.sideIndexBar){ + ActionMgrTestIdx = window.sideIndexBar.changeTest(ActionMgrTestIdx, 0); + } + + return new arrayOfActionMgrTest[ActionMgrTestIdx](); +}; +var previousActionMgrTest = function () { + ActionMgrTestIdx--; + if (ActionMgrTestIdx < 0) + ActionMgrTestIdx += arrayOfActionMgrTest.length; + + if(window.sideIndexBar){ + ActionMgrTestIdx = window.sideIndexBar.changeTest(ActionMgrTestIdx, 0); + } + + return new arrayOfActionMgrTest[ActionMgrTestIdx](); +}; +var restartActionMgrTest = function () { + return new arrayOfActionMgrTest[ActionMgrTestIdx](); +}; diff --git a/tests/js-tests/src/ActionsTest/ActionsTest.js b/tests/js-tests/src/ActionsTest/ActionsTest.js new file mode 100644 index 0000000000..8fae9eecaa --- /dev/null +++ b/tests/js-tests/src/ActionsTest/ActionsTest.js @@ -0,0 +1,2750 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + + +var actionsTestIdx = -1; + +var SPRITE_GROSSINI_TAG = 1; +var SPRITE_TAMARA_TAG = 2; +var SPRITE_KATHIA_TAG = 3; + +// the class inherit from TestScene +// every Scene each test used must inherit from TestScene, +// make sure the test have the menu item for back to main menu +var ActionsTestScene = TestScene.extend({ + runThisTest:function (num) { + actionsTestIdx = (num || num == 0) ? (num - 1) : -1; + this.addChild(nextActionsTest()); + director.runScene(this); + } +}); + +var ActionsDemo = BaseTestLayer.extend({ + _grossini:null, + _tamara:null, + _kathia:null, + _code:null, + + ctor:function () { + this._super(cc.color(0,0,0,255), cc.color(98,99,117,255) ); + + this._grossini = new cc.Sprite(s_pathGrossini); + this._tamara = new cc.Sprite(s_pathSister1); + this._kathia = new cc.Sprite(s_pathSister2); + this.addChild(this._grossini, SPRITE_GROSSINI_TAG); + this.addChild(this._tamara, SPRITE_TAMARA_TAG); + this.addChild(this._kathia, SPRITE_KATHIA_TAG); + var s = director.getWinSize(); + this._grossini.x = s.width / 2; + this._grossini.y = s.height / 3; + this._tamara.x = s.width / 2; + this._tamara.y = 2 * s.height / 3; + this._kathia.x = s.width / 2; + this._kathia.y = s.height / 2; + }, + + centerSprites:function (numberOfSprites) { + var winSize = director.getWinSize(); + + if (numberOfSprites === 0) { + this._tamara.visible = false; + this._kathia.visible = false; + this._grossini.visible = false; + } else if (numberOfSprites == 1) { + this._tamara.visible = false; + this._kathia.visible = false; + this._grossini.x = winSize.width / 2; + this._grossini.y = winSize.height / 2; + } + else if (numberOfSprites == 2) { + this._kathia.x = winSize.width / 3; + this._kathia.y = winSize.height / 2; + this._tamara.x = 2 * winSize.width / 3; + this._tamara.y = winSize.height / 2; + this._grossini.visible = false; + } + else if (numberOfSprites == 3) { + this._grossini.x = winSize.width / 2; + this._grossini.y = winSize.height / 2; + this._tamara.x = winSize.width / 4; + this._tamara.y = winSize.height / 2; + this._kathia.x = 3 * winSize.width / 4; + this._kathia.y = winSize.height / 2; + } + }, + alignSpritesLeft:function (numberOfSprites) { + //----start47----onEnter + var s = director.getWinSize(); + + if (numberOfSprites == 1) { + this._tamara.visible = false; + this._kathia.visible = false; + this._grossini.x = 60; + this._grossini.y = s.height / 2; + } + else if (numberOfSprites == 2) { + this._kathia.x = 60; + this._kathia.y = s.height / 3; + this._tamara.x = 60; + this._tamara.y = 2 * s.height / 3; + this._grossini.visible = false; + } + else if (numberOfSprites == 3) { + this._grossini.x = 60; + this._grossini.y = s.height / 2; + this._tamara.x = 60; + this._tamara.y = 2 * s.height / 3; + this._kathia.x = 60; + this._kathia.y = s.height / 3; + } + //----end47---- + }, + title:function () { + return "ActionsTest"; + }, + subtitle:function () { + return ""; + }, + onBackCallback:function (sender) { + var s = new ActionsTestScene(); + s.addChild(previousActionsTest()); + director.runScene(s); + }, + onRestartCallback:function (sender) { + var s = new ActionsTestScene(); + s.addChild(restartActionsTest()); + director.runScene(s); + }, + onNextCallback:function (sender) { + var s = new ActionsTestScene(); + s.addChild(nextActionsTest()); + director.runScene(s); + }, + numberOfPendingTests:function() { + return ( (arrayOfActionsTest.length-1) - actionsTestIdx ); + }, + + getTestNumber:function() { + return actionsTestIdx; + } +}); + +//------------------------------------------------------------------ +// +// ActionManual +// +//------------------------------------------------------------------ +var ActionManual = ActionsDemo.extend({ + _code:"sprite.x = 10; sprite.y = 20;\n" + + "sprite.rotation = 90;\n" + + "sprite.scale = 2;", + + onEnter:function () { + //----start0----onEnter + this._super(); + + this._tamara.attr({ + x: 100, + y: 70, + opacity: 128, + scaleX: 2.5, + scaleY: -1.0 + }); + + this._grossini.attr({ + x: winSize.width / 2, + y: winSize.height / 2, + rotation: 120, + color: cc.color(255, 0, 0) + }); + + this._kathia.x = winSize.width - 100; + this._kathia.y = winSize.height / 2; + this._kathia.color = cc.color(0, 0, 255); + //----end0---- + }, + + title:function () { + return "Sprite properties"; + }, + subtitle:function () { + return "Manual Transformation"; + }, + + // + // Automation + // + testDuration:0.1, + getExpectedResult:function() { + var ret = [2.5,{"x":100,"y":70},128,120,{"x":winSize.width/2,"y":winSize.height/2},{"r":255,"g":0,"b":0},{"x":winSize.width - 100,"y":winSize.height / 2},{"r":0,"g":0,"b":255}]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = []; + ret.push( this._tamara.scaleX ); + ret.push( cc.p(this._tamara.x, this._tamara.y) ); + ret.push( this._tamara.opacity ); + + ret.push( this._grossini.rotation ); + ret.push( cc.p(this._grossini.x, this._grossini.y) ); + ret.push( this._grossini.color ); + + ret.push( cc.p(this._kathia.x, this._kathia.y) ); + ret.push( this._kathia.color ); + + return JSON.stringify(ret); + } +}); + + +//------------------------------------------------------------------ +// +// ActionMove +// +//------------------------------------------------------------------ +var ActionMove = ActionsDemo.extend({ + + _code:"a =cc.moveBy( time, cc.p(x,y) );\n" + + "a = cc.moveTo( time, cc.p(x,y) );", + + onEnter:function () { + //----start1----onEnter + this._super(); + + this.centerSprites(3); + var s = director.getWinSize(); + + var actionTo = cc.moveTo(2, cc.p(s.width - 40, s.height - 40)); + + var actionBy = cc.moveBy(1, cc.p(80, 80)); + var actionByBack = actionBy.reverse(); + + this._tamara.runAction(actionTo); + this._grossini.runAction(cc.sequence(actionBy, actionByBack)); + this._kathia.runAction(cc.moveTo(1, cc.p(40, 40))); + //----end1---- + }, + title:function () { + return "cc.moveTo / cc.moveBy"; + }, + + // + // Automation + // + testDuration:2.1, + getExpectedResult:function() { + var ret = [{"x":winSize.width-40,"y":winSize.height-40},{"x":winSize.width/2,"y":winSize.height/2},{"x":40,"y":40}]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = []; + ret.push( cc.p(this._tamara.x, this._tamara.y) ); + ret.push( cc.p(this._grossini.x, this._grossini.y) ); + ret.push( cc.p(this._kathia.x, this._kathia.y) ); + + return JSON.stringify(ret); + } + +}); + +//------------------------------------------------------------------ +// +// ActionScale +// +//------------------------------------------------------------------ +var ActionScale = ActionsDemo.extend({ + + _code:"a = cc.scaleBy( time, scale );\n" + + "a = cc.scaleTo( time, scaleX, scaleY );", + + onEnter:function () { + //----start2----onEnter + this._super(); + + this.centerSprites(3); + + var actionTo = cc.scaleTo(2, 0.5); + var actionBy = cc.scaleBy(2, 2); + var actionBy2 = cc.scaleBy(2, 0.25, 4.5); + + this._tamara.runAction(actionTo); + this._kathia.runAction(cc.sequence(actionBy2, cc.delayTime(0.25), actionBy2.reverse())); + this._grossini.runAction(cc.sequence(actionBy, cc.delayTime(0.25), actionBy.reverse())); + + //----end2---- + }, + title:function () { + return "cc.scaleTo / cc.scaleBy"; + }, + + // + // Automation + // + testDuration:2.1, + getExpectedResult:function() { + var ret = [0.5,2,0.25,4.5]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = []; + ret.push( this._tamara.scale ); + ret.push( this._grossini.scale ); + ret.push( this._kathia.scaleX ); + ret.push( this._kathia.scaleY ); + + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// ActionRotate +// +//------------------------------------------------------------------ +var ActionRotate = ActionsDemo.extend({ + + _code:"a = cc.rotateBy( time, degrees );\n" + + "a = cc.rotateTo( time, degrees );", + + onEnter:function () { + //----start3----onEnter + this._super(); + this.centerSprites(3); + var actionTo = cc.rotateTo(2, 45); + var actionTo2 = cc.rotateTo(2, -45); + var actionTo0 = cc.rotateTo(2, 0); + this._tamara.runAction(cc.sequence(actionTo, cc.delayTime(0.25), actionTo0)); + + var actionBy = cc.rotateBy(2, 360); + var actionByBack = actionBy.reverse(); + this._grossini.runAction(cc.sequence(actionBy, cc.delayTime(0.25), actionByBack)); + + this._kathia.runAction(cc.sequence(actionTo2, cc.delayTime(0.25), actionTo0.clone())); + + //----end3---- + }, + title:function () { + return "cc.rotateTo / cc.rotateBy"; + }, + // + // Automation + // + testDuration:2.1, + getExpectedResult:function() { + var ret = [45,360,-45]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = []; + ret.push( this._tamara.rotation ); + ret.push( this._grossini.rotation ); + ret.push( this._kathia.rotation ); + + return JSON.stringify(ret); + } + +}); + +//------------------------------------------------------------------ +// +// ActionRotateXY +// +//------------------------------------------------------------------ +var ActionRotateXY = ActionsDemo.extend({ + onEnter:function () { + //----start4----onEnter + this._super(); + this.centerSprites(3); + var actionTo = cc.rotateTo(2, 37.2, -37.2); + var actionToBack = cc.rotateTo(2, 0, 0); + var actionBy = cc.rotateBy(2, 0, -90); + var actionBy2 = cc.rotateBy(2, 45.0, 45.0); + + var delay = cc.delayTime(0.25); + + this._tamara.runAction(cc.sequence(actionTo, delay, actionToBack)); + this._grossini.runAction(cc.sequence(actionBy, delay.clone(), actionBy.reverse())); + + this._kathia.runAction(cc.sequence(actionBy2, delay.clone(), actionBy2.reverse())); + + if (!cc.sys.isNative && !("opengl" in cc.sys.capabilities)) { + var label = new cc.LabelTTF("Not support Actions on HTML5-canvas", "Times New Roman", 30); + label.x = winSize.width / 2; + label.y = winSize.height / 2 + 50; + this.addChild(label, 100); + } + //----end4---- + }, + title:function () { + return "cc.RotateBy(x,y) / cc.RotateTo(x,y)"; + }, + // + // Automation + // + testDuration:2.1, + getExpectedResult:function() { + var ret = ["37.20","-37.20",0,-90,45,45]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = []; + ret.push( this._tamara.rotationX.toFixed(2) ); + ret.push( this._tamara.rotationY.toFixed(2) ); + + ret.push( this._grossini.rotationX ); + ret.push( this._grossini.rotationY ); + + ret.push( this._kathia.rotationX ); + ret.push( this._kathia.rotationY ); + + return JSON.stringify(ret); + } + +}); +//------------------------------------------------------------------ +// +// ActionSkew +// +//------------------------------------------------------------------ +var ActionSkew = ActionsDemo.extend({ + + _code:"a = cc.skewBy( time, skew );\n" + + "a = cc.skewTo( time, skewX, skewY );", + + onEnter:function () { + //----start5----onEnter + this._super(); + this.centerSprites(3); + var actionTo = cc.skewTo(2, 37.2, -37.2); + var actionToBack = cc.skewTo(2, 0, 0); + var actionBy = cc.skewBy(2, 0, -90); + var actionBy2 = cc.skewBy(2, 45.0, 45.0); + + var delay = cc.delayTime(0.25); + + this._tamara.runAction(cc.sequence(actionTo, delay, actionToBack)); + this._grossini.runAction(cc.sequence(actionBy, delay.clone(), actionBy.reverse())); + + this._kathia.runAction(cc.sequence(actionBy2, delay.clone(), actionBy2.reverse())); + //----end5---- + }, + title:function () { + return "cc.skewTo / cc.skewBy"; + }, + // + // Automation + // + testDuration:2.1, + getExpectedResult:function() { + var ret = ["37.20","-37.20",0,0,45,45]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = []; + ret.push( this._tamara.skewX.toFixed(2) ); + ret.push( this._tamara.skewY.toFixed(2) ); + + ret.push( this._grossini.skewX ); + ret.push( this._grossini.skewY ); + + ret.push( this._kathia.skewX ); + ret.push( this._kathia.skewY ); + + return JSON.stringify(ret); + } +}); + +var ActionSkewRotateScale = ActionsDemo.extend({ + onEnter:function () { + //----start6----onEnter + this._super(); + + this.centerSprites(0); + + var boxW = 100, boxH = 100; + var box = new cc.LayerColor(cc.color(255, 255, 0, 255)); + box.anchorX = 0; + box.anchorY = 0; + box.x = (winSize.width - boxW) / 2; + box.y = (winSize.height - boxH) / 2; + box.width = boxW; + box.height = boxH; + + var markrside = 10.0; + var uL = new cc.LayerColor(cc.color(255, 0, 0, 255)); + box.addChild(uL); + uL.width = markrside; + uL.height = markrside; + uL.x = 0; + uL.y = boxH - markrside; + uL.anchorX = 0; + uL.anchorY = 0; + + var uR = new cc.LayerColor(cc.color(0, 0, 255, 255)); + box.addChild(uR); + uR.width = markrside; + uR.height = markrside; + uR.x = boxW - markrside; + uR.y = boxH - markrside; + uR.anchorX = 0; + uR.anchorY = 0; + + + this.addChild(box); + var actionTo = cc.skewTo(2, 0, 2); + var rotateTo = cc.rotateTo(2, 61.0); + var actionScaleTo = cc.scaleTo(2, -0.44, 0.47); + + var actionScaleToBack = cc.scaleTo(2, 1.0, 1.0); + var rotateToBack = cc.rotateTo(2, 0); + var actionToBack = cc.skewTo(2, 0, 0); + + var delay = cc.delayTime(0.25); + + box.runAction(cc.sequence(actionTo, delay, actionToBack)); + box.runAction(cc.sequence(rotateTo, delay.clone(), rotateToBack)); + box.runAction(cc.sequence(actionScaleTo, delay.clone(), actionScaleToBack)); + + this.box = box; + //----end6---- + }, + title:function () { + return "Skew + Rotate + Scale"; + }, + // + // Automation + // + testDuration:2.1, + getExpectedResult:function() { + var ret = [0,2,61,"-0.44","0.47"]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = []; + ret.push( this.box.skewX ); + ret.push( this.box.skewY ); + ret.push( this.box.rotation ); + ret.push( this.box.scaleX.toFixed(2) ); + ret.push( this.box.scaleY.toFixed(2) ); + + return JSON.stringify(ret); + } + +}); + +//------------------------------------------------------------------ +// +// ActionJump +// +//------------------------------------------------------------------ +var ActionJump = ActionsDemo.extend({ + _code:"a = cc.jumpBy( time, point, height, #_of_jumps );\n" + + "a = cc.jumpTo( time, point, height, #_of_jumps );", + + onEnter:function () { + //----start7----onEnter + this._super(); + this.centerSprites(3); + + var actionTo = cc.jumpTo(2, cc.p(300, 300), 50, 4); + var actionBy = cc.jumpBy(2, cc.p(300, 0), 50, 4); + var actionUp = cc.jumpBy(2, cc.p(0, 0), 80, 4); + var actionByBack = actionBy.reverse(); + + var delay = cc.delayTime(0.25); + + this._tamara.runAction(actionTo); + this._grossini.runAction(cc.sequence(actionBy, delay, actionByBack)); + + var action = cc.sequence(actionUp, delay.clone()).repeatForever(); + this._kathia.runAction(action); + //----end7---- + }, + title:function () { + return "cc.jumpTo / cc.jumpBy"; + }, + subtitle:function () { + return "Actions will stop for 0.25s after 2 seconds"; + }, + + // + // Automation + // + testDuration:2.1, + getExpectedResult:function() { + var ret = [{"x":300,"y":300}, + {"x":winSize.width/2+300,"y":winSize.height/2}, + {"x":3*winSize.width/4,"y":winSize.height/2}]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = []; + ret.push( cc.p(this._tamara.x, this._tamara.y) ); + ret.push( cc.p(this._grossini.x, this._grossini.y) ); + ret.push( cc.p(this._kathia.x, this._kathia.y) ); + + return JSON.stringify(ret); + } + +}); +//------------------------------------------------------------------ +// +// ActionBezier +// +//------------------------------------------------------------------ +var ActionBezier = ActionsDemo.extend({ + onEnter:function () { + //----start8----onEnter + + this._super(); + var s = director.getWinSize(); + + // + // startPosition can be any coordinate, but since the movement + // is relative to the Bezier curve, make it (0,0) + // + + this.centerSprites(3); + + // sprite 1 + + var delay = cc.delayTime(0.25); + + // 3 and only 3 control points should be used for Bezier actions. + var controlPoints = [ cc.p(0, 374), + cc.p(300, -374), + cc.p(300, 100) ]; + + var bezierForward = cc.bezierBy(2, controlPoints); + var rep = cc.sequence(bezierForward, delay, bezierForward.reverse(), delay.clone()).repeatForever(); + + // sprite 2 + this._tamara.x = 80; + this._tamara.y = 160; + + // 3 and only 3 control points should be used for Bezier actions. + var controlPoints2 = [ cc.p(100, s.height / 2), + cc.p(200, -s.height / 2), + cc.p(240, 160) ]; + var bezierTo1 = cc.bezierTo(2, controlPoints2); + + // // sprite 3 + var controlPoints3 = controlPoints2.slice(); + this._kathia.x = 400; + this._kathia.y = 160; + var bezierTo2 = cc.bezierTo(2, controlPoints3); + + this._grossini.runAction(rep); + this._tamara.runAction(bezierTo1); + this._kathia.runAction(bezierTo2); + //----end8---- + }, + title:function () { + return "cc.bezierBy / cc.bezierTo"; + }, + // + // Automation + // + testDuration:2.1, + setupAutomation:function() { + this.scheduleOnce(this.checkControl1, 0.66667); + this.scheduleOnce(this.checkControl2, 1.33333); + }, + checkControl1:function(dt) { + this.control1 = cc.p(this._grossini.x, this._grossini.y); + }, + verifyControl1:function(dt) { + var x = Math.abs( this.control1.x - 77 - winSize.width/2 ); + var y = Math.abs( this.control1.y - 87 - winSize.height/2 ); + // -/+ 5 pixels of error + return ( x < 5 && y < 5); + }, + checkControl2:function(dt) { + this.control2 = cc.p(this._grossini.x, this._grossini.y); + }, + verifyControl2:function(dt) { + var x = Math.abs( this.control2.x - 222 - winSize.width/2 ); + var y = Math.abs( this.control2.y + 53 - winSize.height/2 ); + // -/+ 5 pixels of error + return ( x < 5 && y < 5); + }, + + getExpectedResult:function() { + var ret = [ true, + true, + {"x":winSize.width/2+300,"y":winSize.height/2+100}]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = []; + ret.push( this.verifyControl1() ); + ret.push( this.verifyControl2() ); + ret.push( cc.p(this._grossini.x, this._grossini.y) ); + + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// ActionBezierToCopy +// +//------------------------------------------------------------------ +var ActionBezierToCopy = ActionsDemo.extend({ + onEnter:function () { + //----start9----onEnter + this._super(); + + // + // startPosition can be any coordinate, but since the movement + // is relative to the Bezier curve, make it (0,0) + // + + this.centerSprites(2); + + // sprite 1 + this._tamara.x = 80; + this._tamara.y = 160; + + // 3 and only 3 control points should be used for Bezier actions. + var controlPoints2 = [ cc.p(100, winSize.height / 2), + cc.p(200, -winSize.height / 2), + cc.p(240, 160) ]; + var bezierTo1 = cc.bezierTo(2, controlPoints2); + + // sprite 2 + this._kathia.x = 80; + this._kathia.y = 160; + var bezierTo2 = bezierTo1.clone(); + + this._tamara.runAction(bezierTo1); + this._kathia.runAction(bezierTo2); + //----end9---- + }, + title:function () { + return "cc.bezierTo copy test"; + }, + subtitle:function() { + return "Both sprites should move across the same path"; + } +}); +//------------------------------------------------------------------ +// +// Issue1008 +// +//------------------------------------------------------------------ +var Issue1008 = ActionsDemo.extend({ + onEnter:function () { + + //----start10----onEnter + this._super(); + + this.centerSprites(1); + + // sprite 1 + + this._grossini.x = 428; + this._grossini.y = 279; + + // 3 and only 3 control points should be used for Bezier actions. + var controlPoints1 = [ cc.p(428, 279), cc.p(100, 100), cc.p(100, 100)]; + var controlPoints2 = [ cc.p(100, 100), cc.p(428, 279), cc.p(428, 279)]; + + var bz1 = cc.bezierTo(1.5, controlPoints1); + var bz2 = cc.bezierTo(1.5, controlPoints2); + var trace = cc.callFunc(this.onTrace, this); + var delay = cc.delayTime(0.25); + + var rep = cc.sequence(bz1, bz2, trace,delay).repeatForever(); + this._grossini.runAction(rep); + + //----end10---- + + //this._grossini.runAction(cc.sequence(bz1, bz2, trace,delay)); + + }, + onTrace:function (sender) { + var pos = cc.p(sender.x, sender.y); + cc.log("Position x: " + pos.x + ' y:' + pos.y); + if (Math.round(pos.x) != 428 || Math.round(pos.y) != 279) + this.log("Error: Issue 1008 is still open"); + + this.tracePos = pos; + }, + title:function () { + return "Issue 1008"; + }, + subtitle:function () { + return "cc.bezierTo + Repeat. See console"; + }, + // + // Automation + // + testDuration:3.1, + getExpectedResult:function() { + var ret = {"x":428,"y":279}; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + return JSON.stringify(this.tracePos); + } +}); +//------------------------------------------------------------------ +// +// ActionBlink +// +//------------------------------------------------------------------ +var ActionBlink = ActionsDemo.extend({ + _code:"a = cc.blink( time, #_of_blinks );", + + onEnter:function () { + //----start13----onEnter + this._super(); + this.centerSprites(2); + + var action1 = cc.blink(2, 10); + var action2 = cc.blink(2, 5); + + this._tamara.runAction(action1); + this._kathia.runAction(action2); + //----end13---- + }, + title:function () { + return "cc.blink"; + }, + // + // Automation + // + testDuration:2.1, + setupAutomation:function() { + this.scheduleOnce(this.checkControl1,0.1); + }, + checkControl1:function(dt){ + this.control1 = this._kathia.visible; + }, + getExpectedResult:function() { + var ret = [false,true,true]; + return JSON.stringify(ret); + }, + getCurrentResult:function() { + var ret = []; + ret.push( this.control1 ); + ret.push( this._tamara.visible); + ret.push( this._kathia.visible); + return JSON.stringify(ret); + } +}); +//------------------------------------------------------------------ +// +// ActionFade +// +//------------------------------------------------------------------ +var ActionFade = ActionsDemo.extend({ + _code:"a = cc.fadeIn( time );\n" + + "a = cc.fadeOut( time );", + + onEnter:function () { + //----start14----onEnter + this._super(); + this.centerSprites(2); + var delay = cc.delayTime(0.25); + this._tamara.opacity = 0; + var action1 = cc.fadeIn(1.0); + var action1Back = action1.reverse(); + + var action2 = cc.fadeOut(1.0); + var action2Back = action2.reverse(); + + this._tamara.runAction(cc.sequence(action1, delay, action1Back)); + this._kathia.runAction(cc.sequence(action2, delay.clone(), action2Back)); + //----end14---- + + }, + title:function () { + return "cc.fadeIn / cc.fadeOut"; + }, + // + // Automation + // + testDuration:1.1, + getExpectedResult:function() { + var ret = [255,0]; + return JSON.stringify(ret); + }, + getCurrentResult:function() { + var ret = []; + ret.push( this._tamara.opacity ); + ret.push( this._kathia.opacity); + return JSON.stringify(ret); + } + +}); +//------------------------------------------------------------------ +// +// ActionTint +// +//------------------------------------------------------------------ +var ActionTint = ActionsDemo.extend({ + + _code:"a = cc.tintBy( time, red, green, blue );\n" + + "a = cc.tintTo( time, red, green, blue );", + + onEnter:function () { + + //----start15----onEnter + this._super(); + this.centerSprites(2); + + var action1 = cc.tintTo(2, 255, 0, 255); + var action2 = cc.tintBy(2, -127, -255, -127); + var action2Back = action2.reverse(); + + this._tamara.runAction(action1); + this._kathia.runAction(cc.sequence(action2, cc.delayTime(0.25), action2Back)); + //----end15---- + + }, + title:function () { + return "cc.tintTo / cc.tintBy"; + }, + // + // Automation + // + testDuration:2.1, + getExpectedResult:function() { + var ret = [{"r":255,"g":0,"b":255},{"r":128,"g":0,"b":128}]; + return JSON.stringify(ret); + }, + getCurrentResult:function() { + var ret = []; + ret.push( this._tamara.color ); + ret.push( this._kathia.color ); + return JSON.stringify(ret); + } + +}); + +//------------------------------------------------------------------ +// +// ActionAnimate +// +//------------------------------------------------------------------ +var ActionAnimate = ActionsDemo.extend({ + onEnter:function () { + + //----start44----onEnter + this._super(); + this.centerSprites(3); + + // + // Manual animation + // + var animation = new cc.Animation(); + for (var i = 1; i < 15; i++) { + var frameName = "res/Images/grossini_dance_" + ((i < 10) ? ("0" + i) : i) + ".png"; + animation.addSpriteFrameWithFile(frameName); + } + animation.setDelayPerUnit(2.8 / 14); + animation.setRestoreOriginalFrame(true); + + var action = cc.animate(animation); + this._grossini.runAction(cc.sequence(action, action.reverse())); + + // + // File animation + // + // With 2 loops and reverse + var animCache = cc.animationCache; + + animCache.addAnimations(s_animations2Plist); + var animation2 = animCache.getAnimation("dance_1"); + + var action2 = cc.animate(animation2); + this._tamara.runAction(cc.sequence(action2, action2.reverse())); + + // + // File animation + // + // with 4 loops + var animation3 = animation2.clone(); + animation3.setLoops(4); + + var action3 = cc.animate(animation3); + this._kathia.runAction(action3); + //----end44---- + }, + + title:function () { + return "Animation"; + }, + + subtitle:function () { + return "Center: Manual animation. Border: using file format animation"; + } +}); +//------------------------------------------------------------------ +// +// ActionSequence +// +//------------------------------------------------------------------ +var ActionSequence = ActionsDemo.extend({ + + _code:"a = cc.sequence( a1, a2, a3,..., aN);", + + onEnter:function () { + //----start16----onEnter + this._super(); + this.alignSpritesLeft(1); + + var action = cc.sequence( + cc.moveBy(1.5, cc.p(240, 0)), + cc.rotateBy(1.5, 540) + ); + + this._grossini.runAction(action); + //----end16---- + }, + title:function () { + return "cc.sequence: Move + Rotate"; + }, + // + // Automation + // + testDuration:3.1, + getExpectedResult:function() { + var ret = [{"x":60+240,"y":winSize.height/2},540]; + return JSON.stringify(ret); + }, + getCurrentResult:function() { + var ret = []; + ret.push( cc.p(this._grossini.x, this._grossini.y) ); + ret.push( this._grossini.rotation ); + return JSON.stringify(ret); + } +}); +//------------------------------------------------------------------ +// +// ActionSequence2 +// +//------------------------------------------------------------------ +var ActionSequence2 = ActionsDemo.extend({ + onEnter:function () { + + //----start17----onEnter + this._super(); + this.centerSprites(1); + this._grossini.visible = false; + var action = cc.sequence( + cc.place(cc.p(200, 200)), + cc.show(), + cc.moveBy(1, cc.p(100, 0)), + cc.callFunc(this.onCallback1, this), + cc.callFunc(this.onCallback2.bind(this)), + cc.callFunc(this.onCallback3, this)); + this._grossini.runAction(action); + + this.called1 = this.called2 = this.called3 = false; + //----end17---- + }, + onCallback1:function () { + var s = director.getWinSize(); + var label = new cc.LabelTTF("callback 1 called", "Marker Felt", 16); + label.x = s.width / 4 * 1; + label.y = s.height / 2; + + this.addChild(label); + this.called1 = true; + }, + onCallback2:function () { + var s = director.getWinSize(); + var label = new cc.LabelTTF("callback 2 called", "Marker Felt", 16); + label.x = s.width / 4 * 2; + label.y = s.height / 2; + + this.addChild(label); + this.called2 = true; + }, + onCallback3:function () { + var s = director.getWinSize(); + var label = new cc.LabelTTF("callback 3 called", "Marker Felt", 16); + label.x = s.width / 4 * 3; + label.y = s.height / 2; + + this.addChild(label); + this.called3 = true; + }, + title:function () { + return "Sequence of InstantActions"; + }, + // + // Automation + // + testDuration:1.1, + getExpectedResult:function() { + var ret = [true,true,true,true,{"x":300,"y":200}]; + return JSON.stringify(ret); + }, + getCurrentResult:function() { + var ret = []; + ret.push( this.called1 ); + ret.push( this.called2 ); + ret.push( this.called3 ); + ret.push( this._grossini.visible ); + ret.push( cc.p(this._grossini.x, this._grossini.y) ); + return JSON.stringify(ret); + } +}); +//------------------------------------------------------------------ +// +// ActionCallFunc1 +// +//------------------------------------------------------------------ +var ActionCallFunc1 = ActionsDemo.extend({ + _code:"a = cc.callFunc( this.callback );\n" + + "a = cc.callFunc( this.callback, this, optional_arg );", + + onEnter:function () { + //----start25----onEnter + this._super(); + this.centerSprites(3); + + // Testing different ways to pass "this" + var action = cc.sequence( + cc.moveBy(2, cc.p(200, 0)), + cc.callFunc(this.onCallback1.bind(this)) // 'this' is bound to the callback function using "bind" + ); + + var action2 = cc.sequence( + cc.scaleBy(2, 2), + cc.fadeOut(2), + cc.callFunc(this.onCallback2, this) // 'this' is passed as 2nd argument. + ); + + var action3 = cc.sequence( + cc.rotateBy(3, 360), + cc.fadeOut(2), + cc.callFunc(this.onCallback3, this, "Hi!") // If you want to pass a optional value, like "Hi!", then you should pass 'this' too + ); + + this._grossini.runAction(action); + this._tamara.runAction(action2); + this._kathia.runAction(action3); + //----end25---- + + }, + onCallback1:function (nodeExecutingAction, value) { + var s = director.getWinSize(); + var label = new cc.LabelTTF("callback 1 called", "Marker Felt", 16); + label.x = s.width / 4 * 1; + label.y = s.height / 2; + this.addChild(label); + this.control1 = true; + }, + onCallback2:function (nodeExecutingAction, value) { + var s = director.getWinSize(); + var label = new cc.LabelTTF("callback 2 called", "Marker Felt", 16); + label.x = s.width / 4 * 2; + label.y = s.height / 2; + + this.addChild(label); + this.control2 = true; + }, + onCallback3:function (nodeExecutingAction, value) { + var s = director.getWinSize(); + var label = new cc.LabelTTF("callback 3 called:" + value, "Marker Felt", 16); + label.x = s.width / 4 * 3; + label.y = s.height / 2; + this.addChild(label); + this.control3 = true; + }, + title:function () { + return "Callbacks: CallFunc and friends"; + }, + // + // Automation + // + testDuration:5.05, + setupAutomation:function() { + this.control1 = this.control2 = this.control3 = false; + }, + getExpectedResult:function() { + var ret = [true,true,true]; + return JSON.stringify(ret); + }, + getCurrentResult:function() { + var ret = []; + ret.push( this.control1 ); + ret.push( this.control2 ); + ret.push( this.control3 ); + return JSON.stringify(ret); + } +}); +//------------------------------------------------------------------ +// +// ActionCallFunc2 +// +//------------------------------------------------------------------ +var ActionCallFunc2 = ActionsDemo.extend({ + onEnter:function () { + //----start26----onEnter + this._super(); + this.centerSprites(1); + + var action = cc.sequence(cc.moveBy(2.0, cc.p(200, 0)), + cc.callFunc(this.removeFromParentAndCleanup, this._grossini, true)); + + this._grossini.runAction(action); + //----end26---- + }, + + removeFromParentAndCleanup:function (nodeExecutingAction, data) { + nodeExecutingAction.removeFromParent(data); + }, + + title:function () { + return "cc.CallFunc + auto remove"; + }, + subtitle:function () { + return "cc.CallFunc + removeFromParentAndCleanup. Grossini dissapears in 2s"; + }, + // + // Automation + // + testDuration:2.1, + setupAutomation:function() { + }, + getExpectedResult:function() { + var ret = [null]; + return JSON.stringify(ret); + }, + getCurrentResult:function() { + var ret = []; + ret.push( this.getChildByTag(SPRITE_GROSSINI_TAG) ); + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// ActionCallFunc3 +// +//------------------------------------------------------------------ +var ActionCallFunc3 = ActionsDemo.extend({ + onEnter:function () { + //----start27----onEnter + this._super(); + this.centerSprites(1); + + var action = cc.callFunc(function (nodeExecutingAction, value) { + this.control1 = "Value is: " + value; + this.log("Object:" + nodeExecutingAction + ". " + this.control1); + }, this, "Hello world"); + + this.runAction(action); + //----end27---- + }, + + title:function () { + return "cc.CallFunc + parameters"; + }, + subtitle:function () { + return "cc.CallFunc + parameters. Take a look at the console"; + }, + // + // Automation + // + testDuration:0.1, + setupAutomation:function() { + }, + getExpectedResult:function() { + var ret = ["Value is: Hello world"]; + return JSON.stringify(ret); + }, + getCurrentResult:function() { + var ret = []; + ret.push( this.control1 ); + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// ActionSpawn +// +//------------------------------------------------------------------ +var ActionSpawn = ActionsDemo.extend({ + + _code:"a = cc.spawn( a1, a2, ..., aN );", + + onEnter:function () { + + //----start18----onEnter + this._super(); + this.alignSpritesLeft(1); + + var action = cc.spawn( + cc.jumpBy(2, cc.p(300, 0), 50, 4), + cc.rotateBy(2, 720)); + + this._grossini.runAction(action); + //----end18---- + + }, + title:function () { + return "cc.spawn: Jump + Rotate"; + }, + // + // Automation + // + testDuration:2.1, + getExpectedResult:function() { + var ret = [{"x":300+60,"y":winSize.height/2},720]; + return JSON.stringify(ret); + }, + getCurrentResult:function() { + var ret = []; + ret.push( cc.p(this._grossini.x, this._grossini.y) ); + ret.push( this._grossini.rotation ); + return JSON.stringify(ret); + } +}); +//------------------------------------------------------------------ +// +// ActionRepeatForever +// +//------------------------------------------------------------------ +var ActionRepeatForever = ActionsDemo.extend({ + _code:"a = action.repeatForever();", + + onEnter:function () { + //----start22----onEnter + this._super(); + this.centerSprites(1); + var action = cc.sequence( + cc.delayTime(1), + cc.callFunc(this.repeatForever)); // not passing 'this' since it is not used by the callback func + + this._grossini.runAction(action); + //----end22---- + + }, + repeatForever:function (sender) { + var repeat = cc.rotateBy(1, 360).repeatForever(); + sender.runAction(repeat); + }, + title:function () { + return "cc.CallFunc + cc.RepeatForever"; + }, + // + // Automation + // + testDuration:3.5, + getExpectedResult:function() { + var ret = [true]; + return JSON.stringify(ret); + }, + getCurrentResult:function() { + var ret = []; + var r = this._grossini.rotation; + var expected = 900; + var error = 15; + ret.push( r < expected+error && r > expected-error ); + return JSON.stringify(ret); + } + +}); +//------------------------------------------------------------------ +// +// ActionRotateToRepeat +// +//------------------------------------------------------------------ +var ActionRotateToRepeat = ActionsDemo.extend({ + _code:"a = action_to_repeat.repeat(#_of_times);", + + onEnter:function () { + //----start23----onEnter + this._super(); + this.centerSprites(2); + + var act1 = cc.rotateTo(0.5, 90); + var act2 = cc.rotateTo(0.5, 0); + var seq = cc.sequence(act1, act2); + var seq2 = seq.clone(); + + this._tamara.runAction(seq.repeatForever()); + this._kathia.runAction(seq2.repeat(4)); + //----end23---- + + }, + title:function () { + return "Repeat/RepeatForever + RotateTo"; + }, + // + // Automation + // + testDuration:4.5, + getExpectedResult:function() { + var ret = [0,true]; + return JSON.stringify(ret); + }, + getCurrentResult:function() { + var ret = []; + ret.push( this._kathia.rotation ); + var r = this._tamara.rotation; + var expected = 90; + var error = 15; + ret.push( r < expected+error && r > expected-error ); + return JSON.stringify(ret); + } + +}); +//------------------------------------------------------------------ +// +// ActionRotateJerk +// +//------------------------------------------------------------------ +var ActionRotateJerk = ActionsDemo.extend({ + onEnter:function () { + //----start24----onEnter + this._super(); + this.centerSprites(2); + var seq = cc.sequence( + cc.rotateTo(0.5, -20), + cc.rotateTo(0.5, 20)); + + var rep1 = seq.repeat(10); + var rep2 = seq.clone().repeatForever(); + this._tamara.runAction(rep1); + this._kathia.runAction(rep2); + //----end24---- + }, + title:function () { + return "RepeatForever / Repeat + Rotate"; + } +}); +//------------------------------------------------------------------ +// +// ActionReverse +// +//------------------------------------------------------------------ +var ActionReverse = ActionsDemo.extend({ + + _code:"a = action.reverse();", + + onEnter:function () { + + //----start19----onEnter + this._super(); + this.alignSpritesLeft(1); + + var jump = cc.jumpBy(2, cc.p(300, 0), 50, 4); + var delay = cc.delayTime(0.25); + var action = cc.sequence(jump, delay, jump.reverse()); + + this._grossini.runAction(action); + //----end19---- + }, + title:function () { + return "Reverse Jump action"; + }, + + // + // Automation + // + testDuration:4.4, + setupAutomation:function() { + this.scheduleOnce(this.checkControl1,2.1); + }, + checkControl1:function(dt) { + this.control1 = cc.p(this._grossini.x, this._grossini.y); + }, + getExpectedResult:function() { + var ret = [{"x":360,"y":winSize.height/2},{"x":60,"y":winSize.height/2}]; + return JSON.stringify(ret); + }, + getCurrentResult:function() { + var ret = []; + ret.push( this.control1 ); + ret.push( cc.p(this._grossini.x, this._grossini.y) ); + return JSON.stringify(ret); + } + +}); +//------------------------------------------------------------------ +// +// ActionDelayTime +// +//------------------------------------------------------------------ +var ActionDelayTime = ActionsDemo.extend({ + + _code:"a = cc.delayTime( time );", + + onEnter:function () { + //----start20----onEnter + this._super(); + this.alignSpritesLeft(1); + + var move = cc.moveBy(1, cc.p(150, 0)); + var action = cc.sequence(move, cc.delayTime(2), move.clone()); + + this._grossini.runAction(action); + //----end20---- + }, + title:function () { + return "DelayTime: m + delay + m"; + }, + // + // Automation + // + testDuration:2.9, + getExpectedResult:function() { + var ret = [{"x":210,"y":winSize.height/2}]; + return JSON.stringify(ret); + }, + getCurrentResult:function() { + var ret = []; + ret.push( cc.p(this._grossini.x, this._grossini.y) ); + return JSON.stringify(ret); + } +}); +//------------------------------------------------------------------ +// +// ActionReverseSequence +// +//------------------------------------------------------------------ +var ActionReverseSequence = ActionsDemo.extend({ + onEnter:function () { + + //----start28----onEnter + this._super(); + this.alignSpritesLeft(1); + + var move1 = cc.moveBy(1, cc.p(250, 0)); + var move2 = cc.moveBy(1, cc.p(0, 50)); + var seq = cc.sequence(move1, move2, move1.reverse()); + var action = cc.sequence(seq, seq.reverse()); + + this._grossini.runAction(action); + //----end28---- + + }, + subtitle:function () { + return "Reverse a sequence"; + } +}); +//------------------------------------------------------------------ +// +// ActionReverseSequence2 +// +//------------------------------------------------------------------ +var ActionReverseSequence2 = ActionsDemo.extend({ + onEnter:function () { + + //----start29----onEnter + this._super(); + this.alignSpritesLeft(2); + + + // Test: + // Sequence should work both with IntervalAction and InstantActions + var move1 = cc.moveBy(3, cc.p(250, 0)); + var move2 = cc.moveBy(3, cc.p(0, 50)); + var tog1 = cc.toggleVisibility(); + var tog2 = cc.toggleVisibility(); + var seq = cc.sequence(move1, tog1, move2, tog2, move1.reverse()); + + var action = cc.sequence(seq, seq.reverse()).repeat(3); + + + // Test: + // Also test that the reverse of Hide is Show, and vice-versa + this._kathia.runAction(action); + + var move_tamara = cc.moveBy(1, cc.p(100, 0)); + var move_tamara2 = cc.moveBy(1, cc.p(50, 0)); + var hide = cc.hide(); + var seq_tamara = cc.sequence(move_tamara, hide, move_tamara2); + var seq_back = seq_tamara.reverse(); + this._tamara.runAction(cc.sequence(seq_tamara, seq_back)); + //----end29---- + }, + subtitle:function () { + return "Reverse sequence 2"; + } +}); +//------------------------------------------------------------------ +// +// ActionRepeat +// +//------------------------------------------------------------------ +var ActionRepeat = ActionsDemo.extend({ + onEnter:function () { + //----start21----onEnter + this._super(); + this.alignSpritesLeft(2); + + + var a1 = cc.moveBy(1, cc.p(150, 0)); + + var action1 = cc.sequence(cc.place(cc.p(60, 60)), a1).repeat(3); + var action2 = cc.sequence( a1.clone(), a1.reverse(), cc.delayTime(0.25)).repeatForever(); + + this._kathia.runAction(action1); + this._tamara.runAction(action2); + //----end21---- + }, + title:function () { + return "Repeat / RepeatForever actions"; + }, + // + // Automation + // + testDuration:4.30, + getExpectedResult:function() { + var ret = [{"x":210,"y":60},{"x":60,"y":2*winSize.height/3}]; + return JSON.stringify(ret); + }, + getCurrentResult:function() { + var ret = []; + ret.push( cc.p(this._kathia.x, this._kathia.y) ); + ret.push( cc.p(this._tamara.x, this._tamara.y) ); + return JSON.stringify(ret); + } + +}); +//------------------------------------------------------------------ +// +// ActionOrbit +// +//------------------------------------------------------------------ +var ActionOrbit = ActionsDemo.extend({ + onEnter:function () { + this._super(); + this.centerSprites(3); + + var orbit1 = cc.orbitCamera(2, 1, 0, 0, 180, 0, 0); + var action1 = cc.sequence( + orbit1, + orbit1.reverse()); + + var orbit2 = cc.orbitCamera(2, 1, 0, 0, 180, -45, 0); + var action2 = cc.sequence( + orbit2, + orbit2.reverse()); + + var orbit3 = cc.orbitCamera(2, 1, 0, 0, 180, 90, 0); + var action3 = cc.sequence( + orbit3, + orbit3.reverse()); + + this._kathia.runAction(action1.repeatForever()); + this._tamara.runAction(action2.repeatForever()); + this._grossini.runAction(action3.repeatForever()); + + var move = cc.moveBy(3, cc.p(100, -100)); + var move_back = move.reverse(); + var seq = cc.sequence(move, move_back); + + var rfe = seq.repeatForever(); + + this._kathia.runAction(rfe); + this._tamara.runAction((rfe.clone())); + this._grossini.runAction((rfe.clone())); + + }, + subtitle:function () { + return "OrbitCamera action"; + } +}); +//------------------------------------------------------------------ +// +// ActionFollow +// +//------------------------------------------------------------------ +var ActionFollow = ActionsDemo.extend({ + onEnter:function () { + + //----start30----onEnter + this._super(); + this.centerSprites(1); + var s = director.getWinSize(); + + this._grossini.x = -(s.width / 2); + this._grossini.y = s.height / 2; + var move = cc.moveBy(2, cc.p(s.width * 3, 0)); + var move_back = move.reverse(); + var seq = cc.sequence(move, move_back); + + var rep = seq.repeatForever(); + + this._grossini.runAction(rep); + + this.runAction(cc.follow(this._grossini, cc.rect(0, 0, s.width * 2 - 100, s.height))); + //----end30---- + }, + subtitle:function () { + return "Follow action"; + } +}); + +//------------------------------------------------------------------ +// +// ActionCardinalSpline +// +//------------------------------------------------------------------ +var ActionCardinalSpline = ActionsDemo.extend({ + _array:null, + _drawNode1: null, + _drawNode2: null, + + _code:" a = cc.cadinalSplineBy( time, array_of_points, tension );\n" + + " a = cc.cadinalSplineTo( time, array_of_points, tension );", + + ctor:function () { + this._super(); + this._array = []; + + //add draw node + var winSize = cc.director.getWinSize(); + this._drawNode1 = new cc.DrawNode(); + this.addChild(this._drawNode1); + this._drawNode1.x = 50; + this._drawNode1.y = 50; + this._drawNode1.setDrawColor(cc.color(255,255,255,255)); + + this._drawNode2 = new cc.DrawNode(); + this.addChild(this._drawNode2); + this._drawNode2.x = winSize.width * 0.5; + this._drawNode2.y = 50; + this._drawNode2.setDrawColor(cc.color(255,255,255,255)); + }, + + onEnter:function () { + + //----start11----onEnter + this._super(); + var winSize = cc.director.getWinSize(); + this.centerSprites(2); + + var delay = cc.delayTime(0.25); + + var array = [ + cc.p(0, 0), + cc.p(winSize.width / 2 - 30, 0), + cc.p(winSize.width / 2 - 30, winSize.height - 80), + cc.p(0, winSize.height - 80), + cc.p(0, 0) + ]; + + // + // sprite 1 (By) + // + // Spline with no tension (tension==0) + // + var action1 = cc.cardinalSplineBy(2, array, 0); + var reverse1 = action1.reverse(); + var seq = cc.sequence(action1, delay, reverse1, delay.clone() ); + + this._tamara.x = 50; + this._tamara.y = 50; + this._tamara.runAction(seq); + + // + // sprite 2 (By) + // + // Spline with high tension (tension==1) + // + var action2 = cc.cardinalSplineBy(2, array, 1); + var reverse2 = action2.reverse(); + var seq2 = cc.sequence(action2, delay.clone(), reverse2, delay.clone()); + + this._kathia.x = winSize.width / 2; + this._kathia.y = 50; + this._kathia.runAction(seq2); + + this._drawNode1.drawCardinalSpline(array, 0, 100, 1); + this._drawNode2.drawCardinalSpline(array, 1, 100, 1); + //----end11---- + }, + + subtitle:function () { + return "Cardinal Spline paths. Testing different tensions for one array"; + }, + title:function () { + return "CardinalSplineBy / CardinalSplineAt"; + }, + // + // Automation + // + testDuration:2.1, + setupAutomation:function() { + this.scheduleOnce(this.checkControl1, 0.5); + this.scheduleOnce(this.checkControl2, 1.0); + this.scheduleOnce(this.checkControl3, 1.5); + }, + checkControl1:function(dt) { + this.control1 = cc.p(this._tamara.x, this._tamara.y); + }, + verifyControl1:function(dt) { + var x = Math.abs( 50 + winSize.width/2 - 30 - this.control1.x); + var y = Math.abs( 50 - this.control1.y); + // -/+ 5 pixels of error + return ( x < 5 && y < 5); + }, + checkControl2:function(dt) { + this.control2 = cc.p(this._tamara.x, this._tamara.y); + }, + verifyControl2:function(dt) { + var x = Math.abs( 50 + winSize.width/2 - 30 - this.control2.x ); + var y = Math.abs( 50 + winSize.height - 80 - this.control2.y ); + // -/+ 5 pixels of error + return ( x < 5 && y < 5); + }, + checkControl3:function(dt) { + this.control3 = cc.p(this._tamara.x, this._tamara.y); + }, + verifyControl3:function(dt) { + var x = Math.abs( 50 - this.control3.x ); + var y = Math.abs( 50 + winSize.height - 80 - this.control3.y ); + // -/+ 5 pixels of error + return ( x < 5 && y < 5); + }, + + getExpectedResult:function() { + var ret = [ true, + true, + true, + {"x":50,"y":50}]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = []; + ret.push( this.verifyControl1() ); + ret.push( this.verifyControl2() ); + ret.push( this.verifyControl3() ); + ret.push( cc.p(this._tamara.x, this._tamara.y) ); + + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// ActionCatmullRom +// +//------------------------------------------------------------------ +var ActionCatmullRom = ActionsDemo.extend({ + _drawNode1: null, + _drawNode2: null, + + _code:"a = cc.catmullRomBy( time, array_of_points );\n" + + " a = cc.catmullRomTo( time, array_of_points );", + + ctor:function () { + this._super(); + + this._drawNode1 = new cc.DrawNode(); + this._drawNode1.x = 50; + this._drawNode1.y = 50; + this._drawNode1.setDrawColor(cc.color(255,255,255,255)); + this.addChild(this._drawNode1); + + this._drawNode2 = new cc.DrawNode(); + this._drawNode2.setDrawColor(cc.color(255,255,255,255)); + this.addChild(this._drawNode2); + }, + + onEnter:function () { + + //----start12----onEnter + this._super(); + + this.centerSprites(2); + + var delay = cc.delayTime(0.25); + + // + // sprite 1 (By) + // + // startPosition can be any coordinate, but since the movement + // is relative to the Catmull Rom curve, it is better to start with (0,0). + // + this._tamara.x = 50; + this._tamara.y = 50; + + var array = [ + cc.p(0, 0), + cc.p(80, 80), + cc.p(winSize.width - 80, 80), + cc.p(winSize.width - 80, winSize.height - 80), + cc.p(80, winSize.height - 80), + cc.p(80, 80), + cc.p(winSize.width / 2, winSize.height / 2) + ]; + + var action1 = cc.catmullRomBy(3, array); + var reverse1 = action1.reverse(); + var seq1 = cc.sequence(action1, delay, reverse1); + + this._tamara.runAction(seq1); + + // + // sprite 2 (To) + // + // The startPosition is not important here, because it uses a "To" action. + // The initial position will be the 1st point of the Catmull Rom path + // + var array2 = [ + cc.p(winSize.width / 2, 30), + cc.p(winSize.width - 80, 30), + cc.p(winSize.width - 80, winSize.height - 80), + cc.p(winSize.width / 2, winSize.height - 80), + cc.p(winSize.width / 2, 30) ]; + + var action2 = cc.catmullRomTo(3, array2); + var reverse2 = action2.reverse(); + + var seq2 = cc.sequence(action2, delay.clone(), reverse2); + + this._kathia.runAction(seq2); + + this._drawNode1.drawCatmullRom(array,50, 1); + this._drawNode2.drawCatmullRom(array2,50, 1); + //----end12---- + }, + subtitle:function () { + return "Catmull Rom spline paths. Testing reverse too"; + }, + title:function () { + return "CatmullRomBy / CatmullRomTo"; + }, + // + // Automation + // + testDuration:3.1, + setupAutomation:function() { + this.scheduleOnce(this.checkControl1, 3 / 4 * 0); + this.scheduleOnce(this.checkControl2, 3 / 4 * 1); + this.scheduleOnce(this.checkControl3, 3 / 4 * 2); + }, + checkControl1:function(dt) { + this.control1 = cc.p(this._kathia.x, this._kathia.y); + }, + verifyControl1:function(dt) { + var x = Math.abs( winSize.width/2 - this.control1.x); + var y = Math.abs( 30 - this.control1.y); + // -/+ 5 pixels of error + return ( x < 5 && y < 5); + }, + checkControl2:function(dt) { + this.control2 = cc.p(this._kathia.x, this._kathia.y); + }, + verifyControl2:function(dt) { + var x = Math.abs( winSize.width - 80 - this.control2.x ); + var y = Math.abs( 30 - this.control2.y ); + // -/+ 5 pixels of error + return ( x < 5 && y < 5); + }, + checkControl3:function(dt) { + this.control3 = cc.p(this._kathia.x, this._kathia.y); + }, + verifyControl3:function(dt) { + var x = Math.abs( winSize.width - 80 - this.control3.x ); + var y = Math.abs( winSize.height - 80 - this.control3.y ); + // -/+ 5 pixels of error + return ( x < 5 && y < 5); + }, + + getExpectedResult:function() { + var ret = [ true, + true, + true, + {"x":winSize.width/2,"y":30}]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = []; + ret.push( this.verifyControl1() ); + ret.push( this.verifyControl2() ); + ret.push( this.verifyControl3() ); + ret.push( cc.p(this._kathia.x, this._kathia.y) ); + + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// ActionTargeted +// +//------------------------------------------------------------------ +var ActionTargeted = ActionsDemo.extend({ + _code:"a = cc.targetedAction( target, action );", + + onEnter:function () { + //----start31----onEnter + this._super(); + this.centerSprites(2); + + var jump1 = cc.jumpBy(2, cc.p(0, 0), 100, 3); + var jump2 = jump1.clone(); + var rot1 = cc.rotateBy(1, 360); + var rot2 = rot1.clone(); + + var t1 = cc.targetedAction(this._kathia, jump2); + var t2 = cc.targetedAction(this._kathia, rot2); + + var seq = cc.sequence(jump1, t1, rot1, t2); + + var always = seq.repeatForever(); + + this._tamara.runAction(always); + //----end31---- + }, + title:function () { + return "Action that runs on another target. Useful for sequences"; + }, + subtitle:function () { + return "ActionTargeted"; + } +}); + +//------------------------------------------------------------------ +// +// ActionTargetedCopy +// +//------------------------------------------------------------------ +var ActionTargetedCopy = ActionsDemo.extend({ + onEnter:function () { + //----start32----onEnter + this._super(); + this.centerSprites(2); + + var jump1 = cc.jumpBy(2, cc.p(0, 0), 100, 3); + var jump2 = jump1.clone(); + + var t1 = cc.targetedAction(this._kathia, jump2); + var t_copy = t1.clone(); + + var seq = cc.sequence(jump1, t_copy); + + this._tamara.runAction(seq); + //----end32---- + }, + title:function () { + return "Action that runs on another target. Useful for sequences"; + }, + subtitle:function () { + return "Testing copy on TargetedAction"; + } +}); + +//------------------------------------------------------------------ +// +// ActionStackableMove +// +//------------------------------------------------------------------ +var ActionStackableMove = ActionsDemo.extend({ + onEnter:function () { + //----start33----onEnter + this._super(); + this.centerSprites(1); + + this._grossini.x = 40; + this._grossini.y = winSize.height / 2; + + // shake + var move = cc.moveBy(0.2, cc.p(0,50)); + var move_back = move.reverse(); + var delay = cc.delayTime(0.25); + var move_seq = cc.sequence( move, move_back ); + var move_rep = move_seq.repeatForever(); + this._grossini.runAction( move_rep ); + + // move + var action = cc.moveBy(2, cc.p(winSize.width - 80, 0)); + var back = action.reverse(); + var seq = cc.sequence(action, back); + var repeat = seq.repeatForever(); + this._grossini.runAction(repeat); + //----end33---- + + }, + title:function () { + return "Stackable actions: MoveBy + MoveBy"; + }, + subtitle:function () { + return "Grossini shall move up and down while moving horizontally"; + }, + // + // Automation + // + testDuration:0.2, + getExpectedResult:function() { + var ret = [true, true]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = []; + var x = this._grossini.x, y = this._grossini.y; + var error = 10; + var expected_x = 40 + 0.2 * (winSize.width-80) / 2; + var expected_y =winSize.height/2 + 50; + var ret_x = x < expected_x+error && x > expected_x-error; + var ret_y = y < expected_y+error && y > expected_y-error; + ret.push( ret_x ); + ret.push( ret_y ); + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// ActionStackableJump +// +//------------------------------------------------------------------ +var ActionStackableJump = ActionsDemo.extend({ + onEnter:function () { + + //----start34----onEnter + this._super(); + this.centerSprites(1); + + this._grossini.x = 40; + this._grossini.y = winSize.height / 2; + + // shake + var move = cc.moveBy(0.05, cc.p(8, 8)); + var move_back = move.reverse(); + var move_seq = cc.sequence(move, move_back); + var move_rep = move_seq.repeatForever(); + this._grossini.runAction(move_rep); + + // jump + var action = cc.jumpBy(2, cc.p(winSize.width - 80, 0), 90, 5); + var back = action.reverse(); + var seq = cc.sequence(action, back); + var repeat = seq.repeatForever(); + this._grossini.runAction(repeat); + //----end34---- + + }, + title:function () { + return "Stackable actions: MoveBy + JumpBy"; + }, + subtitle:function () { + return "Grossini shall shake while he is jumping"; + } +}); + +//------------------------------------------------------------------ +// +// ActionStackableBezier +// +//------------------------------------------------------------------ +var ActionStackableBezier = ActionsDemo.extend({ + onEnter:function () { + //----start35----onEnter + this._super(); + this.centerSprites(1); + + this._grossini.x = 40; + this._grossini.y = winSize.height / 2; + + // shake + var move = cc.moveBy(0.05, cc.p(8, 8)); + var move_back = move.reverse(); + var move_seq = cc.sequence(move, move_back); + var move_rep = move_seq.repeatForever(); + this._grossini.runAction(move_rep); + + // Bezier + var controlPoints = [ cc.p(0, winSize.height / 2), + cc.p(winSize.width - 80, -winSize.height / 2), + cc.p(winSize.width - 80, 100) ]; + + var bezierForward = cc.bezierBy(3, controlPoints); + var repeat = cc.sequence(bezierForward, bezierForward.reverse()).repeatForever(); + this._grossini.runAction(repeat); + //----end35---- + + }, + title:function () { + return "Stackable actions: MoveBy + BezierBy"; + }, + subtitle:function () { + return "Grossini shall shake while he moves along a bezier path"; + } +}); + +//------------------------------------------------------------------ +// +// ActionStackableCatmullRom +// +//------------------------------------------------------------------ +var ActionStackableCatmullRom = ActionsDemo.extend({ + onEnter:function () { + //----start36----onEnter + this._super(); + this.centerSprites(1); + + this._grossini.x = 40; + this._grossini.y = 40; + + // shake + var move = cc.moveBy(0.05, cc.p(8, 8)); + var move_back = move.reverse(); + var move_seq = cc.sequence(move, move_back); + var move_rep = move_seq.repeatForever(); + this._grossini.runAction(move_rep); + + // CatmullRom + var array = [ + cc.p(0, 0), + cc.p(80, 80), + cc.p(winSize.width - 80, 80), + cc.p(winSize.width - 80, winSize.height - 80), + cc.p(80, winSize.height - 80), + cc.p(80, 80), + cc.p(winSize.width / 2, winSize.height / 2) + ]; + + var action1 = cc.catmullRomBy(6, array); + var reverse1 = action1.reverse(); + var seq1 = cc.sequence(action1, reverse1); + var repeat = seq1.repeatForever(); + this._grossini.runAction(repeat); + //----end36---- + }, + title:function () { + return "Stackable actions: MoveBy + CatmullRomBy"; + }, + subtitle:function () { + return "Grossini shall shake while he moves along a CatmullRom path"; + } +}); + +//------------------------------------------------------------------ +// +// ActionStackableCardinalSpline +// +//------------------------------------------------------------------ +var ActionStackableCardinalSpline = ActionsDemo.extend({ + onEnter:function () { + //----start37----onEnter + this._super(); + this.centerSprites(1); + + this._grossini.x = 40; + this._grossini.y = 40; + + // shake + var move = cc.moveBy(0.05, cc.p(8, 8)); + var move_back = move.reverse(); + var move_seq = cc.sequence(move, move_back); + var move_rep = move_seq.repeatForever(); + this._grossini.runAction(move_rep); + + // CardinalSpline + var array = [ + cc.p(0, 0), + cc.p(80, 80), + cc.p(winSize.width - 80, 80), + cc.p(winSize.width - 80, winSize.height - 80), + cc.p(80, winSize.height - 80), + cc.p(80, 80), + cc.p(winSize.width / 2, winSize.height / 2) + ]; + + var action1 = cc.cardinalSplineBy(6, array, 0.9); + var reverse1 = action1.reverse(); + var seq1 = cc.sequence(action1, reverse1); + var repeat = seq1.repeatForever(); + this._grossini.runAction(repeat); + //----end37---- + }, + title:function () { + return "Stackable actions: MoveBy + CardinalSplineBy"; + }, + subtitle:function () { + return "Grossini shall shake while he moves along a CardinalSpline path"; + } +}); + +//------------------------------------------------------------------ +// +// PauseResumeActions +// +//------------------------------------------------------------------ +var PauseResumeActions = ActionsDemo.extend({ + _pausedTargets:[], + onEnter:function () { + //----start38----onEnter + this._super(); + this.centerSprites(2); + + this._tamara.runAction(cc.rotateBy(3, 360).repeatForever()); + this._grossini.runAction(cc.rotateBy(3, -360).repeatForever()); + this._kathia.runAction(cc.rotateBy(3, 360).repeatForever()); + + this.schedule(this.pause, 3, false, 0); + this.schedule(this.resume, 5, false, 0); + //----end38---- + }, + + pause:function () { + cc.log("Pausing"); + this._pausedTargets = director.getActionManager().pauseAllRunningActions(); + }, + resume:function () { + cc.log("Resuming"); + director.getActionManager().resumeTargets(this._pausedTargets); + }, + + title:function () { + return "PauseResumeActions"; + }, + subtitle:function () { + return "All actions pause at 3s and resume at 5s"; + } +}); + +//------------------------------------------------------------------ +// +// Issue1305 +// +//------------------------------------------------------------------ +var Issue1305 = ActionsDemo.extend({ + _spriteTemp:null, + onEnter:function () { + //----start39----onEnter + this._super(); + this.centerSprites(0); + + this._spriteTmp = new cc.Sprite(s_pathGrossini); + /* c++ can't support block, so we use CCCallFuncN instead. + [spriteTmp_ runAction:[CCCallBlockN actionWithBlock:^(CCNode* node) { + NSLog(@"This message SHALL ONLY appear when the sprite is added to the scene, NOT BEFORE"); + }] ]; + */ + + this._spriteTmp.runAction(cc.callFunc(this.onLog, this)); + this.scheduleOnce(this.onAddSprite, 2); + //----end39---- + }, + onExit:function () { + this._super(); + }, + onLog:function (pSender) { + cc.log("This message SHALL ONLY appear when the sprite is added to the scene, NOT BEFORE"); + }, + onAddSprite:function (dt) { + this._spriteTmp.x = 250; + this._spriteTmp.y = 250; + this.addChild(this._spriteTmp); + }, + title:function () { + return "Issue 1305"; + }, + subtitle:function () { + return "In two seconds you should see a message on the console. NOT BEFORE."; + } +}); + +//------------------------------------------------------------------ +// +// Issue1305_2 +// +//------------------------------------------------------------------ +var Issue1305_2 = ActionsDemo.extend({ + onEnter:function () { + //----start40----onEnter + this._super(); + this.centerSprites(0); + + var spr = new cc.Sprite(s_pathGrossini); + spr.x = 200; + spr.y = 200; + this.addChild(spr); + + var act1 = cc.moveBy(2, cc.p(0, 100)); + + var act2 = cc.callFunc(this.onLog1); + var act3 = cc.moveBy(2, cc.p(0, -100)); + var act4 = cc.callFunc(this.onLog2, this); + var act5 = cc.moveBy(2, cc.p(100, -100)); + var act6 = cc.callFunc(this.onLog3.bind(this)); + var act7 = cc.moveBy(2, cc.p(-100, 0)); + var act8 = cc.callFunc(this.onLog4, this); + + var actF = cc.sequence(act1, act2, act3, act4, act5, act6, act7, act8); + + // [spr runAction:actF]; + director.getActionManager().addAction(actF, spr, false); + //----end40---- + }, + onLog1:function () { + cc.log("1st block"); + }, + onLog2:function () { + cc.log("2nd block"); + }, + onLog3:function () { + cc.log("3rd block"); + }, + onLog4:function () { + cc.log("4th block"); + }, + title:function () { + return "Issue 1305 #2"; + }, + subtitle:function () { + return "See console. You should only see one message for each block"; + } +}); + +//------------------------------------------------------------------ +// +// Issue1288 +// +//------------------------------------------------------------------ +var Issue1288 = ActionsDemo.extend({ + onEnter:function () { + //----start41----onEnter + this._super(); + this.centerSprites(0); + + var spr = new cc.Sprite(s_pathGrossini); + spr.x = 100; + spr.y = 100; + this.addChild(spr); + + var act1 = cc.moveBy(0.5, cc.p(100, 0)); + var act2 = act1.reverse(); + var act3 = cc.sequence(act1, act2); + var act4 = act3.repeat(2); + + spr.runAction(act4); + //----end41---- + }, + title:function () { + return "Issue 1288"; + }, + subtitle:function () { + return "Sprite should end at the position where it started."; + } +}); + +//------------------------------------------------------------------ +// +// Issue1288_2 +// +//------------------------------------------------------------------ +var Issue1288_2 = ActionsDemo.extend({ + onEnter:function () { + //----start42----onEnter + this._super(); + this.centerSprites(0); + + var spr = new cc.Sprite(s_pathGrossini); + spr.x = 100; + spr.y = 100; + this.addChild(spr); + + var act1 = cc.moveBy(0.5, cc.p(100, 0)); + spr.runAction(act1.repeat(1)); + //----end42---- + }, + title:function () { + return "Issue 1288 #2"; + }, + subtitle:function () { + return "Sprite should move 100 pixels, and stay there"; + } +}); + +//------------------------------------------------------------------ +// +// Issue1327 +// +//------------------------------------------------------------------ +var Issue1327 = ActionsDemo.extend({ + onEnter:function () { + //----start43----onEnter + this._super(); + this.centerSprites(0); + + var spr = new cc.Sprite(s_pathGrossini); + spr.x = 100; + spr.y = 100; + this.addChild(spr); + + var act1 = cc.callFunc(this.onLogSprRotation); + var act2 = cc.rotateBy(0.25, 45); + var act3 = cc.callFunc(this.onLogSprRotation, this); + var act4 = cc.rotateBy(0.25, 45); + var act5 = cc.callFunc(this.onLogSprRotation.bind(this)); + var act6 = cc.rotateBy(0.25, 45); + var act7 = cc.callFunc(this.onLogSprRotation); + var act8 = cc.rotateBy(0.25, 45); + var act9 = cc.callFunc(this.onLogSprRotation); + + var actF = cc.sequence(act1, act2, act3, act4, act5, act6, act7, act8, act9); + spr.runAction(actF); + //----end43---- + }, + onLogSprRotation:function (pSender) { + cc.log(pSender.rotation); + }, + title:function () { + return "Issue 1327"; + }, + subtitle:function () { + return "See console: You should see: 0, 45, 90, 135, 180"; + } +}); + +//------------------------------------------------------------------ +// +// Issue1438 +// +//------------------------------------------------------------------ +var Issue1438 = ActionsDemo.extend({ + onEnter:function () { + //----start45----onEnter + this._super(); + this.centerSprites(2); + + // + // manual animation + // + var animation = new cc.Animation(); + + // Add 60 frames + for (var j = 0; j < 4; j++) { + for (var i = 1; i < 15; i++) { + var frameName = "res/Images/grossini_dance_" + ((i < 10) ? ("0" + i) : i) + ".png"; + animation.addSpriteFrameWithFile(frameName); + } + } + // And display 60 frames per second + animation.setDelayPerUnit(1 / 60); + animation.setRestoreOriginalFrame(true); + + var action = cc.animate(animation); + this._kathia.runAction(action); + + // + // File animation + // + var animCache = cc.animationCache; + animCache.addAnimations(s_animations2Plist); + var animation2 = animCache.getAnimation("dance_1"); + animation2.setDelayPerUnit(1 / 60); + + var action2 = cc.animate(animation2); + this._tamara.runAction(cc.sequence(action2, action2.reverse())); + //----end45---- + }, + + title:function () { + return "Animation"; + }, + + subtitle:function () { + return "Issue 1438. Set FPS to 30 to test this bug."; + } +}); + +//------------------------------------------------------------------ +// +// Issue1438 +// +//------------------------------------------------------------------ +var Issue1446 = ActionsDemo.extend({ + title:function () { + return "Sequence + Speed in 'reverse mode'"; + }, + + subtitle:function () { + return "Issue #1446. 'Hello World' should be visible for only 0.1 seconds"; + }, + + onEnter:function () { + //----start46----onEnter + this._super(); + this.centerSprites(0); + var label = this.label = new cc.LabelTTF("Hello World", "Arial", 64); + + label.x = winSize.width / 2; + label.y = winSize.height / 2; + label.opacity = 0; + + this.addChild(label); + + this.backwardsFade = cc.speed(cc.sequence( + cc.delayTime(2), + cc.fadeTo(1, 255), + cc.delayTime(2)), 1); + label.runAction(this.backwardsFade); + + // Comment out to see that 1.0 in the update function is called which is expected + // Leave it uncommented to see that 0.0 is never called when going in reverse + this.scheduleOnce(this.stepForwardGoBackward, 0.1); + //----end46---- + }, + + stepForwardGoBackward:function () { + var action = this.backwardsFade.getInnerAction(); + action.step(2.5); + // Try with -10.0f and you can see the opacity not fully faded out. Try with lower values to see it 'almost' fade out + this.backwardsFade.setSpeed(-10); + } +}); + +var SequenceRepeatTest = ActionsDemo.extend({ + onEnter:function () { + //----start47----onEnter + this._super(); + this.centerSprites(2); + + this._kathia.runAction(cc.repeat(cc.sequence(cc.blink(2, 3), cc.delayTime(2)), 3)); + + var move = cc.moveBy(1, cc.p(50, 0)); + var move_back = move.reverse(); + var move_seq = cc.sequence(move, cc.delayTime(1), move_back, cc.delayTime(1)); + this._tamara.runAction(move_seq.repeat(3)); + //----end47---- + }, + + title:function () { + return "Sequence.repeat()"; + }, + + subtitle:function () { + return "Tests sequence.repeat function."; + } +}); + +//- +// +// Flow control +// +var arrayOfActionsTest = [ + ActionManual, + ActionMove, + ActionScale, + ActionRotate, + ActionRotateXY, + ActionSkew, + ActionSkewRotateScale, + ActionJump, + ActionBezier, + ActionBezierToCopy, + Issue1008, + ActionCardinalSpline, + ActionCatmullRom, + ActionBlink, + ActionFade, + ActionTint, + ActionSequence, + ActionSequence2, + ActionSpawn, + ActionReverse, + ActionDelayTime, + ActionRepeat, + ActionRepeatForever, + ActionRotateToRepeat, + ActionRotateJerk, + ActionCallFunc1, + ActionCallFunc2, + ActionCallFunc3, + ActionReverseSequence, + ActionReverseSequence2, + + ActionFollow, + ActionTargeted, + ActionTargetedCopy, + + ActionStackableMove, + ActionStackableJump, + ActionStackableBezier, + ActionStackableCatmullRom, + ActionStackableCardinalSpline, + + PauseResumeActions, + Issue1305, + Issue1305_2, + Issue1288, + Issue1288_2, + Issue1327, + ActionAnimate, + Issue1438, + Issue1446, + SequenceRepeatTest +]; + +if("opengl" in cc.sys.capabilities){ + arrayOfActionsTest.push(ActionOrbit); +} + +var nextActionsTest = function () { + actionsTestIdx++; + actionsTestIdx = actionsTestIdx % arrayOfActionsTest.length; + + if(window.sideIndexBar){ + actionsTestIdx = window.sideIndexBar.changeTest(actionsTestIdx, 1); + } + + return new arrayOfActionsTest[actionsTestIdx](); +}; +var previousActionsTest = function () { + actionsTestIdx--; + if (actionsTestIdx < 0) + actionsTestIdx += arrayOfActionsTest.length; + + if(window.sideIndexBar){ + actionsTestIdx = window.sideIndexBar.changeTest(actionsTestIdx, 1); + } + + return new arrayOfActionsTest[actionsTestIdx](); +}; +var restartActionsTest = function () { + return new arrayOfActionsTest[actionsTestIdx](); +}; diff --git a/tests/js-tests/src/BakeLayerTest/BakeLayerTest.js b/tests/js-tests/src/BakeLayerTest/BakeLayerTest.js new file mode 100644 index 0000000000..12b6af4993 --- /dev/null +++ b/tests/js-tests/src/BakeLayerTest/BakeLayerTest.js @@ -0,0 +1,239 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var _bakeLayerTestIdx = -1; + +//------------------------------------------------------------------ +// +// ActionManagerTest +// +//------------------------------------------------------------------ +var BakeLayerBaseTest = BaseTestLayer.extend({ + _atlas:null, + _title:"", + + title:function () { + return "No title"; + }, + + subtitle:function () { + return ""; + }, + + onBackCallback:function (sender) { + var s = new BakeLayerTestScene(); + s.addChild(previousBakeLayerTest()); + director.runScene(s); + }, + onRestartCallback:function (sender) { + var s = new BakeLayerTestScene(); + s.addChild(restartBakeLayerTest()); + director.runScene(s); + }, + onNextCallback:function (sender) { + var s = new BakeLayerTestScene(); + s.addChild(nextBakeLayerTest()); + director.runScene(s); + }, + // automation + numberOfPendingTests:function() { + return ( (arrayOfBakeLayerTest.length-1) - _bakeLayerTestIdx ); + }, + + getTestNumber:function() { + return _bakeLayerTestIdx; + } +}); + +var BakeLayerTest1 = BakeLayerBaseTest.extend({ + _bakeLayer: null, + + title:function () { + return "Test 1. Bake Layer (Canvas only)"; + }, + + ctor: function(){ + this._super(); + + var winSize = cc.winSize; + var bakeItem = new cc.MenuItemFont("bake", this.onBake, this); + var unbakeItem = new cc.MenuItemFont("unbake", this.onUnbake, this); + var runActionItem = new cc.MenuItemFont("run action", this.onRunAction, this); + var menu = new cc.Menu(bakeItem, unbakeItem, runActionItem); + + menu.alignItemsVertically(); + menu.x = winSize.width - 70; + menu.y = winSize.height - 120; + this.addChild(menu, 10); + + var rootLayer = new cc.Layer(); + rootLayer.setPosition(20,20); + this.addChild(rootLayer); + + var bakeLayer = new cc.Layer(); + bakeLayer.bake(); + bakeLayer.setRotation(30); + rootLayer.addChild(bakeLayer); + + for(var i = 0; i < 9; i++){ + var sprite1 = new cc.Sprite(s_pathGrossini); + if (i % 2 === 0) { + sprite1.setPosition(90 + i * 80, winSize.height / 2 - 50); + } else { + sprite1.setPosition(90 + i * 80, winSize.height / 2 + 50); + } + if(i === 4) + this._actionSprite = sprite1; + sprite1.rotation = 360 * Math.random(); + bakeLayer.addChild(sprite1); + } + this._bakeLayer = bakeLayer; + bakeLayer.runAction(cc.sequence(cc.moveBy(2, cc.p(100,100)), cc.moveBy(2, cc.p(-100,-100)))); + }, + + onBake: function(){ + this._bakeLayer.bake(); + }, + + onUnbake: function(){ + this._bakeLayer.unbake(); + }, + + onRunAction: function(){ + this._actionSprite.runAction(cc.rotateBy(1, 180)); + } +}); + +var BakeLayerColorTest = BakeLayerBaseTest.extend({ + _bakeLayer: null, + _actionSprite: null, + + title:function () { + return "Test 2. Bake Layer Gradient (Canvas only)"; + }, + + ctor: function(){ + this._super(); + + var winSize = cc.winSize; + var bakeItem = new cc.MenuItemFont("bake", this.onBake, this); + var unbakeItem = new cc.MenuItemFont("unbake", this.onUnbake, this); + var runActionItem = new cc.MenuItemFont("run action", this.onRunAction, this); + var menu = new cc.Menu(bakeItem, unbakeItem, runActionItem); + + menu.alignItemsVertically(); + menu.x = winSize.width - 70; + menu.y = winSize.height - 120; + this.addChild(menu, 10); + + var rootLayer = new cc.Layer(); + rootLayer.setPosition(20,20); + this.addChild(rootLayer); + + //var bakeLayer = cc.LayerColor.create(cc.color(128,0, 128, 128), 700, 300); //test for LayerColor + //bakeLayer.setPosition(60, 80); + + var bakeLayer = new cc.LayerGradient(cc.color(128,0, 128, 255), cc.color(0, 0, 128, 255)); + bakeLayer.setPosition(60, 80); + bakeLayer.setContentSize(700, 300); + bakeLayer.setRotation(30); + + //bakeLayer.setPosition(winSize.width /2, winSize.height /2); //test for ignoreAnchorPointForPosition + //bakeLayer.ignoreAnchorPointForPosition(false); + rootLayer.addChild(bakeLayer); + + for(var i = 0; i < 9; i++){ + var sprite1 = new cc.Sprite(s_pathGrossini); + if (i % 2 === 0) { + sprite1.setPosition(20 + i * 80, 100); + } else { + sprite1.setPosition(20 + i * 80, 200); + } + if(i === 4) + this._actionSprite = sprite1; + sprite1.rotation = 180 * Math.random(); + bakeLayer.addChild(sprite1); + } + + this._bakeLayer = bakeLayer; + bakeLayer.bake(); + bakeLayer.runAction(cc.sequence(cc.moveBy(2, cc.p(100,100)), cc.moveBy(2, cc.p(-100,-100)))); + }, + + onBake: function(){ + this._bakeLayer.bake(); + }, + + onUnbake: function(){ + this._bakeLayer.unbake(); + }, + + onRunAction: function(){ + this._actionSprite.runAction(cc.rotateBy(2, 180)); + } +}); + +var BakeLayerTestScene = TestScene.extend({ + runThisTest:function (num) { + _bakeLayerTestIdx = (num || 0) - 1; + this.addChild(nextBakeLayerTest()); + director.runScene(this); + } +}); + +//- +// +// Flow control +// +var arrayOfBakeLayerTest = [ + BakeLayerTest1, + BakeLayerColorTest +]; + +var nextBakeLayerTest = function (num) { + _bakeLayerTestIdx = num ? num - 1 : _bakeLayerTestIdx; + _bakeLayerTestIdx++; + _bakeLayerTestIdx = _bakeLayerTestIdx % arrayOfBakeLayerTest.length; + + if(window.sideIndexBar){ + _bakeLayerTestIdx = window.sideIndexBar.changeTest(_bakeLayerTestIdx, 0); + } + return new arrayOfBakeLayerTest[_bakeLayerTestIdx](); +}; + +var previousBakeLayerTest = function () { + _bakeLayerTestIdx--; + if (_bakeLayerTestIdx < 0) + _bakeLayerTestIdx += arrayOfBakeLayerTest.length; + + if(window.sideIndexBar){ + _bakeLayerTestIdx = window.sideIndexBar.changeTest(_bakeLayerTestIdx, 0); + } + return new arrayOfBakeLayerTest[_bakeLayerTestIdx](); +}; +var restartBakeLayerTest = function () { + return new arrayOfBakeLayerTest[_bakeLayerTestIdx](); +}; \ No newline at end of file diff --git a/tests/js-tests/src/BaseTestLayer/BaseTestLayer.js b/tests/js-tests/src/BaseTestLayer/BaseTestLayer.js new file mode 100644 index 0000000000..d06dd54850 --- /dev/null +++ b/tests/js-tests/src/BaseTestLayer/BaseTestLayer.js @@ -0,0 +1,294 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var BASE_TEST_MENUITEM_PREV_TAG = 1; +var BASE_TEST_MENUITEM_RESET_TAG = 2; +var BASE_TEST_MENUITEM_NEXT_TAG = 3; + +var BASE_TEST_MENU_TAG = 10; +var BASE_TEST_TITLE_TAG = 11; +var BASE_TEST_SUBTITLE_TAG = 12; + + +var autoTestEnabled = autoTestEnabled || false; +var autoTestCurrentTestName = autoTestCurrentTestName || "N/A"; + +var BaseTestLayerProps = { + + ctor:function(colorA, colorB ) { + + cc.sys.garbageCollect(); + + // default gradient colors + var a = cc.color(98,99,117,255); + var b = cc.color(0,0,0,255); + + if( arguments.length >= 1 ) + a = colorA; + if( arguments.length == 2 ) + b = colorB; + + // for automation, no gradient. helps for grabbing the screen if needed + if( autoTestEnabled ) { + a = cc.color(0,0,0,255); + b = cc.color(0,0,0,255); + } + + this._super( a, b ); + + // Update winsize in case it was resized + winSize = director.getWinSize(); + + if( autoTestEnabled ) { + this.totalNumberOfTests = this.numberOfPendingTests(); + this.scheduleOnce( this.endTest, this.testDuration ); + + this.setupAutomation(); + } + }, + + setupAutomation:function() { + // override me + // Will be called only if automation is activated + }, + + getTitle:function() { + var t = ""; + + // some tests use "this.title()" and others use "this._title"; + if( 'title' in this ) + t = this.title(); + else if('_title' in this || this._title) + t = this._title; + return t; + }, + getSubtitle:function() { + var st = ""; + // some tests use "this.subtitle()" and others use "this._subtitle"; + if(this.subtitle) + st = this.subtitle(); + else if(this._subtitle) + st = this._subtitle; + + return st; + }, + log:function(str) { + if( !autoTestEnabled ) + cc.log(str); + }, + // + // Menu + // + onEnter:function () { + this._super(); + + var t = this.getTitle(); + var label = new cc.LabelTTF(t, "Arial", 28); + this.addChild(label, 100, BASE_TEST_TITLE_TAG); + label.x = winSize.width / 2; + label.y = winSize.height - 50; + + var st = this.getSubtitle(); + if (st) { + var l = new cc.LabelTTF(st.toString(), "Thonburi", 16); + this.addChild(l, 101, BASE_TEST_SUBTITLE_TAG); + l.x = winSize.width / 2; + l.y = winSize.height - 80; + } + + var item1 = new cc.MenuItemImage(s_pathB1, s_pathB2, this.onBackCallback, this); + var item2 = new cc.MenuItemImage(s_pathR1, s_pathR2, this.onRestartCallback, this); + var item3 = new cc.MenuItemImage(s_pathF1, s_pathF2, this.onNextCallback, this); + + item1.tag = BASE_TEST_MENUITEM_PREV_TAG; + item2.tag = BASE_TEST_MENUITEM_RESET_TAG; + item3.tag = BASE_TEST_MENUITEM_NEXT_TAG; + + var menu = new cc.Menu(item1, item2, item3); + + menu.x = 0; + menu.y = 0; + var width = item2.width, height = item2.height; + item1.x = winSize.width/2 - width*2; + item1.y = height/2 ; + item2.x = winSize.width/2; + item2.y = height/2 ; + item3.x = winSize.width/2 + width*2; + item3.y = height/2 ; + + this.addChild(menu, 102, BASE_TEST_MENU_TAG); + }, + onRestartCallback:function (sender) { + // override me + }, + onNextCallback:function (sender) { + // override me + }, + onBackCallback:function (sender) { + // override me + }, + //------------------------------------------ + // + // Automation Test code + // + //------------------------------------------ + + // How many seconds should this test run + testDuration:0.25, + + // Automated test + getExpectedResult:function() { + // Override me + throw "Not Implemented"; + }, + + // Automated test + getCurrentResult:function() { + // Override me + throw "Not Implemented"; + }, + + compareResults:function(current, expected) { + return (current == expected); + }, + + tearDown:function(dt) { + + // Override to have a different behavior + var current = this.getCurrentResult(); + var expected = this.getExpectedResult(); + + var ret = this.compareResults(current, expected); + if( ! ret ) + this.errorDescription = "Expected value: '" + expected + "'. Current value'" + current + "'."; + + return ret; + }, + + endTest:function(dt) { + + this.errorDescription = ""; + var title = this.getTitle(); + + try { + if( this.tearDown(dt) ) { + // Test OK + cc.log( autoTestCurrentTestName + " - " + this.getTestNumber() + ": Test '" + title + "':' OK"); + } else { + // Test failed + cc.log( autoTestCurrentTestName + " - " +this.getTestNumber() + ": Test '" + title + "': Error: " + this.errorDescription ); + } + } catch(err) { + cc.log( autoTestCurrentTestName + " - " +this.getTestNumber() + ": Test '" + title + "':'" + err); + } + + this.runNextTest(); + }, + + numberOfPendingTests:function() { + // override me. Should return true if the last test was executed + throw "Override me: numberOfPendingTests"; + }, + + getTestNumber:function() { + throw "Override me: getTestNumber"; + }, + + runNextTest:function() { + if( this.numberOfPendingTests() <= 0 ) { + var scene = new cc.Scene(); + var layer = new TestController(); + scene.addChild(layer); + director.runScene(scene); + } else + try { + this.onNextCallback(this); + } catch (err) { + cc.log( autoTestCurrentTestName + " - " +this.getTestNumber() + ": Test '" + this.getTitle() + "':'" + err); + this.runNextTest(); + } + }, + + + containsPixel: function(arr, pix, approx, range) { + + range = range || 50.0; + approx = approx || false; + + var abs = function(a,b) { + return ((a-b) > 0) ? (a-b) : (b-a); + }; + + var pixelEqual = function(pix1, pix2) { + if(approx && abs(pix1, pix2) < range) return true; + else if(!approx && pix1 == pix2) return true; + return false; + }; + + + for(var i=0; i < arr.length; i += 4) { + if(pixelEqual(arr[i], pix[0]) && pixelEqual(arr[i + 1], pix[1]) && + pixelEqual(arr[i + 2], pix[2]) && pixelEqual(arr[i + 3], pix[3])) { + return true; + } + } + return false; + }, + + readPixels:function(x,y,w,h) { + if( 'opengl' in cc.sys.capabilities) { + var size = 4 * w * h; + var array = new Uint8Array(size); + gl.readPixels(x, y, w, h, gl.RGBA, gl.UNSIGNED_BYTE, array); + return array; + } else { + // implement a canvas-html5 readpixels + return cc._renderContext.getImageData(x, winSize.height-y-h, w, h).data; + } + }, + + // + // Useful for comparing results + // From: http://stackoverflow.com/a/1359808 + // + sortObject:function(o) { + var sorted = {}, + key, a = []; + + for (key in o) { + if (o.hasOwnProperty(key)) { + a.push(key); + } + } + + a.sort(); + + for (key = 0; key < a.length; key++) { + sorted[a[key]] = o[a[key]]; + } + return sorted; + } +}; + +var BaseTestLayer = cc.LayerGradient.extend(BaseTestLayerProps); diff --git a/tests/js-tests/src/BillBoardTest/BillBoardTest.js b/tests/js-tests/src/BillBoardTest/BillBoardTest.js new file mode 100644 index 0000000000..d81c74f1bc --- /dev/null +++ b/tests/js-tests/src/BillBoardTest/BillBoardTest.js @@ -0,0 +1,359 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var BillBoardTestIdx = -1; + +var BillBoardTestDemo = cc.Layer.extend({ + _title:"", + _subtitle:"", + + ctor:function () { + this._super(); + }, + + // + // Menu + // + onEnter:function () { + this._super(); + + var label = new cc.LabelTTF(this._title, "Arial", 28); + this.addChild(label, 100, BASE_TEST_TITLE_TAG); + label.x = winSize.width / 2; + label.y = winSize.height - 50; + + var label2 = new cc.LabelTTF(this._subtitle, "Thonburi", 16); + this.addChild(label2, 101, BASE_TEST_SUBTITLE_TAG); + label2.x = winSize.width / 2; + label2.y = winSize.height - 80; + + var item1 = new cc.MenuItemImage(s_pathB1, s_pathB2, this.onBackCallback, this); + var item2 = new cc.MenuItemImage(s_pathR1, s_pathR2, this.onRestartCallback, this); + var item3 = new cc.MenuItemImage(s_pathF1, s_pathF2, this.onNextCallback, this); + + item1.tag = BASE_TEST_MENUITEM_PREV_TAG; + item2.tag = BASE_TEST_MENUITEM_RESET_TAG; + item3.tag = BASE_TEST_MENUITEM_NEXT_TAG; + + var menu = new cc.Menu(item1, item2, item3); + + menu.x = 0; + menu.y = 0; + var width = item2.width, height = item2.height; + item1.x = winSize.width/2 - width*2; + item1.y = height/2 ; + item2.x = winSize.width/2; + item2.y = height/2 ; + item3.x = winSize.width/2 + width*2; + item3.y = height/2 ; + + this.addChild(menu, 102, BASE_TEST_MENU_TAG); + }, + + onRestartCallback:function (sender) { + var s = new BillBoardTestScene(); + s.addChild(restartBillBoardTest()); + director.runScene(s); + }, + + onNextCallback:function (sender) { + var s = new BillBoardTestScene(); + s.addChild(nextBillBoardTest()); + director.runScene(s); + }, + + onBackCallback:function (sender) { + var s = new BillBoardTestScene(); + s.addChild(previousBillBoardTest()); + director.runScene(s); + }, +}); + +var BillBoardTestScene = cc.Scene.extend({ + ctor:function () { + this._super(); + + var label = new cc.LabelTTF("Main Menu", "Arial", 20); + var menuItem = new cc.MenuItemLabel(label, this.onMainMenuCallback, this); + + var menu = new cc.Menu(menuItem); + menu.x = 0; + menu.y = 0; + menuItem.x = winSize.width - 50; + menuItem.y = 25; + this.addChild(menu); + }, + onMainMenuCallback:function () { + var scene = new cc.Scene(); + var layer = new TestController(); + scene.addChild(layer); + director.runScene(scene); + }, + runThisTest:function (num) { + BillBoardTestIdx = (num || num == 0) ? (num - 1) : -1; + var layer = nextBillBoardTest(); + this.addChild(layer); + + director.runScene(this); + } +}); + +var BillBoardRotationTest = BillBoardTestDemo.extend({ + _title:"Rotation Test", + _subtitle:"All the sprites should still facing camera", + + ctor:function(){ + this._super(); + + var root = new jsb.Sprite3D(); + root.setNormalizedPosition(cc.p(0.5, 0.25)); + this.addChild(root); + + var model = new jsb.Sprite3D("Sprite3DTest/orc.c3b"); + model.setScale(5); + model.setRotation3D(cc.math.vec3(0, 180, 0)); + root.addChild(model); + + var bill = new jsb.BillBoard(); + bill.setPosition(0, 120); + root.addChild(bill); + + var sp = new cc.Sprite("Images/SpookyPeas.png"); + bill.addChild(sp); + + var label = new cc.LabelTTF("+100"); + label.setPosition(0, 30); + bill.addChild(label); + + root.runAction(cc.rotateBy(10, cc.math.vec3(0, 360, 0)).repeatForever()); + + var jump = cc.jumpBy(1, cc.p(0, 0), 30, 1); + var scale = cc.scaleBy(2, 2, 2, 0.1); + var rot = cc.rotateBy(2, cc.math.vec3(-90, 0, 0)); + model.runAction(cc.sequence(cc.spawn(cc.sequence(jump, scale), rot), cc.spawn(scale.reverse(), rot.reverse())).repeatForever()); + } +}); + +var BillBoardTest = BillBoardTestDemo.extend({ + _title:"BillBoard Test", + _subtitle:"", + _camera:null, + _layerBillBorad:null, + _billboards:[], + + ctor:function(){ + this._super(); + + //Create touch listener + cc.eventManager.addListener({ + event:cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesMoved:this.onTouchesMoved.bind(this) + }, this); + + var layer3D = new cc.Layer(); + this.addChild(layer3D, 0); + this._layerBillBorad = layer3D; + + var s = cc.winSize; + if(!this._camera){ + this._camera = cc.Camera.createPerspective(60, s.width/s.height, 1, 500); + this._camera.setCameraFlag(cc.CameraFlag.USER1); + this._layerBillBorad.addChild(this._camera); + } + + //Create rotating billboards + var imgs = ["Images/Icon.png", "Images/r2.png"]; + for(var i = 0; i < 4; ++i){ + var layer = new cc.Layer(); + var billboard = new jsb.BillBoard(imgs[Math.floor(Math.random() + 0.5)]); + billboard.setScale(0.5); + billboard.setPosition3D(cc.math.vec3(0, 0, (Math.random() * 2 - 1) * 150)); + billboard.setOpacity(Math.random() * 128 + 128); + this._billboards.push(billboard); + layer.addChild(billboard); + this._layerBillBorad.addChild(layer); + layer.runAction(cc.rotateBy(Math.random() * 10, cc.math.vec3(0, 45, 0)).repeatForever()); + } + + { + var billboard1 = new jsb.BillBoard("Images/Icon.png"); + billboard1.setScale(0.2); + billboard1.setPosition3D(cc.math.vec3(0, 30, 0)); + + var billboard2 = new jsb.BillBoard("Images/r2.png"); + billboard2.setPosition3D(cc.math.vec3(0, 0, 100)); + billboard1.addChild(billboard2); + this._billboards.push(billboard1); + this._billboards.push(billboard2); + + var sprite3d = new jsb.Sprite3D("Sprite3DTest/orc.c3b"); + sprite3d.setScale(2); + sprite3d.addChild(billboard1); + sprite3d.runAction(cc.rotateBy(10, cc.math.vec3(0, 360, 0)).repeatForever()); + this._layerBillBorad.addChild(sprite3d); + } + + this.addNewBillBoradWithCoords(cc.math.vec3(20, 5, 0)); + this.addNewBillBoradWithCoords(cc.math.vec3(60, 5, 0)); + this.addNewBillBoradWithCoords(cc.math.vec3(100, 5, 0)); + this.addNewBillBoradWithCoords(cc.math.vec3(140, 5, 0)); + this.addNewBillBoradWithCoords(cc.math.vec3(180, 5, 0)); + + this.addNewAniBillBoradWithCoords(cc.math.vec3(-20, 0, 0)); + this.addNewAniBillBoradWithCoords(cc.math.vec3(-60, 0, 0)); + this.addNewAniBillBoradWithCoords(cc.math.vec3(-100, 0, 0)); + this.addNewAniBillBoradWithCoords(cc.math.vec3(-140, 0, 0)); + this.addNewAniBillBoradWithCoords(cc.math.vec3(-180, 0, 0)); + + this._camera.setPosition3D(cc.math.vec3(0, 100, 230)); + this._camera.lookAt(cc.math.vec3(0, 0, 0), cc.math.vec3(0, 1, 0)); + + this._layerBillBorad.setCameraMask(2); + + var label1 = new cc.LabelTTF("rotate+", "Arial", 16); + var item1 = new cc.MenuItemLabel(label1, function(){ + var rotation3D = this._camera.getRotation3D(); + rotation3D.y += 10; + this._camera.setRotation3D(rotation3D); + }, this); + var label2 = new cc.LabelTTF("rotate-", "Arial", 16); + var item2 = new cc.MenuItemLabel(label2, function(){ + var rotation3D = this._camera.getRotation3D(); + rotation3D.y -= 10; + this._camera.setRotation3D(rotation3D); + }, this); + var label3 = new cc.LabelTTF("Point Oriented", "Arial", 16); + var item3 = new cc.MenuItemLabel(label3, this.menuCallback_orientedPoint, this); + var label4 = new cc.LabelTTF("Plane Oriented", "Arial", 16); + var item4 = new cc.MenuItemLabel(label4, this.menuCallback_orientedPlane, this); + + item1.setPosition(cc.p(s.width-80, s.height-160)); + item2.setPosition(cc.p(s.width-80, s.height-190)); + item3.setPosition(cc.p(s.width-80, s.height-100)); + item4.setPosition(cc.p(s.width-80, s.height-130)); + + var menu = new cc.Menu(item1, item2, item3, item4); + this.addChild(menu); + menu.setPosition(0, 0); + }, + + addNewBillBoradWithCoords:function(position){ + var imgs = ["Images/Icon.png", "Images/r2.png"]; + for(var i = 0; i < 10; ++i){ + var billboard = new jsb.BillBoard(imgs[Math.floor(Math.random() + 0.5)]); + billboard.setScale(0.5); + billboard.setPosition3D(cc.math.vec3(position.x, position.y, -150+30*i)); + billboard.setOpacity(Math.random() * 128 + 128); + this._layerBillBorad.addChild(billboard); + this._billboards.push(billboard); + } + }, + + addNewAniBillBoradWithCoords:function(position){ + for(var i = 0; i < 10; ++i){ + var billboardAni = new jsb.BillBoard("Images/grossini.png"); + billboardAni.setScale(0.5); + billboardAni.setPosition3D(cc.math.vec3(position.x, position.y, -150+30*i)); + this._layerBillBorad.addChild(billboardAni); + + var animation = new cc.Animation(); + for(var j = 1; j < 15; ++j){ + if(j < 10) + animation.addSpriteFrameWithFile("Images/grossini_dance_0"+j+".png"); + else + animation.addSpriteFrameWithFile("Images/grossini_dance_"+j+".png"); + } + // should last 2.8 seconds. And there are 14 frames. + animation.setDelayPerUnit(2.8/14.0); + animation.setRestoreOriginalFrame(true); + + var action = new cc.Animate(animation); + billboardAni.runAction(action.repeatForever()); + billboardAni.setOpacity(Math.random() * 128 + 128); + this._billboards.push(billboardAni); + } + }, + + menuCallback_orientedPoint:function(sender){ + for(var i = 0; i < this._billboards.length; ++i){ + this._billboards[i].setMode(jsb.BillBoard.Mode.VIEW_POINT_ORIENTED); + } + }, + + menuCallback_orientedPlane:function(sender){ + for(var i = 0; i < this._billboards.length; ++i){ + this._billboards[i].setMode(jsb.BillBoard.Mode.VIEW_PLANE_ORIENTED); + } + }, + + onTouchesMoved:function(touches, event){ + if(touches.length == 1){ + var touch = touches[0]; + var location = touch.getLocation(); + var previousLocation = touch.getPreviousLocation(); + var newPos = cc.p(previousLocation.x - location.x, previousLocation.y - location.y); + + var m = this._camera.getNodeToWorldTransform3D(); + var cameraDir = cc.math.vec3(-m[8], -m[9], -m[10]); + cameraDir.normalize(); + cameraDir.y = 0; + + var cameraRightDir = cc.math.vec3(m[0], m[1], m[2]); + cameraRightDir.normalize(); + cameraRightDir.y = 0; + + var cameraPos = this._camera.getPosition3D(); + cameraPos.x += cameraDir.x * newPos.y * 0.5 + cameraRightDir.x * newPos.x * 0.5; + cameraPos.y += cameraDir.y * newPos.y * 0.5 + cameraRightDir.y * newPos.x * 0.5; + cameraPos.z += cameraDir.z * newPos.y * 0.5 + cameraRightDir.z * newPos.x * 0.5; + this._camera.setPosition3D(cameraPos); + } + } +}); + +// +// Flow control +// +var arrayOfBillBoardTest = [ + BillBoardRotationTest, + BillBoardTest +]; + +var nextBillBoardTest = function () { + BillBoardTestIdx++; + BillBoardTestIdx = BillBoardTestIdx % arrayOfBillBoardTest.length; + + return new arrayOfBillBoardTest[BillBoardTestIdx ](); +}; +var previousBillBoardTest = function () { + BillBoardTestIdx--; + if (BillBoardTestIdx < 0) + BillBoardTestIdx += arrayOfBillBoardTest.length; + + return new arrayOfBillBoardTest[BillBoardTestIdx ](); +}; +var restartBillBoardTest = function () { + return new arrayOfBillBoardTest[BillBoardTestIdx ](); +}; diff --git a/tests/js-tests/src/Box2dTest/Box2dTest.js b/tests/js-tests/src/Box2dTest/Box2dTest.js new file mode 100644 index 0000000000..0757b412d5 --- /dev/null +++ b/tests/js-tests/src/Box2dTest/Box2dTest.js @@ -0,0 +1,197 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var TAG_SPRITE_MANAGER = 1; +var PTM_RATIO = 32; + +var Box2DTestLayer = cc.Layer.extend({ + world:null, + //GLESDebugDraw *m_debugDraw; + + ctor:function () { + + if(window.sideIndexBar){ + window.sideIndexBar.changeTest(0, 2); + } + //----start0----ctor + this._super(); + + cc.eventManager.addListener(cc.EventListener.create({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded: function(touches, event){ + //Add a new body/atlas sprite at the touched location + var touch = touches[0]; + var location = touch.getLocation(); + event.getCurrentTarget().addNewSpriteWithCoords(location); + } + }), this); + + var b2Vec2 = Box2D.Common.Math.b2Vec2 + , b2BodyDef = Box2D.Dynamics.b2BodyDef + , b2Body = Box2D.Dynamics.b2Body + , b2FixtureDef = Box2D.Dynamics.b2FixtureDef + , b2World = Box2D.Dynamics.b2World + , b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape; + + var screenSize = cc.director.getWinSize(); + //UXLog(L"Screen width %0.2f screen height %0.2f",screenSize.width,screenSize.height); + + // Construct a world object, which will hold and simulate the rigid bodies. + this.world = new b2World(new b2Vec2(0, -10), true); + this.world.SetContinuousPhysics(true); + + // Define the ground body. + //var groundBodyDef = new b2BodyDef(); // TODO + //groundBodyDef.position.Set(screenSize.width / 2 / PTM_RATIO, screenSize.height / 2 / PTM_RATIO); // bottom-left corner + + // Call the body factory which allocates memory for the ground body + // from a pool and creates the ground box shape (also from a pool). + // The body is also added to the world. + //var groundBody = this.world.CreateBody(groundBodyDef); + + var fixDef = new b2FixtureDef; + fixDef.density = 1.0; + fixDef.friction = 0.5; + fixDef.restitution = 0.2; + + var bodyDef = new b2BodyDef; + + //create ground + bodyDef.type = b2Body.b2_staticBody; + fixDef.shape = new b2PolygonShape; + fixDef.shape.SetAsBox(20, 2); + // upper + bodyDef.position.Set(10, screenSize.height / PTM_RATIO + 1.8); + this.world.CreateBody(bodyDef).CreateFixture(fixDef); + // bottom + bodyDef.position.Set(10, -1.8); + this.world.CreateBody(bodyDef).CreateFixture(fixDef); + + fixDef.shape.SetAsBox(2, 14); + // left + bodyDef.position.Set(-1.8, 13); + this.world.CreateBody(bodyDef).CreateFixture(fixDef); + // right + bodyDef.position.Set(26.8, 13); + this.world.CreateBody(bodyDef).CreateFixture(fixDef); + + //Set up sprite + + var mgr = new cc.SpriteBatchNode(s_pathBlock, 150); + this.addChild(mgr, 0, TAG_SPRITE_MANAGER); + + this.addNewSpriteWithCoords(cc.p(screenSize.width / 2, screenSize.height / 2)); + + var label = new cc.LabelTTF("Tap screen", "Marker Felt", 32); + this.addChild(label, 0); + label.color = cc.color(0, 0, 255); + label.x = screenSize.width / 2; + label.y = screenSize.height - 50; + + this.scheduleUpdate(); + //----end0---- + }, + + addNewSpriteWithCoords:function (p) { + //----start0----addNewSpriteWithCoords + //UXLog(L"Add sprite %0.2f x %02.f",p.x,p.y); + var batch = this.getChildByTag(TAG_SPRITE_MANAGER); + + //We have a 64x64 sprite sheet with 4 different 32x32 images. The following code is + //just randomly picking one of the images + var idx = (Math.random() > .5 ? 0 : 1); + var idy = (Math.random() > .5 ? 0 : 1); + var sprite = new cc.Sprite(batch.texture, cc.rect(32 * idx, 32 * idy, 32, 32)); + batch.addChild(sprite); + + sprite.x = p.x; + sprite.y = p.y; + + // Define the dynamic body. + //Set up a 1m squared box in the physics world + var b2BodyDef = Box2D.Dynamics.b2BodyDef + , b2Body = Box2D.Dynamics.b2Body + , b2FixtureDef = Box2D.Dynamics.b2FixtureDef + , b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape; + + var bodyDef = new b2BodyDef(); + bodyDef.type = b2Body.b2_dynamicBody; + bodyDef.position.Set(p.x / PTM_RATIO, p.y / PTM_RATIO); + bodyDef.userData = sprite; + var body = this.world.CreateBody(bodyDef); + + // Define another box shape for our dynamic body. + var dynamicBox = new b2PolygonShape(); + dynamicBox.SetAsBox(0.5, 0.5);//These are mid points for our 1m box + + // Define the dynamic body fixture. + var fixtureDef = new b2FixtureDef(); + fixtureDef.shape = dynamicBox; + fixtureDef.density = 1.0; + fixtureDef.friction = 0.3; + body.CreateFixture(fixtureDef); + //----end0---- + }, + update:function (dt) { + //----start0----update + //It is recommended that a fixed time step is used with Box2D for stability + //of the simulation, however, we are using a variable time step here. + //You need to make an informed choice, the following URL is useful + //http://gafferongames.com/game-physics/fix-your-timestep/ + + var velocityIterations = 8; + var positionIterations = 1; + + // Instruct the world to perform a single step of simulation. It is + // generally best to keep the time step and iterations fixed. + this.world.Step(dt, velocityIterations, positionIterations); + + //Iterate over the bodies in the physics world + for (var b = this.world.GetBodyList(); b; b = b.GetNext()) { + if (b.GetUserData() != null) { + //Synchronize the AtlasSprites position and rotation with the corresponding body + var myActor = b.GetUserData(); + myActor.x = b.GetPosition().x * PTM_RATIO; + myActor.y = b.GetPosition().y * PTM_RATIO; + myActor.rotation = -1 * cc.radiansToDegrees(b.GetAngle()); + } + } + //----end0---- + } + //CREATE_NODE(Box2DTestLayer); +}); + +var Box2DTestScene = TestScene.extend({ + runThisTest:function () { + var layer = new Box2DTestLayer(); + this.addChild(layer); + + cc.director.runScene(this); + } +}); + +var arrayOfBox2DTest = [ + Box2DTestLayer +]; diff --git a/tests/js-tests/src/Camera3DTest/Camera3DTest.js b/tests/js-tests/src/Camera3DTest/Camera3DTest.js new file mode 100644 index 0000000000..c3bbeb37b5 --- /dev/null +++ b/tests/js-tests/src/Camera3DTest/Camera3DTest.js @@ -0,0 +1,1278 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var CameraType = { + Free : 0, + FirstPerson : 1, + ThirdPerson : 2, +}; + +var OperateCamType = { + MoveCamera : 0, + RotateCamera : 1 +}; + +var Camera3DTestIdx = -1; + +var Camera3DTestDemo = cc.Layer.extend({ + _title:"", + _subtitle:"", + + ctor:function () { + this._super(); + }, + + // + // Menu + // + onEnter:function () { + this._super(); + + var label = new cc.LabelTTF(this._title, "Arial", 28); + this.addChild(label, 100, BASE_TEST_TITLE_TAG); + label.x = winSize.width / 2; + label.y = winSize.height - 50; + + var label2 = new cc.LabelTTF(this._subtitle, "Thonburi", 16); + this.addChild(label2, 101, BASE_TEST_SUBTITLE_TAG); + label2.x = winSize.width / 2; + label2.y = winSize.height - 80; + + var item1 = new cc.MenuItemImage(s_pathB1, s_pathB2, this.onBackCallback, this); + var item2 = new cc.MenuItemImage(s_pathR1, s_pathR2, this.onRestartCallback, this); + var item3 = new cc.MenuItemImage(s_pathF1, s_pathF2, this.onNextCallback, this); + + item1.tag = BASE_TEST_MENUITEM_PREV_TAG; + item2.tag = BASE_TEST_MENUITEM_RESET_TAG; + item3.tag = BASE_TEST_MENUITEM_NEXT_TAG; + + var menu = new cc.Menu(item1, item2, item3); + + menu.x = 0; + menu.y = 0; + var width = item2.width, height = item2.height; + item1.x = winSize.width/2 - width*2; + item1.y = height/2 ; + item2.x = winSize.width/2; + item2.y = height/2 ; + item3.x = winSize.width/2 + width*2; + item3.y = height/2 ; + + this.addChild(menu, 102, BASE_TEST_MENU_TAG); + }, + + onRestartCallback:function (sender) { + var s = new Camera3DTestScene(); + s.addChild(restartCamera3DTest()); + director.runScene(s); + }, + + onNextCallback:function (sender) { + var s = new Camera3DTestScene(); + s.addChild(nextCamera3DTest()); + director.runScene(s); + }, + + onBackCallback:function (sender) { + var s = new Camera3DTestScene(); + s.addChild(previousCamera3DTest()); + director.runScene(s); + }, +}); + +var Camera3DTestScene = cc.Scene.extend({ + ctor:function () { + this._super(); + + var label = new cc.LabelTTF("Main Menu", "Arial", 20); + var menuItem = new cc.MenuItemLabel(label, this.onMainMenuCallback, this); + + var menu = new cc.Menu(menuItem); + menu.x = 0; + menu.y = 0; + menuItem.x = winSize.width - 50; + menuItem.y = 25; + this.addChild(menu); + }, + onMainMenuCallback:function () { + var scene = new cc.Scene(); + var layer = new TestController(); + scene.addChild(layer); + director.runScene(scene); + }, + runThisTest:function (num) { + Camera3DTestIdx = (num || num == 0) ? (num - 1) : -1; + var layer = nextCamera3DTest(); + this.addChild(layer); + + director.runScene(this); + } +}); + +var CameraRotationTest = Camera3DTestDemo.extend({ + _title:"Camera Rotation Test", + _subtitle:"Slide to rotate", + _camControlNode:null, + _camNode:null, + + ctor:function(){ + this._super(); + + var s = cc.winSize; + this._camControlNode = new cc.Node(); + this._camControlNode.setNormalizedPosition(cc.p(0.5, 0.5)); + this.addChild(this._camControlNode); + + this._camNode = new cc.Node(); + this._camNode.setVertexZ(cc.Camera.getDefaultCamera().getPosition3D().z); + this._camControlNode.addChild(this._camNode); + + var sp3d = new jsb.Sprite3D(); + sp3d.setPosition(s.width/2, s.height/2); + this.addChild(sp3d); + + var lship = new cc.LabelTTF("Ship"); + lship.setPosition(0, 20); + sp3d.addChild(lship); + + //Billboards + //Yellow is at the back + var bill1 = new jsb.BillBoard("Images/Icon.png"); + bill1.setPosition3D(cc.math.vec3(50, 10, -10)); + bill1.setColor(cc.color.YELLOW); + bill1.setScale(0.6); + sp3d.addChild(bill1); + + var l1 = new cc.LabelTTF("Billboard1"); + l1.setPosition(cc.p(0, -10)); + l1.setColor(cc.color.WHITE); + l1.setScale(3); + bill1.addChild(l1); + + var p1 = new cc.ParticleSystem("Particles/SmallSun.plist"); + p1.setPosition(30, 80); + bill1.addChild(p1); + + var bill2 = new jsb.BillBoard("Images/Icon.png"); + bill2.setPosition3D(cc.math.vec3(-50, -10, 10)); + bill2.setScale(0.6); + sp3d.addChild(bill2); + + var l2 = new cc.LabelTTF("Billboard2"); + l2.setPosition(0, -10); + l2.setColor(cc.color.WHITE); + l2.setScale(3); + bill2.addChild(l2); + + var p2 = new cc.ParticleSystem("Particles/SmallSun.plist"); + p2.setPosition(30,80); + bill2.addChild(p2); + + //3D models + var model = new jsb.Sprite3D("Sprite3DTest/boss1.obj"); + model.setScale(4); + model.setTexture("Sprite3DTest/boss.png"); + model.setPosition3D(cc.math.vec3(s.width/2, s.height/2, 0)); + this.addChild(model); + + var self = this; + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + onTouchBegan: function(touch, event){return true;}, + onTouchMoved: function(touch, event){ + var dx = touch.getDelta().x; + var rot = self._camControlNode.getRotation3D(); + rot.y += dx; + self._camControlNode.setRotation3D(rot); + + var matrix = self._camNode.getNodeToWorldTransform3D(); + var worldPos = cc.math.vec3(matrix[12], matrix[13], matrix[14]); + + cc.Camera.getDefaultCamera().setPosition3D(worldPos); + cc.Camera.getDefaultCamera().lookAt(self._camControlNode.getPosition3D()); + } + }, this); + } +}); + +var Camera3DTest = (function(){ + var State = { + State_None : 0, + State_Idle : 0x01, + State_Move : 0x02, + State_Rotate : 0x04, + State_Speak : 0x08, + State_MeleeAttack : 0x10, + State_RemoteAttack : 0x20, + State_Attack : 0x40 + }; + + return Camera3DTestDemo.extend({ + _title:"Testing Camera", + _subtitle:"", + _layer3D:null, + _sprite3D:null, + _targetPos:null, + _camera:null, + _cameraType:-1, + _curState:0, + _bZoomOut:false, + _bZoomIn:false, + _bRotateLeft:false, + _bRotateRight:false, + _ZoomOutlabel:null, + _ZoomInlabel:null, + _RotateLeftlabel:null, + _RotateRightlabel:null, + + ctor:function(){ + this._super(); + }, + + onEnter:function(){ + this._super(); + + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + // onTouchesBegan: this.onTouchesBegan, + onTouchesMoved: this.onTouchesMoved.bind(this), + onTouchesEnded: this.onTouchesEnded.bind(this) + }, this); + + var layer3D = new cc.Layer(); + this.addChild(layer3D, 0); + this._layer3D = layer3D; + this._curState = State.State_None; + this.addNewSpriteWithCoords(cc.math.vec3(0, 0, 0), "Sprite3DTest/girl.c3b", true, 0.2, true); + + var s = cc.winSize; + var containerForLabel1 = new cc.Node(); + this._ZoomOutlabel = new cc.LabelTTF("zoom out", "Arial", 20); + this._ZoomOutlabel.setPosition(s.width-50, cc.visibleRect.top.y-30); + containerForLabel1.addChild(this._ZoomOutlabel); + this.addChild(containerForLabel1, 10); + + cc.eventManager.addListener({ + event:cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches: true, + onTouchBegan:this.onTouchZoomOut.bind(this), + onTouchEnded:this.onTouchZoomOutEnd.bind(this) + }, this._ZoomOutlabel); + + var containerForLabel2 = new cc.Node(); + this._ZoomInlabel = new cc.LabelTTF("zoom in", "Arial", 20); + this._ZoomInlabel.setPosition(s.width-50, cc.visibleRect.top.y - 100); + containerForLabel2.addChild(this._ZoomInlabel); + this.addChild(containerForLabel2, 10); + + cc.eventManager.addListener({ + event:cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches:true, + onTouchBegan:this.onTouchZoomIn.bind(this), + onTouchEnded:this.onTouchZoomInEnd.bind(this) + }, this._ZoomInlabel); + + var containerForLabel3 = new cc.Node(); + this._RotateLeftlabel = new cc.LabelTTF("rotate left", "Arial", 20); + this._RotateLeftlabel.setPosition(s.width-50, cc.visibleRect.top.y - 170); + containerForLabel3.addChild(this._RotateLeftlabel); + this.addChild(containerForLabel3); + + cc.eventManager.addListener({ + event:cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches:true, + onTouchBegan:this.onTouchRotateLeft.bind(this), + onTouchEnded:this.onTouchRotateLeftEnd.bind(this) + }, this._RotateLeftlabel); + + var containerForLabel4 = new cc.Node(); + this._RotateRightlabel = new cc.LabelTTF("rotate right", "Arial", 20); + this._RotateRightlabel.setPosition(s.width-50, cc.visibleRect.top.y - 240); + containerForLabel4.addChild(this._RotateRightlabel); + this.addChild(containerForLabel4, 10); + + cc.eventManager.addListener({ + event:cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches:true, + onTouchBegan:this.onTouchRotateRight.bind(this), + onTouchEnded:this.onTouchRotateRightEnd.bind(this) + }, this._RotateRightlabel); + + var label1 = new cc.LabelTTF("free", "Arial", 20); + var item1 = new cc.MenuItemLabel(label1, this.switchViewCallback, this); + item1.type = CameraType.Free; + item1.setPosition(cc.visibleRect.left.x+100, cc.visibleRect.top.y-50); + + var label2 = new cc.LabelTTF("third person", "Arial", 20); + var item2 = new cc.MenuItemLabel(label2, this.switchViewCallback, this); + item2.type = CameraType.ThirdPerson; + item2.setPosition(cc.visibleRect.left.x+100, cc.visibleRect.top.y-100); + + var label3 = new cc.LabelTTF("first person", "Arial", 20); + var item3 = new cc.MenuItemLabel(label3, this.switchViewCallback, this); + item3.type = CameraType.FirstPerson; + item3.setPosition(cc.visibleRect.left.x+100, cc.visibleRect.top.y-150); + + var menu = new cc.Menu(item1, item2, item3); + menu.setPosition(cc.p(0, 0)); + this.addChild(menu); + + this.schedule(this.updateCamera, 0); + + if(this._camera == null){ + this._camera = cc.Camera.createPerspective(60, s.width/s.height, 1, 1000); + this._camera.setCameraFlag(cc.CameraFlag.USER1); + layer3D.addChild(this._camera); + } + this.switchViewCallback(item2);//third person + + var line = new cc.DrawNode3D(); + //draw x + for(var i = -20; i < 20; ++i) + line.drawLine(cc.math.vec3(-100, 0, 5*i), cc.math.vec3(100, 0, 5*i), cc.color(255, 0, 0, 1)); + + //draw z + for(var j = -20; j < 20; ++j) + line.drawLine(cc.math.vec3(5*j, 0, -100), cc.math.vec3(5*j, 0, 100), cc.color(0, 0, 255, 1)); + + //draw y + line.drawLine(cc.math.vec3(0, -50, 0), cc.math.vec3(0, 0, 0), cc.color(0, 128, 0, 1)); + line.drawLine(cc.math.vec3(0, 0, 0), cc.math.vec3(0, 50, 0), cc.color(0, 255, 0, 1)); + layer3D.addChild(line); + layer3D.setCameraMask(2); + }, + + addNewSpriteWithCoords:function(postion, file, playAnimation, scale, bindCamera){ + var sprite = new jsb.Sprite3D(file); + this._layer3D.addChild(sprite); + var globalZOrder = sprite.getGlobalZOrder(); + sprite.setPosition3D(postion); + sprite.setGlobalZOrder(globalZOrder); + if(playAnimation){ + var animation = jsb.Animation3D.create(file, "Take 001"); + if(animation){ + var animate = jsb.Animate3D.create(animation); + sprite.runAction(cc.repeatForever(animate)); + } + } + if(bindCamera) + this._sprite3D = sprite; + + sprite.setScale(scale); + }, + + updateState:function(dt){ + if(!this._targetPos) + return; + var curPos = this._sprite3D.getPosition3D(); + var m = this._sprite3D.getNodeToWorldTransform3D(); + var curFaceDir = cc.math.vec3(m[8], m[9], m[10]); + curFaceDir.normalize(); + var newFaceDir = cc.math.vec3(this._targetPos.x - curPos.x, this._targetPos.y - curPos.y, this._targetPos.z - curPos.z); + newFaceDir.y = 0; + newFaceDir.normalize(); + var cosAngle = Math.abs(cc.math.vec3Dot(curFaceDir, newFaceDir) - 1); + + var dx = curPos.x - this._targetPos.x, + dy = curPos.y - this._targetPos.y, + dz = curPos.z - this._targetPos.z; + var dist = dx * dx + dy * dy + dz * dz; + + if(dist <= 4){ + if(cosAngle <= 0.01) + this._curState = State.State_Idle; + else + this._curState = State.State_Rotate; + }else{ + if(cosAngle > 0.01) + this._curState = State.State_Rotate | State.State_Move; + else + this._curState = State.State_Move; + } + }, + + move3D:function(dt){ + if(!this._targetPos) + return; + var curPos = this._sprite3D.getPosition3D(); + var newFaceDir = cc.math.vec3(this._targetPos.x - curPos.x, this._targetPos.y - curPos.y, this._targetPos.z - curPos.z); + newFaceDir.y = 0; + newFaceDir.normalize(); + var offset = cc.math.vec3(newFaceDir.x * 25 * dt, newFaceDir.y * 25 * dt, newFaceDir.z * 25 * dt); + curPos.x += offset.x; + curPos.y += offset.y; + curPos.z += offset.z; + this._sprite3D.setPosition3D(curPos); + if(this._cameraType == CameraType.ThirdPerson){ + var cameraPos = this._camera.getPosition3D(); + cameraPos.x += offset.x; + cameraPos.z += offset.z; + this._camera.setPosition3D(cameraPos); + } + }, + + updateCamera:function(dt){ + if(this._cameraType == CameraType.ThirdPerson){ + this.updateState(dt) + + if(this.isState(State.State_Move)){ + this.move3D(dt); + if(this.isState(State.State_Rotate)){ + var curPos = this._sprite3D.getPosition3D(); + var newFaceDir = cc.math.vec3(this._targetPos.x - curPos.x, this._targetPos.y - curPos.y, this._targetPos.z - curPos.z); + newFaceDir.y = 0; + newFaceDir.normalize(); + + var m = this._sprite3D.getNodeToWorldTransform3D(); + var up = cc.math.vec3(m[4], m[5], m[6]); + up.normalize(); + + var right = cc.math.vec3Cross(cc.math.vec3(-newFaceDir.x, -newFaceDir.y, -newFaceDir.z), up); + right.normalize(); + + var mat = [right.x, right.y, right.z, 0, + up.x, up.y, up.z, 0, + newFaceDir.x, newFaceDir.y, newFaceDir.z, 0, + 0, 0, 0, 1]; + + this._sprite3D.setAdditionalTransform(mat); + } + } + } + + if(this._bZoomOut == true){ + if(this._cameraType == CameraType.ThirdPerson){ + var cameraPos = this._camera.getPosition3D(); + var spritePos = this._sprite3D.getPosition3D(); + var lookDir = cc.math.vec3(cameraPos.x - spritePos.x, cameraPos.y - spritePos.y, cameraPos.z - spritePos.z); + if(cc.math.vec3Length(lookDir) <= 300){ + lookDir.normalize(); + cameraPos.x += lookDir.x; + cameraPos.y += lookDir.y; + cameraPos.z += lookDir.z; + this._camera.setPosition3D(cameraPos); + } + }else if(this._cameraType == CameraType.Free){ + var cameraPos = this._camera.getPosition3D(); + if(cc.math.vec3Length(cameraPos) <= 300){ + var n = cc.math.vec3Normalize(cameraPos); + cameraPos.x += n.x; + cameraPos.y += n.y; + cameraPos.z += n.z; + this._camera.setPosition3D(cameraPos); + } + } + } + + if(this._bZoomIn == true){ + if(this._cameraType == CameraType.ThirdPerson){ + var cameraPos = this._camera.getPosition3D(); + var spritePos = this._sprite3D.getPosition3D(); + var lookDir = cc.math.vec3(cameraPos.x - spritePos.x, cameraPos.y - spritePos.y, cameraPos.z - spritePos.z); + if(cc.math.vec3Length(lookDir) >= 50){ + lookDir.normalize(); + cameraPos.x -= lookDir.x; + cameraPos.y -= lookDir.y; + cameraPos.z -= lookDir.z; + this._camera.setPosition3D(cameraPos); + } + }else if(this._cameraType == CameraType.Free){ + var cameraPos = this._camera.getPosition3D(); + if(cc.math.vec3Length(cameraPos) >= 50){ + var n = cc.math.vec3Normalize(cameraPos); + cameraPos.x -= n.x; + cameraPos.y -= n.y; + cameraPos.z -= n.z; + this._camera.setPosition3D(cameraPos); + } + } + } + + if(this._bRotateLeft == true){ + if(this._cameraType == CameraType.Free || this._cameraType == CameraType.FirstPerson){ + var rotation3D = this._camera.getRotation3D(); + rotation3D.y += 1; + this._camera.setRotation3D(rotation3D); + } + } + if(this._bRotateRight == true){ + if(this._cameraType == CameraType.Free || this._cameraType == CameraType.FirstPerson){ + var rotation3D = this._camera.getRotation3D(); + rotation3D.y -= 1; + this._camera.setRotation3D(rotation3D); + } + } + }, + + isState:function(bit){ + return (this._curState & bit) == bit; + }, + + switchViewCallback:function(sender){ + if(this._cameraType == sender.type) + return; + this._cameraType = sender.type; + + if(this._cameraType == CameraType.Free){ var p = this._sprite3D.getPosition3D(); + this._camera.setPosition3D(cc.math.vec3(p.x, p.y+130, p.z+130)); + + this._RotateRightlabel.setColor(cc.color.WHITE); + this._RotateLeftlabel.setColor(cc.color.WHITE); + this._ZoomInlabel.setColor(cc.color.WHITE); + this._ZoomOutlabel.setColor(cc.color.WHITE); + + }else if(this._cameraType == CameraType.FirstPerson){ + var m = this._sprite3D.getWorldToNodeTransform3D(); + var newFaceDir = cc.math.vec3(-m[8], -m[9], -m[10]); + var p = this._sprite3D.getPosition3D(); + this._camera.setPosition3D(cc.math.vec3(p.x, p.y + 35, p.z)); + this._camera.lookAt(cc.math.vec3(p.x + newFaceDir.x*50, p.y + newFaceDir.y*50, p.z+newFaceDir.z*50)); + + this._RotateRightlabel.setColor(cc.color.WHITE); + this._RotateLeftlabel.setColor(cc.color.WHITE); + this._ZoomInlabel.setColor(cc.color.GRAY); + this._ZoomOutlabel.setColor(cc.color.GRAY); + + }else{ + var p = this._sprite3D.getPosition3D(); + this._camera.setPosition3D(cc.math.vec3(p.x, p.y+130, p.z+130)); + this._camera.lookAt(p); + + this._RotateRightlabel.setColor(cc.color.GRAY); + this._RotateLeftlabel.setColor(cc.color.GRAY); + this._ZoomInlabel.setColor(cc.color.WHITE); + this._ZoomOutlabel.setColor(cc.color.WHITE); + } + }, + + onTouchesMoved:function(touches, event){ + if(touches.length == 1){ + var touch = touches[0]; + var location = touch.getLocation(); + var previousLocation = touch.getPreviousLocation(); + var newPos = cc.math.vec3(previousLocation.x - location.x, previousLocation.y - location.y, previousLocation.z - location.z); + if(this._cameraType == CameraType.Free || this._cameraType == CameraType.FirstPerson){ + var m = this._camera.getNodeToWorldTransform3D(); + var cameraDir = cc.math.vec3(-m[8], -m[9], -m[10]); + cameraDir.normalize(); + cameraDir.y = 0; + var cameraRightDir = cc.math.vec3(m[0], m[1], m[2]); + cameraRightDir.normalize(); + cameraRightDir.y = 0; + + var cameraPos = this._camera.getPosition3D(); + cameraPos.x += cameraDir.x*newPos.y*0.1 + cameraRightDir.x*newPos.x*0.1; + cameraPos.y += cameraDir.y*newPos.y*0.1 + cameraRightDir.y*newPos.x*0.1; + cameraPos.z += cameraDir.z*newPos.y*0.1 + cameraRightDir.z*newPos.x*0.1; + this._camera.setPosition3D(cameraPos); + if(this._sprite3D && this._cameraType == CameraType.FirstPerson){ + this._sprite3D.setPosition3D(cc.math.vec3(this._camera.x, 0, this._camera.getVertexZ())); + this._targetPos = this._sprite3D.getPosition3D(); + } + } + } + }, + + onTouchesEnded:function(touches, event){ + for(var i in touches){ + var touch = touches[i]; + var location = touch.getLocationInView(); + if(this._sprite3D && this._cameraType == CameraType.ThirdPerson && this._bZoomOut == false && this._bZoomIn == false && this._bRotateLeft == false && this._bRotateRight == false){ + var nearP = cc.math.vec3(location.x, location.y, -1); + var farP = cc.math.vec3(location.x, location.y, 1); + + nearP = this._camera.unproject(nearP); + farP = this._camera.unproject(farP); + + var dir = cc.math.vec3(farP.x-nearP.x, farP.y-nearP.y, farP.z-nearP.z); + var ndd = dir.y; // (0, 1, 0) * dir + var ndo = nearP.y; // (0, 1, 0) * nearP + var dist = - ndo / ndd; + var p = cc.math.vec3(nearP.x+dist*dir.x, nearP.y+dist*dir.y, nearP.z+dist*dir.z); + + if(p.x > 100) + p.x = 100; + if(p.x < -100) + p.x = -100; + if(p.z > 100) + p.z = 100 + if(p.z < -100) + p.z = -100; + + this._targetPos = p; + } + } + }, + + onTouchZoomOut:function(touch, event){ + var target = event.getCurrentTarget(); + var locationInNode = target.convertToNodeSpace(touch.getLocation()); + var s = target.getContentSize(); + var rect = cc.rect(0, 0, s.width, s.height); + if(cc.rectContainsPoint(rect, locationInNode)){ + this._bZoomOut = true; + return true; + } + return false; + }, + + onTouchZoomOutEnd:function(touch, event){ + this._bZoomOut = false; + }, + + onTouchZoomIn:function(touch, event){ + var target = event.getCurrentTarget(); + var locationInNode = target.convertToNodeSpace(touch.getLocation()); + var s = target.getContentSize(); + var rect = cc.rect(0, 0, s.width, s.height); + if(cc.rectContainsPoint(rect, locationInNode)){ + this._bZoomIn = true; + return true; + } + return false; + }, + + onTouchZoomInEnd:function(touch, event){ + this._bZoomIn = false; + }, + + onTouchRotateLeft:function(touch, event){ + var target = event.getCurrentTarget(); + var locationInNode = target.convertToNodeSpace(touch.getLocation()); + var s = target.getContentSize(); + var rect = cc.rect(0, 0, s.width, s.height); + if(cc.rectContainsPoint(rect, locationInNode)){ + this._bRotateLeft = true; + return true; + } + return false; + }, + + onTouchRotateLeftEnd:function(touch, event){ + this._bRotateLeft = false; + }, + + onTouchRotateRight:function(touch, event){ + var target = event.getCurrentTarget(); + var locationInNode = target.convertToNodeSpace(touch.getLocation()); + var s = target.getContentSize(); + var rect = cc.rect(0, 0, s.width, s.height); + if(cc.rectContainsPoint(rect, locationInNode)){ + this._bRotateRight = true; + return true; + } + return false; + }, + + onTouchRotateRightEnd:function(touch, event){ + this._bRotateRight = false; + } + }); +})(); + +var CameraCullingDemo = Camera3DTestDemo.extend({ + _title:"Camera Frustum Clipping", + _subtitle:"", + _objects:[], + _layer3D:null, + _labelSprite3DCount:null, + _drawAABB:null, + _drawFrustum:null, + _row:3, + _cameraType:CameraType.FirstPerson, + _cameraFirst:null, + _cameraThird:null, + _moveAction:null, + + ctor:function(){ + this._super(); + + this.scheduleUpdate(); + + var layer3D = new cc.Layer(); + this.addChild(layer3D, 0); + this._layer3D = layer3D; + + // swich camera + cc.MenuItemFont.setFontName("Arial"); + cc.MenuItemFont.setFontSize(20); + + var menuItem1 = new cc.MenuItemFont("Switch Camera", this.switchViewCallback, this); + menuItem1.setColor(cc.color(0, 200, 20)); + var menu = new cc.Menu(menuItem1); + menu.setPosition(cc.p(0, 0)); + menuItem1.setPosition(cc.visibleRect.left.x + 80, cc.visibleRect.top.y - 70); + this.addChild(menu); + + // + - + cc.MenuItemFont.setFontSize(40); + var decrease = new cc.MenuItemFont(" - ", this.delSpriteCallback, this); + decrease.setColor(cc.color(0, 200, 20)); + var increase = new cc.MenuItemFont(" + ", this.addSpriteCallback, this); + increase.setColor(cc.color(0, 200, 20)); + + menu = new cc.Menu(decrease, increase); + menu.alignItemsHorizontally(); + menu.setPosition(cc.winSize.width - 60, cc.visibleRect.top.y - 70); + this.addChild(menu, 1); + + this._labelSprite3DCount = new cc.LabelTTF("0 sprites", "Marker Felt", 30); + this._labelSprite3DCount.setColor(cc.color(0, 200, 20)); + this._labelSprite3DCount.setPosition(cc.p(cc.winSize.width / 2, cc.visibleRect.top.y - 70)); + this.addChild(this._labelSprite3DCount); + + // aabb drawNode3D + this._drawAABB = new cc.DrawNode3D(); + this._drawAABB.setCameraMask(cc.CameraFlag.USER1); + this.addChild(this._drawAABB); + + // frustum drawNode3D + this._drawFrustum = new cc.DrawNode3D(); + this._drawFrustum.setCameraMask(cc.CameraFlag.USER1); + this.addChild(this._drawFrustum); + + // set camera + this.switchViewCallback(); + + // add sprite + this.addSpriteCallback(); + }, + + onExit:function(){ + this._super(); + this._moveAction.release(); + }, + + switchViewCallback:function(sender){ + if(!this._cameraFirst){ + var camera = cc.Camera.createPerspective(30, cc.winSize.width/cc.winSize.height, 10, 200); + camera.setCameraFlag(cc.CameraFlag.USER8); + camera.setPosition3D(cc.math.vec3(-100, 0, 0)); + camera.lookAt(cc.math.vec3(1000, 0, 0)); + this._moveAction = cc.moveBy(4, cc.p(200, 0)); + this._moveAction.retain(); + var seq = cc.sequence(this._moveAction, cc.callFunc(this.reachEndCallBack, this)); + seq.setTag(100); + camera.runAction(seq); + this.addChild(camera); + this._cameraFirst = camera; + } + + if(!this._cameraThird){ + var camera = cc.Camera.createPerspective(60, cc.winSize.width/ cc.winSize.height, 1, 1000); + camera.setCameraFlag(cc.CameraFlag.USER8); + camera.setPosition3D(cc.math.vec3(0, 130, 130)); + camera.lookAt(cc.math.vec3(0, 0, 0)); + this.addChild(camera); + this._cameraThird = camera; + } + + if(this._cameraType == CameraType.FirstPerson){ + this._cameraType = CameraType.ThirdPerson; + this._cameraThird.setCameraFlag(cc.CameraFlag.USER1); + this._cameraFirst.setCameraFlag(cc.CameraFlag.USER8); + }else if(this._cameraType == CameraType.ThirdPerson){ + this._cameraType = CameraType.FirstPerson; + this._cameraThird.setCameraFlag(cc.CameraFlag.USER8); + this._cameraFirst.setCameraFlag(cc.CameraFlag.USER1); + this._drawFrustum.clear(); + } + }, + + reachEndCallBack:function(){ + this._cameraFirst.stopActionByTag(100); + var inverse = this._moveAction.reverse(); + inverse.retain(); + this._moveAction.release(); + this._moveAction = inverse; + var rot = cc.rotateBy(1, cc.math.vec3(0, 180, 0)); + var seq = cc.sequence(rot, this._moveAction, cc.callFunc(this.reachEndCallBack, this)); + seq.setTag(100); + this._cameraFirst.runAction(seq); + }, + + delSpriteCallback:function(sender){ + if(this._row == 0) + return; + + this._layer3D.removeAllChildren(); + this._objects.length = 0; + + this._row--; + for(var x = -this._row; x < this._row; ++x){ + for(var z = -this._row; z < this._row; ++z){ + var sprite = new jsb.Sprite3D("Sprite3DTest/orc.c3b"); + sprite.setPosition3D(cc.math.vec3(x * 30, 0, z * 30)); + sprite.setRotation3D(cc.math.vec3(0, 180, 0)); + this._objects.push(sprite); + this._layer3D.addChild(sprite); + } + } + + //set layer mask + this._layer3D.setCameraMask(cc.CameraFlag.USER1); + + //update sprite number + this._labelSprite3DCount.setString(this._layer3D.getChildrenCount() + " sprites"); + }, + + addSpriteCallback:function(sender){ + this._layer3D.removeAllChildren(); + this._objects.length = 0; + this._drawAABB.clear(); + + this._row++; + for(var x = -this._row; x < this._row; ++x){ + for(var z = -this._row; z < this._row; ++z){ + var sprite = new jsb.Sprite3D("Sprite3DTest/orc.c3b"); + sprite.setPosition3D(cc.math.vec3(x * 30, 0, z * 30)); + sprite.setRotation3D(cc.math.vec3(0, 180, 0)); + this._objects.push(sprite); + this._layer3D.addChild(sprite); + } + } + + //set layer mask + this._layer3D.setCameraMask(cc.CameraFlag.USER1); + + //update sprite number + this._labelSprite3DCount.setString(this._layer3D.getChildrenCount() + " sprites"); + }, + + update:function(dt){ + this._drawAABB.clear(); + + if(this._cameraType == CameraType.ThirdPerson) + this.drawCameraFrustum(); + + var children = this._layer3D.getChildren(); + + for(var i in children){ + var aabb = children[i].getAABB(); + if(this._cameraFirst.isVisibleInFrustum(aabb)){ + var corners = cc.math.aabbGetCorners(aabb); + this._drawAABB.drawCube(corners, cc.color(0, 255, 0)); + } + } + }, + + drawCameraFrustum:function(){ + this._drawFrustum.clear(); + var size = cc.winSize; + var color = cc.color(255, 255, 0); + + // top-left + var src = cc.math.vec3(0, 0, 0); + var tl_0 = this._cameraFirst.unproject(src); + src = cc.math.vec3(0, 0, 1); + var tl_1 = this._cameraFirst.unproject(src); + + // top-right + src = cc.math.vec3(size.width, 0, 0); + var tr_0 = this._cameraFirst.unproject(src); + src = cc.math.vec3(size.width, 0, 1); + var tr_1 = this._cameraFirst.unproject(src); + + // bottom-left + src = cc.math.vec3(0, size.height, 0); + var bl_0 = this._cameraFirst.unproject(src); + src = cc.math.vec3(0, size.height, 1); + var bl_1 = this._cameraFirst.unproject(src); + + // bottom-right + src = cc.math.vec3(size.width, size.height, 0); + var br_0 = this._cameraFirst.unproject(src); + src = cc.math.vec3(size.width, size.height, 1); + var br_1 = this._cameraFirst.unproject(src); + + this._drawFrustum.drawLine(tl_0, tl_1, color); + this._drawFrustum.drawLine(tr_0, tr_1, color); + this._drawFrustum.drawLine(bl_0, bl_1, color); + this._drawFrustum.drawLine(br_0, br_1, color); + + this._drawFrustum.drawLine(tl_0, tr_0, color); + this._drawFrustum.drawLine(tr_0, br_0, color); + this._drawFrustum.drawLine(br_0, bl_0, color); + this._drawFrustum.drawLine(bl_0, tl_0, color); + + this._drawFrustum.drawLine(tl_1, tr_1, color); + this._drawFrustum.drawLine(tr_1, br_1, color); + this._drawFrustum.drawLine(br_1, bl_1, color); + this._drawFrustum.drawLine(bl_1, tl_1, color); + } +}); + +var CameraArcBallDemo = Camera3DTestDemo.extend({ + _title:"Camera ArcBall Moving", + _subtitle:"", + _rotationQuat: null, + _layer3D:null, + _camera:null, + _sprite3D1:null, + _sprite3D2:null, + _drawGrid:null, + _operate:OperateCamType.RotateCamera, + _target:0, + _center:cc.math.vec3(0, 0, 0), + _distanceZ:50, + _radius:1, + + ctor:function(){ + this._super(); + this._rotationQuat = cc.math.quaternion(0, 0, 0, 1); + cc.eventManager.addListener({ + event:cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesMoved:this.onTouchesMoved.bind(this) + }, this); + + cc.MenuItemFont.setFontName("Arial"); + cc.MenuItemFont.setFontSize(20); + + var item1 = new cc.MenuItemFont("Switch Operation", this.switchOperateCallback, this); + item1.setColor(cc.color(0, 200, 20)); + var item2 = new cc.MenuItemFont("Switch Target", this.switchTargetCallback, this); + item2.setColor(cc.color(0, 200, 20)); + var menu = new cc.Menu(item1, item2); + menu.setPosition(cc.p(0, 0)); + item1.setPosition(cc.visibleRect.left.x + 80, cc.visibleRect.top.y - 70); + item2.setPosition(cc.visibleRect.left.x + 80, cc.visibleRect.top.y - 100); + this.addChild(menu, 1); + + var layer3D = new cc.Layer(); + this.addChild(layer3D); + this._layer3D = layer3D; + + this._camera = cc.Camera.createPerspective(60, cc.winSize.width/cc.winSize.height, 1, 1000); + this._camera.setCameraFlag(cc.CameraFlag.USER1); + this._camera.setPosition3D(cc.math.vec3(0, 10, 50)); + this._camera.lookAt(cc.math.vec3(0, 0, 0), cc.math.vec3(0, 1, 0)); + layer3D.addChild(this._camera); + + this._sprite3D1 = new jsb.Sprite3D("Sprite3DTest/orc.c3b"); + this._sprite3D1.setScale(0.5); + this._sprite3D1.setRotation3D(cc.math.vec3(0, 180, 0)); + this._sprite3D1.setPosition3D(cc.math.vec3(0, 0, 0)); + layer3D.addChild(this._sprite3D1); + + this._sprite3D2 = new jsb.Sprite3D("Sprite3DTest/boss.c3b"); + this._sprite3D2.setScale(0.6); + this._sprite3D2.setRotation3D(cc.math.vec3(-90, 0, 0)); + this._sprite3D2.setPosition3D(cc.math.vec3(20, 0, 0)); + layer3D.addChild(this._sprite3D2); + + this._drawGrid = new cc.DrawNode3D(); + //draw x + for(var i = -20; i < 20; ++i) + this._drawGrid.drawLine(cc.math.vec3(-100, 0, 5*i), cc.math.vec3(100, 0, 5*i), cc.color(0, 0, 255)); + + //draw z + for(var j = -20; j < 20; ++j) + this._drawGrid.drawLine(cc.math.vec3(5*j, 0, -100), cc.math.vec3(5*j, 0, 100), cc.color(0, 255, 0)); + + //draw y + this._drawGrid.drawLine(cc.math.vec3(0, 0, 0), cc.math.vec3(0, 50, 0), cc.color(0, 255, 0)); + + layer3D.addChild(this._drawGrid); + layer3D.setCameraMask(2); + this.updateCameraTransform(); + }, + + updateCameraTransform:function(){ + var trans = cc.math.mat4CreateTranslation(cc.math.vec3(0, 10, this._distanceZ)); + var rot = cc.math.mat4CreateRotation(this._rotationQuat); + var center = cc.math.mat4CreateTranslation(this._center); + + var result = cc.math.mat4Multiply(cc.math.mat4Multiply(center, rot), trans); + this._camera.setNodeToParentTransform(result); + }, + + switchOperateCallback:function(sender){ + if(this._operate === OperateCamType.MoveCamera) + this._operate = OperateCamType.RotateCamera; + else if(this._operate === OperateCamType.RotateCamera) + this._operate = OperateCamType.MoveCamera; + }, + + switchTargetCallback:function(sender){ + if(this._target === 0 ){ + this._target = 1; + this._center = this._sprite3D2.getPosition3D(); + this.updateCameraTransform(); + }else if(this._target === 1){ + this._target = 0; + this._center = this._sprite3D1.getPosition3D(); + this.updateCameraTransform(); + } + }, + + onTouchesMoved:function(touches, event){ + if(touches.length > 0){ + if(this._operate === OperateCamType.RotateCamera){ //arc ball rotate + var visibleSize = cc.director.getVisibleSize(); + var prelocation = touches[0].getPreviousLocationInView(); + var location = touches[0].getLocationInView(); + location.x = 2 * location.x / visibleSize.width - 1; + location.y = 2 * (visibleSize.height - location.y) / visibleSize.height - 1; + prelocation.x = 2 * prelocation.x / visibleSize.width - 1; + prelocation.y = 2 * (visibleSize.height - prelocation.y) / visibleSize.height - 1; + + var quat = this.calculateArcBall(prelocation.x, prelocation.y, location.x, location.y); //calculate rotation cc.math.quaternion parameters + this._rotationQuat = cc.math.quatMultiply(quat, this._rotationQuat); + + this.updateCameraTransform(); + }else if(this._operate === OperateCamType.MoveCamera){ //camera zoom + var newPos = cc.pSub(touches[0].getPreviousLocation(), touches[0].getLocation()); + this._distanceZ -= newPos.y * 0.1; + + this.updateCameraTransform(); + } + } + }, + + calculateArcBall:function(p1x, p1y, p2x, p2y){ + var axis, angle; + + var rotation_matrix = cc.math.mat4CreateRotation(this._rotationQuat); + + var uv = cc.math.mat4MultiplyVec3(rotation_matrix, cc.math.vec3(0, 1, 0)); //rotation y + var sv = cc.math.mat4MultiplyVec3(rotation_matrix, cc.math.vec3(1, 0, 0)); //rotation x + var lv = cc.math.mat4MultiplyVec3(rotation_matrix, cc.math.vec3(0, 0, -1));//rotation z + + var z = this.projectToSphere(this._radius, p1x, p1y); + var p1 = cc.math.vec3Sub(cc.math.vec3Add(cc.math.vec3(sv.x * p1x, sv.y * p1x, sv.z * p1x), cc.math.vec3(uv.x * p1y, uv.y * p1y, uv.z *p1y)), cc.math.vec3(lv.x * z, lv.y * z, lv.z * z)); //start point screen transform to 3d + z = this.projectToSphere(this._radius, p2x, p2y); + var p2 = cc.math.vec3Sub(cc.math.vec3Add(cc.math.vec3(sv.x * p2x, sv.y * p2x, sv.z * p2x), cc.math.vec3(uv.x * p2y, uv.y * p2y, uv.z *p2y)), cc.math.vec3(lv.x * z, lv.y * z, lv.z * z)); //end point screen transform to 3d + + axis = cc.math.vec3Cross(p2, p1); //calculate rotation axis + axis.normalize(); + + var t = cc.math.vec3Length(cc.math.vec3Sub(p2, p1)) / (2 * this._radius); + //clamp -1 to 1 + if(t > 1) t = 1; + if(t < -1) t = -1; + angle = Math.asin(t); //rotation angle*/ + + return cc.math.quaternion(axis, angle) + }, + + /* project an x,y pair onto a sphere of radius r or a + hyperbolic sheet if we are away from the center of the sphere. */ + projectToSphere:function(r, x, y){ + var d = Math.sqrt(x*x + y*y); + var t, z; + if(d < r * 0.70710678118654752440)//inside sphere + z = Math.sqrt(r*r - d*d) + else{ + t = r / 1.41421356237309504880; + z = t*t / d; + } + return z; + } +}); + +var FogTestDemo = Camera3DTestDemo.extend({ + _title:"Fog Test Demo", + _subtitle:"", + _sprite3D1:null, + _sprite3D2:null, + _camera:null, + _state:null, + + ctor:function(){ + this._super(); + cc.director.setClearColor(cc.color(128, 128, 128)); + + cc.eventManager.addListener({ + event:cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesMoved:this.onTouchesMoved.bind(this) + }, this); + + // swich fog type + var label1 = new cc.LabelTTF("Linear", "Arial", 20); + var item1 = new cc.MenuItemLabel(label1, this.switchTypeCallback, this); + item1.setUserData(0); + var label2 = new cc.LabelTTF("Exp", "Arial", 20); + var item2 = new cc.MenuItemLabel(label2, this.switchTypeCallback, this); + item2.setUserData(1); + var label3 = new cc.LabelTTF("Exp2", "Arial", 20); + var item3 = new cc.MenuItemLabel(label3, this.switchTypeCallback, this); + item3.setUserData(2); + var menu = new cc.Menu(item1, item2, item3); + menu.setPosition(cc.p(0, 0)); + + item1.setPosition(cc.visibleRect.left.x + 60, cc.visibleRect.top.y - 50); + item2.setPosition(cc.visibleRect.left.x + 60, cc.visibleRect.top.y - 100); + item3.setPosition(cc.visibleRect.left.x + 60, cc.visibleRect.top.y - 150); + this.addChild(menu, 0); + + var layer3D = new cc.Layer(); + this.addChild(layer3D, 0); + + var shader = new cc.GLProgram("Sprite3DTest/fog.vert", "Sprite3DTest/fog.frag"); + var state = cc.GLProgramState.create(shader); + this._state = state; + + this._sprite3D1 = new jsb.Sprite3D("Sprite3DTest/teapot.c3b"); + this._sprite3D2 = new jsb.Sprite3D("Sprite3DTest/teapot.c3b"); + + this._sprite3D1.setGLProgramState(state); + this._sprite3D2.setGLProgramState(state); + + //pass mesh's attribute to shader + var offset = 0; + var attributeCount = this._sprite3D1.getMesh().getMeshVertexAttribCount(); + for(var i = 0; i < attributeCount; ++i){ + var meshattribute = this._sprite3D1.getMesh().getMeshVertexAttribute(i); + state.setVertexAttribPointer(cc.attributeNames[meshattribute.vertexAttrib], + meshattribute.size, + meshattribute.type, + gl.FALSE, + this._sprite3D1.getMesh().getVertexSizeInBytes(), + offset); + offset += meshattribute.attribSizeBytes; + } + + var offset1 = 0; + var attributeCount = this._sprite3D2.getMesh().getMeshVertexAttribCount(); + for(var i = 0; i < attributeCount; ++i){ + var meshattribute = this._sprite3D2.getMesh().getMeshVertexAttribute(i); + state.setVertexAttribPointer(cc.attributeNames[meshattribute.vertexAttrib], + meshattribute.size, + meshattribute.type, + gl.FALSE, + this._sprite3D2.getMesh().getVertexSizeInBytes(), + offset1); + offset1 += meshattribute.attribSizeBytes; + } + + state.setUniformVec4("u_fogColor", cc.math.vec4(0.5, 0.5, 0.5, 1.0)); + state.setUniformFloat("u_fogStart", 10); + state.setUniformFloat("u_fogEnd", 60); + state.setUniformInt("u_fogEquation", 0); + + layer3D.addChild(this._sprite3D1); + this._sprite3D1.setPosition3D(cc.math.vec3(0, 0, 0)); + this._sprite3D1.setScale(2); + this._sprite3D1.setRotation3D(cc.math.vec3(-90, 180, 0)); + + layer3D.addChild(this._sprite3D2); + this._sprite3D2.setPosition3D(cc.math.vec3(0, 0, -20)); + this._sprite3D2.setScale(2); + this._sprite3D2.setRotation3D(cc.math.vec3(-90, 180, 0)); + + this._camera = cc.Camera.createPerspective(60, cc.winSize.width/cc.winSize.height, 1, 1000); + this._camera.setCameraFlag(cc.CameraFlag.USER1); + this._camera.setPosition3D(cc.math.vec3(0, 30, 40)); + this._camera.lookAt(cc.math.vec3(0, 0, 0), cc.math.vec3(0, 1, 0)); + layer3D.addChild(this._camera); + layer3D.setCameraMask(2); + }, + + onExit:function(){ + this._super(); + cc.director.setClearColor(cc.color(0, 0, 0)); + }, + + switchTypeCallback:function(sender){ + var type = sender.getUserData(); + if(type === 0){ + this._state.setUniformVec4("u_fogColor", cc.math.vec4(0.5, 0.5, 0.5, 1.0)); + this._state.setUniformFloat("u_fogStart", 10); + this._state.setUniformFloat("u_fogEnd", 60); + this._state.setUniformInt("u_fogEquation", 0); + + this._sprite3D1.setGLProgramState(this._state); + this._sprite3D2.setGLProgramState(this._state); + }else if(type === 1){ + this._state.setUniformVec4("u_fogColor", cc.math.vec4(0.5, 0.5, 0.5, 1.0)); + this._state.setUniformFloat("u_fogDensity", 0.03); + this._state.setUniformInt("u_fogEquation", 1); + + this._sprite3D1.setGLProgramState(this._state); + this._sprite3D2.setGLProgramState(this._state); + }else if(type === 2){ + this._state.setUniformVec4("u_fogColor", cc.math.vec4(0.5, 0.5, 0.5, 1.0)); + this._state.setUniformFloat("u_fogDensity", 0.03); + this._state.setUniformInt("u_fogEquation", 2); + + this._sprite3D1.setGLProgramState(this._state); + this._sprite3D2.setGLProgramState(this._state); + } + }, + + onTouchesMoved:function(touches, event){ + if(touches.length === 1){ + var prelocation = touches[0].getPreviousLocationInView(); + var location = touches[0].getLocationInView(); + var newPos = cc.math.vec3Sub(prelocation, location); + + var m = this._camera.getNodeToWorldTransform3D(); + var cameraDir = cc.math.vec3(-m[8], -m[9], -m[10]); + cameraDir.normalize(); + cameraDir.y = 0; + var cameraRightDir = cc.math.vec3(m[0], m[1], m[2]); + cameraRightDir.normalize(); + cameraRightDir.y = 0; + + var cameraPos = this._camera.getPosition3D(); + cameraPos.x += cameraDir.x*newPos.y*0.1 + cameraRightDir.x*newPos.x*0.1; + cameraPos.y += cameraDir.y*newPos.y*0.1 + cameraRightDir.y*newPos.x*0.1; + cameraPos.z += cameraDir.z*newPos.y*0.1 + cameraRightDir.z*newPos.x*0.1; + this._camera.setPosition3D(cameraPos); + } + } +}); + +// +// Flow control +// +var arrayOfCamera3DTest = [ + CameraRotationTest, + Camera3DTest, + CameraCullingDemo, + CameraArcBallDemo +]; + +if(cc.sys.os !== cc.sys.OS_WP8 || cc.sys.os !== cc.sys.OS_WINRT){ + arrayOfCamera3DTest.push(FogTestDemo); +} + +var nextCamera3DTest = function () { + Camera3DTestIdx++; + Camera3DTestIdx = Camera3DTestIdx % arrayOfCamera3DTest.length; + + return new arrayOfCamera3DTest[Camera3DTestIdx ](); +}; +var previousCamera3DTest = function () { + Camera3DTestIdx--; + if (Camera3DTestIdx < 0) + Camera3DTestIdx += arrayOfCamera3DTest.length; + + return new arrayOfCamera3DTest[Camera3DTestIdx ](); +}; +var restartCamera3DTest = function () { + return new arrayOfCamera3DTest[Camera3DTestIdx ](); +}; diff --git a/tests/js-tests/src/ChipmunkTest/ChipmunkTest.js b/tests/js-tests/src/ChipmunkTest/ChipmunkTest.js new file mode 100644 index 0000000000..1988649904 --- /dev/null +++ b/tests/js-tests/src/ChipmunkTest/ChipmunkTest.js @@ -0,0 +1,2107 @@ + /** + * 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. + * + * + * Chipmunk Demo code: + * Original Demo code written in C by Scott Lembcke + * Ported to JavaScript by Joseph Gentle + * Additions to the demo code by Ricardo Quesada + */ + +// +// JavaScript + chipmunk tests +// + +var chipmunkTestSceneIdx = -1; + + +//------------------------------------------------------------------ +// +// ChipmunkBaseLayer +// +//------------------------------------------------------------------ +var ChipmunkBaseLayer = BaseTestLayer.extend( { + ctor : function() { + // + // VERY IMPORTANT + // + // Only subclasses of a native classes MUST call cc.associateWithNative + // Failure to do so, it will crash. + // + this._super( cc.color(0,0,0,255), cc.color(98*0.5,99*0.5,117*0.5,255) ); + + this._title = "No title"; + this._subtitle = "No Subtitle"; + + // Menu to toggle debug physics on / off + var item = new cc.MenuItemFont("Physics On/Off", this.onToggleDebug, this); + item.fontSize = 24; + var menu = new cc.Menu( item ); + this.addChild( menu ); + menu.x = winSize.width-100; + menu.y = winSize.height-90; + + // Create the initial space + this.space = new cp.Space(); + + this.setupDebugNode(); + }, + + setupDebugNode : function() + { + // debug only + this._debugNode = new cc.PhysicsDebugNode(this.space ); + this._debugNode.visible = false ; + this.addChild( this._debugNode ); + }, + + onToggleDebug : function(sender) { + var state = this._debugNode.visible; + this._debugNode.visible = !state ; + }, + + onEnter : function() { + BaseTestLayer.prototype.onEnter.call(this); + //cc.base(this, 'onEnter'); + + cc.sys.dumpRoot(); + cc.sys.garbageCollect(); + }, + + onCleanup : function() { + // Not compulsory, but recommended: cleanup the scene + this.unscheduleUpdate(); + }, + + onRestartCallback : function (sender) { + this.onCleanup(); + var s = new ChipmunkTestScene(); + s.addChild(restartChipmunkTest()); + director.runScene(s); + }, + + onNextCallback : function (sender) { + this.onCleanup(); + var s = new ChipmunkTestScene(); + s.addChild(nextChipmunkTest()); + director.runScene(s); + }, + + onBackCallback : function (sender) { + this.onCleanup(); + var s = new ChipmunkTestScene(); + s.addChild(previousChipmunkTest()); + director.runScene(s); + }, + + numberOfPendingTests : function() { + return ( (arrayOfChipmunkTest.length-1) - chipmunkTestSceneIdx ); + }, + + getTestNumber : function() { + return chipmunkTestSceneIdx; + } +}); + +//------------------------------------------------------------------ +// +// Chipmunk + Sprite +// +//------------------------------------------------------------------ +var ChipmunkSprite = ChipmunkBaseLayer.extend( { + + ctor: function() { + this._super(); + //cc.base(this); + + this.addSprite = function( pos ) { + var sprite = this.createPhysicsSprite( pos ); + this.addChild( sprite ); + }; + + this._title = 'Chipmunk Sprite Test'; + this._subtitle = 'Chipmunk + cocos2d sprites tests. Tap screen.'; + + this.initPhysics(); + }, + + title : function(){ + return 'Chipmunk Sprite Test'; + }, + + initPhysics : function() { + var space = this.space ; + var staticBody = space.staticBody; + + // Walls + var walls = [ new cp.SegmentShape( staticBody, cp.v(0,0), cp.v(winSize.width,0), 0 ), // bottom + new cp.SegmentShape( staticBody, cp.v(0,winSize.height), cp.v(winSize.width,winSize.height), 0), // top + new cp.SegmentShape( staticBody, cp.v(0,0), cp.v(0,winSize.height), 0), // left + new cp.SegmentShape( staticBody, cp.v(winSize.width,0), cp.v(winSize.width,winSize.height), 0) // right + ]; + for( var i=0; i < walls.length; i++ ) { + var shape = walls[i]; + shape.setElasticity(1); + shape.setFriction(1); + space.addStaticShape( shape ); + } + + // Gravity + space.gravity = cp.v(0, -100); + }, + + createPhysicsSprite : function( pos ) { + var body = new cp.Body(1, cp.momentForBox(1, 48, 108) ); + body.setPos( pos ); + this.space.addBody( body ); + var shape = new cp.BoxShape( body, 48, 108); + shape.setElasticity( 0.5 ); + shape.setFriction( 0.5 ); + this.space.addShape( shape ); + + var sprite = new cc.PhysicsSprite(s_pathGrossini); + sprite.setBody( body ); + return sprite; + }, + + onEnter : function () { + ChipmunkBaseLayer.prototype.onEnter.call(this); + //cc.base(this, 'onEnter'); + + this.scheduleUpdate(); + for(var i=0; i<10; i++) { + var variancex = cc.randomMinus1To1() * 5; + var variancey = cc.randomMinus1To1() * 5; + this.addSprite( cp.v(winSize.width/2 + variancex, winSize.height/2 + variancey) ); + } + + if( 'touches' in cc.sys.capabilities ){ + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded: function(touches, event){ + var l = touches.length, target = event.getCurrentTarget(); + for( var i=0; i < l; i++) { + target.addSprite( touches[i].getLocation() ); + } + } + }, this); + } else if( 'mouse' in cc.sys.capabilities ) + cc.eventManager.addListener({ + event: cc.EventListener.MOUSE, + onMouseDown: function(event){ + event.getCurrentTarget().addSprite(event.getLocation()); + } + }, this); + }, + + update : function( delta ) { + this.space.step( delta ); + } +}); + +//------------------------------------------------------------------ +// +// Chipmunk + Sprite + Batch +// +//------------------------------------------------------------------ +var ChipmunkSpriteBatchTest = ChipmunkSprite.extend( { + ctor : function () { + this._super(); + // cc.base(this); + + // batch node + this.batch = new cc.SpriteBatchNode(s_pathGrossini, 50 ); + this.addChild( this.batch ); + + this.addSprite = function( pos ) { + var sprite = this.createPhysicsSprite( pos ); + this.batch.addChild( sprite ); + }; + + this._title = 'Chipmunk SpriteBatch Test'; + this._subtitle = 'Chipmunk + cocos2d sprite batch tests. Tap screen.'; + }, + + title : function(){ + return 'Chipmunk SpriteBatch Test'; + } +}); + + //------------------------------------------------------------------ + // + // Chipmunk Collision Test + // Using setDefaultCollisionHandler + // The default collision handler is invoked for each colliding pair of shapes that isn't explicitly handled by a specific collision handler. + // + //------------------------------------------------------------------ +var ChipmunkCollisionTest_no_specific_type = ChipmunkBaseLayer.extend({ + ctor : function () { + this._super(); + + this._title = 'Chipmunk Collision test'; + this._subtitle = 'Using setDefaultCollisionHandler'; + }, + + // init physics + initPhysics : function() { + var staticBody = this.space.staticBody; + + // Walls + var walls = [ new cp.SegmentShape( staticBody, cp.v(0,0), cp.v(winSize.width,0), 0 ) // bottom + // new cp.SegmentShape( staticBody, cp.v(0,winSize.height), cp.v(winSize.width,winSize.height), 0), // top + // new cp.SegmentShape( staticBody, cp.v(0,0), cp.v(0,winSize.height), 0), // left + // new cp.SegmentShape( staticBody, cp.v(winSize.width,0), cp.v(winSize.width,winSize.height), 0) // right + ]; + for( var i=0; i < walls.length; i++ ) { + var wall = walls[i]; + wall.setElasticity(1); + wall.setFriction(1); + this.space.addStaticShape( wall ); + } + + // Gravity: + // testing properties + this.space.gravity = cp.v(0,-100); + this.space.iterations = 15; + }, + + createPhysicsSprite : function( pos, file ) { + var body = new cp.Body(1, cp.momentForBox(1, 48, 108) ); + body.setPos(pos); + this.space.addBody(body); + var shape = new cp.BoxShape( body, 48, 108); + shape.setElasticity( 0.5 ); + shape.setFriction( 0.5 ); + this.space.addShape( shape ); + + var sprite = new cc.PhysicsSprite(file); + sprite.setBody( body ); + return sprite; + }, + + onEnter : function () { + ChipmunkBaseLayer.prototype.onEnter.call(this); + + this.initPhysics(); + this.scheduleUpdate(); + + var sprite1 = this.createPhysicsSprite( cc.p(winSize.width/2, winSize.height-20), s_pathGrossini); + this.addChild( sprite1 ); + + this.space.setDefaultCollisionHandler( + this.collisionBegin.bind(this), + this.collisionPre.bind(this), + this.collisionPost.bind(this), + this.collisionSeparate.bind(this) + ); + }, + + onExit : function() { + ChipmunkBaseLayer.prototype.onExit.call(this); + }, + + update : function( delta ) { + this.space.step( delta ); + }, + + collisionBegin : function ( arbiter, space ) { + cc.log('collision begin'); + return true; + }, + + collisionPre : function ( arbiter, space ) { + cc.log('collision pre'); + return true; + }, + + collisionPost : function ( arbiter, space ) { + cc.log('collision post'); + }, + + collisionSeparate : function ( arbiter, space ) { + cc.log('collision separate'); + } +}); +//------------------------------------------------------------------ +// +// Chipmunk Collision Test +// Using Object Oriented API. +// Base your samples on the "Object Oriented" API. +// +//------------------------------------------------------------------ +var ChipmunkCollisionTest = ChipmunkBaseLayer.extend( { + + ctor : function () { + this._super(); + // cc.base(this); + + this._title = 'Chipmunk Collision test'; + this._subtitle = 'Using Object Oriented API. ** Use this API **'; + }, + + // init physics + initPhysics : function() { + var staticBody = this.space.staticBody; + + // Walls + var walls = [ new cp.SegmentShape( staticBody, cp.v(0,0), cp.v(winSize.width,0), 0 ), // bottom + new cp.SegmentShape( staticBody, cp.v(0,winSize.height), cp.v(winSize.width,winSize.height), 0), // top + new cp.SegmentShape( staticBody, cp.v(0,0), cp.v(0,winSize.height), 0), // left + new cp.SegmentShape( staticBody, cp.v(winSize.width,0), cp.v(winSize.width,winSize.height), 0) // right + ]; + for( var i=0; i < walls.length; i++ ) { + var wall = walls[i]; + wall.setElasticity(1); + wall.setFriction(1); + this.space.addStaticShape( wall ); + } + + // Gravity: + // testing properties + this.space.gravity = cp.v(0,-100); + this.space.iterations = 15; + }, + + createPhysicsSprite : function( pos, file, collision_type ) { + var body = new cp.Body(1, cp.momentForBox(1, 48, 108) ); + body.setPos(pos); + this.space.addBody(body); + var shape = new cp.BoxShape( body, 48, 108); + shape.setElasticity( 0.5 ); + shape.setFriction( 0.5 ); + shape.setCollisionType( collision_type ); + this.space.addShape( shape ); + + var sprite = new cc.PhysicsSprite(file); + sprite.setBody( body ); + return sprite; + }, + + onEnter : function () { + ChipmunkBaseLayer.prototype.onEnter.call(this); + // cc.base(this, 'onEnter'); + + this.initPhysics(); + this.scheduleUpdate(); + + var sprite1 = this.createPhysicsSprite( cc.p(winSize.width/2, winSize.height-20), s_pathGrossini, 1); + var sprite2 = this.createPhysicsSprite( cc.p(winSize.width/2, 50), s_pathSister1, 2); + + this.addChild( sprite1 ); + this.addChild( sprite2 ); + + this.space.addCollisionHandler( 1, 2, + this.collisionBegin.bind(this), + this.collisionPre.bind(this), + this.collisionPost.bind(this), + this.collisionSeparate.bind(this) + ); + }, + + onExit : function() { + this.space.removeCollisionHandler( 1, 2 ); + ChipmunkBaseLayer.prototype.onExit.call(this); + }, + + update : function( delta ) { + this.space.step( delta ); + }, + + collisionBegin : function ( arbiter, space ) { + + if( ! this.messageDisplayed ) { + var label = new cc.LabelBMFont("Collision Detected", s_bitmapFontTest5_fnt); + this.addChild( label ); + label.x = winSize.width/2; + label.y = winSize.height/2 ; + this.messageDisplayed = true; + } + cc.log('collision begin'); + var shapes = arbiter.getShapes(); + var collTypeA = shapes[0].collision_type; + var collTypeB = shapes[1].collision_type; + cc.log( 'Collision Type A:' + collTypeA ); + cc.log( 'Collision Type B:' + collTypeB ); + + //test addPostStepCallback + space.addPostStepCallback(function(){ + cc.log("post step callback 1"); + }); + space.addPostStepCallback(function(){ + cc.log("post step callback 2"); + }); + return true; + }, + + collisionPre : function ( arbiter, space ) { + cc.log('collision pre'); + cc.log("arbiter e : " + arbiter.e); + cc.log("arbiter u : " +arbiter.u); + cc.log("arbiter surface_vr : " + arbiter.surface_vr.x + "," + arbiter.surface_vr.y); + return true; + }, + + collisionPost : function ( arbiter, space ) { + cc.log('collision post'); + }, + + collisionSeparate : function ( arbiter, space ) { + cc.log('collision separate'); + }, + + title : function(){ + return 'Chipmunk Collision test'; + } +}); + + +//------------------------------------------------------------------ +// +// Chipmunk Collision Test +// Using "C" API. +// XXX DO NOT USE THE "C" API. +// XXX IT WAS ADDED FOR TESTING PURPOSES ONLY +// +//------------------------------------------------------------------ +var ChipmunkCollisionTestB = ChipmunkBaseLayer.extend( { + + ctor: function () { + this._super(); + // cc.base(this); + + this.messageDisplayed = false; + + this._title = 'Chipmunk Collision Test'; + this._subtitle = 'using "C"-like API. ** DO NOT USE THIS API **'; + }, + + // init physics + initPhysics : function() { + this.space = cp.spaceNew(); + + // update Physics Debug Node with new space + this._debugNode.setSpace(this.space); + + var staticBody = cp.spaceGetStaticBody( this.space ); + + // Walls using "C" API. DO NO USE THIS API + var walls = [cp.segmentShapeNew( staticBody, cp.v(0,0), cp.v(winSize.width,0), 0 ), // bottom + cp.segmentShapeNew( staticBody, cp.v(0,winSize.height), cp.v(winSize.width,winSize.height), 0), // top + cp.segmentShapeNew( staticBody, cp.v(0,0), cp.v(0,winSize.height), 0), // left + cp.segmentShapeNew( staticBody, cp.v(winSize.width,0), cp.v(winSize.width,winSize.height), 0) // right + ]; + + for( var i=0; i < walls.length; i++ ) { + // 'properties' using "C" API. DO NO USE THIS API + var wall = walls[i]; + cp.shapeSetElasticity(wall, 1); + cp.shapeSetFriction(wall, 1); + cp.spaceAddStaticShape( this.space, wall ); + } + + // Gravity + cp.spaceSetGravity( this.space, cp.v(0, -30) ); + }, + + createPhysicsSprite : function( pos, file, collision_type ) { + // using "C" API. DO NO USE THIS API + var body = cp.bodyNew(1, cp.momentForBox(1, 48, 108) ); + cp.bodySetPos( body, pos ); + cp.spaceAddBody( this.space, body ); + var shape = cp.boxShapeNew( body, 48, 108); + cp.shapeSetElasticity( shape, 0.5 ); + cp.shapeSetFriction( shape, 0.5 ); + cp.shapeSetCollisionType( shape, collision_type ); + cp.spaceAddShape( this.space, shape ); + + var sprite = new cc.PhysicsSprite(file); + sprite.setBody( body ); + return sprite; + }, + + onEnter : function () { + ChipmunkBaseLayer.prototype.onEnter.call(this); + // cc.base(this, 'onEnter'); + + this.initPhysics(); + this.scheduleUpdate(); + + var sprite1 = this.createPhysicsSprite( cc.p(winSize.width/2, winSize.height-20), s_pathGrossini, 1); + var sprite2 = this.createPhysicsSprite( cc.p(winSize.width/2, 50), s_pathSister1, 2); + + this.addChild( sprite1 ); + this.addChild( sprite2 ); + + cp.spaceAddCollisionHandler( this.space, 1, 2, + this.collisionBegin.bind(this), + this.collisionPre.bind(this), + this.collisionPost.bind(this), + this.collisionSeparate.bind(this) ); + }, + + onExit : function() { + cp.spaceRemoveCollisionHandler( this.space, 1, 2 ); + cp.spaceFree( this.space ); + ChipmunkBaseLayer.prototype.onExit.call(this); + }, + + update : function( delta ) { + cp.spaceStep( this.space, delta ); + }, + + collisionBegin : function ( arbiter, space ) { + + if( ! this.messageDisplayed ) { + var label = new cc.LabelBMFont("Collision Detected", s_bitmapFontTest5_fnt); + this.addChild( label ); + label.x = winSize.width/2; + label.y = winSize.height/2 ; + this.messageDisplayed = true; + } + cc.log('collision begin'); + var bodies = cp.arbiterGetBodies( arbiter ); + var shapes = cp.arbiterGetShapes( arbiter ); + var collTypeA = cp.shapeGetCollisionType( shapes[0] ); + var collTypeB = cp.shapeGetCollisionType( shapes[1] ); + cc.log( 'Collision Type A:' + collTypeA ); + cc.log( 'Collision Type B:' + collTypeB ); + return true; + }, + + collisionPre : function ( arbiter, space ) { + cc.log('collision pre'); + return true; + }, + + collisionPost : function ( arbiter, space ) { + cc.log('collision post'); + }, + + collisionSeparate : function ( arbiter, space ) { + cc.log('collision separate'); + } +}); + + +//------------------------------------------------------------------ +// +// Chipmunk Collision Memory Leak Test +// +//------------------------------------------------------------------ +var ChipmunkCollisionMemoryLeakTest = ChipmunkBaseLayer.extend({ + + ctor : function() { + this._super(); + // cc.base(this); + + this._title = 'Chipmunk Memory Leak Test'; + this._subtitle = 'Testing possible memory leak on the collision handler. No visual feedback'; + }, + + collisionBegin : function ( arbiter, space ) { + return true; + }, + + collisionPre : function ( arbiter, space ) { + return true; + }, + + collisionPost : function ( arbiter, space ) { + cc.log('collision post'); + }, + + collisionSeparate : function ( arbiter, space ) { + cc.log('collision separate'); + }, + + onEnter : function() { + ChipmunkBaseLayer.prototype.onEnter.call(this); + // cc.base(this, 'onEnter'); + + for( var i=1 ; i < 100 ; i++ ) + this.space.addCollisionHandler( i, i+1, + this.collisionBegin.bind(this), + this.collisionPre.bind(this), + this.collisionPost.bind(this), + this.collisionSeparate.bind(this) + ); + + }, + + onExit : function() { + ChipmunkBaseLayer.prototype.onExit.call(this); + + for( var i=1 ; i < 100 ; i++ ) + this.space.removeCollisionHandler( i, i+1 ); + }, + + title : function(){ + return 'Chipmunk Memory Leak Test'; + } +}); + +//------------------------------------------------------------------ +// +// Test Anchor Point with PhysicsSprite +// +//------------------------------------------------------------------ +var ChipmunkSpriteAnchorPoint = ChipmunkBaseLayer.extend({ + + ctor : function() { + this._super(); + // cc.base(this); + + this._title = 'AnchorPoint in PhysicsSprite'; + this._subtitle = 'Tests AnchorPoint in PhysicsSprite. See animated sprites'; + }, + + onEnter : function() { + ChipmunkBaseLayer.prototype.onEnter.call(this); + // cc.base(this, 'onEnter'); + + this._debugNode.visible = true ; + + this.space.gravity = v(0, 0); + + var sprite1 = this.createPhysicsSprite( cp.v(winSize.width/4*1, winSize.height/2) ); + var sprite2 = this.createPhysicsSprite( cp.v(winSize.width/4*2, winSize.height/2) ); + var sprite3 = this.createPhysicsSprite( cp.v(winSize.width/4*3, winSize.height/2) ); + + sprite1.anchorX = 0; + sprite1.anchorY = 0; + sprite2.anchorX = 0.5; + sprite2.anchorY = 0.5; + sprite3.anchorX = 1; + sprite3.anchorY = 1; + + // scale sprite + var scaledown = cc.scaleBy(0.5, 0.5); + var scaleup = scaledown.reverse(); + var seq = cc.sequence( scaledown, scaleup); + var repeat = seq.repeatForever(); + + sprite1.runAction( repeat ); + sprite2.runAction( repeat.clone() ); + sprite3.runAction( repeat.clone() ); + + this.addChild(sprite1); + this.addChild(sprite2); + this.addChild(sprite3); + + this.scheduleUpdate(); + }, + + title : function(){ + return 'AnchorPoint in PhysicsSprite'; + }, + + createPhysicsSprite : function(pos) { + + // create body + var body = new cp.Body(1, cp.momentForBox(1, 48, 108) ); + body.setPos( pos ); + this.space.addBody( body ); + + // create shape + var shape = new cp.BoxShape( body, 48, 108); + shape.setElasticity( 0.5 ); + shape.setFriction( 0.5 ); + this.space.addShape( shape ); + + // create sprite + var sprite = new cc.PhysicsSprite(s_pathGrossini); + + // associate sprite with body + sprite.setBody( body ); + + return sprite; + }, + + update : function(dt) { + var steps = 1; + dt /= steps; + for (var i = 0; i < steps; i++){ + this.space.step(dt); + } + } +}); + + +//------------------------------------------------------------------ +// +// ChipmunkReleaseTest +// +//------------------------------------------------------------------ +var ChipmunkReleaseTest = ChipmunkBaseLayer.extend({ + + ctor : function () { + this._super(); + // cc.base(this); + + this._title = 'Chipmunk Release Test'; + this._subtitle = 'Space finalizer should be called'; + }, + + collisionBegin : function ( arbiter, space ) { + return true; + }, + + collisionPre : function ( arbiter, space ) { + return true; + }, + + collisionPost : function ( arbiter, space ) { + cc.log('collision post'); + }, + + collisionSeparate : function ( arbiter, space ) { + cc.log('collision separate'); + }, + + onEnter : function() { + ChipmunkBaseLayer.prototype.onEnter.call(this); + // cc.base(this, 'onEnter'); + + cc.log("OnEnter"); + cc.sys.dumpRoot(); + cc.sys.garbageCollect(); + + this.space.addCollisionHandler( 10,11, + this.collisionBegin.bind(this), + this.collisionPre.bind(this), + this.collisionPost.bind(this), + this.collisionSeparate.bind(this) + ); + + }, + + onExit : function() { + + cc.log("OnExit"); + + // not calling this on purpose + // this.space.removeCollisionHandler( 10, 11 ); + + this.space = null; + + cc.sys.dumpRoot(); + cc.sys.garbageCollect(); + + // cc.base(this, 'onExit'); + ChipmunkBaseLayer.prototype.onExit.call(this); + } +}); + +// +// Base class for Chipmunk Demo +// +// Chipmunk Demos from Chipmunk-JS project +// https://github.com/josephg/chipmunk-js +// + +var v = cp.v; +var ctx; +var GRABABLE_MASK_BIT = 1<<31; +var NOT_GRABABLE_MASK = ~GRABABLE_MASK_BIT; + +var ChipmunkDemo = ChipmunkBaseLayer.extend( { + ctor : function () { + this._super(); + //cc.base(this); + + this.remainder = 0; + + // debug only + this._debugNode.visible = true ; + + this.scheduleUpdate(); + }, + + update : function(dt) { + this.space.step(dt); + }, + + addFloor : function() { + var space = this.space; + var floor = space.addShape(new cp.SegmentShape(space.staticBody, v(0, 0), v(640, 0), 0)); + floor.setElasticity(1); + floor.setFriction(1); + floor.setLayers(NOT_GRABABLE_MASK); + }, + + addWalls : function() { + var space = this.space; + var wall1 = space.addShape(new cp.SegmentShape(space.staticBody, v(0, 0), v(0, 480), 0)); + wall1.setElasticity(1); + wall1.setFriction(1); + wall1.setLayers(NOT_GRABABLE_MASK); + + var wall2 = space.addShape(new cp.SegmentShape(space.staticBody, v(640, 0), v(640, 480), 0)); + wall2.setElasticity(1); + wall2.setFriction(1); + wall2.setLayers(NOT_GRABABLE_MASK); + } +}); + +//------------------------------------------------------------------ +// +// Chipmunk Demo: Pyramid Stack +// +//------------------------------------------------------------------ +var PyramidStack = ChipmunkDemo.extend( { + + ctor : function () { + this._super(); + // cc.base(this); + this._subtitle = 'Chipmunk Demo'; + this._title = 'Pyramid Stack'; + + var space = this.space; + //space.iterations = 30; + space.gravity = v(0, -100); + space.sleepTimeThreshold = 0.5; + space.collisionSlop = 0.5; + + var body, staticBody = space.staticBody; + var shape; + + this.addFloor(); + this.addWalls(); + + // Add lots of boxes. + for(var i=0; i<14; i++){ + for(var j=0; j<=i; j++){ + body = space.addBody(new cp.Body(1, cp.momentForBox(1, 30, 30))); + body.setPos(v(j*32 - i*16 + 320, 540 - i*32)); + + shape = space.addShape(new cp.BoxShape(body, 30, 30)); + shape.setElasticity(0); + shape.setFriction(0.8); + } + } + + // Add a ball to make things more interesting + var radius = 15; + body = space.addBody(new cp.Body(10, cp.momentForCircle(10, 0, radius, v(0,0)))); + body.setPos(v(320, radius+5)); + + shape = space.addShape(new cp.CircleShape(body, radius, v(0,0))); + shape.setElasticity(0); + shape.setFriction(0.9); + }, + + title : function(){ + return 'Pyramid Stack'; + } +}); + +//------------------------------------------------------------------ +// +// Chipmunk Demo: Pyramid Topple +// +//------------------------------------------------------------------ +var PyramidTopple = ChipmunkDemo.extend( { + + ctor : function() { + this._super(); + // cc.base(this); + this._subtitle = 'Chipmunk Demo'; + this._title = 'Pyramid Topple'; + + var WIDTH = 4; + var HEIGHT = 30; + + var space = this.space; + + var add_domino = function(pos, flipped) + { + var mass = 1; + var moment = cp.momentForBox(mass, WIDTH, HEIGHT); + + var body = space.addBody(new cp.Body(mass, moment)); + body.setPos(pos); + + var shape = (flipped ? new cp.BoxShape(body, HEIGHT, WIDTH) : new cp.BoxShape(body, WIDTH, HEIGHT)); + space.addShape(shape); + shape.setElasticity(0); + shape.setFriction(0.6); + }; + + space.iterations = 30; + space.gravity = v(0, -300); + space.sleepTimeThreshold = 0.5; + space.collisionSlop = 0.5; + + this.addFloor(); + + // Add the dominoes. + var n = 12; + for(var i=0; i= 0; y -= 120) { + shape = space.addShape(new cp.SegmentShape(staticBody, v(0,y), v(640,y), 0)); + shape.setElasticity(1); + shape.setFriction(1); + shape.layers = NOT_GRABABLE_MASK; + } + + for(var x = 0; x <= 640; x += 160) { + shape = space.addShape(new cp.SegmentShape(staticBody, v(x,0), v(x,480), 0)); + shape.setElasticity(1); + shape.setFriction(1); + shape.layers = NOT_GRABABLE_MASK; + } + + var body1, body2; + + var posA = v( 50, 60); + var posB = v(110, 60); + + var POS_A = function() { return cp.v.add(boxOffset, posA); }; + var POS_B = function() { return cp.v.add(boxOffset, posB); }; + //#define POS_A vadd(boxOffset, posA) + //#define POS_B vadd(boxOffset, posB) + + this.labels = labels = []; + var label = function(text) { + labels.push({text:text, pos:boxOffset}); + }; + + // Pin Joints - Link shapes with a solid bar or pin. + // Keeps the anchor points the same distance apart from when the joint was created. + boxOffset = v(0, 0); + label('Pin Joint'); + body1 = addBall(posA); + body2 = addBall(posB); + body2.setAngle(Math.PI); + var pinJoint = new cp.PinJoint(body1, body2, v(15,0), v(15,0)); + space.addConstraint(pinJoint); + cc.log("pin joint anchr1 : " + pinJoint.anchr1.x + "," + pinJoint.anchr1.y); + cc.log("pin joint anchr2 : " + pinJoint.anchr2.x + "," + pinJoint.anchr2.y); + cc.log("pin joint dist : " + pinJoint.dist); + + // Slide Joints - Like pin joints but with a min/max distance. + // Can be used for a cheap approximation of a rope. + boxOffset = v(160, 0); + label('Slide Joint'); + body1 = addBall(posA); + body2 = addBall(posB); + body2.setAngle(Math.PI); + var slideJoint = new cp.SlideJoint(body1, body2, v(15,0), v(15,0), 20, 40); + space.addConstraint(slideJoint); + cc.log("slide joint anchr1 : " + slideJoint.anchr1.x + "," + slideJoint.anchr1.y); + cc.log("slide joint anchr2 : " + slideJoint.anchr2.x + "," + slideJoint.anchr2.y); + cc.log("slide joint min : " + slideJoint.min); + cc.log("slide joint max : " + slideJoint.max); + + // Pivot Joints - Holds the two anchor points together. Like a swivel. + boxOffset = v(320, 0); + label('Pivot Joint'); + body1 = addBall(posA); + body2 = addBall(posB); + body2.setAngle(Math.PI); + // cp.PivotJoint(a, b, v) takes it's anchor parameter in world coordinates. The anchors are calculated from that + // Alternately, specify two anchor points using cp.PivotJoint(a, b, anch1, anch2) + var pivotJoint = new cp.PivotJoint(body1, body2, cp.v.add(boxOffset, v(80,60))); + space.addConstraint(pivotJoint); + cc.log("pivot joint anchr1 : " + pivotJoint.anchr1.x + "," + pivotJoint.anchr1.y); + cc.log("pivot joint anchr2 : " + pivotJoint.anchr2.x + "," + pivotJoint.anchr2.y); + + // Groove Joints - Like a pivot joint, but one of the anchors is a line segment that the pivot can slide in + boxOffset = v(480, 0); + label('Groove Joint'); + body1 = addBall(posA); + body2 = addBall(posB); + var grooveJoint = new cp.GrooveJoint(body1, body2, v(30,30), v(30,-30), v(-30,0)); + space.addConstraint(grooveJoint); + cc.log("groove joint anchr2 : " + grooveJoint.anchr2.x + "," + grooveJoint.anchr2.y); + cc.log("groove joint grv_a : " +grooveJoint.grv_a.x + "," + grooveJoint.grv_a.y); + cc.log("groove joint grv_b : " +grooveJoint.grv_b.x + "," + grooveJoint.grv_b.y); + + // Damped Springs + boxOffset = v(0, 120); + label('Damped Spring'); + body1 = addBall(posA); + body2 = addBall(posB); + body2.setAngle(Math.PI); + var dampedSpring = new cp.DampedSpring(body1, body2, v(15,0), v(15,0), 20, 5, 0.3); + space.addConstraint(dampedSpring); + cc.log("damped spring anchr1 : " + dampedSpring.anchr1.x + "," + dampedSpring.anchr1.y); + cc.log("damped spring anchr2 : " + dampedSpring.anchr2.x + "," + dampedSpring.anchr2.y); + cc.log("damped spring damping : " + dampedSpring.damping); + cc.log("damped spring restLength : " + dampedSpring.restLength); + cc.log("damped spring stiffness : " + dampedSpring.stiffness); + + // Damped Rotary Springs + boxOffset = v(160, 120); + label('Damped Rotary Spring'); + body1 = addBar(posA); + body2 = addBar(posB); + // Add some pin joints to hold the circles in place. + space.addConstraint(new cp.PivotJoint(body1, staticBody, POS_A())); + space.addConstraint(new cp.PivotJoint(body2, staticBody, POS_B())); + var dampedRotarySpring = new cp.DampedRotarySpring(body1, body2, 0, 3000, 60); + space.addConstraint(dampedRotarySpring); + cc.log("damped rotary spring restAngle : " + dampedRotarySpring.restAngle); + cc.log("damped rotary spring stiffness : " + dampedRotarySpring.stiffness); + cc.log("damped rotary spring damping : " + dampedRotarySpring.damping); + + // Rotary Limit Joint + boxOffset = v(320, 120); + label('Rotary Limit Joint'); + body1 = addLever(posA); + body2 = addLever(posB); + // Add some pin joints to hold the circles in place. + space.addConstraint(new cp.PivotJoint(body1, staticBody, POS_A())); + space.addConstraint(new cp.PivotJoint(body2, staticBody, POS_B())); + // Hold their rotation within 90 degrees of each other. + var rotaryLimitJoint = new cp.RotaryLimitJoint(body1, body2, -Math.PI/2, Math.PI/2); + space.addConstraint(rotaryLimitJoint); + cc.log("rotary limit joint min : " + rotaryLimitJoint.min); + cc.log("rotary limit joint max : " + rotaryLimitJoint.max); + + // Ratchet Joint - A rotary ratchet, like a socket wrench + boxOffset = v(480, 120); + label('Ratchet Joint'); + body1 = addLever(posA); + body2 = addLever(posB); + // Add some pin joints to hold the circles in place. + space.addConstraint(new cp.PivotJoint(body1, staticBody, POS_A())); + space.addConstraint(new cp.PivotJoint(body2, staticBody, POS_B())); + // Ratchet every 90 degrees + var ratchet = new cp.RatchetJoint(body1, body2, 0, Math.PI/2); + space.addConstraint(ratchet); + cc.log("ratchet phase : " + ratchet.phase); + cc.log("ratchet ratchet : " + ratchet.ratchet); + cc.log("ratchet angle : " + ratchet.angle); + + // Gear Joint - Maintain a specific angular velocity ratio + boxOffset = v(0, 240); + label('Gear Joint'); + body1 = addBar(posA); + body2 = addBar(posB); + // Add some pin joints to hold the circles in place. + space.addConstraint(new cp.PivotJoint(body1, staticBody, POS_A())); + space.addConstraint(new cp.PivotJoint(body2, staticBody, POS_B())); + // Force one to sping 2x as fast as the other + var gearJoint = new cp.GearJoint(body1, body2, 0, 2); + space.addConstraint(gearJoint); + cc.log("gear joint phase : " + gearJoint.phase); + cc.log("gear jonit ratio : " + gearJoint.ratio); + + // Simple Motor - Maintain a specific angular relative velocity + boxOffset = v(160, 240); + label('Simple Motor'); + body1 = addBar(posA); + body2 = addBar(posB); + // Add some pin joints to hold the circles in place. + space.addConstraint(new cp.PivotJoint(body1, staticBody, POS_A())); + space.addConstraint(new cp.PivotJoint(body2, staticBody, POS_B())); + // Make them spin at 1/2 revolution per second in relation to each other. + var simpleMotor = new cp.SimpleMotor(body1, body2, Math.PI); + space.addConstraint(simpleMotor); + cc.log("simple motor rate : " + simpleMotor.rate); + + // Make a car with some nice soft suspension + boxOffset = v(320, 240); + var wheel1 = addWheel(posA); + var wheel2 = addWheel(posB); + var chassis = addChassis(v(80, 100)); + + space.addConstraint(new cp.GrooveJoint(chassis, wheel1, v(-30, -10), v(-30, -40), v(0,0))); + space.addConstraint(new cp.GrooveJoint(chassis, wheel2, v( 30, -10), v( 30, -40), v(0,0))); + + space.addConstraint(new cp.DampedSpring(chassis, wheel1, v(-30, 0), v(0,0), 50, 20, 10)); + space.addConstraint(new cp.DampedSpring(chassis, wheel2, v( 30, 0), v(0,0), 50, 20, 10)); + }, + + title : function(){ + return 'Joints'; + } +}); + +//------------------------------------------------------------------ +// +// Chipmunk Demo: Balls +// +//------------------------------------------------------------------ +var Balls = ChipmunkDemo.extend({ + ctor: function() { + this._super(); + // cc.base(this); + this._subtitle = 'Chipmunk Demo'; + this._title = 'Balls'; + + var space = this.space; + space.iterations = 60; + space.gravity = v(0, -500); + space.sleepTimeThreshold = 0.5; + space.collisionSlop = 0.5; + space.sleepTimeThreshold = 0.5; + + this.addFloor(); + this.addWalls(); + + var width = 50; + var height = 60; + var mass = width * height * 1/1000; + var rock = space.addBody(new cp.Body(mass, cp.momentForBox(mass, width, height))); + rock.setPos(v(500, 100)); + rock.setAngle(1); + shape = space.addShape(new cp.BoxShape(rock, width, height)); + shape.setFriction(0.3); + shape.setElasticity(0.3); + + for (var i = 1; i <= 10; i++) { + var radius = 20; + mass = 3; + var body = space.addBody(new cp.Body(mass, cp.momentForCircle(mass, 0, radius, v(0, 0)))); + body.setPos(v(200 + i, (2 * radius + 5) * i)); + var circle = space.addShape(new cp.CircleShape(body, radius, v(0, 0))); + circle.setElasticity(0.8); + circle.setFriction(1); + } + /* + * atom.canvas.onmousedown = function(e) { + radius = 10; + mass = 3; + body = space.addBody(new cp.Body(mass, cp.momentForCircle(mass, 0, radius, v(0, 0)))); + body.setPos(v(e.clientX, e.clientY)); + circle = space.addShape(new cp.CircleShape(body, radius, v(0, 0))); + circle.setElasticity(0.5); + return circle.setFriction(1); + }; + */ + + // this.ctx.strokeStyle = "black"; + + var ramp = space.addShape(new cp.SegmentShape(space.staticBody, v(100, 100), v(300, 200), 10)); + ramp.setElasticity(1); + ramp.setFriction(1); + ramp.setLayers(NOT_GRABABLE_MASK); + }, + + title : function(){ + return 'Balls'; + } +}); + + +//------------------------------------------------------------------ +// +// Buoyancy +// +//------------------------------------------------------------------ + +var FLUID_DENSITY = 0.00014; +var FLUID_DRAG = 2.0; + +var Buoyancy = ChipmunkDemo.extend( { + ctor: function() { + this._super(); + // cc.base(this); + this._subtitle = 'Chipmunk Demo'; + this._title = 'Buoyancy'; + + var space = this.space; + space.iterations = 30; + space.gravity = cp.v(0,-500); + // cpSpaceSetDamping(space, 0.5); + space.sleepTimeThreshold = 0.5; + space.collisionSlop = 0.5; + + var staticBody = space.staticBody; + + // Create segments around the edge of the screen. + var shape = space.addShape( new cp.SegmentShape(staticBody, cp.v(0,0), cp.v(0,480), 0.0)); + shape.setElasticity(1.0); + shape.setFriction(1.0); + shape.setLayers(NOT_GRABABLE_MASK); + + shape = space.addShape( new cp.SegmentShape(staticBody, cp.v(640,0), cp.v(640,480), 0.0)); + shape.setElasticity(1.0); + shape.setFriction(1.0); + shape.setLayers(NOT_GRABABLE_MASK); + + shape = space.addShape( new cp.SegmentShape(staticBody, cp.v(0,0), cp.v(640,0), 0.0)); + shape.setElasticity(1.0); + shape.setFriction(1.0); + shape.setLayers(NOT_GRABABLE_MASK); + + shape = space.addShape( new cp.SegmentShape(staticBody, cp.v(0,480), cp.v(640,480), 0.0)); + shape.setElasticity(1.0); + shape.setFriction(1.0); + shape.setLayers(NOT_GRABABLE_MASK); + + // { + // Add the edges of the bucket + var bb = new cp.BB(20, 40, 420, 240); + var radius = 5.0; + + shape = space.addShape( new cp.SegmentShape(staticBody, cp.v(bb.l, bb.b), cp.v(bb.l, bb.t), radius)); + shape.setElasticity(1.0); + shape.setFriction(1.0); + shape.setLayers(NOT_GRABABLE_MASK); + + shape = space.addShape( new cp.SegmentShape(staticBody, cp.v(bb.r, bb.b), cp.v(bb.r, bb.t), radius)); + shape.setElasticity(1.0); + shape.setFriction(1.0); + shape.setLayers(NOT_GRABABLE_MASK); + + shape = space.addShape( new cp.SegmentShape(staticBody, cp.v(bb.l, bb.b), cp.v(bb.r, bb.b), radius)); + shape.setElasticity(1.0); + shape.setFriction(1.0); + shape.setLayers(NOT_GRABABLE_MASK); + + // Add the sensor for the water. + shape = space.addShape( new cp.BoxShape2(staticBody, bb) ); + shape.setSensor(true); + shape.setCollisionType(1); + // } + + + // { + var width = 200.0; + var height = 50.0; + var mass = 0.3*FLUID_DENSITY*width*height; + var moment = cp.momentForBox(mass, width, height); + + body = space.addBody( new cp.Body(mass, moment)); + body.setPos( cp.v(270, 140)); + body.setVel( cp.v(0, -100)); + body.setAngVel( 1 ); + + shape = space.addShape( new cp.BoxShape(body, width, height)); + shape.setFriction(0.8); + // } + + // { + width = 40.0; + height = width*2; + mass = 0.3*FLUID_DENSITY*width*height; + moment = cp.momentForBox(mass, width, height); + + body = space.addBody( new cp.Body(mass, moment)); + body.setPos(cp.v(120, 190)); + body.setVel(cp.v(0, -100)); + body.setAngVel(1); + + shape = space.addShape(new cp.BoxShape(body, width, height)); + shape.setFriction(0.8); + // } + }, + + update: function(dt) { + var steps = 3; + dt /= steps; + for (var i = 0; i < 3; i++){ + this.space.step(dt); + } + }, + + onEnter: function() { + this._super(); + this.space.addCollisionHandler( 1, 0, null, this.waterPreSolve, null, null); + }, + + onExit: function() { + this.space.removeCollisionHandler(1, 0); + this._super(); + }, + + title: function() { + return 'Buoyancy'; + }, + + waterPreSolve : function(arb, space, ptr) { + var shapes = arb.getShapes(); + var water = shapes[0]; + var poly = shapes[1]; + + var body = poly.getBody(); + + // Get the top of the water sensor bounding box to use as the water level. + var level = water.getBB().t; + + // Clip the polygon against the water level + var count = poly.getNumVerts(); + + var clipped = []; + + var j=count-1; + for(var i=0; i>3) + y*image_row_length]>>(~x&0x7)) & 1; + }; + + var make_ball = function(x, y) + { + var body = new cp.Body(1, Infinity); + body.setPos(cp.v(x, y)); + + var shape = new cp.CircleShape(body, 0.95, cp.vzero); + shape.setElasticity(0); + shape.setFriction(0); + + return shape; + }; + + return ChipmunkBaseLayer.extend({ + ctor:function(){ + this._super(); + this._title = "LogoSmash"; + this._subtitle = "Chipmunk Demo"; + + var space = this.space; + space.setIterations(1); + + // The space will contain a very large number of similary sized objects. + // This is the perfect candidate for using the spatial hash. + // Generally you will never need to do this. + // + // (... Except the spatial hash isn't implemented in JS) + // but it is implemented in JSB :) + if(cc.sys.isNative) + space.useSpatialHash(2.0, 10000); + + var batch = new cc.SpriteBatchNode(s_hole_stencil_png); + this.addChild(batch); + + var body; + var shape; + var sprite; + + for(var y=0; y= 1) { + this.setMenuItemEnabled(true); + } + } +}); + +//------------------------------------------------------------------ +// +// TestDirectLoading +// +//------------------------------------------------------------------ +var TestDirectLoading = ArmatureTestLayer.extend({ + onEnter:function () { + this._super(); + // remove sigle resource + ccs.armatureDataManager.removeArmatureFileInfo(s_bear_json); + // load resource directly + ccs.armatureDataManager.addArmatureFileInfo(s_bear_json); + + var armature = new ccs.Armature("bear"); + armature.getAnimation().playWithIndex(0); + armature.anchorX = 0.5; + armature.anchorY = 0.5; + armature.x = winSize.width / 2; + armature.y = winSize.height / 2; + armature.runAction(cc.sequence(cc.tintTo(5, 200,100,0), cc.tintTo(5, 255,255,255))); + this.addChild(armature); + }, + title:function () { + return "Test Direct Loading"; + } +}); + +//------------------------------------------------------------------ +// +// TestCSWithSkeleton +// +//------------------------------------------------------------------ +var TestCSWithSkeleton = ArmatureTestLayer.extend({ + onEnter:function () { + this._super(); + ccs.armatureDataManager.addArmatureFileInfo(s_Cowboy_json); + + var armature = new ccs.Armature("Cowboy"); + armature.getAnimation().playWithIndex(0); + armature.scale = 0.2; + armature.anchorX = 0.5; + armature.anchorY = 0.5; + armature.x = winSize.width / 2; + armature.y = winSize.height / 2; + this.addChild(armature); + }, + title:function () { + return "Test Export From CocoStudio With Skeleton Effect"; + } +}); + +//------------------------------------------------------------------ +// +// TestDragonBones20 +// +//------------------------------------------------------------------ +var TestDragonBones20 = ArmatureTestLayer.extend({ + onEnter:function () { + this._super(); + ccs.armatureDataManager.addArmatureFileInfo(s_Dragon_png, s_Dragon_plist, s_Dragon_xml); + var armature = new ccs.Armature("Dragon"); + armature.getAnimation().playWithIndex(0); + armature.getAnimation().setSpeedScale(0.4); + armature.scale = 0.6; + armature.anchorX = 0.5; + armature.anchorY = 0.5; + armature.x = winSize.width / 2; + armature.y = winSize.height / 2; + this.addChild(armature); + }, + title:function () { + return "Test Export From DragonBones version 2.0"; + } +}); + +//------------------------------------------------------------------ +// +// TestPerformance +// +//------------------------------------------------------------------ +var ArmaturePerformanceTag = 20000; +var TestPerformance = ArmatureTestLayer.extend({ + armatureCount: 0, + onEnter: function () { + this._super(); + ccs.armatureDataManager.addArmatureFileInfo(s_knight_png, s_knight_plist, s_knight_xml); + cc.MenuItemFont.setFontSize(65); + var decrease = new cc.MenuItemFont(" - ", this.onDecrease, this); + decrease.color = cc.color(0, 200, 20); + var increase = new cc.MenuItemFont(" + ", this.onIncrease, this); + increase.color = cc.color(0, 200, 20); + + var menu = new cc.Menu(decrease, increase); + menu.alignItemsHorizontally(); + menu.x = cc.visibleRect.width / 2; + menu.y = cc.visibleRect.height - 100; + this.addChild(menu, 10000); + + }, + title: function () { + return "Test Performance"; + }, + subtitle: function () { + return "Current CCArmature Count :"; + }, + onIncrease: function (sender) { + this.addArmature(20); + }, + onDecrease: function (sender) { + if (this.armatureCount == 0) + return; + + for (var i = 0; i < 20; i++) { + this.removeArmatureFromParent(ArmaturePerformanceTag + this.armatureCount); + this.armatureCount--; + this.refreshTitile(); + } + }, + addArmature: function (number) { + for (var i = 0; i < number; i++) { + this.armatureCount++; + var armature = new ccs.Armature("Knight_f/Knight"); + armature.getAnimation().playWithIndex(0); + armature.x = 50 + this.armatureCount * 2; + armature.y = 150; + armature.scale = 0.6; + this.addArmatureToParent(armature); + } + this.refreshTitile(); + }, + addArmatureToParent: function (armature) { + this.addChild(armature, 0, ArmaturePerformanceTag + this.armatureCount); + }, + removeArmatureFromParent: function (tag) { + this.removeChildByTag(tag); + }, + refreshTitile: function () { + var subTile = this.getChildByTag(BASE_TEST_SUBTITLE_TAG); + subTile.setString(this.subtitle() + this.armatureCount); + } +}); + +//------------------------------------------------------------------ +// +// TestPerformanceBatchNode +// +//------------------------------------------------------------------ +var TestPerformanceBatchNode = TestPerformance.extend({ + batchNode: null, + onEnter: function () { + this._super(); + this.batchNode = new ccs.BatchNode(); + this.addChild(this.batchNode); + }, + title: function () { + return "Test Performance of using CCBatchNode"; + }, + addArmatureToParent: function (armature) { + this.batchNode.addChild(armature, 0, ArmaturePerformanceTag + this.armatureCount); + }, + removeArmatureFromParent: function (tag) { + this.batchNode.removeChildByTag(tag); + } +}); + +//------------------------------------------------------------------ +// +// TestChangeZorder +// +//------------------------------------------------------------------ +var TestChangeZorder = ArmatureTestLayer.extend({ + currentTag:0, + onEnter:function () { + this._super(); + var armature = null; + var armatureDataManager = ccs.armatureDataManager; + armatureDataManager.addArmatureFileInfo(s_knight_png, s_knight_plist, s_knight_xml); + armature = new ccs.Armature("Knight_f/Knight"); + armature.getAnimation().playWithIndex(0); + armature.x = winSize.width / 2; + armature.y = winSize.height / 2 - 100; + armature.scale = 0.6; + this.addChild(armature, 0, 0); + + armatureDataManager.addArmatureFileInfo(s_Cowboy_json); + armature = new ccs.Armature("Cowboy"); + armature.getAnimation().playWithIndex(0); + armature.scale = 0.24; + armature.x = winSize.width / 2; + armature.y = winSize.height / 2 - 100; + this.addChild(armature, 1, 1); + + armatureDataManager.addArmatureFileInfo(s_Dragon_png, s_Dragon_plist, s_Dragon_xml); + armature = new ccs.Armature("Dragon"); + armature.getAnimation().playWithIndex(0); + armature.x = winSize.width / 2; + armature.y = winSize.height / 2 - 100; + armature.scale = 0.6; + this.addChild(armature, 2, 2); + + this.schedule(this.changeZorder, 1); + }, + title:function () { + return "Test Change ZOrder Of Different CCArmature"; + }, + changeZorder:function (dt) { + var node = this.getChildByTag(this.currentTag); + node.zIndex = Math.random() * 3; + this.currentTag++; + this.currentTag = this.currentTag % 3; + } + +}); + +//------------------------------------------------------------------ +// +// TestAnimationEvent +// +//------------------------------------------------------------------ +var TestAnimationEvent = ArmatureTestLayer.extend({ + _armature:null, + _direction:1, + onEnter:function () { + this._super(); + + ccs.armatureDataManager.addArmatureFileInfo(s_Cowboy_json); + this._armature = new ccs.Armature("Cowboy"); + this._armature.getAnimation().play("Fire"); + this._armature.scaleX = -0.25; + this._armature.scaleY = 0.25; + this._armature.x = winSize.width / 2 - 150; + this._armature.y = winSize.height / 2; + var self = this; + this._armature.getAnimation().setMovementEventCallFunc(function(armature, movementType, movementID) { + self.animationEvent(armature, movementType, movementID); + }); + this.addChild(this._armature); + + this._direction = 1; + + }, + title:function () { + return "Test Armature Animation Event"; + }, + animationEvent:function (armature, movementType, movementID) { + if (movementType == ccs.MovementEventType.loopComplete) { + if (movementID == "Fire") { + var moveBy = cc.moveBy(2, cc.p(300 * this._direction, 0)); + this._armature.stopAllActions(); + this._armature.runAction(cc.sequence(moveBy, cc.callFunc(this.callback, this))); + this._armature.getAnimation().play("Walk"); + + this._direction *= -1; + } + } + }, + callback:function () { + this._armature.runAction(cc.scaleTo(0.3, 0.25 * this._direction * -1, 0.25)); + this._armature.getAnimation().play("Fire", 10); + } +}); + +//------------------------------------------------------------------ +// +// TestAnimationEvent +// +//------------------------------------------------------------------ + +var FRAME_EVENT_ACTION_TAG = 10000; +var TestFrameEvent = ArmatureTestLayer.extend({ + _nodeGrid: null, + onEnter: function () { + this._super(); + ccs.armatureDataManager.addArmatureFileInfo(s_HeroAnimation_json); + var armature = new ccs.Armature("HeroAnimation"); + armature.getAnimation().play("attack"); + armature.getAnimation().setSpeedScale(0.5); + var center = cc.visibleRect.center; + armature.x = center.x - 50; + armature.y = center.y - 100; + + this._nodeGrid = new cc.NodeGrid(); + this._nodeGrid.addChild(armature); + this.addChild(this._nodeGrid); + /* + * Set armature's frame event callback function + * To disconnect this event, just setFrameEventCallFunc(NULL, NULL); + */ + var self = this; + armature.getAnimation().setFrameEventCallFunc(function(bone, evt, originFrameIndex, currentFrameIndex) { + self.onFrameEvent(bone, evt, originFrameIndex, currentFrameIndex); + }); + + this.schedule(this.checkAction); + }, + title: function () { + return "Test Frame Event"; + }, + onFrameEvent: function (bone, evt, originFrameIndex, currentFrameIndex) { + cc.log("(" + bone.getName() + ") emit a frame event (" + evt + ") at frame index (" + currentFrameIndex + ")."); + if (!this.getActionByTag(FRAME_EVENT_ACTION_TAG) || this.getActionByTag(FRAME_EVENT_ACTION_TAG).isDone()) { + if ("opengl" in cc.sys.capabilities) { + this.stopAllActions(); + var action = cc.shatteredTiles3D(0.2, cc.size(16, 12), 5, false); + action.tag = FRAME_EVENT_ACTION_TAG; + this._nodeGrid.runAction(action); + } + } + }, + checkAction: function (dt) { + if ("opengl" in cc.sys.capabilities) { + if (this._nodeGrid.getNumberOfRunningActions() == 0 && this._nodeGrid.grid != null) + this._nodeGrid.grid = null; + } + } +}); + +//------------------------------------------------------------------ +// +// TestParticleDisplay +// +//------------------------------------------------------------------ +var TestParticleDisplay = ArmatureTestLayer.extend({ + animationID:0, + armature:null, + ctor:function(){ + this._super(); + + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded: function (touches, event) { + var target = event.getCurrentTarget(); + ++target.animationID; + target.animationID = target.animationID % target.armature.getAnimation().getMovementCount(); + target.armature.getAnimation().playWithIndex(target.animationID,10); + return false; + } + }, this); + }, + onEnter:function () { + this._super(); + + this.animationID = 0; + + ccs.armatureDataManager.addArmatureFileInfo(s_robot_png, s_robot_plist, s_robot_xml); + this.armature = new ccs.Armature("robot"); + this.armature.getAnimation().playWithIndex(4); + var center = cc.visibleRect.center; + this.armature.x = center.x; + this.armature.y = center.y; + this.armature.scale = 0.48; + this.armature.getAnimation().setSpeedScale(0.5); + this.addChild(this.armature); + + var p1 = new cc.ParticleSystem("res/Particles/SmallSun.plist"); + p1.setTotalParticles(30); + var p2 = new cc.ParticleSystem("res/Particles/SmallSun.plist"); + p2.setTotalParticles(30); + var bone = new ccs.Bone("p1"); + bone.addDisplay(p1, 0); + bone.changeDisplayWithIndex(0, true); + bone.setIgnoreMovementBoneData(true); + bone.zIndex = 100; + bone.scale = 1.2; + this.armature.addBone(bone, "bady-a3"); + + bone = new ccs.Bone("p2"); + bone.addDisplay(p2, 0); + bone.changeDisplayWithIndex(0, true); + bone.setIgnoreMovementBoneData(true); + bone.zIndex = 100; + bone.scale = 1.2; + this.armature.addBone(bone, "bady-a30"); + }, + title:function () { + return "Test Particle Display"; + }, + subtitle:function () { + return "Touch to change animation"; + } +}); + +//------------------------------------------------------------------ +// +// TestUseMutiplePicture +// +//------------------------------------------------------------------ +var TestUseMutiplePicture = ArmatureTestLayer.extend({ + displayIndex:0, + armature:null, + ctor:function(){ + this._super(); + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded: this.onTouchesEnded.bind(this) + }, this); + }, + onEnter:function () { + this._super(); + this.displayIndex = 0; + var armatureDataManager = ccs.armatureDataManager; + armatureDataManager.addArmatureFileInfo(s_knight_png, s_knight_plist, s_knight_xml); + armatureDataManager.addArmatureFileInfo(s_weapon_png, s_weapon_plist, s_weapon_xml); + + this.armature = new ccs.Armature("Knight_f/Knight"); + this.armature.getAnimation().playWithIndex(0); + this.armature.x = winSize.width / 2; + this.armature.y = winSize.height / 2; + this.armature.scale = 1.2; + this.addChild(this.armature); + + var 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"]; + + //add skin + for (var i = 0; i < 7; i++) { + var skin = ccs.Skin.createWithSpriteFrameName(weapon[i]); + this.armature.getBone("weapon").addDisplay(skin, i); + } + + //add label + var label = new cc.LabelTTF("This is a weapon!", "Arial", 18); + label.anchorX = 0.2; + label.anchorY = 0.5; + this.armature.getBone("weapon").addDisplay(label, 7); + }, + title:function () { + return "Test One CCArmature Use Different Picture"; + }, + subtitle:function () { + return "Tap Screen"; + }, + onTouchesEnded:function (touch, event) { + ++this.displayIndex; + this.displayIndex = (this.displayIndex) % 8; + this.armature.getBone("weapon").changeDisplayWithIndex(this.displayIndex, true); + return false; + } +}); + +//------------------------------------------------------------------ +// +// TestColliderDetector +// +//------------------------------------------------------------------ +var TestColliderDetector = ArmatureTestLayer.extend({ + armature1:null, + armature2:null, + bullet:null, + space:null, + enemyTag: 1, + bulletTag: 2, + + onEnter:function () { + this._super(); + ccs.ENABLE_PHYSICS_CHIPMUNK_DETECT = true; + ccs.armatureDataManager.addArmatureFileInfo(s_Cowboy_json); + + this.armature1 = new ccs.Armature("Cowboy"); + this.armature1.getAnimation().play("FireWithoutBullet"); + this.armature1.getAnimation().setSpeedScale(0.2); + this.armature1.scaleX = -0.2; + this.armature1.scaleY = 0.2; + this.armature1.x = 170; + this.armature1.y = winSize.height / 2; + + /* + * Set armature's frame event callback function + * To disconnect this event, just setFrameEventCallFunc(nul, null); + */ + this.armature1.getAnimation().setFrameEventCallFunc(this.onFrameEvent,this); + + this.addChild(this.armature1); + + this.armature2 = new ccs.Armature("Cowboy"); + this.armature2.getAnimation().play("Walk"); + this.armature2.scaleX = -0.2; + this.armature2.scaleY = 0.2; + this.armature2.x = winSize.width - 160; + this.armature2.y = winSize.height / 2; + this.addChild(this.armature2); + + this.bullet = new cc.PhysicsSprite("#25.png"); + this.addChild(this.bullet); + + this.initWorld(); + this.scheduleUpdate(); + }, + initWorld:function(){ + this.space = new cp.Space(); + this.space.gravity = cp.v(0, 0); + + // Physics debug layer + var debugLayer = new cc.PhysicsDebugNode(this.space); + this.addChild(debugLayer, 9999); + + //init bullet body + var width = this.bullet.width, height = this.bullet.height; + var verts = [ + -width/2,-height/2, + -width/2,height/2, + width/2,height/2, + width/2,-height/2 + ]; + var body = new cp.Body(1, cp.momentForPoly(1,verts, cp.vzero)); + this.space.addBody(body); + var shape = new cp.PolyShape(body,verts, cp.vzero); + shape.collision_type = this.bulletTag; + this.space.addShape(shape); + this.bullet.setBody(body); + this.bullet.x = -100; + this.bullet.y = -100; + + //init armature body + body = new cp.Body(Infinity, Infinity); + this.space.addBody(body); + this.armature2.setBody(body); + var filter = new ccs.ColliderFilter(this.enemyTag); + this.armature2.setColliderFilter(filter); + //init collision handler + this.space.addCollisionHandler(this.enemyTag, this.bulletTag, this.beginHit.bind(this), null, null, this.endHit.bind(this)); + }, + onFrameEvent: function (bone, evt, originFrameIndex, currentFrameIndex) { + cc.log("(" + bone.getName() + ") emit a frame event (" + evt + ") at frame index (" + currentFrameIndex + ")."); + /* + * originFrameIndex is the frame index editted in Action Editor + * currentFrameIndex is the current index animation played to + * frame event may be delay emit, so originFrameIndex may be different from currentFrameIndex. + */ + var p = this.armature1.getBone("Layer126").getDisplayRenderNode().convertToWorldSpaceAR(cc.p(0, 0)); + this.bullet.x = p.x + 60; + this.bullet.y = p.y; + this.bullet.stopAllActions(); + this.bullet.runAction(cc.moveBy(1.5, cc.p(800, 0))); + }, + beginHit:function(arbiter, space){ + var shapes = arbiter.getShapes(); + var shapeA = shapes[0]; + var shapeB = shapes[1]; + var bone; + if(shapeA.collision_type==this.enemyTag) + bone = shapeA.data; + if(shapeB.collision_type==this.enemyTag) + bone = shapeB.data; + if(bone) + bone.getArmature().visible = false; + }, + + endHit:function(arbiter, space){ + var shapes = arbiter.getShapes(); + var shapeA = shapes[0]; + var shapeB = shapes[1]; + var bone; + if(shapeA.collision_type==this.enemyTag) + bone = shapeA.data; + if(shapeB.collision_type==this.enemyTag) + bone = shapeB.data; + if(bone) + bone.getArmature().visible = true; + }, + update:function(dt){ + this.space.step(dt); + }, + title:function () { + return "Test Collider Detector"; + }, + onExit:function(){ + this._super(); + var shapeList = this.armature2.getShapeList(); + for(var i = 0 ;i maxx ? vertex.x : maxx; + maxy = vertex.y > maxy ? vertex.y : maxy; + } + } + var temp = cc.rect(minx, miny, maxx - minx, maxy - miny); + + if (cc.rectContainsRect(temp, rect)) { + this.armature2.visible = false; + } + } + } + }, + draw: function () { + this.armature2.drawContour(); + }, + title: function () { + return "Test calculated vertex"; + }, + onExit:function(){ + this._super(); + ccs.ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX = false; + } +}); + +//------------------------------------------------------------------ +// +// TestBoundingBox +// +//------------------------------------------------------------------ +var TestBoundingBox = ArmatureTestLayer.extend({ + armature: null, + drawNode: null, + onEnter:function () { + var _this = this; + _this._super(); + + _this.drawNode = new cc.DrawNode(); + _this.drawNode.setDrawColor(cc.color(100,100,100,255)); + _this.addChild(_this.drawNode); + + ccs.armatureDataManager.addArmatureFileInfo(s_Cowboy_json); + + _this.armature = new ccs.Armature("Cowboy"); + _this.armature.getAnimation().playWithIndex(0); + _this.armature.x = winSize.width / 2; + _this.armature.y = winSize.height / 2; + _this.armature.scale = 0.2; + _this.addChild(_this.armature); + + _this.scheduleUpdate(); + }, + + title:function () { + return "Test BoundingBox"; + }, + update: function () { + var rect = this.armature.getBoundingBox(); + this.drawNode.clear(); + this.drawNode.drawRect(cc.p(rect.x, rect.y), cc.p(cc.rectGetMaxX(rect), cc.rectGetMaxY(rect))); + } +}); + +//------------------------------------------------------------------ +// +// TestAnchorPoint +// +//------------------------------------------------------------------ +var TestAnchorPoint = ArmatureTestLayer.extend({ + onEnter:function () { + this._super(); + ccs.armatureDataManager.addArmatureFileInfo(s_Cowboy_json); + for (var i = 0; i < 5; i++) { + var armature = new ccs.Armature("Cowboy"); + armature.getAnimation().playWithIndex(0); + armature.x = winSize.width / 2; + armature.y = winSize.height / 2; + armature.scale = 0.2; + this.addChild(armature, 0, i); + } + + this.getChildByTag(0).anchorX = 0; + this.getChildByTag(0).anchorY = 0; + this.getChildByTag(1).anchorX = 0; + this.getChildByTag(1).anchorY = 1; + this.getChildByTag(2).anchorX = 1; + this.getChildByTag(2).anchorY = 0; + this.getChildByTag(3).anchorX = 1; + this.getChildByTag(3).anchorY = 1; + this.getChildByTag(4).anchorX = 0.5; + this.getChildByTag(4).anchorY = 0.5; + }, + title:function () { + return "Test Set AnchorPoint"; + } +}); + +//------------------------------------------------------------------ +// +// TestArmatureNesting +// +//------------------------------------------------------------------ +var TestArmatureNesting = ArmatureTestLayer.extend({ + armature:null, + weaponIndex:0, + ctor:function(){ + this._super(); + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded: this.onTouchesEnded.bind(this) + }, this); + }, + onEnter:function () { + this._super(); + ccs.armatureDataManager.addArmatureFileInfo(s_cyborg_png, s_cyborg_plist, s_cyborg_xml); + this.armature = new ccs.Armature("cyborg"); + this.armature.getAnimation().playWithIndex(1); + this.armature.x = winSize.width / 2; + this.armature.y = winSize.height / 2; + this.armature.scale = 1.2; + this.armature.getAnimation().setSpeedScale(0.4); + this.addChild(this.armature); + this.weaponIndex = 0; + }, + title:function () { + return "Test CCArmature Nesting"; + }, + onTouchesEnded:function (touch, event) { + ++this.weaponIndex; + this.weaponIndex = this.weaponIndex % 4; + this.armature.getBone("armInside").getChildArmature().getAnimation().playWithIndex(this.weaponIndex); + this.armature.getBone("armOutside").getChildArmature().getAnimation().playWithIndex(this.weaponIndex); + } +}); + +//------------------------------------------------------------------ +// +// TestArmatureNesting2 +// +//------------------------------------------------------------------ +var Hero = ccs.Armature.extend({ + _mount: null, + _layer: null, + ctor: function () { + this._super(); + this._mount = null; + this._layer = null; + }, + + changeMount: function (armature) { + if (armature == null) { + this.retain(); + + this.playWithIndex(0); + //Remove hero from display list + this._mount.getBone("hero").removeDisplay(0); + this._mount.stopAllActions(); + + //Set position to current position + this.x = this._mount.x; + this.y = this._mount.y; + //Add to layer + this._layer.addChild(this); + this._mount = armature; + } + else { + this._mount = armature; + this.retain(); + //Remove from layer + this.removeFromParent(false); + + //Get the hero bone + var bone = armature.getBone("hero"); + //Add hero as a display to this bone + bone.addDisplay(this, 0); + //Change this bone's display + bone.changeDisplayWithIndex(0, true); + bone.setIgnoreMovementBoneData(true); + + this.x = 0; + + this.y = 0; + //Change animation + this.playWithIndex(1); + this.scale = 1; + } + + }, + + playWithIndex: function (index) { + this.getAnimation().playWithIndex(index); + if (this._mount) { + this._mount.getAnimation().playWithIndex(index); + } + }, + setLayer:function(layer){ + this._layer = layer; + }, + getLayer:function(){ + return this._layer; + }, + setMount:function(mount){ + this._mount = mount; + }, + getMount:function(){ + return this._mount; + } +}); + + +Hero.create = function(name){ + var hero = new Hero(); + if (hero && hero.init(name)) { + return hero; + } + return null; +}; + +var TestArmatureNesting2 = ArmatureTestLayer.extend({ + _hero: null, + _horse: null, + _horse2: null, + _bear: null, + _touchedMenu: false, + ctor:function(){ + this._super(); + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded: this.onTouchesEnded.bind(this) + }, this); + }, + onEnter: function () { + this._super(); + + this._touchedMenu = false; + var label = new cc.LabelTTF("Change Mount", "Arial", 20); + var menuItem = new cc.MenuItemLabel(label, this.changeMountCallback, this); + var menu = new cc.Menu(menuItem); + menu.x = 0; + menu.y = 0; + menuItem.x = cc.visibleRect.right.x - 67; + menuItem.y = cc.visibleRect.bottom.y + 50; + this.addChild(menu, 2); + + //Create a hero + var hero = Hero.create("hero"); + hero.setLayer(this); + hero.playWithIndex(0); + hero.x = cc.visibleRect.left.x + 20; + hero.y = cc.visibleRect.left.y; + this.addChild(hero); + this._hero = hero; + + //Create 3 mount + this._horse = this.createMount("horse", cc.visibleRect.center); + this._horse2 = this.createMount("horse", cc.p(120, 200)); + this._horse2.opacity = 200; + this._bear = this.createMount("bear", cc.p(300, 70)); + }, + title: function () { + return "Test CCArmature Nesting 2"; + }, + subtitle: function () { + return "Move to a mount and press the ChangeMount Button."; + }, + onTouchesEnded: function (touches, event) { + var point = touches[0].getLocation(); + var armature = this._hero.getMount() == null ? this._hero : this._hero.getMount(); + //Set armature direction + if (point.x < armature.x) { + armature.scaleX = -1; + } + else { + armature.scaleX = 1; + } + + var move = cc.moveTo(2, point); + armature.stopAllActions(); + armature.runAction(move); + return false; + }, + + changeMountCallback: function (sender) { + this._hero.stopAllActions(); + if (this._hero.getMount()) { + this._hero.changeMount(null); + } + else { + var heroPos = cc.p(this._hero.x, this._hero.y); + var horsePos = cc.p(this._horse.x, this._horse.y); + var horse2Pos = cc.p(this._horse2.x, this._horse2.y); + var bearPos = cc.p(this._bear.x, this._bear.y); + + if (cc.pDistance(heroPos, horsePos) < 20) { + this._hero.changeMount(this._horse); + } + else if (cc.pDistance(heroPos, horse2Pos) < 20) { + this._hero.changeMount(this._horse2); + } + else if (cc.pDistance(heroPos, bearPos) < 30) { + this._hero.changeMount(this._bear); + } + } + }, + createMount: function (name, position) { + var armature = new ccs.Armature(name); + armature.getAnimation().playWithIndex(0); + armature.x = position.x; + armature.y = position.y; + this.addChild(armature); + return armature; + } +}); + +//------------------------------------------------------------------ +// +// TestPlaySeveralMovement +// +//------------------------------------------------------------------ +var TestPlaySeveralMovement = ArmatureTestLayer.extend({ + onEnter:function () { + this._super(); + ccs.armatureDataManager.addArmatureFileInfo(s_Cowboy_json); + var armature = new ccs.Armature("Cowboy"); + armature.getAnimation().playWithNames(["Walk", "FireMax", "Fire"],10,true); + armature.scale = 0.2; + armature.x = winSize.width / 2; + armature.y = winSize.height / 2; + this.addChild(armature); + }, + title:function () { + return "Test play several movement"; + }, + subtitle:function () { + return "Movement is played one by one"; + } +}); + +//------------------------------------------------------------------ +// +// TestChangeAnimationInternal +// +//------------------------------------------------------------------ +var TestChangeAnimationInternal = ArmatureTestLayer.extend({ + ctor:function(){ + this._super(); + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded: this.onTouchesEnded.bind(this) + }, this); + }, + onEnter:function () { + this._super(); + + ccs.armatureDataManager.addArmatureFileInfo(s_Cowboy_json); + var armature = new ccs.Armature("Cowboy"); + armature.getAnimation().playWithIndex(0); + armature.scale = 0.2; + armature.x = winSize.width / 2; + armature.y = winSize.height / 2; + this.addChild(armature); + }, + title:function () { + return "Test change animation internal"; + }, + subtitle:function () { + return "Touch to change animation internal"; + }, + onTouchesEnded: function (touch, event) { + if (cc.director.getAnimationInterval() == 1 / 30) { + cc.director.setAnimationInterval(1 / 60); + } + else { + cc.director.setAnimationInterval(1 / 30); + } + return false; + }, + onExit: function () { + this._super(); + cc.director.setAnimationInterval(1 / 60); + } +}); + +//------------------------------------------------------------------ +// +// TestChangeAnimationInternal +// +//------------------------------------------------------------------ +var TestEasing = ArmatureTestLayer.extend({ + animationID: 0, + armature: null, + ctor:function(){ + this._super(); + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded: this.onTouchesEnded.bind(this) + }, this); + }, + onEnter: function () { + this._super(); + + ccs.armatureDataManager.addArmatureFileInfo(s_testEasing_json); + var armature = new ccs.Armature("testEasing"); + armature.getAnimation().playWithIndex(0); + armature.scale = 0.8; + armature.x = winSize.width / 2; + armature.y = winSize.height / 2; + this.addChild(armature); + this.armature = armature; + this.updateSubTitle(); + }, + title: function () { + return "Test easing effect"; + }, + subtitle: function () { + return "Current easing :"; + }, + onTouchesEnded: function (touch, event) { + this.animationID++; + this.animationID = this.animationID % this.armature.getAnimation().getMovementCount(); + this.armature.getAnimation().playWithIndex(this.animationID); + + this.updateSubTitle(); + return false; + }, + updateSubTitle: function () { + var str = this.subtitle() + this.armature.getAnimation().getCurrentMovementID(); + var label = this.getChildByTag(BASE_TEST_SUBTITLE_TAG); + label.setString(str); + } +}); + +var runArmatureTestScene = function(){ + var pScene = new ArmatureTestScene(); + if (pScene) { + pScene.runThisTest(); + } +}; \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/CocoStudioTest.js b/tests/js-tests/src/CocoStudioTest/CocoStudioTest.js new file mode 100644 index 0000000000..b8e18bba3e --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/CocoStudioTest.js @@ -0,0 +1,139 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var LINE_SPACE = 40; +var ITEM_TAG_BASIC = 1000; + +var cocoStudioTestItemNames = [ + { + itemTitle:"CocoStudioArmatureTest", + testScene:function () { + runArmatureTestScene(); + } + }, + { + itemTitle:"CocoStudioGUITest", + testScene:function () { + runGuiTestMain(); + } + }, + { + itemTitle:"CocoStudioSceneTest", + testScene:function () { + runSceneEditorTest(); + } + }, + { + itemTitle:"ParserTest", + testScene:function(){ + runParserTest(); + } + } +]; + +if(!cc.sys.isNative){ + cocoStudioTestItemNames.push({ + itemTitle: "CocoStudioComponentsTest", + testScene: function () { + runComponentsTestLayer(); + } + }); + cocoStudioTestItemNames.push({ + itemTitle:"CustomWidget", + testScene:function(){ + runCustomGUITest(); + } + }); +} + +var CocoStudioMainLayer = cc.Layer.extend({ + onEnter:function () { + this._super(); + + var winSize = cc.director.getWinSize(); + + var pMenu = new cc.Menu(); + pMenu.x = 0; + pMenu.y = 0; + cc.MenuItemFont.setFontName("Arial"); + cc.MenuItemFont.setFontSize(24); + for (var i = 0; i < cocoStudioTestItemNames.length; ++i) { + var selItem = cocoStudioTestItemNames[i]; + var pItem = new cc.MenuItemFont(selItem.itemTitle, + this.menuCallback, this); + pItem.x = winSize.width / 2; + pItem.y = winSize.height - (i + 1) * LINE_SPACE; + pMenu.addChild(pItem, ITEM_TAG_BASIC + i); + } + this.addChild(pMenu); + }, + + menuCallback:function (sender) { + var nIndex = sender.zIndex - ITEM_TAG_BASIC; + cocoStudioTestItemNames[nIndex].testScene(); + } +}); + +var cocoStudioOldApiFlag = 0; +var CocoStudioTestScene = TestScene.extend({ + + onEnter: function(){ + TestScene.prototype.onEnter.call(this); + + var winSize = cc.director.getWinSize(); + + var pMenu = new cc.Menu(); + pMenu.x = 0; + pMenu.y = 0; + cc.MenuItemFont.setFontName("Arial"); + cc.MenuItemFont.setFontSize(24); + var str = "new api"; + if(cocoStudioOldApiFlag){ + str = "old api"; + } + var pItem = new cc.MenuItemFont(str, + function(){ + if(cocoStudioOldApiFlag){ + cocoStudioOldApiFlag = 0; + pItem.setString("new api"); + }else{ + cocoStudioOldApiFlag = 1; + pItem.setString("old api"); + } + }, this); + pItem.x = 50; + pItem.y = winSize.height - 20; + pMenu.addChild(pItem); + + this.addChild(pMenu); + }, + + runThisTest:function () { + var pLayer = new CocoStudioMainLayer(); + this.addChild(pLayer); + cc.director.runScene(this); + } +}); diff --git a/tests/js-tests/src/CocoStudioTest/ComponentsTest/ComponentsTestScene.js b/tests/js-tests/src/CocoStudioTest/ComponentsTest/ComponentsTestScene.js new file mode 100644 index 0000000000..5d13cf29bb --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/ComponentsTest/ComponentsTestScene.js @@ -0,0 +1,77 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var ComponentsTestLayer = cc.LayerColor.extend({ + init: function () { + if (cc.LayerColor.prototype.init.call(this, cc.color(255, 255, 255, 255))) { + var root = this.createGameScene(); + this.addChild(root, 0, 1); + root.getChildByTag(1).addComponent(new ccs.ComAudio()); + root.getChildByTag(1).addComponent(PlayerController.create()); + root.addComponent(new ccs.ComAudio()); + root.addComponent(new ccs.ComAttribute()); + root.addComponent(SceneController.create()); + return true; + } + return false; + }, + + createGameScene: function () { + var root = new cc.Node(); + var winSize = cc.director.getWinSize(); + var player = new cc.Sprite("res/components/Player.png", cc.rect(0, 0, 27, 40)); + player.x = 30; + player.y = winSize.height / 2; + root.addChild(player, 1, 1); + + var itemBack = new cc.MenuItemFont("Back", this.toExtensionsMainLayer, this); + itemBack.color = cc.color(0, 0, 0); + itemBack.x = cc.visibleRect.bottomRight.x - 50; + itemBack.y = cc.visibleRect.bottomRight.y + 25; + var menuBack = new cc.Menu(itemBack); + menuBack.x = 0; + menuBack.y = 0; + this.addChild(menuBack); + return root; + }, + + toExtensionsMainLayer: function (sender) { + cc.audioEngine.stopMusic("res/Sound/background-music-aac.wav"); + var scene = new CocoStudioTestScene(); + scene.runThisTest(); + } +}); +ComponentsTestLayer.scene = function(){ + var scene = new cc.Scene(); + var layer = new ComponentsTestLayer(); + layer.init(); + scene.addChild(layer); + return scene; +}; +var runComponentsTestLayer = function () { + var scene = ComponentsTestLayer.scene(); + cc.director.runScene(scene); +}; \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/ComponentsTest/EnemyController.js b/tests/js-tests/src/CocoStudioTest/ComponentsTest/EnemyController.js new file mode 100644 index 0000000000..fa186339af --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/ComponentsTest/EnemyController.js @@ -0,0 +1,83 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var EnemyController = ccs.ComController.extend({ + ctor: function () { + this._super(); + this._name = "EnemyController"; + }, + init: function () { + return true; + }, + + onEnter: function () { + // Determine where to spawn the target along the Y axis + var winSize = cc.director.getWinSize(); + var minY = this.getOwner().height / 2; + var rangeY = winSize.height - this.getOwner().height; + var actualY = (Math.random() * rangeY ) + minY; + + // Create the target slightly off-screen along the right edge, + // and along a random position along the Y axis as calculated + this.getOwner().x = winSize.width + (this.getOwner().width / 2); + this.getOwner().y = actualY; + + + // Determine speed of the target + var minDuration = 2.0; + var maxDuration = 4.0; + var rangeDuration = maxDuration - minDuration; + var actualDuration = ( Math.random() % rangeDuration ) + minDuration; + + // Create the actions + var actionMove = cc.moveTo(actualDuration, cc.p(0 - this.getOwner().width / 2, actualY)); + var actionMoveDone = cc.callFunc(function () { + var comController = this.getOwner().parent.getComponent("SceneController"); + comController.spriteMoveFinished(this.getOwner()); + }, this); + this.getOwner().runAction(cc.sequence(actionMove, actionMoveDone)); + }, + + onExit: function () { + }, + + update: function (dt) { + + }, + + die: function () { + var com = this.getOwner().parent.getComponent("SceneController"); + var targets = com.getTargets(); + cc.arrayRemoveObject(targets, this.getOwner()); + this.getOwner().removeFromParent(true); + com.increaseKillCount(); + } +}); +EnemyController.create = function () { + var controller = new EnemyController(); + controller.init(); + return controller; +}; diff --git a/tests/js-tests/src/CocoStudioTest/ComponentsTest/GameOverScene.js b/tests/js-tests/src/CocoStudioTest/ComponentsTest/GameOverScene.js new file mode 100644 index 0000000000..573bde95bb --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/ComponentsTest/GameOverScene.js @@ -0,0 +1,74 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var GameOverLayer = cc.LayerColor.extend({ + _label: null, + init: function () { + if (this._super(cc.color(255, 255, 255, 255))) { + var winSize = cc.director.getWinSize(); + this._label = new cc.LabelTTF("", "Artial", 32); + this._label.retain(); + this._label.color = cc.color(0, 0, 0); + this._label.x = winSize.width / 2; + this._label.y = winSize.height / 2; + this.addChild(this._label); + this.runAction(cc.sequence(cc.delayTime(3), cc.callFunc(this.gameOverDone, this))); + var itemBack = new cc.MenuItemFont("Back", this.toExtensionsMainLayer, this); + itemBack.color = cc.color(0, 0, 0); + itemBack.x = cc.visibleRect.bottomRight.x - 50; + itemBack.y = cc.visibleRect.bottomRight.y + 25; + var menuBack = new cc.Menu(itemBack); + menuBack.x = 0; + menuBack.y = 0; + this.addChild(menuBack); + return true; + } + return false; + }, + gameOverDone: function () { + cc.director.runScene(ComponentsTestLayer.scene()); + }, + getLabel: function () { + return this._label; + } +}); +var GameOverScene = cc.Scene.extend({ + _layer: null, + init: function () { + this._super(); + this._layer = new GameOverLayer(); + this._layer.init(); + this.addChild(this._layer); + }, + getLayer: function () { + return this._layer; + } +}); +GameOverScene.create = function () { + var scene = new GameOverScene(); + scene.init(); + return scene; +}; diff --git a/tests/js-tests/src/CocoStudioTest/ComponentsTest/PlayerController.js b/tests/js-tests/src/CocoStudioTest/ComponentsTest/PlayerController.js new file mode 100644 index 0000000000..03dc538619 --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/ComponentsTest/PlayerController.js @@ -0,0 +1,66 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var PlayerController = ccs.ComController.extend({ + ctor: function () { + this._super(); + this._name = "PlayerController"; + + this._listener1 = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded: this.onTouchesEnded.bind(this) + }); + + cc.eventManager.addListener(this._listener1, 1); + }, + + update: function (dt) { + + }, + + onTouchesEnded: function (touch, event) { + var location = touch[0].getLocation(); + + var projectile = new cc.Sprite("res/components/Projectile.png", cc.rect(0, 0, 20, 20)); + this.getOwner().parent.addChild(projectile, 1, 4); + + var com = ProjectileController.create(); + projectile.addComponent(com); + com.move(location.x, location.y); + + this.getOwner().getComponent("Audio").playEffect("res/Sound/pew-pew-lei.wav"); + }, + onExit:function(){ + cc.eventManager.removeListener(this._listener1); + this._super(); + } +}); + +PlayerController.create = function () { + var controller = new PlayerController(); + controller.init(); + return controller; +}; \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/ComponentsTest/ProjectileController.js b/tests/js-tests/src/CocoStudioTest/ComponentsTest/ProjectileController.js new file mode 100644 index 0000000000..a4813fc0ea --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/ComponentsTest/ProjectileController.js @@ -0,0 +1,122 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var ProjectileController = ccs.ComController.extend({ + ctor: function () { + this._super(); + this._name = "ProjectileController"; + }, + init: function () { + return true; + }, + + onEnter: function () { + var winSize = cc.director.getWinSize(); + this.getOwner().x = 30; + this.getOwner().y = winSize.height / 2; + this.getOwner().tag = 3; + var com = this.getOwner().parent.getComponent("SceneController"); + com.getProjectiles().push(this.getOwner()); + }, + + onExit: function () { + }, + + update: function (dt) { + var com = this.getOwner().parent.getComponent("SceneController"); + var targets = com.getTargets(); + + var projectile = this.getOwner(); + var projectileRect = cc.rect(projectile.x - (projectile.width / 2), projectile.y - (projectile.height / 2), projectile.width, projectile.height); + + var targetsToDelete = []; + var target = null; + var targetSize = null; + for (var i = 0; i < targets.length; i++) { + target = targets[i]; + var targetRect = cc.rect(target.x - (target.width / 2), target.y - (target.height / 2), target.width, target.height); + if (cc.rectIntersectsRect(projectileRect, targetRect)) { + targetsToDelete.push(target); + } + } + + for (var i = 0; i < targetsToDelete.length; i++) { + var target = targetsToDelete[i]; + target.getComponent("EnemyController").die(); + } + + var isDied = targetsToDelete.length; + + if (isDied) { + this.die(); + } + }, + + move: function (x, y) { + var winSize = cc.director.getWinSize(); + + var offX = x - this.getOwner().x; + var offY = y - this.getOwner().y; + + if (offX <= 0) return; + + // Determine where we wish to shoot the projectile to + var realX = winSize.width + (this.getOwner().width / 2); + var ratio = offY / offX; + var realY = (realX * ratio) + this.getOwner().y; + var realDest = cc.p(realX, realY); + + // Determine the length of how far we're shooting + var offRealX = realX - this.getOwner().x; + var offRealY = realY - this.getOwner().y; + var length = Math.sqrt((offRealX * offRealX) + (offRealY * offRealY)); + var velocity = 480 / 1; // 480pixels/1sec + var realMoveDuration = length / velocity; + + // Move projectile to actual endpoint + this.getOwner().runAction(cc.sequence( + cc.moveTo(realMoveDuration, realDest), + cc.callFunc(function () { + var sceneController = this.getOwner().parent.getComponent("SceneController"); + sceneController.spriteMoveFinished(this.getOwner()); + }, this))); + + }, + + die: function () { + var com = this.getOwner().parent.getComponent("SceneController"); + var projectiles = com.getProjectiles(); + cc.arrayRemoveObject(projectiles, this.getOwner()); + this.getOwner().removeFromParent(true); + } + +}); + +ProjectileController.create = function () { + var controller = new ProjectileController(); + controller.init(); + return controller; +}; \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/ComponentsTest/SceneController.js b/tests/js-tests/src/CocoStudioTest/ComponentsTest/SceneController.js new file mode 100644 index 0000000000..e244174e99 --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/ComponentsTest/SceneController.js @@ -0,0 +1,107 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var SceneController = ccs.ComController.extend({ + _targets: null, + _projectiles: null, + _addTargetTime: 0, + _elapsedTime: 0, + ctor: function () { + this._super(); + this._name = "SceneController"; + this._targets = []; + this._projectiles = []; + }, + init: function () { + return true; + }, + + onEnter: function () { + this._addTargetTime = 1; + this._targets = []; + this._projectiles = []; + this.getOwner().getComponent("Audio").playBackgroundMusic("res/Sound/background-music-aac.wav", true); + this.getOwner().getComponent("CCComAttribute").setInt("KillCount", 0); + }, + + onExit: function () { + + }, + + update: function (dt) { + this._elapsedTime += dt; + if (this._elapsedTime > this._addTargetTime) { + this.addTarget(); + this._elapsedTime = 0.0; + } + }, + + addTarget: function () { + var target = new cc.Sprite("res/components/Target.png", cc.rect(0, 0, 27, 40)); + this.getOwner().addChild(target, 1, 2); + target.addComponent(EnemyController.create()); + target.tag = 2; + this._targets.push(target); + }, + + spriteMoveFinished: function (sender) { + var sprite = sender; + this.getOwner().removeChild(sprite, true); + if (sprite.tag == 2) { + cc.arrayRemoveObject(this._targets, sprite); + var gameOverScene = GameOverScene.create(); + gameOverScene.getLayer().getLabel().setString("You Lose!"); + cc.director.runScene(gameOverScene); + } + else if (sprite.tag == 3) { + cc.arrayRemoveObject(this._projectiles, sprite); + } + + }, + + increaseKillCount: function () { + var comAttribute = this.getOwner().getComponent("CCComAttribute"); + var projectilesDestroyed = comAttribute.getInt("KillCount"); + comAttribute.setInt("KillCount", ++projectilesDestroyed); + if (projectilesDestroyed >= 5) { + var gameOverScene = GameOverScene.create(); + gameOverScene.getLayer().getLabel().setString("You Win!"); + cc.director.runScene(gameOverScene); + } + }, + getProjectiles: function () { + return this._projectiles; + }, + getTargets: function () { + return this._targets; + } +}); + +SceneController.create = function () { + var controller = new SceneController(); + controller.init(); + return controller; +}; \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/CustomTest/CustomGUIScene.js b/tests/js-tests/src/CocoStudioTest/CustomTest/CustomGUIScene.js new file mode 100644 index 0000000000..5b8ea55864 --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/CustomTest/CustomGUIScene.js @@ -0,0 +1,107 @@ +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var g_guisTests = [ + { + title: "custom gui image Test", + test: function(){ + var pScene = new CustomImageScene(); + pScene.runThisTest(); + } + },{ + title: "custom gui particle widget Test", + test: function(){ + var pScene = new CustomParticleWidgetScene(); + pScene.runThisTest(); + } + } +]; + +var CustomGUITestMainLayer = cc.Layer.extend({ + onEnter: function(){ + cc.Layer.prototype.onEnter.call(this); + + var winSize = cc.director.getWinSize(); + + var pMenu = new cc.Menu(); + pMenu.x = 0; + pMenu.y = 0; + cc.MenuItemFont.setFontName("fonts/arial.ttf"); + cc.MenuItemFont.setFontSize(24); + + for (var i = 0; i < g_guisTests.length; ++i) { + var selItem = g_guisTests[i]; + var pItem = new cc.MenuItemFont(selItem.title, + selItem.test, this); + pItem.x = winSize.width / 2; + pItem.y = winSize.height - (i + 1) * LINE_SPACE; + pMenu.addChild(pItem, ITEM_TAG_BASIC + i); + } + this.addChild(pMenu); + + }, + onTouchesBegan: function(touches, event){ + var touch = touches[0]; + + this._beginPos = touch.getLocation(); + }, + touchEvent: function(){ + + } + +}); + +var CustomGUITestScene = cc.Scene.extend({ + onEnter: function(){ + cc.Scene.prototype.onEnter.call(this); + + var label = new cc.LabelTTF("Back", "fonts/arial.ttf", 20); + //#endif + var pMenuItem = new cc.MenuItemLabel(label, this.BackCallback, this); + + var pMenu = new cc.Menu(pMenuItem); + + pMenu.setPosition( cc.p(0, 0) ); + pMenuItem.setPosition(cc.pAdd(cc.visibleRect.bottomRight,cc.p(-50,25))); + + this.addChild(pMenu, 1); + + }, + runThisTest: function(){ + var pLayer = new CustomGUITestMainLayer(); + this.addChild(pLayer); + + cc.director.runScene(this); + }, + BackCallback: function(pSender){ + var pScene = new CocoStudioTestScene(); + pScene.runThisTest(); + + } +}); + +var runCustomGUITest = function(){ + var scene = new CustomGUITestScene(); + scene.runThisTest(); +}; \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/CustomTest/CustomImageScene/CustomImageScene.js b/tests/js-tests/src/CocoStudioTest/CustomTest/CustomImageScene/CustomImageScene.js new file mode 100644 index 0000000000..57042f3e62 --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/CustomTest/CustomImageScene/CustomImageScene.js @@ -0,0 +1,67 @@ +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var CustomImageLayer = cc.Layer.extend({ + + onEnter: function(){ + cc.Layer.prototype.onEnter.call(this); + + var guiReader = ccs.uiReader; + guiReader.registerTypeAndCallBack("CustomImageView", + CustomImageView, + customImageViewReader, + customImageViewReader.setProperties); + + var layout = guiReader.widgetFromJsonFile("res/cocosui/CustomImageViewTest/NewProject_2_1.ExportJson"); + this.addChild(layout); + } +}); + +var CustomImageScene = cc.Scene.extend({ + + onEnter: function(){ + cc.Scene.prototype.onEnter.call(this); + + var label = new cc.LabelTTF("Back", "fonts/arial.ttf", 20); + //#endif + var pMenuItem = new cc.MenuItemLabel(label, this.BackCallback, this); + + var pMenu = new cc.Menu(pMenuItem); + + pMenu.setPosition( cc.p(0, 0) ); + pMenuItem.setPosition( cc.p( 750, 25) ); + + this.addChild(pMenu, 1); + }, + runThisTest: function(){ + var pLayer = new CustomImageLayer(); + this.addChild(pLayer); + + cc.director.runScene(this); + }, + BackCallback: function(pSender){ + var pScene = new CustomGUITestScene(); + pScene.runThisTest(); + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/CustomTest/CustomImageView/CustomImageView.js b/tests/js-tests/src/CocoStudioTest/CustomTest/CustomImageView/CustomImageView.js new file mode 100644 index 0000000000..ca09265f98 --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/CustomTest/CustomImageView/CustomImageView.js @@ -0,0 +1,66 @@ +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var CustomImageView = ccui.ImageView.extend({ + + _label: null, + + init: function(){ + if (ccui.ImageView.prototype.init.call(this)) + { + return true; + } + return false; + }, + + _initRenderer: function(){ + ccui.ImageView.prototype._initRenderer.call(this); + + this._label = new cc.LabelTTF(); + cc.ProtectedNode.prototype.addChild.call(this, this._label, this.getLocalZOrder() + 1, -1); + }, + + createInstance: function(){ + return CustomImageView; + }, + + setText: function(text){ + this._label.setString(text); + }, + + getText: function(){ + return this._label.getString(); + } +}); + +CustomImageView.create = function(){ + var custom = new CustomImageView(); + + if (custom && custom.init()) + { + return custom; + } + return null; + +}; \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/CustomTest/CustomImageView/CustomImageViewReader.js b/tests/js-tests/src/CocoStudioTest/CustomTest/CustomImageView/CustomImageViewReader.js new file mode 100644 index 0000000000..b2aec77aee --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/CustomTest/CustomImageView/CustomImageViewReader.js @@ -0,0 +1,42 @@ +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var customImageViewReader = { + + _instanceCustomImageViewReader: null, + + setProperties: function(classType, widget, customOptions){ + var custom = widget; + + var StringTest = customOptions["StringTest"]; + if (StringTest) { + custom.setText(StringTest); + } + + }, + + setPropsFromJsonDictionary: function(){ + ccs.imageViewReader.setPropsFromJsonDictionary.apply(this, arguments); + } +}; \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/CustomTest/CustomImageView/CustomParticWidgetReader.js b/tests/js-tests/src/CocoStudioTest/CustomTest/CustomImageView/CustomParticWidgetReader.js new file mode 100644 index 0000000000..f947e2f5ec --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/CustomTest/CustomImageView/CustomParticWidgetReader.js @@ -0,0 +1,43 @@ +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var customParticleWidgetReader = { + + setProperties: function(classType, widget, customOptions){ + var guiReader = ccs.uiReader; + + var custom = widget; + + var isExistPlistFile = customOptions["PlistFile"]; + if (isExistPlistFile) + { + var PlistFile = customOptions["PlistFile"]; + var PlistFilePath = guiReader.getFilePath(); + PlistFilePath += PlistFile; + custom.setParticlePlist(PlistFilePath); + + } + + } +}; \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/CustomTest/CustomImageView/CustomParticleWidget.js b/tests/js-tests/src/CocoStudioTest/CustomTest/CustomImageView/CustomParticleWidget.js new file mode 100644 index 0000000000..e3d3901ea0 --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/CustomTest/CustomImageView/CustomParticleWidget.js @@ -0,0 +1,104 @@ +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var CustomParticleWidget = ccui.Widget.extend({ + + _emitter: null, + + _emitterPlist: null, + + _emitterPostion: null, + + init: function(){ + if (ccui.Widget.prototype.init.call(this)) + { + return true; + } + return false; + }, + + _initRenderer: function(){ + ccui.Widget.prototype._initRenderer.call(this); + }, + + removeAllChildren: function(){ + ccui.Widget.prototype.removeAllChildren.call(this); + }, + + createInstance: function(){ + return CustomParticleWidget.create(); + }, + setParticlePlist: function(plist){ + if (!this._emitter) + { + this._emitter = new cc.ParticleSystem(plist); + + } + else + { + this._emitter.removeFromParent(); + this._emitter = new cc.ParticleSystem(plist); + } + //Warning!!! don't forget to set the position + this.addProtectedChild(this._emitter , this.getLocalZOrder() + 1, -1); + this.setParticlePosition(cc.p(0, 0)); + + this._emitterPlist = plist; + + }, + getParticlePlist: function(){ + return this._emitterPlist; + }, + setParticlePosition: function(pos){ + this._emitter.setPosition(pos); + + this._emitterPostion = pos; + + }, + getParticlePosition: function(){ + return this._emitterPostion; + }, + playParticle: function(){ + if (this._emitter) + { + this._emitter.resetSystem(); + } + }, + stopParticle: function(){ + if (this._emitter) + { + this._emitter.stopSystem(); + } + } +}); + +CustomParticleWidget.create = function(){ + var custom = new CustomParticleWidget(); + + if (custom && custom.init()) + { + return custom; + } + return null; +}; \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/CustomTest/CustomImageView/CustomReader.js b/tests/js-tests/src/CocoStudioTest/CustomTest/CustomImageView/CustomReader.js new file mode 100644 index 0000000000..333fb4f90f --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/CustomTest/CustomImageView/CustomReader.js @@ -0,0 +1,43 @@ +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +ccui.customReader = { + + _instanceCustomReader: null, + + setProperties: function(classType, widget, customOptions){ + if (classType.compare("CustomImageView") == 0) + { + var customImageView = widget; + + var isExistText = customOptions["text"]; + if (isExistText) + { + var text = customOptions["text"]; + customImageView.setText(text); + } + } + + } +}; \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/CustomTest/CustomParticleWidgetTest/CustomParticleWidgetTest.js b/tests/js-tests/src/CocoStudioTest/CustomTest/CustomParticleWidgetTest/CustomParticleWidgetTest.js new file mode 100644 index 0000000000..772f2c1c2e --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/CustomTest/CustomParticleWidgetTest/CustomParticleWidgetTest.js @@ -0,0 +1,74 @@ +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var CustomParticleWidgetLayer = cc.Layer.extend({ + + onEnter: function(){ + cc.Layer.prototype.onEnter.call(this); + + var guiReader = ccs.uiReader; + guiReader.registerTypeAndCallBack("CustomParticleWidget", + CustomParticleWidget, + customParticleWidgetReader, + customParticleWidgetReader.setProperties); + + var custom = CustomParticleWidget.create(); + custom.setPosition(cc.p(370, 210)); + custom.setParticlePlist("res/Particles/BoilingFoam.plist"); + + this.addChild(custom, 10, -1); + } +}); + + +var CustomParticleWidgetScene = cc.Scene.extend({ + + onEnter: function(){ + cc.Scene.prototype.onEnter.call(this); + + var label = new cc.LabelTTF("Back", "fonts/arial.ttf", 20); + //#endif + var pMenuItem = new cc.MenuItemLabel(label, this.BackCallback, this); + + var pMenu = new cc.Menu(pMenuItem); + + pMenu.setPosition( cc.p(0, 0) ); + pMenuItem.setPosition( cc.p( 750, 25) ); + + this.addChild(pMenu, 1); + + }, + + runThisTest: function(){ + var pLayer = new CustomParticleWidgetLayer(); + this.addChild(pLayer); + + cc.director.runScene(this); + }, + + BackCallback: function(pSender){ + var pScene = new CustomGUITestScene(); + pScene.runThisTest(); + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/GUITest/UIBaseLayer.js b/tests/js-tests/src/CocoStudioTest/GUITest/UIBaseLayer.js new file mode 100644 index 0000000000..3937657cde --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/GUITest/UIBaseLayer.js @@ -0,0 +1,70 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var UIBaseLayer = cc.Layer.extend({ + _mainNode:null, + _topDisplayText:null, + ctor: function () { + this._super(); + var winSize = cc.director.getWinSize(); + + //add main node + var mainNode = new cc.Node(); + var scale = winSize.height / 320; + mainNode.attr({anchorX: 0, anchorY: 0, scale: scale, x: (winSize.width - 480 * scale) / 2, y: (winSize.height - 320 * scale) / 2}); + this.addChild(mainNode); + + var topDisplayText = new ccui.Text(); + topDisplayText.attr({ + string: "", + font: "20px Arial", + x: 240, + y: 320-50 + }); + mainNode.addChild(topDisplayText,100); + + this._mainNode = mainNode; + this._topDisplayText = topDisplayText; + }, + + _parseUIFile: function(file){ + if(cocoStudioOldApiFlag == 0){ + cc.log("ccs.load : %s", file); + var json = ccs.load(file); + return json.node; + }else{ + //ccs.uiReader.widgetFromJsonFile only supports 1.x file. + cc.log("ccs.uiReader.widgetFromJsonFile : %s", file); + return ccs.uiReader.widgetFromJsonFile(file) + } + }, + + backEvent: function (sender, type) { + if (type == ccui.Widget.TOUCH_ENDED) { + runGuiTestMain(); + } + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/GUITest/UIButtonTest/UIButtonTest.js b/tests/js-tests/src/CocoStudioTest/GUITest/UIButtonTest/UIButtonTest.js new file mode 100644 index 0000000000..cfff52221a --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/GUITest/UIButtonTest/UIButtonTest.js @@ -0,0 +1,68 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var UIButtonEditorTest = UIBaseLayer.extend({ + ctor: function () { + this._super(); + var root = this._parseUIFile("res/cocosui/CCS/Button/Button_1.json"); + this._mainNode.addChild(root); + + var back_label = ccui.helper.seekWidgetByName(root, "back"); + back_label.addTouchEventListener(this.backEvent,this); + + var button = ccui.helper.seekWidgetByName(root, "Button_123"); + button.addTouchEventListener(this.touchEvent,this); + + var title_button = ccui.helper.seekWidgetByName(root, "Button_126"); + title_button.addTouchEventListener(this.touchEvent,this); + + var scale9_button = ccui.helper.seekWidgetByName(root, "Button_129"); + scale9_button.addTouchEventListener(this.touchEvent,this); + }, + + touchEvent: function (sender, type) { + switch (type) { + case ccui.Widget.TOUCH_BEGAN: + this._topDisplayText.setString("Touch Down"); + break; + + case ccui.Widget.TOUCH_MOVED: + this._topDisplayText.setString("Touch Move"); + break; + + case ccui.Widget.TOUCH_ENDED: + this._topDisplayText.setString("Touch Up"); + break; + + case ccui.Widget.TOUCH_CANCELED: + this._topDisplayText.setString("Touch Cancelled"); + break; + + default: + break; + } + } +}); diff --git a/tests/js-tests/src/CocoStudioTest/GUITest/UICheckBoxTest/UICheckBoxTest.js b/tests/js-tests/src/CocoStudioTest/GUITest/UICheckBoxTest/UICheckBoxTest.js new file mode 100644 index 0000000000..d5f89573a4 --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/GUITest/UICheckBoxTest/UICheckBoxTest.js @@ -0,0 +1,113 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var CEHCK_BOX_INDEX = 0; + +var UICheckBoxEditorTest = UIBaseLayer.extend({ + ctor: function () { + this._super(); + var left_button = new ccui.Button(); + left_button.loadTextures("res/Images/b1.png", "res/Images/b2.png", ""); + left_button.x = 240-50; + left_button.y = 50; + left_button.anchorX = 0.5; + left_button.anchorY = 0.5; + left_button.addTouchEventListener(this.previousCallback, this); + this._mainNode.addChild(left_button, 999); + + var right_button = new ccui.Button(); + right_button.loadTextures("res/Images/f1.png", "res/Images/f2.png", ""); + right_button.x = 240+50; + right_button.y = 50; + right_button.anchorX = 0.5; + right_button.anchorY = 0.5; + right_button.addTouchEventListener(this.nextCallback, this); + this._mainNode.addChild(right_button, 999); + }, + previousCallback: function (render, type) { + if (type == ccui.Widget.TOUCH_ENDED) { + CEHCK_BOX_INDEX--; + if (CEHCK_BOX_INDEX < 0)CEHCK_BOX_INDEX = CEHCK_BOX_SCENE.length-1; + if (CEHCK_BOX_INDEX >= CEHCK_BOX_SCENE.length)CEHCK_BOX_INDEX = 0; + this.runNextScene(); + } + }, + nextCallback: function (render, type) { + if (type == ccui.Widget.TOUCH_ENDED) { + CEHCK_BOX_INDEX++; + if (CEHCK_BOX_INDEX < 0)CEHCK_BOX_INDEX = CEHCK_BOX_SCENE.length-1; + if (CEHCK_BOX_INDEX >= CEHCK_BOX_SCENE.length)CEHCK_BOX_INDEX = 0; + this.runNextScene(); + } + }, + runNextScene: function () { + var scene = new cc.Scene(); + scene.addChild(new CEHCK_BOX_SCENE[CEHCK_BOX_INDEX]()); + cc.director.runScene(scene); + }, + + selectedStateEvent: function (sender, type) { + switch (type) { + case ccui.CheckBox.EVENT_SELECTED: + this._topDisplayText.setString("Selected"); + break; + case ccui.CheckBox.EVENT_UNSELECTED: + this._topDisplayText.setString("Unselected"); + break; + + default: + break; + } + } +}); + +var UICheckBoxOldTest = UICheckBoxEditorTest.extend({ + ctor: function () { + this._super(); + var root = this._parseUIFile("res/cocosui/CCS/CheckBox/checkbox_1.json"); + this._mainNode.addChild(root); + + var back_label =ccui.helper.seekWidgetByName(root, "back"); + back_label.addTouchEventListener(this.backEvent,this); + + var checkbox = ccui.helper.seekWidgetByName(root, "CheckBox_540"); + checkbox.addEventListener(this.selectedStateEvent,this); + } +}); + +var UICheckBoxNewTest = UICheckBoxEditorTest.extend({ + ctor: function () { + this._super(); + var root = ccs.load("res/cocosui/CCS/CheckBox/MainScene.json"); + this._mainNode.addChild(root.node); + var checkbox = ccui.helper.seekWidgetByName(root.node, "CheckBox_1"); + checkbox.addEventListener(this.selectedStateEvent,this); + } +}); + +var CEHCK_BOX_SCENE = [ + UICheckBoxOldTest, + UICheckBoxNewTest +]; diff --git a/tests/js-tests/src/CocoStudioTest/GUITest/UIImageViewTest/UIImageViewTest.js b/tests/js-tests/src/CocoStudioTest/GUITest/UIImageViewTest/UIImageViewTest.js new file mode 100644 index 0000000000..f92f400761 --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/GUITest/UIImageViewTest/UIImageViewTest.js @@ -0,0 +1,36 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var UIImageViewEditorTest = UIBaseLayer.extend({ + ctor: function () { + this._super(); + var root = this._parseUIFile("res/cocosui/CCS/ImageView/ImageView_1.json"); + this._mainNode.addChild(root); + + var back_label =ccui.helper.seekWidgetByName(root, "back"); + back_label.addTouchEventListener(this.backEvent,this); + } +}); diff --git a/tests/js-tests/src/CocoStudioTest/GUITest/UILayoutTest/UILayoutTest.js b/tests/js-tests/src/CocoStudioTest/GUITest/UILayoutTest/UILayoutTest.js new file mode 100644 index 0000000000..6284598fca --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/GUITest/UILayoutTest/UILayoutTest.js @@ -0,0 +1,88 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var LAYOUT_RES = [ + "res/cocosui/CCS/Layout/Layout/layout_1.json", + "res/cocosui/CCS/Layout/Color/color_1.json", + "res/cocosui/CCS/Layout/Gradient_Color/gradient_color_1.json", + "res/cocosui/CCS/Layout/BackgroundImage/backgroundimage_1.json", + "res/cocosui/CCS/Layout/Scale9/scale9.json", + "res/cocosui/CCS/Layout/Linear_Vertical/linear_vertical.json", + "res/cocosui/CCS/Layout/Linear_Horizontal/linear_horizontal.json", + "res/cocosui/CCS/Layout/Relative_Align_Parent/relative_align_parent.json", + "res/cocosui/CCS/Layout/Relative_Align_Location/relative_align_location.json" +]; +var LAYOUT_INDEX = 0; +var UILayoutEditorTest = UIBaseLayer.extend({ + ctor: function () { + this._super(); + var root = this._parseUIFile(LAYOUT_RES[LAYOUT_INDEX]); + this._mainNode.addChild(root); + + var back_label = ccui.helper.seekWidgetByName(root, "back"); + back_label.addTouchEventListener(this.backEvent, this); + + var left_button = new ccui.Button(); + left_button.loadTextures("res/Images/b1.png", "res/Images/b2.png", ""); + left_button.x = 240-50; + left_button.y = 50; + left_button.anchorX = 0.5; + left_button.anchorY = 0.5; + left_button.zOrder = 999; + left_button.addTouchEventListener(this.previousCallback, this); + this._mainNode.addChild(left_button); + + var right_button = new ccui.Button(); + right_button.loadTextures("res/Images/f1.png", "res/Images/f2.png", ""); + right_button.x = 240+50; + right_button.y = 50; + right_button.zOrder = 999; + right_button.anchorX = 0.5; + right_button.anchorY = 0.5; + right_button.addTouchEventListener(this.nextCallback, this); + this._mainNode.addChild(right_button); + }, + previousCallback: function (render, type) { + if (type == ccui.Widget.TOUCH_ENDED) { + LAYOUT_INDEX--; + if (LAYOUT_INDEX < 0)LAYOUT_INDEX = LAYOUT_RES.length-1; + if (LAYOUT_INDEX >= LAYOUT_RES.length)LAYOUT_INDEX = 0; + this.runNextScene(); + } + }, + nextCallback: function (render, type) { + if (type == ccui.Widget.TOUCH_ENDED) { + LAYOUT_INDEX++; + if (LAYOUT_INDEX < 0)LAYOUT_INDEX = LAYOUT_RES.length-1; + if (LAYOUT_INDEX >= LAYOUT_RES.length)LAYOUT_INDEX = 0; + this.runNextScene(); + } + }, + runNextScene: function () { + var scene = new cc.Scene(); + scene.addChild(new UILayoutEditorTest()); + cc.director.runScene(scene); + } +}); diff --git a/tests/js-tests/src/CocoStudioTest/GUITest/UIListViewTest/UIListViewTest.js b/tests/js-tests/src/CocoStudioTest/GUITest/UIListViewTest/UIListViewTest.js new file mode 100644 index 0000000000..54201c6dcb --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/GUITest/UIListViewTest/UIListViewTest.js @@ -0,0 +1,97 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var LISTVIEW_RES = [ + "res/cocosui/CCS/ListView/Vertical/vertical_1.json", + "res/cocosui/CCS/ListView/Horizontal/horizontal_1.json" +]; +var LISTVIEW_INDEX = 0; +var UIListViewEditorTest = UIBaseLayer.extend({ + ctor: function () { + this._super(); + var root = this._parseUIFile(LISTVIEW_RES[LISTVIEW_INDEX]); + this._mainNode.addChild(root); + + var back_label = ccui.helper.seekWidgetByName(root, "back"); + back_label.addTouchEventListener(this.backEvent, this); + + var listView = ccui.helper.seekWidgetByName(root, "ListView_1214"); + listView.addEventListener(this.selectedItemEvent,this); + + var left_button = new ccui.Button(); + left_button.loadTextures("res/Images/b1.png", "res/Images/b2.png", ""); + left_button.x = 240-50; + left_button.y = 50; + left_button.anchorX = 0.5; + left_button.anchorY = 0.5; + left_button.zOrder = 999; + left_button.addTouchEventListener(this.previousCallback, this); + this._mainNode.addChild(left_button); + + var right_button = new ccui.Button(); + right_button.loadTextures("res/Images/f1.png", "res/Images/f2.png", ""); + right_button.x = 240+50; + right_button.y = 50; + right_button.zOrder = 999; + right_button.anchorX = 0.5; + right_button.anchorY = 0.5; + right_button.addTouchEventListener(this.nextCallback, this); + this._mainNode.addChild(right_button); + }, + selectedItemEvent: function (sender, type) { + switch (type) { + case ccui.ListView.EVENT_SELECTED_ITEM: + var listViewEx = sender; + cc.log("select child index = " + listViewEx.getCurSelectedIndex()); + break; + + default: + break; + } + }, + previousCallback: function (render, type) { + if (type == ccui.Widget.TOUCH_ENDED) { + LISTVIEW_INDEX--; + if (LISTVIEW_INDEX < 0)LISTVIEW_INDEX = LISTVIEW_RES.length-1; + if (LISTVIEW_INDEX >= LISTVIEW_RES.length)LISTVIEW_INDEX = 0; + this.runNextScene(); + } + }, + nextCallback: function (render, type) { + if (type == ccui.Widget.TOUCH_ENDED) { + LISTVIEW_INDEX++; + if (LISTVIEW_INDEX < 0)LISTVIEW_INDEX = LISTVIEW_RES.length-1; + if (LISTVIEW_INDEX >= LISTVIEW_RES.length)LISTVIEW_INDEX = 0; + this.runNextScene(); + } + }, + runNextScene: function () { + var scene = new cc.Scene(); + scene.addChild(new UIListViewEditorTest()); + cc.director.runScene(scene); + } +}); + + diff --git a/tests/js-tests/src/CocoStudioTest/GUITest/UILoadingBarTest/UILoadingBarTest.js b/tests/js-tests/src/CocoStudioTest/GUITest/UILoadingBarTest/UILoadingBarTest.js new file mode 100644 index 0000000000..677f71301b --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/GUITest/UILoadingBarTest/UILoadingBarTest.js @@ -0,0 +1,55 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var UILoadingBarEditorTest = UIBaseLayer.extend({ + _count: 0, + _loadingBar_left_to_right:null, + _loadingBar_right_to_left:null, + ctor: function () { + this._super(); + var root = this._parseUIFile("res/cocosui/CCS/LoadingBar/loadingbar_1.json"); + this._mainNode.addChild(root); + + var back_label =ccui.helper.seekWidgetByName(root, "back"); + back_label.addTouchEventListener(this.backEvent,this); + + this._loadingBar_left_to_right = ccui.helper.seekWidgetByName(root, "LoadingBar_856"); + this._loadingBar_left_to_right.setPercent(0); + + this._loadingBar_right_to_left = ccui.helper.seekWidgetByName(root, "LoadingBar_857"); + this._loadingBar_right_to_left.setPercent(0); + + this.scheduleUpdate(); + }, + update: function (dt) { + this._count++; + if (this._count > 100) { + this._count = 0; + } + this._loadingBar_left_to_right.setPercent(this._count); + this._loadingBar_right_to_left.setPercent(this._count); + } +}); diff --git a/tests/js-tests/src/CocoStudioTest/GUITest/UINodeContainerTest/UINodeContainerTest.js b/tests/js-tests/src/CocoStudioTest/GUITest/UINodeContainerTest/UINodeContainerTest.js new file mode 100644 index 0000000000..f2f047cb0c --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/GUITest/UINodeContainerTest/UINodeContainerTest.js @@ -0,0 +1,41 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var UIWidgetAddNodeEditorTest = UIBaseLayer.extend({ + ctor: function () { + this._super(); + var root = this._parseUIFile("res/cocosui/CCS/WidgetAddNode/widget_add_node.json"); + this._mainNode.addChild(root); + + var back_label =ccui.helper.seekWidgetByName(root, "back"); + back_label.addTouchEventListener(this.backEvent,this); + + var sprite = new cc.Sprite("res/cocosui/ccicon.png"); + sprite.x = 240; + sprite.y = 160; + root.addNode(sprite,9999); + } +}); diff --git a/tests/js-tests/src/CocoStudioTest/GUITest/UIPageViewTest/UIPageViewTest.js b/tests/js-tests/src/CocoStudioTest/GUITest/UIPageViewTest/UIPageViewTest.js new file mode 100644 index 0000000000..f50749bfe0 --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/GUITest/UIPageViewTest/UIPageViewTest.js @@ -0,0 +1,50 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var UIPageViewEditorTest = UIBaseLayer.extend({ + ctor: function () { + this._super(); + var root = this._parseUIFile("res/cocosui/CCS/PageView/pageview_1.json"); + this._mainNode.addChild(root); + + var back_label =ccui.helper.seekWidgetByName(root, "back"); + back_label.addTouchEventListener(this.backEvent,this); + + var pageView =ccui.helper.seekWidgetByName(root, "PageView_1269"); + pageView.addEventListener(this.pageViewEvent, this); + }, + + pageViewEvent: function (sender, type) { + switch (type) { + case ccui.PageView.EVENT_TURNING: + var pageView = sender; + this._topDisplayText.setString("page = " + (pageView.getCurPageIndex() + 1)); + break; + default: + break; + } + } +}); diff --git a/tests/js-tests/src/CocoStudioTest/GUITest/UIRichTextTest/UIRichTextTest.js b/tests/js-tests/src/CocoStudioTest/GUITest/UIRichTextTest/UIRichTextTest.js new file mode 100644 index 0000000000..16c0ce2324 --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/GUITest/UIRichTextTest/UIRichTextTest.js @@ -0,0 +1,92 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var UIRichTextTest = UISceneEditor.extend({ + _richText:null, + init: function () { + if (this._super()) { + //init text + this._topDisplayLabel.setString(""); + this._bottomDisplayLabel.setString("RichText"); + + var widgetSize = this._widget.getContentSize(); + var button = new ccui.Button(); + button.setTouchEnabled(true); + button.loadTextures("res/cocosui/animationbuttonnormal.png", "res/cocosui/animationbuttonpressed.png", ""); + button.setTitleText("switch"); + button.setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2 + button.getContentSize().height * 2.5)); + button.addTouchEventListener(this.touchEvent,this); + this._mainNode.addChild(button); + + + // RichText + var richText = new ccui.RichText(); + richText.ignoreContentAdaptWithSize(false); + richText.setContentSize(cc.size(120, 100)); + + var re1 = new ccui.RichElementText(1, cc.color.WHITE, 255, "This color is white. ", "Helvetica", 10); + var re2 = new ccui.RichElementText(2, cc.color.YELLOW, 255, "And this is yellow. ", "Helvetica", 10); + var re3 = new ccui.RichElementText(3, cc.color.BLUE, 255, "This one is blue. ", "Helvetica", 10); + var re4 = new ccui.RichElementText(4, cc.color.GREEN, 255, "And green. ", "Helvetica", 10); + var re5 = new ccui.RichElementText(5, cc.color.RED, 255, "Last one is red ", "Helvetica", 10); + + var reimg = new ccui.RichElementImage(6, cc.color.WHITE, 255, "res/cocosui/sliderballnormal.png"); + + ccs.armatureDataManager.addArmatureFileInfo("res/cocosui/100/100.ExportJson"); + var pAr = new ccs.Armature("100"); + pAr.getAnimation().play("Animation1"); + + var recustom = new ccui.RichElementCustomNode(1, cc.color.WHITE, 255, pAr); + var re6 = new ccui.RichElementText(7, cc.color.ORANGE, 255, "Have fun!! ", "Helvetica", 10); + richText.pushBackElement(re1); + richText.insertElement(re2, 1); + richText.pushBackElement(re3); + richText.pushBackElement(re4); + richText.pushBackElement(re5); + richText.insertElement(reimg, 2); + richText.pushBackElement(recustom); + richText.pushBackElement(re6); + + richText.setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2)); + + this._mainNode.addChild(richText); + this._richText = richText; + return true; + } + return false; + }, + touchEvent: function (sender, type) { + if (type == ccui.Widget.TOUCH_ENDED) { + if (this._richText.isIgnoreContentAdaptWithSize()) { + this._richText.ignoreContentAdaptWithSize(false); + this._richText.setContentSize(cc.size(120, 100)); + } + else { + this._richText.ignoreContentAdaptWithSize(true); + } + } + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/GUITest/UISceneTest.js b/tests/js-tests/src/CocoStudioTest/GUITest/UISceneTest.js new file mode 100644 index 0000000000..d1e25af47e --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/GUITest/UISceneTest.js @@ -0,0 +1,177 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var s_GuiTestEditorArray = [ + { + title: "Button", + layer: function () { + return new UIButtonEditorTest(); + } + }, + { + title: "CheckBox", + layer: function () { + return new CEHCK_BOX_SCENE[0](); + } + }, + { + title: "ImageView", + layer: function () { + return new UIImageViewEditorTest(); + } + }, + { + title: "Text", + layer: function () { + return new UITextEditorTest(); + } + }, + { + title: "TextAtlas", + layer: function () { + return new UITextAtlasEditorTest(); + } + }, + { + title: "TextBMFont", + layer: function () { + return new UITextBMFontEditorTest(); + } + }, + { + title: "LoadingBar", + layer: function () { + return new UILoadingBarEditorTest(); + } + }, + { + title: "Slider", + layer: function () { + return new UISliderEditorTest(); + } + }, + { + title: "TextField", + layer: function () { + return new UITextFieldEditorTest(); + } + }, + { + title: "AddNode", + layer: function () { + return new UIWidgetAddNodeEditorTest(); + } + }, + { + title: "Layout", + layer: function () { + return new UILayoutEditorTest(); + } + }, + { + title: "ListView", + layer: function () { + return new UIListViewEditorTest(); + } + }, + { + title: "PageView", + layer: function () { + return new UIPageViewEditorTest(); + } + }, + { + title: "ScrollView", + layer: function () { + return new UIScrollViewEditorTest(); + } + } +]; + +var GuiTestMainLayer = cc.Layer.extend({ + ctor: function () { + this._super(); + var winSize = cc.winSize; + var x = 0; + var y = winSize.height - 10; + for (var i = 0; i < s_GuiTestEditorArray.length; i++) { + var guiTest = s_GuiTestEditorArray[i]; + var text = new ccui.Text(); + if (i % 2 == 0) { + x = winSize.width / 2 - 100; + y -= 30; + } else { + x = winSize.width / 2 + 100; + } + text.attr({ + string: guiTest.title, + font: "20px Arial", + x: x, + y: y, + tag: i + }); + text.setTouchEnabled(true); + text.setTouchScaleChangeEnabled(true); + text.addTouchEventListener(this.touchEvent, this); + this.addChild(text); + } + + var backText = new ccui.Text(); + backText.attr({ + string: "Back", + font: "20px Arial", + x: winSize.width-50, + y: 50, + tag: 10000 + }); + backText.setTouchEnabled(true); + backText.setTouchScaleChangeEnabled(true); + backText.addTouchEventListener(this.backEvent, this); + this.addChild(backText); + }, + touchEvent:function(sender,type){ + if(type==ccui.Widget.TOUCH_ENDED){ + var tag = sender.tag; + var scene = new cc.Scene(); + var guiTest = s_GuiTestEditorArray[tag]; + scene.addChild(guiTest.layer()); + cc.director.runScene(scene); + } + }, + backEvent:function(sender,type){ + if(type==ccui.Widget.TOUCH_ENDED){ + var scene = new CocoStudioTestScene(); + scene.runThisTest(); + } + } +}); + +var runGuiTestMain = function(){ + var scene = new cc.Scene(); + var main = new GuiTestMainLayer(); + scene.addChild(main); + cc.director.runScene(scene); +} \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/GUITest/UIScrollViewTest/UIScrollViewTest.js b/tests/js-tests/src/CocoStudioTest/GUITest/UIScrollViewTest/UIScrollViewTest.js new file mode 100644 index 0000000000..6bf63a4bfc --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/GUITest/UIScrollViewTest/UIScrollViewTest.js @@ -0,0 +1,84 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var SCROLLVIEW_RES = [ + "res/cocosui/CCS/ScrollView/Vertical/vertical_1.json", + "res/cocosui/CCS/ScrollView/Horizontal/horizontal_1.json", + "res/cocosui/CCS/ScrollView/Both/both_1.json" +]; +var SCROLLVIEW_INDEX = 0; +var UIScrollViewEditorTest = UIBaseLayer.extend({ + ctor: function () { + this._super(); + var root = this._parseUIFile(SCROLLVIEW_RES[SCROLLVIEW_INDEX]); + this._mainNode.addChild(root); + + var back_label = ccui.helper.seekWidgetByName(root, "back"); + back_label.addTouchEventListener(this.backEvent, this); + + var left_button = new ccui.Button(); + left_button.loadTextures("res/Images/b1.png", "res/Images/b2.png", ""); + left_button.x = 240-50; + left_button.y = 50; + left_button.anchorX = 0.5; + left_button.anchorY = 0.5; + left_button.zOrder = 999; + left_button.addTouchEventListener(this.previousCallback, this); + this._mainNode.addChild(left_button); + + var right_button = new ccui.Button(); + right_button.loadTextures("res/Images/f1.png", "res/Images/f2.png", ""); + right_button.x = 240+50; + right_button.y = 50; + right_button.zOrder = 999; + right_button.anchorX = 0.5; + right_button.anchorY = 0.5; + right_button.addTouchEventListener(this.nextCallback, this); + this._mainNode.addChild(right_button); + }, + + previousCallback: function (render, type) { + if (type == ccui.Widget.TOUCH_ENDED) { + SCROLLVIEW_INDEX--; + if (SCROLLVIEW_INDEX < 0)SCROLLVIEW_INDEX = SCROLLVIEW_RES.length-1; + if (SCROLLVIEW_INDEX >= SCROLLVIEW_RES.length)SCROLLVIEW_INDEX = 0; + this.runNextScene(); + } + }, + nextCallback: function (render, type) { + if (type == ccui.Widget.TOUCH_ENDED) { + SCROLLVIEW_INDEX++; + if (SCROLLVIEW_INDEX < 0)SCROLLVIEW_INDEX = SCROLLVIEW_RES.length-1; + if (SCROLLVIEW_INDEX >= SCROLLVIEW_RES.length)SCROLLVIEW_INDEX = 0; + this.runNextScene(); + } + }, + runNextScene: function () { + var scene = new cc.Scene(); + scene.addChild(new UIScrollViewEditorTest()); + cc.director.runScene(scene); + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/GUITest/UISliderTest/UISliderTest.js b/tests/js-tests/src/CocoStudioTest/GUITest/UISliderTest/UISliderTest.js new file mode 100644 index 0000000000..727e9cddc3 --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/GUITest/UISliderTest/UISliderTest.js @@ -0,0 +1,54 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var UISliderEditorTest = UIBaseLayer.extend({ + ctor: function () { + this._super(); + var root = this._parseUIFile("res/cocosui/CCS/Slider/slider_1.json"); + this._mainNode.addChild(root); + + var back_label =ccui.helper.seekWidgetByName(root, "back"); + back_label.addTouchEventListener(this.backEvent,this); + + var slider = ccui.helper.seekWidgetByName(root, "Slider_738"); + slider.addEventListener(this.sliderEvent,this); + + var scale9_slider = ccui.helper.seekWidgetByName(root, "Slider_740"); + scale9_slider.addEventListener(this.sliderEvent,this); + }, + + sliderEvent: function (sender, type) { + switch (type) { + case ccui.Slider.EVENT_PERCENT_CHANGED: + var slider = sender; + var percent = slider.getPercent(); + this._topDisplayText.setString("Percent " + percent.toFixed(0)); + break; + default: + break; + } + } +}); diff --git a/tests/js-tests/src/CocoStudioTest/GUITest/UITextAtlasTest/UITextAtlasTest.js b/tests/js-tests/src/CocoStudioTest/GUITest/UITextAtlasTest/UITextAtlasTest.js new file mode 100644 index 0000000000..d7aed9254c --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/GUITest/UITextAtlasTest/UITextAtlasTest.js @@ -0,0 +1,38 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + + +var UITextAtlasEditorTest = UIBaseLayer.extend({ + ctor: function () { + this._super(); + var root = this._parseUIFile("res/cocosui/CCS/LabelAtlas/labelatlas_1.json"); + + this._mainNode.addChild(root); + + var back_label =ccui.helper.seekWidgetByName(root, "back"); + back_label.addTouchEventListener(this.backEvent,this); + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/GUITest/UITextBMFontTest/UITextBMFontTest.js b/tests/js-tests/src/CocoStudioTest/GUITest/UITextBMFontTest/UITextBMFontTest.js new file mode 100644 index 0000000000..1b23e535e6 --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/GUITest/UITextBMFontTest/UITextBMFontTest.js @@ -0,0 +1,37 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + + +var UITextBMFontEditorTest = UIBaseLayer.extend({ + ctor: function () { + this._super(); + var root = this._parseUIFile("res/cocosui/CCS/LabelBMFont/labelbmfont_1.json"); + this._mainNode.addChild(root); + + var back_label =ccui.helper.seekWidgetByName(root, "back"); + back_label.addTouchEventListener(this.backEvent,this); + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/GUITest/UITextFieldTest/UITextFieldTest.js b/tests/js-tests/src/CocoStudioTest/GUITest/UITextFieldTest/UITextFieldTest.js new file mode 100644 index 0000000000..e8fa7a86a1 --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/GUITest/UITextFieldTest/UITextFieldTest.js @@ -0,0 +1,63 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var UITextFieldEditorTest = UIBaseLayer.extend({ + ctor: function () { + this._super(); + var root = this._parseUIFile("res/cocosui/CCS/TextField/textfield_1.json"); + this._mainNode.addChild(root); + + var back_label =ccui.helper.seekWidgetByName(root, "back"); + back_label.addTouchEventListener(this.backEvent,this); + + var textField_normal = ccui.helper.seekWidgetByName(root, "TextField_1109"); + textField_normal.addEventListener(this.textFieldEvent,this); + + var textField_max_character = ccui.helper.seekWidgetByName(root, "TextField_1110"); + textField_max_character.addEventListener(this.textFieldEvent,this); + + var textField_password = ccui.helper.seekWidgetByName(root, "TextField_1107"); + textField_password.addEventListener(this.textFieldEvent,this); + }, + textFieldEvent: function (sender, type) { + switch (type) { + case ccui.TextField. EVENT_ATTACH_WITH_IME: + this._topDisplayText.setString("attach with IME"); + break; + case ccui.TextField. EVENT_DETACH_WITH_IME: + this._topDisplayText.setString("detach with IME"); + break; + case ccui.TextField. EVENT_INSERT_TEXT: + this._topDisplayText.setString("insert words"); + break; + case ccui.TextField. EVENT_DELETE_BACKWARD: + this._topDisplayText.setString("delete word"); + break; + default: + break; + } + } +}); diff --git a/tests/js-tests/src/CocoStudioTest/GUITest/UITextTest/UITextTest.js b/tests/js-tests/src/CocoStudioTest/GUITest/UITextTest/UITextTest.js new file mode 100644 index 0000000000..ecadf762f1 --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/GUITest/UITextTest/UITextTest.js @@ -0,0 +1,37 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + + +var UITextEditorTest = UIBaseLayer.extend({ + ctor: function () { + this._super(); + var root = this._parseUIFile("res/cocosui/CCS/Label/label_1.json"); + this._mainNode.addChild(root); + + var back_label =ccui.helper.seekWidgetByName(root, "back"); + back_label.addTouchEventListener(this.backEvent,this); + } +}); diff --git a/tests/js-tests/src/CocoStudioTest/ParserTest/ParserTest.js b/tests/js-tests/src/CocoStudioTest/ParserTest/ParserTest.js new file mode 100644 index 0000000000..5fbd215ebc --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/ParserTest/ParserTest.js @@ -0,0 +1,151 @@ +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + + +var g_parsersTests = [ + { + title: "cocostudio 1.3", + test: function(){ + new CocostudioParserJsonScene("res/cocosui/CCS/ccs1_3/CCSV1_3_1.ExportJson").runThisTest(); + } + },{ + title: "cocostudio 1.4", + test: function(){ + new CocostudioParserJsonScene("res/cocosui/CCS/ccs1_4/CCS1_4_1.ExportJson").runThisTest(); + } + },{ + title: "cocostudio 1.5", + test: function(){ + new CocostudioParserJsonScene("res/cocosui/CCS/ccs1_5/CCS1_5_1.ExportJson").runThisTest(); + } + },{ + title: "cocostudio 2.1", + test: function(){ + new CocostudioParserJsonScene("res/cocosui/CCS/2.1/MainScene.json").runThisTest(); + } + } +]; + +var runParserTest = function () { + var pScene = new CocostudioParserJsonScene(); + if (pScene) { + pScene.runThisTest(); + } +}; + +var CocostudioParserJsonLayer = cc.Layer.extend({ + + _jsonFile: null, + + ctor: function(jsonFile){ + this._super(); + this._jsonFile = jsonFile; + }, + + onEnter: function(){ + this._super(); + cc.Layer.prototype.onEnter.call(this); + + var layout; + if(cocoStudioOldApiFlag == 0){ + cc.log("ccs.load : %s", this._jsonFile); + var json = ccs.load(this._jsonFile); + layout = json.node; + }else{ + //ccs.uiReader.widgetFromJsonFile only supports 1.x file + cc.log("ccs.uiReader.widgetFromJsonFile : %s", this._jsonFile); + var guiReader = ccs.uiReader; + layout = guiReader.widgetFromJsonFile(this._jsonFile); + } + if(layout){ + if(layout.getScale() == 1) + layout.setScale(0.7); + + this.addChild(layout); + } + } +}); + +var CocostudioParserJsonScene = cc.Scene.extend({ + + _jsonFile: null, + + ctor: function(jsonFile){ + this._super(); + if(jsonFile){ + this._jsonFile = jsonFile; + } + }, + + onEnter: function(){ + cc.Scene.prototype.onEnter.call(this); + + var label = new cc.LabelTTF("Back", "fonts/arial.ttf", 20); + //#endif + var pMenuItem = new cc.MenuItemLabel(label, this.BackCallback, this); + + var pMenu = new cc.Menu(pMenuItem); + + pMenu.setPosition( cc.p(0, 0) ); + pMenuItem.setPosition( cc.pAdd(cc.visibleRect.bottomRight,cc.p(-50,25)) ); + + this.addChild(pMenu, 1); + + }, + runThisTest: function(){ + if(this._jsonFile){ + var pLayer = new CocostudioParserJsonLayer(this._jsonFile); + this.addChild(pLayer); + }else{ + var winSize = cc.director.getWinSize(); + + var pMenu = new cc.Menu(); + pMenu.x = 0; + pMenu.y = 0; + cc.MenuItemFont.setFontName("fonts/arial.ttf"); + cc.MenuItemFont.setFontSize(24); + + for (var i = 0; i < g_parsersTests.length; ++i) { + var selItem = g_parsersTests[i]; + var pItem = new cc.MenuItemFont(selItem.title, + selItem.test, this); + pItem.x = winSize.width / 2; + pItem.y = winSize.height - (i + 1) * LINE_SPACE; + pMenu.addChild(pItem, ITEM_TAG_BASIC + i); + } + this.addChild(pMenu); + } + + cc.director.runScene(this); + }, + BackCallback: function(){ + cc.audioEngine.stopMusic(); + cc.audioEngine.stopAllEffects(); + if(this._jsonFile){ + new CocostudioParserJsonScene().runThisTest(); + }else{ + new CocoStudioTestScene().runThisTest(); + } + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/SceneTest/SceneEditorTest.js b/tests/js-tests/src/CocoStudioTest/SceneTest/SceneEditorTest.js new file mode 100644 index 0000000000..7a4238df2b --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/SceneTest/SceneEditorTest.js @@ -0,0 +1,547 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var sceneTestIdx = -1; + +var SceneEditorScene = TestScene.extend({ + onEnter: function () { + this._super(); + }, + runThisTest: function () { + sceneTestIdx = -1; + this.addChild(nextSceneEditorTest()); + director.runScene(this); + }, + onMainMenuCallback: function () { + var scene = new CocoStudioTestScene(); + scene.runThisTest(); + }, + onExit: function () { + this._super(); + } +}); +var sceneEditorArr = [ + function () { + return new LoadSceneEdtiorFileTest(); + }, + function () { + return new SpriteComponentTest(); + }, + function () { + return new ArmatureComponentTest(); + }, + function () { + return new UIComponentTest(); + }, + function () { + return new TmxMapComponentTest(); + }, + function () { + return new ParticleComponentTest(); + }, + function () { + return new EffectComponentTest(); + }, + function () { + return new BackgroundComponentTest(); + }, + function () { + return new AttributeComponentTest(); + }, + function () { + return new TriggerTest(); + } +]; + +var nextSceneEditorTest = function () { + sceneTestIdx++; + sceneTestIdx = sceneTestIdx % sceneEditorArr.length; + return sceneEditorArr[sceneTestIdx](); +}; + +var backSceneEditorTest = function () { + sceneTestIdx--; + if (sceneTestIdx < 0) + sceneTestIdx += sceneEditorArr.length; + + return sceneEditorArr[sceneTestIdx](); +}; + +var restartSceneEditorTest = function () { + return sceneEditorArr[sceneTestIdx](); +}; +var SceneEditorTestLayer = BaseTestLayer.extend({ + ctor: function () { + if (arguments.length === 0) { + this._super(cc.color(0, 0, 0, 255), cc.color(98, 99, 117, 255)); + } else { + this._super.apply(this, arguments); + } + }, + + onRestartCallback: function (sender) { + var s = new SceneEditorScene(); + s.addChild(restartSceneEditorTest()); + director.runScene(s); + }, + + onNextCallback: function (sender) { + var s = new SceneEditorScene(); + s.addChild(nextSceneEditorTest()); + director.runScene(s); + }, + + onBackCallback: function (sender) { + var s = new SceneEditorScene(); + s.addChild(backSceneEditorTest()); + director.runScene(s); + }, + onExit: function () { + ccs.armatureDataManager.clear(); + ccs.sceneReader.clear(); + ccs.actionManager.clear(); + ccs.uiReader.clear(); + this._super(); + }, + initSize:function(node){ + var winSize = cc.director.getWinSize(); + var scale = winSize.height / 320; + node.scale = scale; + node.x = (winSize.width - 480 * scale) / 2; + node.y = (winSize.height - 320 * scale) / 2; + } +}); + +var runSceneEditorTest = function () { + var pScene = new SceneEditorScene(); + if (pScene) { + pScene.runThisTest(); + } +}; + +//------------------------------------------------------------------ +// +// LoadSceneEdtiorFileTest +// +//------------------------------------------------------------------ +var LoadSceneEdtiorFileTest = SceneEditorTestLayer.extend({ + onEnter: function () { + this._super(); + var node, + file = "res/scenetest/LoadSceneEdtiorFileTest/FishJoy2.json"; + if(cocoStudioOldApiFlag == 0){ + cc.log("ccs.load : %s", file); + var json = ccs.load(file); + node = json.node; + }else{ + //ccs.sceneReader only supports 1.x file + cc.log("ccs.sceneReader.createNodeWithSceneFile : %s", file); + node = ccs.sceneReader.createNodeWithSceneFile(file); + } + this.addChild(node); + ccs.actionManager.playActionByName("startMenu_1.json", "Animation1"); + this.initSize(node); + }, + onExit: function() { + ccs.actionManager.releaseActions(); + this._super(); + }, + title: function () { + return "loadSceneEdtiorFile Test"; + } +}); + +//------------------------------------------------------------------ +// +// SpriteComponentTest +// +//------------------------------------------------------------------ +var SpriteComponentTest = SceneEditorTestLayer.extend({ + onEnter: function () { + this._super(); + var node, + file = "res/scenetest/SpriteComponentTest/SpriteComponentTest.json"; + if(cocoStudioOldApiFlag == 0){ + cc.log("ccs.load : %s", file); + var json = ccs.load(file); + node = json.node; + }else{ + //ccs.sceneReader only supports 1.x file + cc.log("ccs.sceneReader.createNodeWithSceneFile : %s", file); + node = ccs.sceneReader.createNodeWithSceneFile(file); + } + this.addChild(node); + + var action1 = cc.blink(2, 10); + var action2 = cc.blink(2, 5); + var sister1 = node.getChildByTag(10003).getComponent("CCSprite").getNode(); + sister1.runAction(action1); + + var sister2 = node.getChildByTag(10004).getComponent("CCSprite").getNode(); + sister2.runAction(action2); + + this.initSize(node); + }, + title: function () { + return "Sprite Component Test"; + } +}); + +//------------------------------------------------------------------ +// +// ArmatureComponentTest +// +//------------------------------------------------------------------ +var ArmatureComponentTest = SceneEditorTestLayer.extend({ + onEnter: function () { + this._super(); + var node, + file = "res/scenetest/ArmatureComponentTest/ArmatureComponentTest.json"; + if(cocoStudioOldApiFlag == 0){ + cc.log("ccs.load : %s", file); + var json = ccs.load(file); + node = json.node;ccs.load(file); + }else{ + //ccs.sceneReader only supports 1.x file + cc.log("ccs.sceneReader.createNodeWithSceneFile : %s", file); + node = ccs.sceneReader.createNodeWithSceneFile(file); + } + this.addChild(node); + + var blowFish = node.getChildByTag(10007).getComponent("CCArmature").getNode(); + blowFish.runAction(cc.moveBy(10, cc.p(-1000, 0))); + + var butterFlyFish = node.getChildByTag(10008).getComponent("CCArmature").getNode(); + butterFlyFish.runAction(cc.moveBy(10, cc.p(-1000, 0))); + + this.initSize(node); + }, + title: function () { + return "Armature Component Test"; + } +}); + +//------------------------------------------------------------------ +// +// UIComponentTest +// +//------------------------------------------------------------------ +var UIComponentTest = SceneEditorTestLayer.extend({ + _node: null, + onEnter: function () { + this._super(); + var node, + file = "res/scenetest/UIComponentTest/UIComponentTest.json"; + if(cocoStudioOldApiFlag == 0){ + cc.log("ccs.load : %s", file); + var json = ccs.load(file); + node = json.node; + }else{ + //ccs.sceneReader only supports 1.x file + cc.log("ccs.sceneReader.createNodeWithSceneFile : %s", file); + node = ccs.sceneReader.createNodeWithSceneFile(file); + } + this._node = node; + this.addChild(this._node); + var widget = this._node.getChildByTag(10025).getComponent("GUIComponent").getNode(); + var button = widget.getChildByName("Button_156"); + button.addTouchEventListener(this.touchEvent, this); + + this.initSize(this._node); + }, + touchEvent: function (sender, type) { + switch (type) { + case ccui.Widget.TOUCH_BEGAN: + var blowFish = this._node.getChildByTag(10010).getComponent("CCArmature").getNode(); + blowFish.runAction(cc.moveBy(10, cc.p(-1000, 0))); + + var butterFlyFish = this._node.getChildByTag(10011).getComponent("CCArmature").getNode(); + butterFlyFish.runAction(cc.moveBy(10, cc.p(-1000.0, 0))); + break; + default: + break; + } + }, + title: function () { + return "UI Component Test"; + } +}); + +//------------------------------------------------------------------ +// +// TmxMapComponentTest +// +//------------------------------------------------------------------ +var TmxMapComponentTest = SceneEditorTestLayer.extend({ + onEnter: function () { + this._super(); + var node, + file = "res/scenetest/TmxMapComponentTest/TmxMapComponentTest.json"; + if(cocoStudioOldApiFlag == 0){ + cc.log("ccs.load : %s", file); + var json = ccs.load(file); + node = json.node; + }else{ + //ccs.sceneReader only supports 1.x file + cc.log("ccs.sceneReader.createNodeWithSceneFile : %s", file); + node = ccs.sceneReader.createNodeWithSceneFile(file); + } + this.addChild(node); + var tmxMap = node.getChildByTag(10015).getComponent("CCTMXTiledMap").getNode(); + var actionTo = cc.skewTo(2, 0, 2); + var rotateTo = cc.rotateTo(2, 61); + var actionScaleTo = cc.scaleTo(2, -0.44, 0.47); + + var actionScaleToBack = cc.scaleTo(2, 1, 1); + var rotateToBack = cc.rotateTo(2, 0); + var actionToBack = cc.skewTo(2, 0, 0); + + tmxMap.runAction(cc.sequence(actionTo, actionToBack)); + tmxMap.runAction(cc.sequence(rotateTo, rotateToBack)); + tmxMap.runAction(cc.sequence(actionScaleTo, actionScaleToBack)); + + this.initSize(node); + }, + title: function () { + return "TmxMap Component Test"; + } +}); + + +//------------------------------------------------------------------ +// +// ParticleComponentTest +// +//------------------------------------------------------------------ +var ParticleComponentTest = SceneEditorTestLayer.extend({ + onEnter: function () { + this._super(); + var node, + file = "res/scenetest/ParticleComponentTest/ParticleComponentTest.json"; + if(cocoStudioOldApiFlag == 0){ + cc.log("ccs.load : %s", file); + var json = ccs.load(file); + node = json.node; + }else{ + //ccs.sceneReader only supports 1.x file + cc.log("ccs.sceneReader.createNodeWithSceneFile : %s", file); + node = ccs.sceneReader.createNodeWithSceneFile(file); + } + this.addChild(node); + + var particle = node.getChildByTag(10020).getComponent("CCParticleSystemQuad").getNode(); + var jump = cc.jumpBy(5, cc.p(-500, 0), 50, 4); + var action = cc.sequence(jump, jump.reverse()); + particle.runAction(action); + + this.initSize(node); + }, + title: function () { + return "Particle Component Test"; + } +}); + +//------------------------------------------------------------------ +// +// EffectComponentTest +// +//------------------------------------------------------------------ +var EffectComponentTest = SceneEditorTestLayer.extend({ + _node: null, + onEnter: function () { + this._super(); + var node, + file = "res/scenetest/EffectComponentTest/EffectComponentTest.json"; + if(cocoStudioOldApiFlag == 0){ + cc.log("ccs.load : %s", file); + var json = ccs.load(file); + node = json.node; + }else{ + //ccs.sceneReader only supports 1.x file + cc.log("ccs.sceneReader.createNodeWithSceneFile : %s", file); + node = ccs.sceneReader.createNodeWithSceneFile(file); + } + this._node = node; + this.addChild(this._node); + + var armature = this._node.getChildByTag(10015).getComponent("CCArmature").getNode(); + armature.getAnimation().setMovementEventCallFunc(this.animationEvent, this); + + this.initSize(this._node); + }, + title: function () { + return "Effect Component Test"; + }, + animationEvent: function (armature, movementType, movementID) { + if (movementType == ccs.MovementEventType.loopComplete) { + if (movementID == "Fire") { + var audio = this._node.getChildByTag(10015).getComponent("CCComAudio"); + audio.playEffect(); + } + } + } +}); + +//------------------------------------------------------------------ +// +// BackgroundComponentTest +// +//------------------------------------------------------------------ +var BackgroundComponentTest = SceneEditorTestLayer.extend({ + onEnter: function () { + this._super(); + var node, + file = "res/scenetest/BackgroundComponentTest/BackgroundComponentTest.json"; + if(cocoStudioOldApiFlag == 0){ + cc.log("ccs.load : %s", file); + var json = ccs.load(file); + node = json.node; + }else{ + //ccs.sceneReader only supports 1.x file + cc.log("ccs.sceneReader.createNodeWithSceneFile : %s", file); + node = ccs.sceneReader.createNodeWithSceneFile(file); + } + this.addChild(node); + ccs.actionManager.playActionByName("startMenu_1.json", "Animation1"); + + var audio = node.getComponent("CCBackgroundAudio"); + audio.playBackgroundMusic(); + + this.initSize(node); + }, + onExit: function() { + ccs.actionManager.releaseActions(); + this._super(); + }, + title: function () { + return "Background Component Test"; + } +}); + +//------------------------------------------------------------------ +// +// AttributeComponentTest +// +//------------------------------------------------------------------ +var AttributeComponentTest = SceneEditorTestLayer.extend({ + onEnter: function () { + this._super(); + var node, + file = "res/scenetest/AttributeComponentTest/AttributeComponentTest.json"; + if(cocoStudioOldApiFlag == 0){ + cc.log("ccs.load : %s", file); + var json = ccs.load(file); + node = json.node; + }else{ + //ccs.sceneReader only supports 1.x file + cc.log("ccs.sceneReader.createNodeWithSceneFile : %s", file); + node = ccs.sceneReader.createNodeWithSceneFile(file); + } + this.addChild(node); + + var comAttribute = node.getChildByTag(10015).getComponent("CCComAttribute"); + cc.log("name:" + comAttribute.getString("name")); + cc.log("maxHP:" + comAttribute.getFloat("maxHP")); + cc.log("maxMP:" + comAttribute.getFloat("maxMP")); + + this.initSize(node); + }, + title: function () { + return "Attribute Component Test"; + }, + subtitle:function(){ + return "See console"; + } +}); + +//------------------------------------------------------------------ +// +// TriggerTest +// +//------------------------------------------------------------------ +var TriggerTest = SceneEditorTestLayer.extend({ + _blowFishNode: null, + _flyFishNode: null, + onEnter: function () { + this._super(); + var node, + file = "res/scenetest/TriggerTest/TriggerTest.json"; + if(cocoStudioOldApiFlag == 0){ + cc.log("ccs.load : %s", file); + var json = ccs.load(file); + node = json.node; + }else{ + //ccs.sceneReader only supports 1.x file + cc.log("ccs.sceneReader.createNodeWithSceneFile : %s", file); + node = ccs.sceneReader.createNodeWithSceneFile(file); + } + this.addChild(node); + ccs.actionManager.playActionByName("startMenu_1.json", "Animation1"); + + this.schedule(this.gameLogic); + ccs.sendEvent(TRIGGER_EVENT_ENTERSCENE); + + var listener1 = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches: true, + onTouchBegan: this.onTouchBegan.bind(this), + onTouchMoved: this.onTouchMoved.bind(this), + onTouchEnded: this.onTouchEnded.bind(this) + }); + cc.eventManager.addListener(listener1, this); + this.initSize(node); + }, + onExit: function () { + ccs.actionManager.releaseActions(); + ccs.sendEvent(TRIGGER_EVENT_LEAVESCENE); + this.unschedule(this.gameLogic, this); + this._super(); + }, + + onTouchBegan: function (touch, event) { + ccs.sendEvent(TRIGGER_EVENT_TOUCHBEGAN); + return true; + }, + + onTouchMoved: function (touch, event) { + ccs.sendEvent(TRIGGER_EVENT_TOUCHMOVED); + }, + + onTouchEnded: function (touch, event) { + ccs.sendEvent(TRIGGER_EVENT_TOUCHENDED); + }, + + onTouchCancelled: function (touch, event) { + ccs.sendEvent(TRIGGER_EVENT_TOUCHCANCELLED); + }, + + gameLogic: function () { + ccs.sendEvent(TRIGGER_EVENT_UPDATESCENE); + }, + title: function () { + return "Trigger Test"; + } +}); diff --git a/tests/js-tests/src/CocoStudioTest/SceneTest/TriggerCode/Acts.js b/tests/js-tests/src/CocoStudioTest/SceneTest/TriggerCode/Acts.js new file mode 100644 index 0000000000..c25e015603 --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/SceneTest/TriggerCode/Acts.js @@ -0,0 +1,642 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var PlayMusic = ccs.BaseTriggerAction.extend({ + _tag: -1, + _comName: "", + _type: -1, + ctor: function () { + this._tag = -1; + this._comName = ""; + this._type = -1; + }, + + init: function () { + return true; + }, + + done: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + if (!node) + return; + var audio = node.getComponent(this._comName); + if (!audio) + return; + if (this._type == 0) { + audio.playBackgroundMusic(); + } + else if (this._type == 1) { + audio.playEffect(); + } + }, + + serialize: function (jsonVal) { + var dataitems = jsonVal["dataitems"] || []; + for (var i = 0; i < dataitems.length; i++) { + var subDict = dataitems[i]; + var key = subDict["key"]; + if (key == "Tag") { + this._tag = subDict["value"]; + continue; + } + if (key == "componentName") { + this._comName = subDict["value"]; + continue; + } + if (key == "type") { + this._type = subDict["value"]; + } + } + }, + + removeAll: function () { + } +}); + +var TMoveTo = ccs.BaseTriggerAction.extend({ + _tag: -1, + _duration: 0, + _pos: cc.p(0, 0), + ctor: function () { + this._tag = -1; + this._duration = 0; + this._pos = cc.p(0, 0); + }, + + init: function () { + return true; + }, + + done: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + if (!node) + return; + var actionTo = cc.moveTo(this._duration, cc.p(this._pos.x, this._pos.y)); + node.runAction(actionTo); + }, + + serialize: function (jsonVal) { + var dataitems = jsonVal["dataitems"] || []; + for (var i = 0; i < dataitems.length; i++) { + var subDict = dataitems[i]; + + var key = subDict["key"]; + if (key == "Tag") { + this._tag = subDict["value"]; + continue; + } + if (key == "Duration") { + this._duration = subDict["value"]; + continue; + } + if (key == "x") { + this._pos.x = subDict["value"]; + continue; + } + if (key == "y") { + this._pos.y = subDict["value"]; + } + } + }, + + removeAll: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + node.actionManager.removeAllActions(); + } +}); + +var TMoveBy = ccs.BaseTriggerAction.extend({ + _tag: -1, + _duration: 0, + _pos: cc.p(0, 0), + _reverse: false, + ctor: function () { + this._tag = -1; + this._duration = 0; + this._pos = cc.p(0, 0); + this._reverse = false; + }, + + init: function () { + return true; + }, + + done: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + if (!node) + return; + var moveBy = cc.moveBy(this._duration, cc.p(this._pos.x, this._pos.y)); + if (this._reverse) { + var actionByBack = moveBy.reverse(); + node.runAction(cc.sequence(moveBy, actionByBack)); + } else { + node.runAction(moveBy); + } + }, + + serialize: function (jsonVal) { + var dataitems = jsonVal["dataitems"] || []; + for (var i = 0; i < dataitems.length; i++) { + var subDict = dataitems[i]; + + var key = subDict["key"]; + if (key == "Tag") { + this._tag = subDict["value"]; + continue; + } + if (key == "Duration") { + this._duration = subDict["value"]; + continue; + } + if (key == "x") { + this._pos.x = subDict["value"]; + continue; + } + if (key == "y") { + this._pos.y = subDict["value"]; + continue; + } + if (key == "IsReverse") { + this._reverse = subDict["value"] || false; + } + } + }, + + removeAll: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + node.actionManager.removeAllActions(); + } +}); + +var TRotateTo = ccs.BaseTriggerAction.extend({ + _tag: -1, + _duration: 0, + _deltaAngle: 0, + ctor: function () { + this._tag = -1; + this._duration = 0; + this._deltaAngle = 0; + }, + + init: function () { + return true; + }, + + done: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + if (!node) + return; + var actionTo = cc.rotateTo(this._duration, this._deltaAngle); + node.runAction(actionTo); + }, + + serialize: function (jsonVal) { + var dataitems = jsonVal["dataitems"] || []; + for (var i = 0; i < dataitems.length; i++) { + var subDict = dataitems[i]; + + var key = subDict["key"]; + if (key == "Tag") { + this._tag = subDict["value"]; + continue; + } + if (key == "Duration") { + this._duration = subDict["value"]; + continue; + } + if (key == "DeltaAngle") { + this._deltaAngle = subDict["value"]; + } + } + }, + + removeAll: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + node.actionManager.removeAllActions(); + } +}); + +var TRotateBy = ccs.BaseTriggerAction.extend({ + _tag: -1, + _duration: 0, + _deltaAngle: 0, + _reverse: false, + ctor:function(){ + this._tag = -1; + this._duration = 0; + this._deltaAngle = 0; + this._reverse = false; + }, + + init: function () { + return true; + }, + + done: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + if (!node) + return; + var actionBy = cc.rotateBy(this._duration, this._deltaAngle); + if (this._reverse == true) { + var actionByBack = actionBy.reverse(); + node.runAction(cc.sequence(actionBy, actionByBack)); + } + else { + node.runAction(actionBy); + } + }, + + serialize: function (jsonVal) { + var dataitems = jsonVal["dataitems"] || []; + for (var i = 0; i < dataitems.length; i++) { + var subDict = dataitems[i]; + + var key = subDict["key"]; + if (key == "Tag") { + this._tag = subDict["value"]; + continue; + } + if (key == "Duration") { + this._duration = subDict["value"]; + continue; + } + if (key == "DeltaAngle") { + this._deltaAngle = subDict["value"]; + continue; + } + if (key == "IsReverse") { + this._reverse = subDict["value"]; + } + } + }, + + removeAll: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + node.actionManager.removeAllActions(); + } +}); + +var TScaleTo = ccs.BaseTriggerAction.extend({ + _tag: -1, + _duration: 0, + _scaleX: 0, + _scaleY: 0, + ctor: function () { + this._tag = -1; + this._duration = 0; + this._scaleX = 0; + this._scaleY = 0; + }, + + init: function () { + return true; + }, + + done: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + if (!node) + return; + var actionTo = cc.scaleTo(this._duration, this._scaleX, this._scaleY); + node.runAction(actionTo); + }, + + serialize: function (jsonVal) { + var dataitems = jsonVal["dataitems"] || []; + for (var i = 0; i < dataitems.length; i++) { + var subDict = dataitems[i]; + + var key = subDict["key"]; + if (key == "Tag") { + this._tag = subDict["value"]; + continue; + } + if (key == "Duration") { + this._duration = subDict["value"]; + continue; + } + if (key == "ScaleX") { + this._scaleX = subDict["value"]; + continue; + } + if (key == "ScaleY") { + this._scaleY = subDict["value"]; + } + } + }, + + removeAll: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + node.actionManager.removeAllActions(); + } +}); + +var TScaleBy = ccs.BaseTriggerAction.extend({ + _tag: -1, + _duration: 0, + _scaleX: 0, + _scaleY: 0, + _reverse: false, + ctor: function () { + this._tag = -1; + this._duration = 0; + this._scaleX = 0; + this._scaleY = 0; + this._reverse = false; + }, + + init: function () { + return true; + }, + + done: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + if (!node) + return; + var actionBy = cc.scaleBy(this._duration, this._scaleX, this._scaleY); + if (this._reverse == true) { + var actionByBack = actionBy.reverse(); + node.runAction(cc.sequence(actionBy, actionByBack)); + } + else { + node.runAction(actionBy); + } + }, + + serialize: function (jsonVal) { + var dataitems = jsonVal["dataitems"] || []; + for (var i = 0; i < dataitems.length; i++) { + var subDict = dataitems[i]; + + var key = subDict["key"]; + if (key == "Tag") { + this._tag = subDict["value"]; + continue; + } + if (key == "Duration") { + this._duration = subDict["value"]; + continue; + } + if (key == "ScaleX") { + this._scaleX = subDict["value"]; + continue; + } + if (key == "ScaleY") { + this._scaleY = subDict["value"]; + } + } + }, + + removeAll: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + node.actionManager.removeAllActions(); + } +}); + +var TSkewTo = ccs.BaseTriggerAction.extend({ + _tag: -1, + _duration: 0, + _skewX: 0, + _skewY: 0, + ctor: function () { + this._tag = -1; + this._duration = 0; + this._skewX = 0; + this._skewY = 0; + }, + + init: function () { + return true; + }, + + done: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + if (!node) + return; + var actionTo = cc.skewTo(this._duration, this._skewX, this._skewY); + node.runAction(actionTo); + }, + + serialize: function (jsonVal) { + var dataitems = jsonVal["dataitems"] || []; + for (var i = 0; i < dataitems.length; i++) { + var subDict = dataitems[i]; + + var key = subDict["key"]; + if (key == "Tag") { + this._tag = subDict["value"]; + continue; + } + if (key == "Duration") { + this._duration = subDict["value"]; + continue; + } + if (key == "SkewX") { + this._skewX = subDict["value"]; + continue; + } + if (key == "SkewY") { + this._skewY = subDict["value"]; + } + } + }, + + removeAll: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + node.actionManager.removeAllActions(); + } +}); + +var TSkewBy = ccs.BaseTriggerAction.extend({ + _tag: -1, + _duration: 0, + _skewX: 0, + _skewY: 0, + _reverse: false, + ctor: function () { + this._tag = -1; + this._duration = 0; + this._skewX = 0; + this._skewY = 0; + this._reverse = false; + }, + + init: function () { + return true; + }, + + done: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + if (!node) + return; + var actionBy = cc.skewBy(this._duration, this._skewX, this._skewY); + if (this._reverse == true) { + var actionByBack = actionBy.reverse(); + node.runAction(cc.sequence(actionBy, actionByBack)); + } + else { + node.runAction(actionBy); + } + }, + + serialize: function (jsonVal) { + var dataitems = jsonVal["dataitems"] || []; + for (var i = 0; i < dataitems.length; i++) { + var subDict = dataitems[i]; + + var key = subDict["key"]; + if (key == "Tag") { + this._tag = subDict["value"]; + continue; + } + if (key == "Duration") { + this._duration = subDict["value"]; + continue; + } + if (key == "SkewX") { + this._skewX = subDict["value"]; + continue; + } + if (key == "SkewY") { + this._skewY = subDict["value"]; + } + } + }, + + removeAll: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + node.actionManager.removeAllActions(); + } +}); + +var TriggerState = ccs.BaseTriggerAction.extend({ + _id: -1, + _state: 0, + ctor: function () { + this._id = -1; + this._state = 0; + }, + + init: function () { + return true; + }, + + done: function () { + var obj = ccs.triggerManager.getTriggerObj(this._id); + if (obj) { + if (this._state == 0) { + obj.setEnable(false); + } + else if (this._state == 1) { + obj.setEnable(true); + } + else if (this._state == 2) { + ccs.triggerManager.removeTriggerObj(this._id); + } + + } + }, + + serialize: function (jsonVal) { + var dataitems = jsonVal["dataitems"] || []; + for (var i = 0; i < dataitems.length; i++) { + var subDict = dataitems[i]; + + var key = subDict["key"]; + if (key == "ID") { + this._id = subDict["value"]; + continue; + } + if (key == "State") { + this._state = subDict["value"]; + } + } + }, + + removeAll: function () { + } +}); + +var ArmaturePlayAction = ccs.BaseTriggerAction.extend({ + _tag: -1, + _comName: 0, + _aniName: "", + ctor: function () { + this._tag = -1; + this._comName = 0; + this._aniName = ""; + }, + + init: function () { + return true; + }, + + done: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + if (!node) + return; + var render = node.getComponent(this._comName); + if (!render) + return; + var armature = render.getNode(); + if (!armature) + return; + armature.getAnimation().play(this._aniName); + }, + + serialize: function (jsonVal) { + var dataitems = jsonVal["dataitems"] || []; + for (var i = 0; i < dataitems.length; i++) { + var subDict = dataitems[i]; + + var key = subDict["key"]; + if (key == "ID") { + this._id = subDict["value"]; + continue; + } + if (key == "componentName") { + this._comName = subDict["value"]; + continue; + } + if (key == "AnimationName") { + this._aniName = subDict["value"]; + } + } + }, + + removeAll: function () { + } +}); + +ccs.registerTriggerClass("PlayMusic", PlayMusic); +ccs.registerTriggerClass("TMoveTo", TMoveTo); +ccs.registerTriggerClass("TMoveBy", TMoveBy); +ccs.registerTriggerClass("TRotateTo", TRotateTo); +ccs.registerTriggerClass("TRotateBy", TRotateBy); +ccs.registerTriggerClass("TScaleTo", TScaleTo); +ccs.registerTriggerClass("TScaleBy", TScaleBy); +ccs.registerTriggerClass("TSkewTo", TSkewTo); +ccs.registerTriggerClass("TSkewBy", TSkewBy); +ccs.registerTriggerClass("TriggerState", TriggerState); +ccs.registerTriggerClass("ArmaturePlayAction", ArmaturePlayAction); \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/SceneTest/TriggerCode/Cons.js b/tests/js-tests/src/CocoStudioTest/SceneTest/TriggerCode/Cons.js new file mode 100644 index 0000000000..3cc6a1cb6a --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/SceneTest/TriggerCode/Cons.js @@ -0,0 +1,245 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var TimeElapsed = ccs.BaseTriggerCondition.extend({ + _totalTime: 0, + _tmpTime: 0, + _scheduler: null, + _success: false, + ctor: function () { + this._totalTime = 0; + this._tmpTime = 0; + this._scheduler = null; + this._success = false; + this._scheduler = cc.director.getScheduler(); + }, + + init: function () { + this._scheduler.scheduleCallbackForTarget(this, this.update); + return true; + }, + + detect: function () { + return this._success; + }, + + serialize: function (jsonVal) { + var dataitems = jsonVal["dataitems"] || []; + for (var i = 0; i < dataitems.length; i++) { + var subDict = dataitems[i]; + var key = subDict["key"]; + if (key == "TotalTime") { + this._totalTime = subDict["value"]; + } + } + }, + + removeAll: function () { + this._scheduler.unscheduleUpdateForTarget(this); + }, + + update: function (dt) { + this._tmpTime += dt; + if (this._tmpTime > this._totalTime) { + this._tmpTime = 0.0; + this._success = true; + } + } +}); +var ArmatureActionState = ccs.BaseTriggerCondition.extend({ + _tag: -1, + _state: -1, + _success: false, + _aniName: "", + _comName: "", + _armature: null, + ctor: function () { + this._tag = -1; + this._state = -1; + this._success = false; + this._aniName = ""; + this._comName = ""; + this._armature = null; + }, + + init: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + if (!node) return false; + var render = node.getComponent(this._comName); + if (!render) return false; + var armature = render.getNode(); + if (!armature) return false; + this._armature = armature; + ccs.triggerManager.addArmatureMovementCallBack(this._armature, this.animationEvent, this); + return true; + }, + + detect: function () { + return this._success; + }, + + serialize: function (jsonVal) { + var dataitems = jsonVal["dataitems"] || []; + for (var i = 0; i < dataitems.length; i++) { + var subDict = dataitems[i]; + var key = subDict["key"]; + if (key == "TotalTime") { + this._totalTime = subDict["value"]; + continue; + } + if (key == "componentName") { + this._comName = subDict["value"]; + continue; + } + if (key == "AnimationName") { + this._aniName = subDict["value"]; + continue; + } + if (key == "ActionType") { + this._state = subDict["value"]; + } + } + }, + + removeAll: function () { + if (this._armature) { + ccs.triggerManager.removeArmatureMovementCallBack(this._armature, this.animationEvent, this); + } + }, + + animationEvent: function (armature, movementType, movementID) { + if (movementType == this._state && movementID == this._aniName) { + this._success = true; + } + } +}); +var NodeInRect = ccs.BaseTriggerCondition.extend({ + _tag: -1, + _origin: null, + _size: null, + ctor: function () { + this._tag = -1; + this._origin = null; + this._size = null; + this._origin = cc.p(0, 0); + this._size = cc.p(0, 0); + }, + + init: function () { + + return true; + }, + + detect: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + if (node && Math.abs(node.x - this._origin.x) <= this._size.width && Math.abs(node.y - this._origin.y) <= this._size.height) { + return true; + } + return false; + }, + serialize: function (jsonVal) { + var dataitems = jsonVal["dataitems"] || []; + for (var i = 0; i < dataitems.length; i++) { + var subDict = dataitems[i]; + var key = subDict["key"]; + if (key == "Tag") { + this._tag = subDict["value"]; + continue; + } + if (key == "originX") { + this._origin.x = subDict["value"]; + continue; + } + if (key == "originY") { + this._origin.y = subDict["value"]; + continue; + } + if (key == "originX") { + this._origin.x = subDict["value"]; + continue; + } + if (key == "originY") { + this._origin.y = subDict["value"]; + continue; + } + if (key == "sizeWidth") { + this._size.width = subDict["value"]; + continue; + } + if (key == "sizeHeight") { + this._size.height = subDict["value"]; + } + } + }, + + removeAll: function () { + + } +}); + +var NodeVisible = ccs.BaseTriggerCondition.extend({ + _tag: -1, + _visible: false, + cotr: function () { + this._tag = -1; + this._visible = false; + }, + + init: function () { + return true; + }, + + detect: function () { + var node = ccs.sceneReader.getNodeByTag(this._tag); + if (node && node.visible == this._visible) { + return true; + } + return false; + }, + serialize: function (jsonVal) { + var dataitems = jsonVal["dataitems"] || []; + for (var i = 0; i < dataitems.length; i++) { + var subDict = dataitems[i]; + var key = subDict["key"]; + if (key == "Tag") { + this._tag = subDict["value"]; + continue; + } + if (key == "Visible") { + this._visible = subDict["value"]; + } + } + }, + + removeAll: function () { + + } +}); + + +ccs.registerTriggerClass("TimeElapsed", TimeElapsed); +ccs.registerTriggerClass("ArmatureActionState", ArmatureActionState); +ccs.registerTriggerClass("NodeInRect", NodeInRect); +ccs.registerTriggerClass("NodeVisible", NodeVisible); \ No newline at end of file diff --git a/tests/js-tests/src/CocoStudioTest/SceneTest/TriggerCode/EventDef.js b/tests/js-tests/src/CocoStudioTest/SceneTest/TriggerCode/EventDef.js new file mode 100644 index 0000000000..f9bc131a73 --- /dev/null +++ b/tests/js-tests/src/CocoStudioTest/SceneTest/TriggerCode/EventDef.js @@ -0,0 +1,33 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var TRIGGER_EVENT_ENTERSCENE = 0; +var TRIGGER_EVENT_LEAVESCENE = 1; +var TRIGGER_EVENT_INITSCENE = 2; +var TRIGGER_EVENT_UPDATESCENE = 3; +var TRIGGER_EVENT_TOUCHBEGAN = 4; +var TRIGGER_EVENT_TOUCHMOVED = 5; +var TRIGGER_EVENT_TOUCHENDED = 6; +var TRIGGER_EVENT_TOUCHCANCELLED = 7; \ No newline at end of file diff --git a/tests/js-tests/src/CocosDenshionTest/CocosDenshionTest.js b/tests/js-tests/src/CocosDenshionTest/CocosDenshionTest.js new file mode 100644 index 0000000000..b076eca8e1 --- /dev/null +++ b/tests/js-tests/src/CocosDenshionTest/CocosDenshionTest.js @@ -0,0 +1,328 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var audioEngine = cc.audioEngine; + +var MUSIC_FILE = cc.sys.os == cc.sys.OS_WP8 || cc.sys.os == cc.sys.OS_WINRT ? "res/Sound/background-music-aac.wav" : "res/Sound/background.mp3"; +var EFFECT_FILE = cc.sys.os == cc.sys.OS_WP8 || cc.sys.os == cc.sys.OS_WINRT ? "res/Sound/pew-pew-lei.wav" : "res/Sound/effect2.mp3"; + +var _DenshionTests = [ + 'Music Test' +]; +var DenshionTests = [ + { + title:"Play Music", + playFunc:function () { + return new playMusic(); + } + }, + { + title:"Stop Music", + playFunc:function () { + return new stopMusic(); + } + }, + { + title:"Pause Music", + playFunc:function () { + return new pauseMusic(); + } + }, + { + title:"Resume Music", + playFunc:function () { + return new resumeMusic(); + } + }, + { + title:"Rewind Music", + playFunc:function () { + return new rewindMusic(); + } + }, + { + title:"is Music Playing", + playFunc:function () { + return new isMusicPlaying(); + } + }, + { + title:"Increase Music Volume", + playFunc:function () { + return new addMusicVolume(); + } + }, + { + title:"Decrease Music Volume", + playFunc:function () { + return new subMusicVolume(); + } + }, + { + title:"Play Sound Effect", + playFunc:function () { + return new playEffect(); + } + }, + { + title:"Repeat Sound Effect", + playFunc:function () { + return new playEffectRepeatly(); + } + }, + { + title:"Stop Sound Effect", + playFunc:function () { + return new stopEffect(); + } + }, + { + title:"Unload Sound Effect", + playFunc:function () { + return new unloadEffect(); + } + }, + { + title:"Increase Sound Effect Volume", + playFunc:function () { + return new addEffectsVolume(); + } + }, + { + title:"Decrease Sound Effect Volume", + playFunc:function () { + return new subEffectsVolume(); + } + }, + { + title:"Pause Sound Effect", + playFunc:function () { + return new pauseEffect(); + } + }, + { + title:"Resume Sound Effect", + playFunc:function () { + return new resumeEffect(); + } + }, + { + title:"Pause All Sound Effects", + playFunc:function () { + return new pauseAllEffects(); + } + }, + { + title:"Resume All Sound Effects", + playFunc:function () { + return new resumeAllEffects(); + } + }, + { + title:"Stop All Sound Effects", + playFunc:function () { + return new stopAllEffects(); + } + } +]; + +var CocosDenshionTest = cc.LayerGradient.extend({ + _itemMenu:null, + _beginPos:cc.p(0, 0), + _testCount:0, + ctor:function () { + this._super(cc.color(0, 0, 0, 255), cc.color(148, 80, 120, 255)); + + this._itemMenu = new cc.Menu(); + var winSize = director.getWinSize(); + for (var i = 0; i < DenshionTests.length; i++) { + var label = new cc.LabelTTF(DenshionTests[i].title, "Arial", 24); + var menuItem = new cc.MenuItemLabel(label, this.onMenuCallback, this); + this._itemMenu.addChild(menuItem, i + 10000); + menuItem.x = winSize.width / 2; + menuItem.y = winSize.height - (i + 1) * LINE_SPACE; + } + this._testCount = i; + this._itemMenu.width = winSize.width; + this._itemMenu.height = (this._testCount + 1) * LINE_SPACE; + this._itemMenu.x = 0; + this._itemMenu.y = 0; + this.addChild(this._itemMenu); + + if( 'touches' in cc.sys.capabilities ) { + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesMoved: function (touches, event) { + event.getCurrentTarget().moveMenu(touches[0].getDelta()); + } + }, this); + } else if ('mouse' in cc.sys.capabilities ) + cc.eventManager.addListener({ + event: cc.EventListener.MOUSE, + onMouseMove: function(event){ + if(event.getButton() == cc.EventMouse.BUTTON_LEFT) + event.getCurrentTarget().moveMenu(event.getDelta()); + } + }, this); + + // set default volume + audioEngine.setEffectsVolume(0.5); + audioEngine.setMusicVolume(0.5); + }, + onExit:function () { + this._super(); + audioEngine.stopMusic(); + audioEngine.stopAllEffects(); + }, + + onMenuCallback:function (sender) { + var idx = sender.zIndex - 10000; + // create the test scene and run it + var scene = DenshionTests[idx].playFunc(); + }, + + moveMenu:function (delta) { + var newY = this._itemMenu.y + delta.y; + + if (newY < 0) + newY = 0; + + if (newY > ((DenshionTests.length + 1) * LINE_SPACE - winSize.height)) + newY = ((DenshionTests.length + 1) * LINE_SPACE - winSize.height); + + this._itemMenu.y = newY; + } +}); + +var CocosDenshionTestScene = TestScene.extend({ + runThisTest:function () { + + audioEngine = cc.audioEngine; + var layer = new CocosDenshionTest(); + this.addChild(layer); + director.runScene(this); + } +}); + +var soundId = null; + +var playMusic = function () { + cc.log("play background music"); + audioEngine.playMusic(MUSIC_FILE, false); +}; + +var stopMusic = function () { + cc.log("stop background music"); + audioEngine.stopMusic(); +}; + +var pauseMusic = function () { + cc.log("pause background music"); + audioEngine.pauseMusic(); +}; + +var resumeMusic = function () { + cc.log("resume background music"); + audioEngine.resumeMusic(); +}; + +var rewindMusic = function () { + cc.log("rewind background music"); + audioEngine.rewindMusic(); +}; + +// is background music playing +var isMusicPlaying = function () { + if (audioEngine.isMusicPlaying()) { + cc.log("background music is playing"); + } + else { + cc.log("background music is not playing"); + } +}; + +var playEffect = function () { + cc.log("play effect"); + soundId = audioEngine.playEffect(EFFECT_FILE); +}; + +var playEffectRepeatly = function () { + cc.log("play effect repeatly"); + soundId = audioEngine.playEffect(EFFECT_FILE, true); +}; + +var stopEffect = function () { + cc.log("stop effect"); + audioEngine.stopEffect(soundId); +}; + +var unloadEffect = function () { + cc.log("unload effect"); + audioEngine.unloadEffect(EFFECT_FILE); +}; + +var addMusicVolume = function () { + cc.log("add bakcground music volume"); + audioEngine.setMusicVolume(audioEngine.getMusicVolume() + 0.1); +}; + +var subMusicVolume = function () { + cc.log("sub backgroud music volume"); + audioEngine.setMusicVolume(audioEngine.getMusicVolume() - 0.1); +}; + +var addEffectsVolume = function () { + cc.log("add effects volume"); + audioEngine.setEffectsVolume(audioEngine.getEffectsVolume() + 0.1); +}; + +var subEffectsVolume = function () { + cc.log("sub effects volume"); + audioEngine.setEffectsVolume(audioEngine.getEffectsVolume() - 0.1); +}; + +var pauseEffect = function () { + cc.log("pause effect"); + audioEngine.pauseEffect(soundId); +}; + +var resumeEffect = function () { + cc.log("resume effect"); + audioEngine.resumeEffect(soundId); +}; + +var pauseAllEffects = function () { + cc.log("pause all effects"); + audioEngine.pauseAllEffects(); +}; +var resumeAllEffects = function () { + cc.log("resume all effects"); + audioEngine.resumeAllEffects(); +}; +var stopAllEffects = function () { + cc.log("stop all effects"); + audioEngine.stopAllEffects(); +}; \ No newline at end of file diff --git a/tests/js-tests/src/CocosNodeTest/CocosNodeTest.js b/tests/js-tests/src/CocosNodeTest/CocosNodeTest.js new file mode 100644 index 0000000000..5cc47249be --- /dev/null +++ b/tests/js-tests/src/CocosNodeTest/CocosNodeTest.js @@ -0,0 +1,1075 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var TAG_SPRITE1 = 1; +var TAG_SPRITE2 = 2; +var TAG_SPRITE3 = 3; +var TAG_SLIDER = 4; + +var nodeTestSceneIdx = -1; +var MAX_LAYER = 9; + +var TestNodeDemo = BaseTestLayer.extend({ + ctor:function () { + this._super(); + }, + title:function () { + return "No title"; + }, + subtitle:function () { + return ""; + }, + onRestartCallback:function (sender) { + var s = new NodeTestScene(); + s.addChild(restartNodeTest()); + director.runScene(s); + }, + onNextCallback:function (sender) { + var s = new NodeTestScene(); + s.addChild(nextNodeTest()); + director.runScene(s); + }, + onBackCallback:function (sender) { + var s = new NodeTestScene(); + s.addChild(previousNodeTest()); + director.runScene(s); + }, + // automation + numberOfPendingTests:function () { + return ( (arrayOfNodeTest.length - 1) - nodeTestSceneIdx ); + }, + + getTestNumber:function () { + return nodeTestSceneIdx; + } +}); + +var CCNodeTest2 = TestNodeDemo.extend({ + onEnter:function () { + //----start0----onEnter + this._super(); + + var sp1 = new cc.Sprite(s_pathSister1); + var sp2 = new cc.Sprite(s_pathSister2); + var sp3 = new cc.Sprite(s_pathSister1); + var sp4 = new cc.Sprite(s_pathSister2); + + sp1.x = winSize.width / 4; + sp1.y = winSize.height / 2; + sp2.x = winSize.width / 4 * 3; + sp2.y = winSize.height / 2; + this.addChild(sp1); + this.addChild(sp2); + + sp3.scale = 0.25; + sp4.scale = 0.25; + + sp1.addChild(sp3); + sp2.addChild(sp4); + + var a1 = cc.rotateBy(2, 360); + var a2 = cc.scaleBy(2, 2); + var delay = cc.delayTime(0.2); + + var action1 = cc.sequence(a1, a2, delay, a2.reverse()).repeatForever(); + var action2 = cc.sequence(a1.clone(), a2.clone(), delay.clone(), a2.reverse()).repeatForever(); + + sp2.anchorX = 0; + sp2.anchorY = 0; + + sp1.runAction(action1); + sp2.runAction(action2); + //----end0---- + }, + title:function () { + return "anchorPoint and children"; + }, + // + // Automation + // + testDuration:4.1, + pixel1:{"0":255, "1":230, "2":204, "3":255}, + pixel2:{"0":204, "1":153, "2":102, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 4 - 54, winSize.height / 2 - 146, 5, 5); + var ret2 = this.readPixels(winSize.width / 4 * 3 + 93, winSize.height / 2 + 113, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1, true, 5) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2, true, 5) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +var SID_DELAY2 = 1; +var SID_DELAY4 = 2; +var CCNodeTest4 = TestNodeDemo.extend({ + ctor:function () { + //----start1----ctor + this._super(); + var sp1 = new cc.Sprite(s_pathSister1); + var sp2 = new cc.Sprite(s_pathSister2); + sp1.x = 150; + sp1.y = winSize.height / 2; + sp2.x = winSize.width - 150; + sp2.y = winSize.height / 2; + + this.addChild(sp1, 0, 2); + this.addChild(sp2, 0, 3); + + this.schedule(this.delay2, 2.0); + this.schedule(this.delay4, 4.0); + + //Automation param + this.autoParam = sp1; + //----end1---- + }, + delay2:function (dt) { + //----start1----delay2 + var node = this.getChildByTag(2); + var action1 = cc.rotateBy(1, 360); + node.runAction(action1); + //----end1---- + }, + delay4:function (dt) { + //----start1----delay4 + this.unschedule(this.delay4); + this.removeChildByTag(3, false); + //----end1---- + }, + title:function () { + return "tags"; + }, + // + // Automation + // + testDuration:1, + getExpectedResult:function () { + return this.autoParam; + }, + getCurrentResult:function () { + var node = this.getChildByTag(2); + return node; + } +}); + +var CCNodeTest5 = TestNodeDemo.extend({ + ctor:function () { + //----start2----ctor + this._super(); + var sp1 = new cc.Sprite(s_pathSister1); + var sp2 = new cc.Sprite(s_pathSister2); + sp1.x = 150; + sp1.y = winSize.height / 2; + sp2.x = winSize.width - 150; + sp2.y = winSize.height / 2; + + var rot = cc.rotateBy(2, 360); + var rot_back = rot.reverse(); + var forever = cc.sequence(rot, rot_back).repeatForever(); + var forever2 = forever.clone(); + forever.tag = 101; + forever2.tag = 102; + + this.addChild(sp1, 0, TAG_SPRITE1); + this.addChild(sp2, 0, TAG_SPRITE2); + + sp1.runAction(forever); + sp2.runAction(forever2); + + this.schedule(this.onAddAndRemove, 2.0); + //----end2---- + }, + onAddAndRemove:function (dt) { + //----start2----onAddAndRemove + var sp1 = this.getChildByTag(TAG_SPRITE1); + var sp2 = this.getChildByTag(TAG_SPRITE2); + + // hack for JSB. + sp1.retain(); + sp2.retain(); + + this.removeChild(sp1, false); + this.removeChild(sp2, true); + + this.testSP1 = this.getChildByTag(TAG_SPRITE1); + this.testSP2 = this.getChildByTag(TAG_SPRITE2); + + this.addChild(sp1, 0, TAG_SPRITE1); + this.addChild(sp2, 0, TAG_SPRITE2); + + // hack for JSB. + sp1.release(); + sp2.release(); + //----end2---- + }, + title:function () { + return "remove and cleanup"; + }, + // + // Automation + // + testDuration:2.5, + testSP1:null, + testSP2:null, + pixel1:{"0":0, "1":0, "2":0, "3":255}, + pixel2:{"0":51, "1":0, "2":0, "3":255}, + getExpectedResult:function () { + var ret = {"sp1":null, "sp2":null, "pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(134, 164, 5, 5); + var ret2 = this.readPixels(winSize.width - 148, winSize.height / 2 + 51, 5, 5); + var ret = {"sp1":this.testSP1, "sp2":this.testSP2, + "pixel1":this.containsPixel(ret1, this.pixel1, false) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2, true, 3) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +var CCNodeTest6 = TestNodeDemo.extend({ + ctor:function () { + //----start3----ctor + this._super(); + var sp1 = new cc.Sprite(s_pathSister1); + var sp11 = new cc.Sprite(s_pathSister1); + + var sp2 = new cc.Sprite(s_pathSister2); + var sp21 = new cc.Sprite(s_pathSister2); + + sp1.x = 150; + sp1.y = winSize.height / 2; + sp2.x = winSize.width - 150; + sp2.y = winSize.height / 2; + + var rot = cc.rotateBy(2, 360); + var rot_back = rot.reverse(); + var forever1 = cc.sequence(rot, rot_back).repeatForever(); + var forever11 = forever1.clone(); + + var forever2 = forever1.clone(); + var forever21 = forever1.clone(); + + this.addChild(sp1, 0, TAG_SPRITE1); + sp1.addChild(sp11, 11); + this.addChild(sp2, 0, TAG_SPRITE2); + sp2.addChild(sp21, 21); + + sp1.runAction(forever1); + sp11.runAction(forever11); + sp2.runAction(forever2); + sp21.runAction(forever21); + + this.schedule(this.onAddAndRemove, 2.0); + //----end3---- + }, + onAddAndRemove:function (dt) { + //----start3----onAddAndRemove + var sp1 = this.getChildByTag(TAG_SPRITE1); + var sp2 = this.getChildByTag(TAG_SPRITE2); + + // hack for JSB. + sp1.retain(); + sp2.retain(); + + this.removeChild(sp1, false); + this.removeChild(sp2, true); + + //Automation parameters + this.autoParam1 = sp1.getChildByTag(11); + this.autoParam2 = sp2.getChildByTag(21); + + this.addChild(sp1, 0, TAG_SPRITE1); + this.addChild(sp2, 0, TAG_SPRITE2); + + // hack for JSB. + sp1.release(); + sp2.release(); + //----end3---- + + }, + title:function () { + return "remove/cleanup with children"; + }, + // + // Automation + // + testDuration:2.1, + getExpectedResult:function () { + var ret = [null, null]; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret = [this.autoParam1, this.autoParam2]; + return JSON.stringify(ret); + } +}); + +var StressTest1 = TestNodeDemo.extend({ + ctor:function () { + //----start4----ctor + this._super(); + + var sp1 = new cc.Sprite(s_pathSister1); + this.addChild(sp1, 0, TAG_SPRITE1); + this.width = 0 + this.height = 0; + + sp1.x = winSize.width / 2; + sp1.y = winSize.height / 2; + + this.schedule(this.onShouldNotCrash, 1.0); + //----end4---- + }, + onShouldNotCrash:function (dt) { + //----start4----onShouldNotCrash + this.unschedule(this.onShouldNotCrash); + + // if the node has timers, it crashes + var explosion = new cc.ParticleSun(); + explosion.texture = cc.textureCache.addImage(s_fire); + + explosion.x = winSize.width / 2; + explosion.y = winSize.height / 2; + + this.runAction( + cc.sequence( + cc.rotateBy(2, 360), + cc.callFunc(this.onRemoveMe, this) + ) + ); + + this.addChild(explosion); + //----end4---- + }, + onRemoveMe:function (node) { + //----start4----onRemoveMe + if (autoTestEnabled) { + this.testPass = true; + return; + } + this.parent.removeChild(node, true); + this.onNextCallback(this); + //----end4---- + }, + title:function () { + return "stress test #1: no crashes"; + }, + // + // Automation + // + testDuration:3.2, + testPass:false, + getExpectedResult:function () { + var ret = {"pass":true}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret = {"pass":this.testPass}; + return JSON.stringify(ret); + } +}); + +var StressTest2 = TestNodeDemo.extend({ + ctor:function () { + //----start5----ctor + this._super(); + + var sublayer = new cc.Layer(); + + var sp1 = new cc.Sprite(s_pathSister1); + sp1.x = 80; + sp1.y = winSize.height / 2; + + var move = cc.moveBy(3, cc.p(350, 0)); + var move_ease_inout3 = move.clone().easing(cc.easeInOut(2.0)); + var move_ease_inout_back3 = move_ease_inout3.reverse(); + var seq3 = cc.sequence(move_ease_inout3, move_ease_inout_back3); + sp1.runAction(seq3.repeatForever()); + sublayer.addChild(sp1, 1); + + var fire = new cc.ParticleFire(); + fire.texture = cc.textureCache.addImage(s_fire); + fire.x = 80; + fire.y = winSize.height / 2 - 50; + + var copy_seq3 = seq3.clone(); + + fire.runAction(copy_seq3.repeatForever()); + sublayer.addChild(fire, 2); + + this.schedule(this.shouldNotLeak, 6.0); + + this.addChild(sublayer, 0, TAG_SPRITE1); + //----end5---- + }, + shouldNotLeak:function (dt) { + //----start5----shouleNotLeak + this.unschedule(this.shouldNotLeak); + var sublayer = this.getChildByTag(TAG_SPRITE1); + sublayer.removeAllChildren(); + //----end5---- + }, + title:function () { + return "stress test #2: no leaks"; + } +}); + +var NodeToWorld = TestNodeDemo.extend({ + ctor:function () { + //----start6----ctor + // This code tests that nodeToParent works OK: + // - It tests different anchor Points + // - It tests different children anchor points + this._super(); + var back = new cc.Sprite(s_back3); + this.addChild(back, 5); + back.anchorX = 0; + back.anchorY = 0; + + var item = new cc.MenuItemImage(s_playNormal, s_playSelect, this.onClicked); + var menu = new cc.Menu(item); + menu.alignItemsVertically(); + menu.x = back.width / 2; + menu.y = back.height / 2; + back.addChild(menu); + + var rot = cc.rotateBy(3, 360); + var delay = cc.delayTime(0.3); + var fe = cc.sequence(rot, delay).repeatForever(); + item.runAction(fe); + + var move = cc.moveBy(3, cc.p(200, 0)); + var move_back = move.reverse(); + var seq = cc.sequence(move, delay.clone(), move_back); + var fe2 = seq.repeatForever(); + back.runAction(fe2); + + //Automation parameters + this.autoParam = item; + //----end6---- + }, + onClicked:function () { + //----start6----ctor + cc.log("On clicked"); + //----end6---- + }, + title:function () { + return "nodeToParent transform"; + }, + // + // Automation + // + testDuration:3.1, + getExpectedResult:function () { + var ret = {"a":1, "b":"0.00", "c":"-0.00", "d":1, "tx":"378", "ty":"139"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret = this.autoParam.nodeToWorldTransform(); + ret.b = ret.b.toFixed(2); + ret.c = ret.c.toFixed(2); + ret.tx = ret.tx.toFixed(0); + ret.ty = ret.ty.toFixed(0); + return JSON.stringify(ret); + } +}); + +var CameraOrbitTest = TestNodeDemo.extend({ + ctor:function () { + //----start11----ctor + this._super(); + + var p = new cc.Sprite(s_back3); + this.addChild(p, 0); + p.x = winSize.width / 2; + p.y = winSize.height / 2; + p.opacity = 128; + + // LEFT + var sw = p.width, sh = p.height; + var sprite = new cc.Sprite(s_pathGrossini); + sprite.scale = 0.5; + p.addChild(sprite, 0); + sprite.x = sw / 4; + sprite.y = sh / 2; + var orbit = cc.orbitCamera(2, 1, 0, 0, 360, 0, 0); + sprite.runAction(orbit.repeatForever()); + + // CENTER + sprite = new cc.Sprite(s_pathGrossini); + sprite.scale = 1.0; + p.addChild(sprite, 0); + sprite.x = sw / 4 * 2; + sprite.y = sh / 2; + orbit = cc.orbitCamera(2, 1, 0, 0, 360, 45, 0); + sprite.runAction(orbit.repeatForever()); + + // RIGHT + sprite = new cc.Sprite(s_pathGrossini); + sprite.scale = 2.0; + p.addChild(sprite, 0); + sprite.x = sw / 4 * 3; + sprite.y = sh / 2; + orbit = cc.orbitCamera(2, 1, 0, 0, 360, 90, -45); + sprite.runAction(orbit.repeatForever()); + + // PARENT + orbit = cc.orbitCamera(10, 1, 0, 0, 360, 0, 90); + p.runAction(orbit.repeatForever()); + + this.scale = 1; + //----end11---- + }, + onEnter:function () { + //----start11----onEnter + this._super(); + director.setProjection(cc.Director.PROJECTION_3D); + //----end11---- + }, + onExit:function () { + //----start11----onExit + director.setProjection(cc.Director.PROJECTION_2D); + this._super(); + //----end11---- + }, + title:function () { + return "Camera Orbit test"; + } +}); + +var CameraZoomTest = TestNodeDemo.extend({ + _z:0, + ctor:function () { + //----start12----ctor + this._super(); + + // LEFT + var sprite = new cc.Sprite(s_pathGrossini); + this.addChild(sprite, 0); + sprite.x = winSize.width / 4; + sprite.y = winSize.height / 2; + if ("opengl" in cc.sys.capabilities) { + var cam = sprite.getCamera(); + cam.setEye(0, 0, 415 / 2); + cam.setCenter(0, 0, 0); + } + + // CENTER + sprite = new cc.Sprite(s_pathGrossini); + this.addChild(sprite, 0, 40); + sprite.x = winSize.width / 4 * 2; + sprite.y = winSize.height / 2; + //cam = [sprite camera); + //[cam setEyeX:0 eyeY:0 eyeZ:415/2); + + // RIGHT + sprite = new cc.Sprite(s_pathGrossini); + this.addChild(sprite, 0, 20); + sprite.x = winSize.width / 4 * 3; + sprite.y = winSize.height / 2; + //cam = [sprite camera); + //[cam setEyeX:0 eyeY:0 eyeZ:-485); + //[cam setCenterX:0 centerY:0 centerZ:0); + + this._z = 0; + this.scheduleUpdate(); + + //Automation parameters + this.autoParam = sprite; + //----end12---- + }, + update:function (dt) { + //----start12----update + if (!("opengl" in cc.sys.capabilities)) + return; + + this._z += dt * 100; + var sprite = this.getChildByTag(20); + var cam = sprite.getCamera(); + cam.setEye(0, 0, this._z); + if(!cc.sys.isNative) + sprite.setNodeDirty(); + + sprite = this.getChildByTag(40); + cam = sprite.getCamera(); + cam.setEye(0, 0, -this._z); + if(!cc.sys.isNative) + sprite.setNodeDirty(); + //----end12---- + }, + onEnter:function () { + //TODO + //----start12----onEnter + this._super(); + director.setProjection(cc.Director.PROJECTION_3D); + //----end12---- + }, + onExit:function () { + //TODO + //----start12----onExit + director.setProjection(cc.Director.PROJECTION_2D); + this._super(); + //----end12---- + }, + title:function () { + return "Camera Zoom test"; + }, + // + // Automation + // + testDuration:1.1, + pixel:{"0":115, "1":0, "2":115, "3":255}, + getExpectedResult:function () { + var ret1 = {"z":this._z.toFixed(2)}; + var ret2 = {"pixel":"yes"}; + return JSON.stringify([ret1, ret2]); + }, + getCurrentResult:function () { + var ret1 = {"z":this.autoParam.getCamera().getEye().z.toFixed(2)}; + var readPixel = this.readPixels(winSize.width / 4 * 3, winSize.height / 2, 5, 5); + var ret2 = {"pixel":!this.containsPixel(readPixel, this.pixel, false) ? "yes" : "no"}; + return JSON.stringify([ret1, ret2]); + } +}); + +var CameraCenterTest = TestNodeDemo.extend({ + ctor:function () { + //----start10----ctor + this._super(); + + // LEFT-TOP + var sprite = new cc.Sprite(s_texture512); + this.addChild(sprite, 0); + sprite.x = winSize.width / 5; + sprite.y = winSize.height / 5; + sprite.color = cc.color.RED; + sprite.setTextureRect(cc.rect(0, 0, 120, 50)); + var orbit = cc.orbitCamera(10, 1, 0, 0, 360, 0, 0); + sprite.runAction(orbit.repeatForever()); + + // LEFT-BOTTOM + sprite = new cc.Sprite(s_texture512); + this.addChild(sprite, 0, 40); + sprite.x = winSize.width / 5; + sprite.y = winSize.height / 5 * 4; + sprite.color = cc.color.BLUE; + sprite.setTextureRect(cc.rect(0, 0, 120, 50)); + orbit = cc.orbitCamera(10, 1, 0, 0, 360, 0, 0); + sprite.runAction(orbit.repeatForever()); + + // RIGHT-TOP + sprite = new cc.Sprite(s_texture512); + this.addChild(sprite, 0); + sprite.x = winSize.width / 5 * 4; + sprite.y = winSize.height / 5; + sprite.color = cc.color.YELLOW; + sprite.setTextureRect(cc.rect(0, 0, 120, 50)); + orbit = cc.orbitCamera(10, 1, 0, 0, 360, 0, 0); + sprite.runAction(orbit.repeatForever()); + + // RIGHT-BOTTOM + sprite = new cc.Sprite(s_texture512); + this.addChild(sprite, 0, 40); + sprite.x = winSize.width / 5 * 4; + sprite.y = winSize.height / 5 * 4; + sprite.color = cc.color.GREEN; + sprite.setTextureRect(cc.rect(0, 0, 120, 50)); + orbit = cc.orbitCamera(10, 1, 0, 0, 360, 0, 0); + sprite.runAction(orbit.repeatForever()); + + // CENTER + sprite = new cc.Sprite(s_texture512); + this.addChild(sprite, 0, 40); + sprite.x = winSize.width / 2; + sprite.y = winSize.height / 2; + sprite.color = cc.color.WHITE; + sprite.setTextureRect(cc.rect(0, 0, 120, 50)); + orbit = cc.orbitCamera(10, 1, 0, 0, 360, 0, 0); + sprite.runAction(orbit.repeatForever()); + //----end10---- + }, + + onEnter:function(){ + //----start10----onEnter + this._super(); + cc.director.setProjection(cc.Director.PROJECTION_3D); + //----end10---- + }, + + onExit:function(){ + //----start10----onExit + cc.director.setProjection(cc.Director.PROJECTION_2D); + this._super(); + //----end10---- + }, + + title:function () { + return "Camera Center test"; + }, + subtitle:function () { + return "Sprites should rotate at the same speed"; + }, + // + // Automation + // + testDuration:2.6, + pixel1:{"0":255, "1":255, "2":255, "3":255}, + pixel2:{"0":255, "1":255, "2":255, "3":255}, + pixel3:{"0":255, "1":255, "2":255, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 2, winSize.height / 2, 5, 5); + var ret2 = this.readPixels(winSize.width / 2 - 25, winSize.height / 2, 5, 5); + var ret3 = this.readPixels(winSize.width / 2 + 20, winSize.height / 2, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1, false) ? "yes" : "no", + "pixel2":!this.containsPixel(ret2, this.pixel2, false) ? "yes" : "no", + "pixel3":!this.containsPixel(ret3, this.pixel3, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +// +// ConvertToNode +// +var ConvertToNode = TestNodeDemo.extend({ + ctor:function () { + //----start9----ctor + this._super(); + if ('touches' in cc.sys.capabilities){ + cc.eventManager.addListener(cc.EventListener.create({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded:function (touches, event) { + var target = event.getCurrentTarget(); + for (var it = 0; it < touches.length; it++) { + var touch = touches[it]; + var location = touch.getLocation(); + target.processEvent(location); + } + } + }), this); + } else if ('mouse' in cc.sys.capabilities) + cc.eventManager.addListener({ + event: cc.EventListener.MOUSE, + onMouseUp: function(event){ + event.getCurrentTarget().processEvent(event.getLocation()); + } + }, this); + + var rotate = cc.rotateBy(10, 360); + var action = rotate.repeatForever(); + for (var i = 0; i < 3; i++) { + var sprite = new cc.Sprite(s_pathGrossini); + sprite.x = winSize.width / 4 * (i + 1); + sprite.y = winSize.height / 2; + var point = new cc.Sprite(s_pathR1); + point.scale = 0.25; + point.x = sprite.x; + point.y = sprite.y; + this.addChild(point, 10, 100 + i); + + switch (i) { + case 0: + sprite.anchorX = 0; + sprite.anchorY = 0; + break; + case 1: + sprite.anchorX = 0.5; + sprite.anchorY = 0.5; + break; + case 2: + sprite.anchorX = 1; + sprite.anchorY = 1; + break; + } + + point.x = sprite.x; + point.y = sprite.y; + + var copy = action.clone(); + sprite.runAction(copy); + this.addChild(sprite, i); + } + //----end9---- + }, + processEvent:function (location) { + //----start9----processEvent + this.testP1 = []; + this.testP2 = []; + for (var i = 0; i < 3; i++) { + var node = this.getChildByTag(100 + i); + + var p1 = node.convertToNodeSpaceAR(location); + var p2 = node.convertToNodeSpace(location); + + cc.log("AR: x=" + p1.x.toFixed(2) + ", y=" + p1.y.toFixed(2) + " -- Not AR: x=" + p2.x.toFixed(2) + ", y=" + p2.y.toFixed(2)); + + this.testP1.push({"x":p1.x, "y":p1.y}); + this.testP2.push({"x":p2.x, "y":p2.y}); + } + //----end9---- + }, + + title:function () { + return "Convert To Node Space"; + }, + subtitle:function () { + return "testing convertToNodeSpace / AR. Touch and see console"; + }, + // + // Automation + // + testDuration:1, + testP1:[], + expectedP1:[], + testP2:[], + expectedP2:[], + setupAutomation:function () { + this.expectedP1.push({"x":-winSize.width, "y":-winSize.height * 2}); + this.expectedP1.push({"x":-winSize.width * 2, "y":-winSize.height * 2}); + this.expectedP1.push({"x":-winSize.width * 3, "y":-winSize.height * 2}); + + this.expectedP2.push({"x":-winSize.width + 24.5, "y":-winSize.height * 2 + 23.5}); + this.expectedP2.push({"x":-winSize.width * 2 + 24.5, "y":-winSize.height * 2 + 23.5}); + this.expectedP2.push({"x":-winSize.width * 3 + 24.5, "y":-winSize.height * 2 + 23.5}); + }, + getExpectedResult:function () { + return JSON.stringify({"p1":this.expectedP1, "p2":this.expectedP2}); + }, + getCurrentResult:function () { + this.processEvent(cc.p(0, 0)); + var ret = {"p1":this.testP1, "p2":this.testP2}; + return JSON.stringify(ret); + } +}); + +// +// BoundingBox Test +// +var BoundingBoxTest = TestNodeDemo.extend({ + ctor:function () { + //----start8----ctor + this._super(); + var sprite = new cc.Sprite(s_pathGrossini); + this.addChild(sprite); + sprite.x = winSize.width / 2; + sprite.y = winSize.height / 2; + var bb = sprite.getBoundingBox(); + this.log('BoundingBox:'); + //for( var i in bb ) + // cc.log( i + " = " + bb[i] ); + cc.log('origin = [ ' + bb.x + "," + bb.y + "]"); + cc.log('size = [ ' + bb.width + "," + bb.height + "]"); + + this.testBB = bb; + //----end8---- + }, + title:function () { + return "Bounding Box Test"; + }, + subtitle:function () { + return "Testing getBoundingBox(). See console"; + }, + // + // Automation + // + testDuration:0.5, + testBB:null, + getExpectedResult:function () { + var ret = {"x":0 | (winSize.width / 2 - 42.5), "y":0 | (winSize.height / 2 - 60.5), "w":85, "h":121}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret = {"x":0 | this.testBB.x, "y":0 | this.testBB.y, "w":this.testBB.width, "h":this.testBB.height}; + return JSON.stringify(ret); + } +}); + +var SchedulerTest1 = TestNodeDemo.extend({ + ctor:function () { + //----start7----ctor + this._super(); + var layer = new cc.Layer(); + //UXLOG("retain count after init is %d", layer->retainCount()); + // 1 + + this.addChild(layer, 0); + //UXLOG("retain count after addChild is %d", layer->retainCount()); + // 2 + + layer.schedule(this.doSomething); + //UXLOG("retain count after schedule is %d", layer->retainCount()); + // 3 : (object-c viersion), but win32 version is still 2, because CCTimer class don't save target. + + layer.unschedule(this.doSomething); + //UXLOG("retain count after unschedule is %d", layer->retainCount()); + // STILL 3! (win32 is '2') + //----end7---- + }, + + doSomething:function (dt) { + //----start7----doSomething + this.testBool = false; + //----end7---- + }, + + title:function () { + return "cocosnode scheduler test #1"; + }, + // + // Automation + // + testDuration:0.5, + testBool:true, + getExpectedResult:function () { + return true; + }, + getCurrentResult:function () { + return this.testBool; + } +}); + +var NodeOpaqueTest = TestNodeDemo.extend({ + ctor:function () { + //----start13----ctor + this._super(); + var winSize = cc.director.getWinSize(); + var background; + for (var i = 0; i < 50; i++) { + background = new cc.Sprite(s_back1); + background.setBlendFunc(cc.ONE, cc.ONE_MINUS_SRC_ALPHA); + background.x = winSize.width / 2; + background.y = winSize.height / 2; + this.addChild(background); + } + //----end13---- + }, + + title:function () { + return "Node Opaque Test"; + }, + + subtitle:function () { + return "Node rendered with GL_BLEND disabled"; + } +}); + +var NodeNonOpaqueTest = TestNodeDemo.extend({ + ctor:function () { + //----start14----ctor + this._super(); + var winSize = cc.director.getWinSize(); + var background; + for (var i = 0; i < 50; i++) { + background = new cc.Sprite(s_back1); + background.setBlendFunc(cc.ONE, cc.ZERO); + background.x = winSize.width / 2; + background.y = winSize.height / 2; + this.addChild(background); + } + //----end14---- + }, + title:function () { + return "Node Non Opaque Test"; + }, + + subtitle:function () { + return "Node rendered with GL_BLEND enabled"; + } +}); + +// +// MAIN ENTRY POINT +// +var NodeTestScene = TestScene.extend({ + runThisTest:function (num) { + nodeTestSceneIdx = (num || num == 0) ? (num - 1) : -1; + MAX_LAYER = 9; + var layer = nextNodeTest(); + this.addChild(layer); + + director.runScene(this); + } +}); + +// +// Flow control +// +var arrayOfNodeTest = [ + CCNodeTest2, + CCNodeTest4, + CCNodeTest5, + CCNodeTest6, + StressTest1, + StressTest2, + NodeToWorld, + SchedulerTest1, + BoundingBoxTest, + ConvertToNode +]; + +if ('opengl' in cc.sys.capabilities) { + cc.sys.isNative || arrayOfNodeTest.push(CameraCenterTest); + arrayOfNodeTest.push(CameraOrbitTest); + cc.sys.isNative || arrayOfNodeTest.push(CameraZoomTest); + arrayOfNodeTest.push(NodeOpaqueTest); + arrayOfNodeTest.push(NodeNonOpaqueTest); +} + + +var nextNodeTest = function () { + nodeTestSceneIdx++; + nodeTestSceneIdx = nodeTestSceneIdx % arrayOfNodeTest.length; + + if(window.sideIndexBar){ + nodeTestSceneIdx = window.sideIndexBar.changeTest(nodeTestSceneIdx, 24); + } + + return new arrayOfNodeTest[nodeTestSceneIdx](); +}; +var previousNodeTest = function () { + nodeTestSceneIdx--; + if (nodeTestSceneIdx < 0) + nodeTestSceneIdx += arrayOfNodeTest.length; + + if(window.sideIndexBar){ + nodeTestSceneIdx = window.sideIndexBar.changeTest(nodeTestSceneIdx, 24); + } + + return new arrayOfNodeTest[nodeTestSceneIdx](); +}; +var restartNodeTest = function () { + return new arrayOfNodeTest[nodeTestSceneIdx](); +}; + + +new RegExp() \ No newline at end of file diff --git a/tests/js-tests/src/CurrentLanguageTest/CurrentLanguageTest.js b/tests/js-tests/src/CurrentLanguageTest/CurrentLanguageTest.js new file mode 100644 index 0000000000..8d36605cf1 --- /dev/null +++ b/tests/js-tests/src/CurrentLanguageTest/CurrentLanguageTest.js @@ -0,0 +1,85 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var CurrentLanguageTest = cc.Layer.extend({ + ctor:function () { + this._super(); + + var s = cc.director.getWinSize(); + var label = new cc.LabelTTF("Current language Test", "Arial", 28); + this.addChild(label, 0); + label.x = s.width / 2; + label.y = s.height - 50; + + var labelLanguage = new cc.LabelTTF("", "Arial", 20); + labelLanguage.x = s.width / 2; + labelLanguage.y = s.height / 2; + + var currentLanguageType = cc.sys.language; + switch (currentLanguageType) { + case cc.sys.LANGUAGE_ENGLISH: + labelLanguage.setString("current language is English"); + break; + case cc.sys.LANGUAGE_CHINESE: + labelLanguage.setString("current language is Chinese"); + break; + case cc.sys.LANGUAGE_FRENCH: + labelLanguage.setString("current language is French"); + break; + case cc.sys.LANGUAGE_GERMAN: + labelLanguage.setString("current language is German"); + break; + case cc.sys.LANGUAGE_ITALIAN: + labelLanguage.setString("current language is Italian"); + break; + case cc.sys.LANGUAGE_RUSSIAN: + labelLanguage.setString("current language is Russian"); + break; + case cc.sys.LANGUAGE_SPANISH: + labelLanguage.setString("current language is Spanish"); + break; + } + + this.addChild(labelLanguage); + } +}); + +var CurrentLanguageTestScene = TestScene.extend({ + runThisTest:function () { + if(window.sideIndexBar){ + window.sideIndexBar.changeTest(0, 8); + } + + var layer = new CurrentLanguageTest(); + this.addChild(layer); + + cc.director.runScene(this); + } +}); + +var arrayOfCurrentLanguageTest = [ + CurrentLanguageTest +]; \ No newline at end of file diff --git a/tests/js-tests/src/DrawPrimitivesTest/DrawPrimitivesTest.js b/tests/js-tests/src/DrawPrimitivesTest/DrawPrimitivesTest.js new file mode 100644 index 0000000000..dba7b44657 --- /dev/null +++ b/tests/js-tests/src/DrawPrimitivesTest/DrawPrimitivesTest.js @@ -0,0 +1,246 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var drawTestSceneIdx = -1; + +//------------------------------------------------------------------ +// +// DrawTestDemo +// +//------------------------------------------------------------------ +var DrawTestDemo = BaseTestLayer.extend({ + _title:"", + _subtitle:"", + + ctor:function() { + this._super(cc.color(0,0,0,255), cc.color(98,99,117,255)); + }, + + onRestartCallback:function (sender) { + var s = new DrawPrimitivesTestScene(); + s.addChild(restartDrawTest()); + director.runScene(s); + }, + onNextCallback:function (sender) { + var s = new DrawPrimitivesTestScene(); + s.addChild(nextDrawTest()); + director.runScene(s); + }, + onBackCallback:function (sender) { + var s = new DrawPrimitivesTestScene(); + s.addChild(previousDrawTest()); + director.runScene(s); + }, + // automation + numberOfPendingTests:function() { + return ( (arrayOfDrawTest.length-1) - drawTestSceneIdx ); + }, + + getTestNumber:function() { + return drawTestSceneIdx; + } + +}); + +//------------------------------------------------------------------ +// +// Testing cc.DrawNode API 2 +// +//------------------------------------------------------------------ +var DrawNewAPITest2 = DrawTestDemo.extend({ + _title: "cc.DrawNode", + _subtitle: "Testing cc.DrawNode API 2", + ctor: function () { + //----start0----ctor + this._super(); + var draw = new cc.DrawNode(); + this.addChild(draw, 10); + var winSize = cc.director.getWinSize(); + var centerPos = cc.p(winSize.width / 2, winSize.height / 2); + //drawSegment + draw.drawSegment(cc.p(0, 0), cc.p(winSize.width, winSize.height), 1, cc.color(255, 255, 255, 255)); + draw.drawSegment(cc.p(0, winSize.height), cc.p(winSize.width, 0), 5, cc.color(255, 0, 0, 255)); + + //drawDot + draw.drawDot(cc.p(winSize.width / 2, winSize.height / 2), 40, cc.color(0, 0, 255, 128)); + var points = [cc.p(60, 60), cc.p(70, 70), cc.p(60, 70), cc.p(70, 60)]; + for (var i = 0; i < points.length; i++) { + draw.drawDot(points[i], 4, cc.color(0, 255, 255, 255)); + } + //drawCircle + draw.drawCircle(cc.p(winSize.width / 2, winSize.height / 2), 100, 0, 10, false, 6, cc.color(0, 255, 0, 255)); + draw.drawCircle(cc.p(winSize.width / 2, winSize.height / 2), 50, cc.degreesToRadians(90), 50, true, 2, cc.color(0, 255, 255, 255)); + + //draw poly + //not fill + var vertices = [cc.p(0, 0), cc.p(50, 50), cc.p(100, 50), cc.p(100, 100), cc.p(50, 100) ]; + draw.drawPoly(vertices, null, 5, cc.color(255, 255, 0, 255)); + var vertices2 = [cc.p(30, 130), cc.p(30, 230), cc.p(50, 200)]; + draw.drawPoly(vertices2, null, 2, cc.color(255, 0, 255, 255)); + //fill + var vertices3 = [cc.p(60, 130), cc.p(60, 230), cc.p(80, 200)]; + draw.drawPoly(vertices3, cc.color(0, 255, 255, 50), 2, cc.color(255, 0, 255, 255)); + + //draw rect + //not fill + draw.drawRect(cc.p(120, 120), cc.p(200, 200), null, 2, cc.color(255, 0, 255, 255)); + //fill + draw.drawRect(cc.p(120, 220), cc.p(200, 300), cc.color(0, 255, 255, 50), 2, cc.color(128, 128, 0, 255)); + + // draw quad bezier path + draw.drawQuadBezier(cc.p(0, winSize.height), cc.p(centerPos.x, centerPos.y), cc.p(winSize.width, winSize.height), 50, 2, cc.color(255, 0, 255, 255)); + + // draw cubic bezier path + draw.drawCubicBezier(cc.p(winSize.width / 2, winSize.height / 2), cc.p(winSize.width / 2 + 30, winSize.height / 2 + 50), + cc.p(winSize.width / 2 + 60, winSize.height / 2 - 50), cc.p(winSize.width, winSize.height / 2), 100, 2, cc.color(255, 0, 255, 255)); + + //draw cardinal spline + var vertices4 = [ + cc.p(centerPos.x - 130, centerPos.y - 130), + cc.p(centerPos.x - 130, centerPos.y + 130), + cc.p(centerPos.x + 130, centerPos.y + 130), + cc.p(centerPos.x + 130, centerPos.y - 130), + cc.p(centerPos.x - 130, centerPos.y - 130) + ]; + draw.drawCardinalSpline(vertices4, 0.5, 100, 2, cc.color(255, 255, 255, 255)); + //----end0---- + } +}); +DrawNewAPITest2.prototype.title = function(){ + return 'cc.DrawNode 2'; +}; + +//------------------------------------------------------------------ +// +// Draw New API Test +// +//------------------------------------------------------------------ +var DrawNewAPITest = DrawTestDemo.extend({ + _title : "cc.DrawNode", + _subtitle : "Testing cc.DrawNode API", + + ctor:function() { + //----start1----ctor + this._super(); + + var draw = new cc.DrawNode(); + this.addChild(draw, 10); + // + // Circles + // + for( var i=0; i < 10; i++) { + draw.drawDot( cc.p(winSize.width/2, winSize.height/2), 10*(10-i), cc.color( Math.random()*255, Math.random()*255, Math.random()*255, 255) ); + } + + // + // Polygons + // + var points = [ cc.p(winSize.height/4,0), cc.p(winSize.width,winSize.height/5), cc.p(winSize.width/3*2,winSize.height) ]; + draw.drawPoly(points, cc.color(255,0,0,128), 8, cc.color(0,128,128,255) ); + + // star poly (triggers bugs) + var o=80; + var w=20; + var h=50; + var star = [ + cc.p(o+w,o-h), cc.p(o+w*2, o), // lower spike + cc.p(o + w*2 + h, o+w ), cc.p(o + w*2, o+w*2), // right spike + cc.p(o +w, o+w*2+h), cc.p(o,o+w*2), // top spike + cc.p(o -h, o+w), cc.p(o,o) // left spike + ]; + draw.drawPoly(star, cc.color(255,0,0,128), 2, cc.color(0,0,255,255) ); + + // star poly (doesn't trigger bug... order is important un tesselation is supported. + o=180; + w=20; + h=50; + star = [ + cc.p(o,o), cc.p(o+w,o-h), cc.p(o+w*2, o), // lower spike + cc.p(o + w*2 + h, o+w ), cc.p(o + w*2, o+w*2), // right spike + cc.p(o +w, o+w*2+h), cc.p(o,o+w*2), // top spike + cc.p(o -h, o+w) // left spike + ]; + draw.drawPoly(star, cc.color(255,0,0,128), 2, cc.color(0,0,255,255) ); + + // + // Segments + // + draw.drawSegment( cc.p(20,winSize.height), cc.p(20,winSize.height/2), 10, cc.color(0, 255, 0, 255) ); + draw.drawSegment( cc.p(10,winSize.height/2), cc.p(winSize.width/2, winSize.height/2), 40, cc.color(255, 0, 255, 128) ); + //----end1---- + } +}); + +DrawNewAPITest.prototype.title = function(){ + return 'cc.DrawNode 1'; +}; + +// +// +var DrawPrimitivesTestScene = TestScene.extend({ + runThisTest:function (num) { + drawTestSceneIdx = (num || num == 0) ? (num - 1) : -1; + var layer = nextDrawTest(); + this.addChild(layer); + + director.runScene(this); + } +}); + +// +// Flow control +// + +var arrayOfDrawTest = [ + DrawNewAPITest, + DrawNewAPITest2 +]; + +var nextDrawTest = function () { + drawTestSceneIdx++; + drawTestSceneIdx = drawTestSceneIdx % arrayOfDrawTest.length; + + if(window.sideIndexBar){ + drawTestSceneIdx = window.sideIndexBar.changeTest(drawTestSceneIdx, 9); + } + + return new arrayOfDrawTest[drawTestSceneIdx](); +}; +var previousDrawTest = function () { + drawTestSceneIdx--; + if (drawTestSceneIdx < 0) + drawTestSceneIdx += arrayOfDrawTest.length; + + if(window.sideIndexBar){ + drawTestSceneIdx = window.sideIndexBar.changeTest(drawTestSceneIdx, 9); + } + + return new arrayOfDrawTest[drawTestSceneIdx](); +}; +var restartDrawTest = function () { + return new arrayOfDrawTest[drawTestSceneIdx](); +}; + diff --git a/tests/js-tests/src/EaseActionsTest/EaseActionsTest.js b/tests/js-tests/src/EaseActionsTest/EaseActionsTest.js new file mode 100644 index 0000000000..3abf9b7cfa --- /dev/null +++ b/tests/js-tests/src/EaseActionsTest/EaseActionsTest.js @@ -0,0 +1,1223 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +TAG_ACTION1_EASE_ACTIONS = 1; +TAG_ACTION2_EASE_ACTIONS = 2; +TAG_SLIDER_EASE_ACTIONS = 1; + +var easeActionsTestIdx = -1; + +// the class inherit from TestScene +// every .Scene each test used must inherit from TestScene, +// make sure the test have the menu item for back to main menu +var EaseActionsTestScene = TestScene.extend({ + runThisTest:function (num) { + easeActionsTestIdx = (num || num == 0) ? (num - 1) : -1; + this.addChild(nextEaseActionsTest()); + director.runScene(this); + } +}); + + +var EaseSpriteDemo = BaseTestLayer.extend({ + _grossini:null, + _tamara:null, + _kathia:null, + _title:null, + + ctor:function () { + this._super(cc.color(0, 0, 0, 255), cc.color(98, 99, 117, 255)); + }, + + title:function () { + return "No title"; + }, + onEnter:function () { + this._super(); + + // Or you can create an sprite using a filename. PNG and BMP files are supported. Probably TIFF too + this._grossini = new cc.Sprite(s_pathGrossini); + this._tamara = new cc.Sprite(s_pathSister1); + this._kathia = new cc.Sprite(s_pathSister2); + + this.addChild(this._grossini, 3); + this.addChild(this._kathia, 2); + this.addChild(this._tamara, 1); + + this._grossini.x = 60; + + this._grossini.y = winSize.height / 5; + this._kathia.x = 60; + this._kathia.y = winSize.height / 2; + this._tamara.x = 60; + this._tamara.y = winSize.height * 4 / 5; + + this.twoSprites = false; + }, + + onRestartCallback:function (sender) { + var s = new EaseActionsTestScene();//cc.Scene.create(); + s.addChild(restartEaseActionsTest()); + director.runScene(s); + }, + onNextCallback:function (sender) { + var s = new EaseActionsTestScene();//cc.Scene.create(); + s.addChild(nextEaseActionsTest()); + director.runScene(s); + }, + onBackCallback:function (sender) { + var s = new EaseActionsTestScene();//cc.Scene.create(); + s.addChild(previousEaseActionsTest()); + director.runScene(s); + }, + positionForTwo:function () { + this.twoSprites = true; + this._grossini.x = 60; + this._grossini.y = winSize.height / 5; + this._tamara.x = 60; + this._tamara.y = winSize.height * 4 / 5; + this._kathia.visible = false; + }, + + // + // Automation + // + numberOfPendingTests:function() { + return ( (arrayOfEaseActionsTest.length-1) - easeActionsTestIdx ); + }, + + getTestNumber:function() { + return easeActionsTestIdx; + }, + + // default values for automation + testDuration:2.05, + getExpectedResult:function() { + var ret; + var w = 60 + winSize.width - 80; + if( this.twoSprites ) + ret = [w, w]; + else + ret = [w, w, w]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret; + if( this.twoSprites) + ret = [ this._grossini.x, this._tamara.x]; + else + ret = [ this._grossini.x, this._tamara.x, this._kathia.x ]; + return JSON.stringify(ret); + } + +}); + +//------------------------------------------------------------------ +// +// SpriteEase +// +//------------------------------------------------------------------ +var SpriteEase = EaseSpriteDemo.extend({ + + onEnter:function () { + //----start0----onEnter + this._super(); + + var move = cc.moveBy(2, cc.p(winSize.width - 80, 0)); + var move_back = move.reverse(); + + //old api + //var move_ease_in = cc.EaseIn.create(move.clone(), 2.0); + + var move_ease_in = move.clone().easing(cc.easeIn(2.0)); + var move_ease_in_back = move_ease_in.reverse(); + + //old api + //var move_ease_out = cc.EaseOut.create(move.clone(), 2.0); + + var move_ease_out = move.clone().easing(cc.easeOut(2.0)); + var move_ease_out_back = move_ease_out.reverse(); + + + var delay = cc.delayTime(0.10); + + var seq1 = cc.sequence(move, delay, move_back, delay.clone()); + var seq2 = cc.sequence(move_ease_in, delay.clone(), move_ease_in_back, delay.clone()); + var seq3 = cc.sequence(move_ease_out, delay.clone(), move_ease_out_back, delay.clone()); + + + var a2 = this._grossini.runAction(seq1.repeatForever()); + a2.tag = 1; + + var a1 = this._tamara.runAction(seq2.repeatForever()); + a1.tag = 1; + + var a = this._kathia.runAction(seq3.repeatForever()); + a.tag = 1; + + this.scheduleOnce(this.testStopAction, 4.1); + //----end0---- + }, + title:function () { + return "EaseIn - EaseOut - Stop"; + }, + + testStopAction:function (dt) { + this._tamara.stopActionByTag(1); + this._kathia.stopActionByTag(1); + this._grossini.stopActionByTag(1); + }, + + // + // Automation + // + testDuration:4.2, + getExpectedResult:function() { + var ret = [60,60,60]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = [ this._grossini.x, this._tamara.x, this._kathia.x ]; + return JSON.stringify(ret); + } + +}); + +//------------------------------------------------------------------ +// +// SpriteEaseInOut +// +//------------------------------------------------------------------ +var SpriteEaseInOut = EaseSpriteDemo.extend({ + + onEnter:function () { + //----start1----onEnter + this._super(); + + var move = cc.moveBy(2, cc.p(winSize.width - 80, 0)); + // id move_back = move.reverse(); + + //old api + //var move_ease_inout1 = cc.EaseInOut.create(move.clone(), 2.0); + + var move_ease_inout1 = move.clone().easing(cc.easeInOut(2.0)); + var move_ease_inout_back1 = move_ease_inout1.reverse(); + + //old api + //var move_ease_inout2 = cc.EaseInOut.create(move.clone(), 3.0); + + var move_ease_inout2 = move.clone().easing(cc.easeInOut(3.0)); + var move_ease_inout_back2 = move_ease_inout2.reverse(); + + //old api + //var move_ease_inout3 = cc.EaseInOut.create(move.clone(), 4.0); + + var move_ease_inout3 = move.clone().easing(cc.easeInOut(4.0)); + var move_ease_inout_back3 = move_ease_inout3.reverse(); + + var delay = cc.delayTime(0.1); + + var seq1 = cc.sequence(move_ease_inout1, delay, move_ease_inout_back1, delay.clone()); + var seq2 = cc.sequence(move_ease_inout2, delay.clone(), move_ease_inout_back2, delay.clone()); + var seq3 = cc.sequence(move_ease_inout3, delay.clone(), move_ease_inout_back3, delay.clone()); + + this._tamara.runAction(seq1.repeatForever()); + this._kathia.runAction(seq2.repeatForever()); + this._grossini.runAction(seq3.repeatForever()); + //----end1---- + }, + title:function () { + return "EaseInOut and rates"; + } +}); + +//------------------------------------------------------------------ +// +// SpriteEaseExponential +// +//------------------------------------------------------------------ +var SpriteEaseExponential = EaseSpriteDemo.extend({ + + onEnter:function () { + //----start2----onEnter + this._super(); + + var move = cc.moveBy(2, cc.p(winSize.width - 80, 0)); + var move_back = move.reverse(); + + //old api + //var move_ease_in = cc.EaseExponentialIn.create(move.clone()); + + var move_ease_in = move.clone().easing(cc.easeExponentialIn()); + var move_ease_in_back = move_ease_in.reverse(); + + var move_ease_out = move.clone().easing(cc.easeExponentialOut()); + var move_ease_out_back = move_ease_out.reverse(); + + var delay = cc.delayTime(0.1); + + var seq1 = cc.sequence(move, delay, move_back, delay.clone()); + var seq2 = cc.sequence(move_ease_in, delay.clone(), move_ease_in_back, delay.clone()); + var seq3 = cc.sequence(move_ease_out, delay.clone(), move_ease_out_back, delay.clone()); + + + this._grossini.runAction(seq1.repeatForever()); + this._tamara.runAction(seq2.repeatForever()); + this._kathia.runAction(seq3.repeatForever()); + //----end2----- + }, + title:function () { + return "ExpIn - ExpOut actions"; + } +}); + +//------------------------------------------------------------------ +// +// SpriteEaseExponentialInOut +// +//------------------------------------------------------------------ +var SpriteEaseExponentialInOut = EaseSpriteDemo.extend({ + onEnter:function () { + //----start3----onEnter + this._super(); + + var move = cc.moveBy(2, cc.p(winSize.width - 80, 0)); + var move_back = move.reverse(); + + //old api + //var move_ease = cc.EaseExponentialInOut.create(move.clone()); + + var move_ease = move.clone().easing(cc.easeExponentialInOut()); + var move_ease_back = move_ease.reverse(); + + var delay = cc.delayTime(0.1); + + var seq1 = cc.sequence(move, delay, move_back, delay.clone()); + var seq2 = cc.sequence(move_ease, delay.clone(), move_ease_back, delay.clone()); + + this.positionForTwo(); + + this._grossini.runAction(seq1.repeatForever()); + this._tamara.runAction(seq2.repeatForever()); + //----end3---- + }, + title:function () { + return "EaseExponentialInOut action"; + } +}); + +//------------------------------------------------------------------ +// +// SpriteEaseSine +// +//------------------------------------------------------------------ +var SpriteEaseSine = EaseSpriteDemo.extend({ + onEnter:function () { + //----start4----onEnter + this._super(); + + var move = cc.moveBy(2, cc.p(winSize.width - 80, 0)); + var move_back = move.reverse(); + + //old api + //var move_ease_in = cc.EaseSineIn.create(move.clone()); + + var move_ease_in = move.clone().easing(cc.easeSineIn()); + var move_ease_in_back = move_ease_in.reverse(); + + //old api + //var move_ease_out = cc.EaseSineOut.create(move.clone()); + + var move_ease_out = move.clone().easing(cc.easeSineOut()); + var move_ease_out_back = move_ease_out.reverse(); + + var delay = cc.delayTime(0.1); + + var seq1 = cc.sequence(move, delay, move_back, delay.clone()); + var seq2 = cc.sequence(move_ease_in, delay, move_ease_in_back, delay.clone()); + var seq3 = cc.sequence(move_ease_out, delay, move_ease_out_back, delay.clone()); + + + this._grossini.runAction(seq1.repeatForever()); + this._tamara.runAction(seq2.repeatForever()); + this._kathia.runAction(seq3.repeatForever()); + //----end4---- + }, + title:function () { + return "EaseSineIn - EaseSineOut"; + } +}); + +//------------------------------------------------------------------ +// +// SpriteEaseSineInOut +// +//------------------------------------------------------------------ +var SpriteEaseSineInOut = EaseSpriteDemo.extend({ + onEnter:function () { + //----start5----onEnter + this._super(); + + var move = cc.moveBy(2, cc.p(winSize.width - 80, 0)); + var move_back = move.reverse(); + + //old api + //var move_ease = cc.EaseSineInOut.create(move.clone()); + + var move_ease = move.clone().easing(cc.easeSineInOut()); + var move_ease_back = move_ease.reverse(); + + var delay = cc.delayTime(0.1); + + var seq1 = cc.sequence(move, delay, move_back, delay.clone()); + var seq2 = cc.sequence(move_ease, delay.clone(), move_ease_back, delay.clone()); + + this.positionForTwo(); + + this._grossini.runAction(seq1.repeatForever()); + this._tamara.runAction(seq2.repeatForever()); + //----end5---- + }, + title:function () { + return "EaseSineInOut action"; + } +}); + +//------------------------------------------------------------------ +// +// SpriteEaseElastic +// +//------------------------------------------------------------------ +var SpriteEaseElastic = EaseSpriteDemo.extend({ + onEnter:function () { + //----start6----onEnter + this._super(); + + var move = cc.moveBy(2, cc.p(winSize.width - 80, 0)); + var move_back = move.reverse(); + + //old api + //var move_ease_in = cc.EaseElasticIn.create(move.clone()); + + var move_ease_in = move.clone().easing(cc.easeElasticIn()); + var move_ease_in_back = move_ease_in.reverse(); + + //old api + //var move_ease_out = cc.EaseElasticOut.create(move.clone()); + + var move_ease_out = move.clone().easing(cc.easeElasticOut()); + var move_ease_out_back = move_ease_out.reverse(); + + var delay = cc.delayTime(0.1); + + var seq1 = cc.sequence(move, delay, move_back, delay.clone()); + var seq2 = cc.sequence(move_ease_in, delay.clone(), move_ease_in_back, delay.clone()); + var seq3 = cc.sequence(move_ease_out, delay.clone(), move_ease_out_back, delay.clone()); + + this._grossini.runAction(seq1.repeatForever()); + this._tamara.runAction(seq2.repeatForever()); + this._kathia.runAction(seq3.repeatForever()); + //----end6---- + }, + title:function () { + return "Elastic In - Out actions"; + } +}); + +//------------------------------------------------------------------ +// +// SpriteEaseElasticInOut +// +//------------------------------------------------------------------ +var SpriteEaseElasticInOut = EaseSpriteDemo.extend({ + onEnter:function () { + //----start7----onEnter + this._super(); + + var move = cc.moveBy(2, cc.p(winSize.width - 80, 0)); + + //old api + //var move_ease_inout1 = cc.EaseElasticInOut.create(move.clone(), 0.3); + + var move_ease_inout1 = move.clone().easing(cc.easeElasticInOut(0.3)); + var move_ease_inout_back1 = move_ease_inout1.reverse(); + + //old api + //var move_ease_inout2 = cc.EaseElasticInOut.create(move.clone(), 0.45); + + var move_ease_inout2 = move.clone().easing(cc.easeElasticInOut(0.45)); + var move_ease_inout_back2 = move_ease_inout2.reverse(); + + //old api + //var move_ease_inout3 = cc.EaseElasticInOut.create(move.clone(), 0.6); + + var move_ease_inout3 = move.clone().easing(cc.easeElasticInOut(0.6)); + var move_ease_inout_back3 = move_ease_inout3.reverse(); + + var delay = cc.delayTime(0.1); + + var seq1 = cc.sequence(move_ease_inout1, delay, move_ease_inout_back1, delay.clone()); + var seq2 = cc.sequence(move_ease_inout2, delay.clone(), move_ease_inout_back2, delay.clone()); + var seq3 = cc.sequence(move_ease_inout3, delay.clone(), move_ease_inout_back3, delay.clone()); + + this._tamara.runAction(seq1.repeatForever()); + this._kathia.runAction(seq2.repeatForever()); + this._grossini.runAction(seq3.repeatForever()); + //----end7---- + }, + title:function () { + return "EaseElasticInOut action"; + } +}); + +//------------------------------------------------------------------ +// +// SpriteEaseBounce +// +//------------------------------------------------------------------ +var SpriteEaseBounce = EaseSpriteDemo.extend({ + onEnter:function () { + //----start8----onEnter + this._super(); + + var move = cc.moveBy(2, cc.p(winSize.width - 80, 0)); + var move_back = move.reverse(); + + //old api + //var move_ease_in = cc.EaseBounceIn.create(move.clone()); + + var move_ease_in = move.clone().easing(cc.easeBounceIn()); + var move_ease_in_back = move_ease_in.reverse(); + + //old api + //var move_ease_out = cc.EaseBounceOut.create(move.clone()); + + var move_ease_out = move.clone().easing(cc.easeBounceOut()); + var move_ease_out_back = move_ease_out.reverse(); + + var delay = cc.delayTime(0.1); + + var seq1 = cc.sequence(move, delay, move_back, delay.clone()); + var seq2 = cc.sequence(move_ease_in, delay.clone(), move_ease_in_back, delay.clone()); + var seq3 = cc.sequence(move_ease_out, delay.clone(), move_ease_out_back, delay.clone()); + + this._grossini.runAction(seq1.repeatForever()); + this._tamara.runAction(seq2.repeatForever()); + this._kathia.runAction(seq3.repeatForever()); + //----end8---- + }, + title:function () { + return "Bounce In - Out actions"; + } +}); + +//------------------------------------------------------------------ +// +// SpriteEaseBounceInOut +// +//------------------------------------------------------------------ +var SpriteEaseBounceInOut = EaseSpriteDemo.extend({ + onEnter:function () { + //----start9----onEnter + this._super(); + + var move = cc.moveBy(2, cc.p(winSize.width - 80, 0)); + var move_back = move.reverse(); + + //old api + //var move_ease = cc.EaseBounceInOut.create(move.clone()); + + var move_ease = move.clone().easing(cc.easeBounceInOut()); + var move_ease_back = move_ease.reverse(); + + var delay = cc.delayTime(0.1); + + var seq1 = cc.sequence(move, delay, move_back, delay.clone()); + var seq2 = cc.sequence(move_ease, delay.clone(), move_ease_back, delay.clone()); + + this.positionForTwo(); + + this._grossini.runAction(seq1.repeatForever()); + this._tamara.runAction(seq2.repeatForever()); + //----end9---- + }, + title:function () { + return "EaseBounceInOut action"; + } +}); + +//------------------------------------------------------------------ +// +// SpriteEaseBack +// +//------------------------------------------------------------------ +var SpriteEaseBack = EaseSpriteDemo.extend({ + onEnter:function () { + //----start10----onEnter + this._super(); + + var move = cc.moveBy(2, cc.p(winSize.width - 80, 0)); + var move_back = move.reverse(); + + //old api + //var move_ease_in = cc.EaseBackIn.create(move.clone()); + + var move_ease_in = move.clone().easing(cc.easeBackIn()); + var move_ease_in_back = move_ease_in.reverse(); + + //old api + //var move_ease_out = cc.EaseBackOut.create(move.clone()); + + var move_ease_out = move.clone().easing(cc.easeBackOut()); + var move_ease_out_back = move_ease_out.reverse(); + + var delay = cc.delayTime(0.1); + + var seq1 = cc.sequence(move, delay, move_back, delay.clone()); + var seq2 = cc.sequence(move_ease_in, delay.clone(), move_ease_in_back, delay.clone()); + var seq3 = cc.sequence(move_ease_out, delay.clone(), move_ease_out_back, delay.clone()); + + this._grossini.runAction(seq1.repeatForever()); + this._tamara.runAction(seq2.repeatForever()); + this._kathia.runAction(seq3.repeatForever()); + //----end10---- + }, + title:function () { + return "Back In - Out actions"; + } +}); + +//------------------------------------------------------------------ +// +// SpriteEaseBackInOut +// +//------------------------------------------------------------------ +var SpriteEaseBackInOut = EaseSpriteDemo.extend({ + onEnter:function () { + //----start11----onEnter + this._super(); + + var move = cc.moveBy(2, cc.p(winSize.width - 80, 0)); + var move_back = move.reverse(); + + //old api + //var move_ease = cc.EaseBackInOut.create(move.clone()); + + var move_ease = move.clone().easing(cc.easeBackInOut()); + var move_ease_back = move_ease.reverse(); + + var delay = cc.delayTime(0.1); + + var seq1 = cc.sequence(move, delay, move_back, delay.clone()); + var seq2 = cc.sequence(move_ease, delay.clone(), move_ease_back, delay.clone()); + + this.positionForTwo(); + + this._grossini.runAction(seq1.repeatForever()); + this._tamara.runAction(seq2.repeatForever()); + //----end11---- + }, + title:function () { + return "EaseBackInOut action"; + } +}); + +var SpeedTest = EaseSpriteDemo.extend({ + onEnter:function () { + //----start12----onEnter + this._super(); + + // rotate and jump + var jump1 = cc.jumpBy(4, cc.p(-winSize.width + 80, 0), 100, 4); + var jump2 = jump1.reverse(); + var rot1 = cc.rotateBy(4, 360 * 2); + var rot2 = rot1.reverse(); + + var seq3_1 = cc.sequence(jump2, jump1); + var seq3_2 = cc.sequence(rot1, rot2); + var spawn = cc.spawn(seq3_1, seq3_2); + + var action = spawn.repeatForever().speed(2); + action.tag = TAG_ACTION1_EASE_ACTIONS; + + var action2 = action.clone(); + var action3 = action.clone(); + + action2.tag = TAG_ACTION1_EASE_ACTIONS; + action3.tag = TAG_ACTION1_EASE_ACTIONS; + + this._grossini.runAction(action2); + this._tamara.runAction(action3); + this._kathia.runAction(action); + + this.schedule(this.altertime, 1.0); + //----end12---- + }, + title:function () { + return "Speed action"; + }, + + altertime:function (dt) { + //----start12----altertime + var action1 = this._grossini.getActionByTag(TAG_ACTION1_EASE_ACTIONS); + var action2 = this._tamara.getActionByTag(TAG_ACTION1_EASE_ACTIONS); + var action3 = this._kathia.getActionByTag(TAG_ACTION1_EASE_ACTIONS); + + action1.setSpeed(Math.random() * 2); + action2.setSpeed(Math.random() * 2); + action3.setSpeed(Math.random() * 2); + //----end12---- + }, + // automation + testDuration:0.1, + getExpectedResult:function() { + throw "Not Implemented"; + }, + getCurrentResult:function() { + throw "Not Implemented"; + } +}); + +//------------------------------------------------------------------ +// +// SchedulerTest +// +//------------------------------------------------------------------ +var SchedulerTest = EaseSpriteDemo.extend({ + onEnter:function () { + //----start13----onEnter + this._super(); + + // rotate and jump + var jump1 = cc.jumpBy(4, cc.p(-winSize.width + 80, 0), 100, 4); + var jump2 = jump1.reverse(); + var rot1 = cc.rotateBy(4, 360 * 2); + var rot2 = rot1.reverse(); + + var seq3_1 = cc.sequence(jump2, jump1); + var seq3_2 = cc.sequence(rot1, rot2); + var spawn = cc.spawn(seq3_1, seq3_2); + var action = spawn.repeatForever(); + + var action2 = action.clone(); + var action3 = action.clone(); + + //old api + //this._grossini.runAction(cc.speed(action, 0.5)); + //this._tamara.runAction(cc.speed(action2, 1.5)); + //this._kathia.runAction(cc.speed(action3, 1.0)); + + this._grossini.runAction(action.speed(0.5)); + this._tamara.runAction(action2.speed(1.5)); + this._kathia.runAction(action3.speed(1.0)); + + var emitter = new cc.ParticleFireworks(); + emitter.setTotalParticles(250); + emitter.texture = cc.textureCache.addImage("res/Images/fire.png"); + this.addChild(emitter); + //----end13---- + }, + title:function () { + return "Scheduler scaleTime Test"; + }, + + // automation + testDuration:0.1, + getExpectedResult:function() { + throw "Not Implemented"; + }, + getCurrentResult:function() { + throw "Not Implemented"; + } +}); + +// +// SpriteEaseBezier action +// +var SpriteEaseBezierTest = EaseSpriteDemo.extend({ + + onEnter: function(){ + this._super(); + //----start14----onEnter + + var size = director.getWinSize(); + + // + // startPosition can be any coordinate, but since the movement + // is relative to the Bezier curve, make it (0,0) + // + + this._grossini.setPosition( cc.p(size.width/2, size.height/2)); + this._tamara.setPosition( cc.p(size.width/4, size.height/2)); + this._kathia.setPosition( cc.p(3 * size.width/4, size.height/2)); + + // sprite 1 + var bezier = [ + cc.p(0, size.height / 2), + cc.p(300 / 480 * 800, -size.height / 2), + cc.p(300 / 480 * 800, 100 / 320 * 450) + ]; + var bezierForward = cc.bezierBy(3, bezier); + //var bezierEaseForward = cc.EaseBezierAction.create(bezierForward); + //bezierEaseForward.setBezierParamer(0.5, 0.5, 1.0, 1.0); + var bezierEaseForward = bezierForward.easing(cc.easeBezierAction(0.5, 0.5, 1.0, 1.0)); + + var bezierEaseBack = bezierEaseForward.reverse(); + var bezierEaseTo = cc.sequence(bezierEaseForward, bezierEaseBack).repeatForever(); + + // sprite 2 + this._tamara.setPosition(cc.p(135,225)); + var bezier2 = [ + cc.p(100 / 480 * 800, size.height / 2), + cc.p(200 / 480 * 800, -size.height / 2), + cc.p(200 / 480 * 800, 160 / 320 * 450) + ]; + var bezierTo1 = cc.bezierTo(2, bezier2); + //var bezierEaseTo1 = cc.EaseBezierAction.create(bezierTo1); + //bezierEaseTo1.setBezierParamer(0.5, 0.5, 1.0, 1.0); + var bezierEaseTo1 = bezierTo1.easing(cc.easeBezierAction(0.5, 0.5, 1.0, 1.0)); + + // sprite 3 + this._kathia.setPosition(cc.p(667, 225)); + var bezierTo2 = cc.bezierTo(2, bezier2); + //var bezierEaseTo2 = cc.EaseBezierAction.create(bezierTo2); + //bezierEaseTo2.setBezierParamer(0.0, 0.5, -5.0, 1.0); + var bezierEaseTo2 = bezierTo2.easing(cc.easeBezierAction(0.0, 0.5, -5.0, 1.0)); + + + this._grossini.runAction(bezierEaseTo); + this._tamara.runAction(bezierEaseTo1); + this._kathia.runAction(bezierEaseTo2); + + //----end14---- + }, + title: function(){ + return "SpriteEaseBezier action"; + } +}); + + +// +// SpriteEaseQuadratic +// +var SpriteEaseQuadraticTest = EaseSpriteDemo.extend({ + + onEnter: function(){ + this._super(); + //----start15----onEnter + + var move = cc.moveBy(3, cc.p(winSize.width - 130, 0)); + var move_back = move.reverse(); + + //var move_ease_in = cc.EaseQuadraticActionIn.create(move.clone()); + var move_ease_in = move.clone().easing(cc.easeQuadraticActionIn()); + var move_ease_in_back = move_ease_in.reverse(); + + //var move_ease_out = cc.EaseQuadraticActionOut.create(move.clone()); + var move_ease_out = move.clone().easing(cc.easeQuadraticActionOut()); + var move_ease_out_back = move_ease_out.reverse(); + + var delay = cc.delayTime(0.25); + + var seq1 = cc.sequence(move, delay, move_back, delay.clone()); + var seq2 = cc.sequence(move_ease_in, delay.clone(), move_ease_in_back, delay.clone()); + var seq3 = cc.sequence(move_ease_out, delay.clone(), move_ease_out_back, delay.clone()); + + this._grossini.runAction( seq1.repeatForever() ); + this._tamara.runAction( seq2.repeatForever() ); + this._kathia.runAction( seq3.repeatForever() ); + + //----end15---- + }, + title: function(){ + return "SpriteEaseQuadratic action"; + } +}); + +// +// SpriteEaseQuadraticInOut +// +var SpriteEaseQuadraticInOutTest = EaseSpriteDemo.extend({ + + onEnter: function(){ + this._super(); + //----start16----onEnter + + var move = cc.moveBy(3, cc.p(winSize.width - 130, 0)); + var move_back = move.reverse(); + + //var move_ease = cc.EaseQuadraticActionInOut.create(move.clone()); + var move_ease = move.clone().easing(cc.easeQuadraticActionInOut()); + var move_ease_back = move_ease.reverse(); + + var delay = cc.delayTime(0.25); + + var seq1 = cc.sequence(move, delay, move_back, delay.clone()).repeatForever(); + var seq2 = cc.sequence(move_ease, delay.clone(), move_ease_back, delay.clone()).repeatForever(); + + this.positionForTwo(); + + this._grossini.runAction( seq1 ); + this._tamara.runAction( seq2 ); + //----end16---- + }, + title: function(){ + return "SpriteEaseQuadraticInOut action"; + } +}); + +// +// SpriteEaseQuartic +// +var SpriteEaseQuarticTest = EaseSpriteDemo.extend({ + + onEnter: function(){ + this._super(); + //----start17----onEnter + + var move = cc.moveBy(3, cc.p(winSize.width - 130, 0)); + var move_back = move.reverse(); + + //var move_ease_in = cc.EaseQuarticActionIn.create(move.clone() ); + var move_ease_in = move.clone().easing(cc.easeQuarticActionIn()); + var move_ease_in_back = move_ease_in.reverse(); + + //var move_ease_out = cc.EaseQuarticActionOut.create(move.clone() ); + var move_ease_out = move.clone().easing(cc.easeQuarticActionOut()); + var move_ease_out_back = move_ease_out.reverse(); + + var delay = cc.delayTime(0.25); + + var seq1 = cc.sequence(move, delay, move_back, delay.clone()); + var seq2 = cc.sequence(move_ease_in, delay.clone(), move_ease_in_back, delay.clone()); + var seq3 = cc.sequence(move_ease_out, delay.clone(), move_ease_out_back, delay.clone()); + + this._grossini.runAction( seq1.repeatForever() ); + this._tamara.runAction( seq2.repeatForever() ); + this._kathia.runAction( seq3.repeatForever() ); + //----end17---- + }, + title: function(){ + return "SpriteEaseQuartic action"; + } +}); + +// +// SpriteEaseQuarticInOut +// +var SpriteEaseQuarticInOutTest = EaseSpriteDemo.extend({ + onEnter: function(){ + this._super(); + //----start18----onEnter + + var move = cc.moveBy(3, cc.p(winSize.width - 130, 0)); + var move_back = move.reverse(); + + //var move_ease = cc.EaseQuarticActionInOut.create(move.clone() ); + var move_ease = move.clone().easing(cc.easeQuarticActionInOut()); + var move_ease_back = move_ease.reverse(); + + var delay = cc.delayTime(0.25); + + var seq1 = cc.sequence(move, delay, move_back, delay.clone()); + var seq2 = cc.sequence(move_ease, delay.clone(), move_ease_back, delay.clone()); + + this.positionForTwo(); + + this._grossini.runAction( seq1.repeatForever() ); + this._tamara.runAction( seq2.repeatForever() ); + + //----end18---- + }, + title: function(){ + return "SpriteEaseQuarticInOut action"; + } +}); + +// +// SpriteEaseQuintic +// +var SpriteEaseQuinticTest = EaseSpriteDemo.extend({ + onEnter: function(){ + this._super(); + //----start19----onEnter + + var move = cc.moveBy(3, cc.p(winSize.width - 130, 0)); + var move_back = move.reverse(); + + //var move_ease_in = cc.EaseQuinticActionIn.create(move.clone() ); + var move_ease_in = move.clone().easing(cc.easeQuinticActionIn()); + var move_ease_in_back = move_ease_in.reverse(); + + //var move_ease_out = cc.EaseQuinticActionOut.create(move.clone() ); + var move_ease_out = move.clone().easing(cc.easeQuinticActionOut()); + var move_ease_out_back = move_ease_out.reverse(); + + var delay = cc.delayTime(0.25); + + var seq1 = cc.sequence(move, delay, move_back, delay.clone()); + var seq2 = cc.sequence(move_ease_in, delay.clone(), move_ease_in_back, delay.clone()); + var seq3 = cc.sequence(move_ease_out, delay.clone(), move_ease_out_back, delay.clone()); + + this._grossini.runAction( seq1.repeatForever() ); + this._tamara.runAction( seq2.repeatForever() ); + this._kathia.runAction( seq3.repeatForever() ); + + + //----end19---- + }, + title: function(){ + return "SpriteEaseQuintic action"; + } +}); + +// +// SpriteEaseQuinticInOut +// +var SpriteEaseQuinticInOutTest = EaseSpriteDemo.extend({ + onEnter: function(){ + this._super(); + //----start20----onEnter + + var move = cc.moveBy(3, cc.p(winSize.width - 130, 0)); + var move_back = move.reverse(); + + //var move_ease = cc.EaseQuinticActionInOut.create(move.clone() ); + var move_ease = move.clone().easing(cc.easeQuinticActionInOut()); + var move_ease_back = move_ease.reverse(); + + var delay = cc.delayTime(0.25); + + var seq1 = cc.sequence(move, delay, move_back, delay.clone()); + var seq2 = cc.sequence(move_ease, delay.clone(), move_ease_back, delay.clone()); + + this.positionForTwo(); + + this._grossini.runAction( seq1.repeatForever() ); + this._tamara.runAction( seq2.repeatForever() ); + + //----end20---- + }, + title: function(){ + return "SpriteEaseQuinticInOut action"; + } +}); + +// +// SpriteEaseCircle +// +var SpriteEaseCircleTest = EaseSpriteDemo.extend({ + onEnter: function(){ + this._super(); + //----start21----onEnter + + var move = cc.moveBy(3, cc.p(winSize.width - 130, 0)); + var move_back = move.reverse(); + + //var move_ease_in = cc.EaseCircleActionIn.create(move.clone() ); + var move_ease_in = move.clone().easing(cc.easeCircleActionIn()); + var move_ease_in_back = move_ease_in.reverse(); + + //var move_ease_out = cc.EaseCircleActionOut.create(move.clone() ); + var move_ease_out = move.clone().easing(cc.easeCircleActionOut()); + var move_ease_out_back = move_ease_out.reverse(); + + var delay = cc.delayTime(0.25); + + var seq1 = cc.sequence(move, delay, move_back, delay.clone()); + var seq2 = cc.sequence(move_ease_in, delay.clone(), move_ease_in_back, delay.clone()); + var seq3 = cc.sequence(move_ease_out, delay.clone(), move_ease_out_back, delay.clone()); + + this._grossini.runAction( seq1.repeatForever() ); + this._tamara.runAction( seq2.repeatForever() ); + this._kathia.runAction( seq3.repeatForever() ); + + //----end21---- + }, + title: function(){ + return "SpriteEaseCircle action"; + } +}); + +// +// SpriteEaseCircleInOut +// +var SpriteEaseCircleInOutTest = EaseSpriteDemo.extend({ + onEnter: function(){ + this._super(); + //----start22----onEnter + + var move = cc.moveBy(3, cc.p(winSize.width - 130, 0)); + var move_back = move.reverse(); + + //var move_ease = cc.EaseCircleActionInOut.create(move.clone() ); + var move_ease = move.clone().easing(cc.easeCircleActionInOut()); + var move_ease_back = move_ease.reverse(); + + var delay = cc.delayTime(0.25); + + var seq1 = cc.sequence(move, delay, move_back, delay.clone()); + var seq2 = cc.sequence(move_ease, delay.clone(), move_ease_back, delay.clone()); + + this.positionForTwo(); + + this._grossini.runAction( seq1.repeatForever() ); + this._tamara.runAction( seq2.repeatForever() ); + + //----end22---- + }, + title: function(){ + return "SpriteEaseCircleInOut action"; + } +}); + +// +// SpriteEaseCubic +// +var SpriteEaseCubicTest = EaseSpriteDemo.extend({ + onEnter: function(){ + this._super(); + //----start23----onEnter + + var move = cc.moveBy(3, cc.p(winSize.width - 130, 0)); + var move_back = move.reverse(); + + //var move_ease_in = cc.EaseCubicActionIn.create(move.clone() ); + var move_ease_in = move.clone().easing(cc.easeCubicActionIn()); + var move_ease_in_back = move_ease_in.reverse(); + + //var move_ease_out = cc.EaseCubicActionOut.create(move.clone() ); + var move_ease_out = move.clone().easing(cc.easeCubicActionOut()); + var move_ease_out_back = move_ease_out.reverse(); + + var delay = cc.delayTime(0.25); + + var seq1 = cc.sequence(move, delay, move_back, delay.clone()); + var seq2 = cc.sequence(move_ease_in, delay.clone(), move_ease_in_back, delay.clone()); + var seq3 = cc.sequence(move_ease_out, delay.clone(), move_ease_out_back, delay.clone()); + + this._grossini.runAction( seq1.repeatForever() ); + this._tamara.runAction( seq2.repeatForever() ); + this._kathia.runAction( seq3.repeatForever() ); + + + //----end23---- + }, + title: function(){ + return "SpriteEaseCubic action"; + } +}); + +// +// SpriteEaseCubicInOut +// +var SpriteEaseCubicInOutTest = EaseSpriteDemo.extend({ + onEnter: function(){ + this._super(); + //----start24----onEnter + + var move = cc.moveBy(3, cc.p(winSize.width - 130, 0)); + var move_back = move.reverse(); + + //var move_ease = cc.EaseCubicActionInOut.create(move.clone() ); + var move_ease = move.clone().easing(cc.easeCubicActionInOut()); + var move_ease_back = move_ease.reverse(); + + var delay = cc.delayTime(0.25); + + var seq1 = cc.sequence(move, delay, move_back, delay.clone()); + var seq2 = cc.sequence(move_ease, delay.clone(), move_ease_back, delay.clone()); + + this.positionForTwo(); + + this._grossini.runAction( seq1.repeatForever() ); + this._tamara.runAction( seq2.repeatForever() ); + + + //----end24---- + }, + title: function(){ + return "SpriteEaseCubicInOut action"; + } +}); + +// +// Flow control +// +var arrayOfEaseActionsTest = [ + SpriteEase, + SpriteEaseInOut, + SpriteEaseExponential, + SpriteEaseExponentialInOut, + SpriteEaseSine, + SpriteEaseSineInOut, + SpriteEaseElastic, + SpriteEaseElasticInOut, + SpriteEaseBounce, + SpriteEaseBounceInOut, + SpriteEaseBack, + SpriteEaseBackInOut, + SpeedTest, + SchedulerTest, + SpriteEaseBezierTest, + SpriteEaseQuadraticTest, + SpriteEaseQuadraticInOutTest, + SpriteEaseQuarticTest, + SpriteEaseQuarticInOutTest, + SpriteEaseQuinticTest, + SpriteEaseQuinticInOutTest, + SpriteEaseCircleTest, + SpriteEaseCircleInOutTest, + SpriteEaseCubicTest, + SpriteEaseCubicInOutTest +]; + +var nextEaseActionsTest = function () { + easeActionsTestIdx++; + easeActionsTestIdx = easeActionsTestIdx % arrayOfEaseActionsTest.length; + + if(window.sideIndexBar){ + easeActionsTestIdx = window.sideIndexBar.changeTest(easeActionsTestIdx, 10); + } + + return new arrayOfEaseActionsTest[easeActionsTestIdx](); +}; +var previousEaseActionsTest = function () { + easeActionsTestIdx--; + if (easeActionsTestIdx < 0) + easeActionsTestIdx += arrayOfEaseActionsTest.length; + + if(window.sideIndexBar){ + easeActionsTestIdx = window.sideIndexBar.changeTest(easeActionsTestIdx, 10); + } + + return new arrayOfEaseActionsTest[easeActionsTestIdx](); +}; +var restartEaseActionsTest = function () { + return new arrayOfEaseActionsTest[easeActionsTestIdx](); +}; diff --git a/tests/js-tests/src/EffectsAdvancedTest/EffectsAdvancedTest.js b/tests/js-tests/src/EffectsAdvancedTest/EffectsAdvancedTest.js new file mode 100644 index 0000000000..580096ddc0 --- /dev/null +++ b/tests/js-tests/src/EffectsAdvancedTest/EffectsAdvancedTest.js @@ -0,0 +1,406 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var EffectsAdvancedTest = EffectsAdvancedTest || {}; + +EffectsAdvancedTest.TAG_TEXTLAYER = 1; + +EffectsAdvancedTest.TAG_SPRITE1 = 1; + +EffectsAdvancedTest.TAG_SPRITE2 = 2; + +EffectsAdvancedTest.TAG_BACKGROUND = 1; + +EffectsAdvancedTest.TAG_LABEL = 2; + +EffectsAdvancedTest.IDC_NEXT = 100; + +EffectsAdvancedTest.IDC_BACK = 101; + +EffectsAdvancedTest.IDC_RESTART = 102; + +var sceneIndex = -1; + +var EffectAdvanceTextLayer = cc.Layer.extend({ + _atlas:null, + _title:null, + rootNode: null, + + ctor:function() { + this._super(); + this.init(); + }, + + onEnter:function () { + this._super(); + + // back gradient + this.rootNode = new cc.LayerGradient(cc.color(0, 0, 0, 255), cc.color(98, 99, 117, 255)); + var nodeGrid = new cc.NodeGrid(); + nodeGrid.addChild(this.rootNode); + this.addChild(nodeGrid, 0, EffectsAdvancedTest.TAG_BACKGROUND); + + var bg = new cc.Sprite(s_back3); + //this.addChild(bg, 0, EffectsAdvancedTest.TAG_BACKGROUND); + this.rootNode.addChild(bg); + bg.x = winSize.width / 2; + bg.y = winSize.height / 2; + + var grossini = new cc.Sprite(s_pathSister2); + var grossiniGrid = new cc.NodeGrid(); + grossiniGrid.addChild(grossini); + this.rootNode.addChild(grossiniGrid, 1, EffectsAdvancedTest.TAG_SPRITE1); + grossini.x = winSize.width / 3; + grossini.y = winSize.height / 2; + var sc = cc.scaleBy(2, 5); + var sc_back = sc.reverse(); + grossini.runAction(cc.sequence(sc, sc_back).repeatForever()); + + var tamara = new cc.Sprite(s_pathSister1); + var tamaraGrid = new cc.NodeGrid(); + tamaraGrid.addChild(tamara); + this.rootNode.addChild(tamaraGrid, 1, EffectsAdvancedTest.TAG_SPRITE2); + tamara.x = winSize.width * 2 / 3; + tamara.y = winSize.height / 2; + var sc2 = cc.scaleBy(2, 5); + var sc2_back = sc2.reverse(); + tamara.runAction(cc.sequence(sc2, sc2_back).repeatForever()); + + var label = new cc.LabelTTF(this.title(), "Arial", 28); + label.x = cc.visibleRect.center.x; + label.y = cc.visibleRect.top.y - 80; + this.addChild(label); + label.tag = EffectsAdvancedTest.TAG_LABEL; + + var strSubtitle = this.subtitle(); + if (strSubtitle != "") { + var subtitleLabel = new cc.LabelTTF(strSubtitle, "Arial", 16); + this.addChild(subtitleLabel, 101); + subtitleLabel.x = cc.visibleRect.center.x; + subtitleLabel.y = cc.visibleRect.top.y - 80; + } + + var item1 = new cc.MenuItemImage(s_pathB1, s_pathB2, this.backCallback, this); + var item2 = new cc.MenuItemImage(s_pathR1, s_pathR2, this.restartCallback, this); + var item3 = new cc.MenuItemImage(s_pathF1, s_pathF2, this.nextCallback, this); + + var menu = new cc.Menu(item1, item2, item3); + + menu.x = 0; + menu.y = 0; + var centerx = cc.visibleRect.center.x, bottomy = cc.visibleRect.bottom.y; + item1.x = centerx - item2.width * 2; + item1.y = bottomy + item2.height / 2; + item2.x = centerx; + item2.y = bottomy + item2.height / 2; + item3.x = centerx + item2.width * 2; + item3.y = bottomy + item2.height / 2; + + this.addChild(menu, 1); + }, + + title:function () { + return "No title"; + }, + + subtitle:function () { + return ""; + }, + + restartCallback:function (sender) { + var scene = new EffectAdvanceScene(); + scene.addChild(restartEffectAdvanceAction()); + cc.director.runScene(scene); + }, + + nextCallback:function (sender) { + var scene = new EffectAdvanceScene(); + scene.addChild(nextEffectAdvanceAction()); + cc.director.runScene(scene); + }, + + backCallback:function (sender) { + var scene = new EffectAdvanceScene(); + scene.addChild(backEffectAdvanceAction()); + cc.director.runScene(scene); + } +}); + +var Effect1 = EffectAdvanceTextLayer.extend({ + title:function () { + return "Lens + Waves3d and OrbitCamera"; + }, + + onEnter:function () { + this._super(); + + var target = this.getChildByTag(EffectsAdvancedTest.TAG_BACKGROUND); + + // To reuse a grid the grid size and the grid type must be the same. + // in this case: + // Lens3D is Grid3D and it's size is (15,10) + // Waves3D is Grid3D and it's size is (15,10) + var size = cc.director.getWinSize(); + var lens = cc.lens3D(0.0, cc.size(15, 10), cc.p(size.width / 2, size.height / 2), 240); + var waves = cc.waves3D(10, cc.size(15, 10), 18, 15); + + var reuse = cc.reuseGrid(1); + var delay = cc.delayTime(8); + + var orbit = cc.orbitCamera(5, 1, 2, 0, 180, 0, -90); + var orbit_back = orbit.reverse(); + + target.runAction(cc.sequence(orbit, orbit_back).repeatForever()); + target.runAction(cc.sequence(lens, delay, reuse, waves)); + } +}); + +var Effect2 = EffectAdvanceTextLayer.extend({ + title:function () { + return "ShakyTiles + ShuffleTiles + TurnOffTiles"; + }, + + onEnter:function () { + this._super(); + var target = this.getChildByTag(EffectsAdvancedTest.TAG_BACKGROUND); + + // To reuse a grid the grid size and the grid type must be the same. + // in this case: + // ShakyTiles is TiledGrid3D and it's size is (15,10) + // Shuffletiles is TiledGrid3D and it's size is (15,10) + // TurnOfftiles is TiledGrid3D and it's size is (15,10) + var shaky = cc.shakyTiles3D(5, cc.size(15, 10), 4, false); + var shuffle = cc.shuffleTiles(0, cc.size(15, 10), 3); + var turnoff = cc.turnOffTiles(0, cc.size(15, 10), 3); + var turnon = turnoff.reverse(); + + // reuse 2 times: + // 1 for shuffle + // 2 for turn off + // turnon tiles will use a new grid + var reuse = cc.reuseGrid(2); + var delay = cc.delayTime(1); + + target.runAction(cc.sequence(shaky, delay, reuse, shuffle, delay.clone(), turnoff, turnon)); + } +}); + +var Effect3 = EffectAdvanceTextLayer.extend({ + title:function () { + return "Effects on 2 sprites"; + }, + + onEnter:function () { + this._super(); + + var bg = this.getChildByTag(EffectsAdvancedTest.TAG_BACKGROUND); + var target1 = this.rootNode.getChildByTag(EffectsAdvancedTest.TAG_SPRITE1); + var target2 = this.rootNode.getChildByTag(EffectsAdvancedTest.TAG_SPRITE2); + + var waves = cc.waves(5, cc.size(15, 10), 5, 20, true, false); + var shaky = cc.shaky3D(5, cc.size(15, 10), 4, false); + + target1.runAction(waves.repeatForever()); + target2.runAction(shaky.repeatForever()); + + // moving background. Testing issue #244 + var move = cc.moveBy(3, cc.p(200, 0)); + bg.runAction(cc.sequence(move, move.reverse()).repeatForever()); + } +}); + +var Lens3DTarget = cc.Node.extend({ + _lens3D:null, + + ctor:function() { + this._super(); + this.init(); + }, + + update: function(dt) { + this._lens3D.x = this.x; + this._lens3D.y = this.y; + }, + + onEnter: function() { + cc.log("Lens3DTarget onEnter"); + this.scheduleUpdate(); + }, + + onExit: function() { + cc.log("Lens3DTarget onExit"); + this.unscheduleUpdate(); + } + +}); + +Lens3DTarget.create = function (action) { + var target = new Lens3DTarget(); + target._lens3D = action; + return target; +}; + +var Effect4 = EffectAdvanceTextLayer.extend({ + title:function () { + return "Jumpy Lens3D"; + }, + + onEnter:function () { + this._super(); + + var lens = cc.lens3D(10, cc.size(32, 24), cc.p(100, 180), 150); + var move = cc.jumpBy(5, cc.p(380, 0), 100, 4); + var move_back = move.reverse(); + var seq = cc.sequence(move, move_back); + + /* In cocos2d-iphone, the type of action's target is 'id', so it supports using the instance of 'CCLens3D' as its target. + While in cocos2d-x, the target of action only supports CCNode or its subclass, + so we make an encapsulation for CCLens3D to achieve that. + */ + var director = cc.director; + var target = Lens3DTarget.create(lens); + // Please make sure the target been added to its parent. + this.addChild(target); + + director.getActionManager().addAction(seq, target, false); + this.runAction(cc.sequence(lens, cc.callFunc( + function(sender) { + sender.removeChild(target, true); + } + ))); + } +}); + +var Effect5 = EffectAdvanceTextLayer.extend({ + title:function () { + return "Test Stop-Copy-Restar"; + }, + + onEnter:function () { + this._super(); + + var effect = cc.liquid(2, cc.size(32, 24), 1, 20); + var stopEffect = cc.sequence(effect, cc.delayTime(2), cc.stopGrid()); + + var bg = this.getChildByTag(EffectsAdvancedTest.TAG_BACKGROUND); + bg.runAction(stopEffect); + }, + + onExit:function () { + this._super(); + cc.director.setProjection(cc.Director.PROJECTION_3D); + } +}); + +var Issue631 = EffectAdvanceTextLayer.extend({ + title:function () { + return "Testing Opacity"; + }, + + subtitle:function () { + return "Effect image should be 100% opaque. Testing issue #631"; + }, + + onEnter:function () { + this._super(); + + var effect = cc.sequence(cc.delayTime(2.0), cc.shaky3D(5.0, cc.size(5, 5), 16, false)); + + // cleanup + var bg = this.getChildByTag(EffectsAdvancedTest.TAG_BACKGROUND); + this.removeChild(bg, true); + + // background + var layer = new cc.LayerColor(cc.color(255, 0, 0, 255)); + this.addChild(layer, -10); + var sprite = new cc.Sprite(s_pathGrossini); + sprite.x = 50; + sprite.y = 80; + layer.addChild(sprite, 10); + + // foreground + var layer2 = new cc.LayerColor(cc.color(0, 255, 0, 255)); + var fog = new cc.Sprite(s_pathFog); + + fog.setBlendFunc(cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA); + var nodeGrid = new cc.NodeGrid(); + layer2.addChild(fog, 1); + nodeGrid.addChild(layer2); + this.addChild(nodeGrid, 1); + + nodeGrid.runAction(effect.repeatForever()); + } +}); + +var arrayOfEffectsAdvancedTest = [ + Effect3, + Effect2, + Effect1, + Effect5, + Issue631 +]; + +if (!cc.sys.isNative) + arrayOfEffectsAdvancedTest.push(Effect4); + +var nextEffectAdvanceAction = function () { + sceneIndex++; + sceneIndex = sceneIndex % arrayOfEffectsAdvancedTest.length; + + if(window.sideIndexBar){ + sceneIndex = window.sideIndexBar.changeTest(sceneIndex, 15); + } + + return new arrayOfEffectsAdvancedTest[sceneIndex](); +}; + +var backEffectAdvanceAction = function () { + sceneIndex--; + if (sceneIndex < 0) + sceneIndex += arrayOfEffectsAdvancedTest.length; + + if(window.sideIndexBar){ + sceneIndex = window.sideIndexBar.changeTest(sceneIndex, 15); + } + + return new arrayOfEffectsAdvancedTest[sceneIndex](); +}; + +var restartEffectAdvanceAction = function () { + return new arrayOfEffectsAdvancedTest[sceneIndex](); +}; + +var EffectAdvanceScene = TestScene.extend({ + runThisTest:function () { + sceneIndex = -1; + var pLayer = nextEffectAdvanceAction(); + this.addChild(pLayer); + cc.director.runScene(this); + } +}); + + + diff --git a/tests/js-tests/src/EffectsTest/EffectsTest.js b/tests/js-tests/src/EffectsTest/EffectsTest.js new file mode 100644 index 0000000000..9ffde46d48 --- /dev/null +++ b/tests/js-tests/src/EffectsTest/EffectsTest.js @@ -0,0 +1,484 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + + +var effectsTestSceneIdx = -1; + +// +// Base Layer +// + +var EffecstsBaseLayer = BaseTestLayer.extend({ + + code:function () { + return ""; + }, + + // callbacks + onRestartCallback:function (sender) { + var s = new EffectsTestScene(); + s.addChild(restartEffectsTest()); + director.runScene(s); + }, + onNextCallback:function (sender) { + var s = new EffectsTestScene(); + s.addChild(nextEffectsTest()); + //director.runScene(cc.TransitionZoomFlipX.create(5, s)); + director.runScene(s); + }, + onBackCallback:function (sender) { + var s = new EffectsTestScene(); + s.addChild(previousEffectsTest()); + director.runScene(s); + }, + onEnter:function () { + this._super(); + + var node = new cc.Node(); + var nodeGrid = new cc.NodeGrid(); + nodeGrid.addChild(node); + nodeGrid.runAction( this.getEffect(3) ); + this.addChild( nodeGrid ); + + // back gradient + var gradient = new cc.LayerGradient( cc.color(0,0,0,255), cc.color(98,99,117,255)); + node.addChild( gradient ); + + // back image + var bg = new cc.Sprite(s_back3); + bg.x = winSize.width/2; + bg.y = winSize.height/2; + node.addChild( bg ); + + var sister1 = new cc.Sprite(s_pathSister1); + sister1.x = winSize.width/3; + sister1.y = winSize.height/2; + node.addChild( sister1, 1 ); + + var sister2 = new cc.Sprite(s_pathSister2); + sister2.x = winSize.width*2/3; + sister2.y = winSize.height/2; + node.addChild( sister2, 1 ); + + var sc = cc.scaleBy(2, 5); + var sc_back = sc.reverse(); + var seq = cc.sequence( sc, sc_back ); + var repeat = seq.repeatForever(); + + sister1.runAction( repeat ); + sister2.runAction( repeat.clone() ); + }, + + getEffect:function(duration) { + // override me + return cc.moveBy(2, cc.p(10,10) ); + }, + + // automation + numberOfPendingTests:function() { + return ( (arrayOfEffectsTest.length-1) - effectsTestSceneIdx ); + }, + + getTestNumber:function() { + return effectsTestSceneIdx; + } + +}); + +//------------------------------------------------------------------ +// +// Tests +// +//------------------------------------------------------------------ +var Shaky3DTest = EffecstsBaseLayer.extend({ + title:function () { + return "Shaky 3D"; + }, + code:function () { + return "a = cc.shaky3D(duration, gridSize, range, shakeZ)"; + }, + getEffect:function(duration) { + return cc.shaky3D( duration, cc.size(15,10), 5, false ); + } +}); + +var Waves3DTest = EffecstsBaseLayer.extend({ + title:function () { + return "Waves 3D"; + }, + code:function () { + return "a = cc.waves3D(duration, gridSize, range, shakeZ)"; + }, + getEffect:function(duration) { + return cc.waves3D(duration, cc.size(15,10), 5, 40 ); + } +}); + +var FlipXTest = EffecstsBaseLayer.extend({ + title:function () { + return "FlipX3D"; + }, + code:function () { + return "a = cc.flipX3D(duration )"; + }, + getEffect:function(duration) { + var a = cc.flipX3D(duration); + var delay = cc.delayTime(2); + var r = a.reverse(); + return cc.sequence( a, delay, r ); + } +}); + +var FlipYTest = EffecstsBaseLayer.extend({ + title:function () { + return "FlipY3D"; + }, + code:function () { + return "a = cc.flipY3D(duration )"; + }, + getEffect:function(duration) { + var a = cc.flipY3D(duration ); + var delay = cc.delayTime(2); + var r = a.reverse(); + return cc.sequence( a, delay, r ); + } +}); + +var Lens3DTest = EffecstsBaseLayer.extend({ + title:function () { + return "Lens3D"; + }, + code:function () { + return "a = cc.lens3D(duration, gridSize, position, radius)"; + }, + getEffect:function(duration) { + return cc.lens3D( duration, cc.size(15,10), cc.p(winSize.width/2, winSize.height/2), 240); + } +}); + +var Ripple3DTest = EffecstsBaseLayer.extend({ + title:function () { + return "Ripple3D"; + }, + code:function () { + return "a = cc.ripple3D(duration, gridSize, position, radius, waves, amplitude)"; + }, + getEffect:function(duration) { + return cc.ripple3D( duration, cc.size(32,24), cc.p(winSize.width/2, winSize.height/2), 240, 4, 160); + } +}); + +var LiquidTest = EffecstsBaseLayer.extend({ + title:function () { + return "Liquid"; + }, + code:function () { + return "a = cc.liquid(duration, gridSize, waves, amplitude)"; + }, + getEffect:function(duration) { + return cc.liquid( duration, cc.size(16,12), 4, 20); + } +}); + +var WavesTest = EffecstsBaseLayer.extend({ + title:function () { + return "Waves"; + }, + code:function () { + return "a = cc.waves(duration, gridSize, waves, amplitude, horizontal, vertical)"; + }, + getEffect:function(duration) { + return cc.waves( duration, cc.size(16,12), 4, 20, true, true); + } +}); + +var TwirlTest = EffecstsBaseLayer.extend({ + title:function () { + return "Twirl"; + }, + code:function () { + return "a = cc.twirl(duration, gridSize, position, twirls, amplitude)"; + }, + getEffect:function(duration) { + return cc.twirl( duration, cc.size(12,8), cc.p(winSize.width/2, winSize.height/2), 1, 2.5); + } +}); + +var ShakyTiles3DTest = EffecstsBaseLayer.extend({ + title:function () { + return "ShakyTiles3D"; + }, + code:function () { + return "a = cc.shakyTiles3D(duration, gridSize, range, shakeZ)"; + }, + getEffect:function(duration) { + return cc.shakyTiles3D( duration, cc.size(16,12), 5, false); + } +}); + +var ShatteredTiles3DTest = EffecstsBaseLayer.extend({ + title:function () { + return "ShatteredTiles3D"; + }, + code:function () { + return "a = cc.shatteredTiles3D(duration, gridSize, range, shatterZ)"; + }, + getEffect:function(duration) { + return cc.shatteredTiles3D( duration, cc.size(16,12), 5, false); + } +}); + +var ShuffleTilesTest = EffecstsBaseLayer.extend({ + title:function () { + return "ShuffleTiles"; + }, + code:function () { + return "a = cc.shuffleTiles(duration, gridSize, seed)"; + }, + getEffect:function(duration) { + var action = cc.shuffleTiles( duration, cc.size(16,12), 25); + var delay = cc.delayTime(2); + var back = action.reverse(); + var seq = cc.sequence( action, delay, back); + return seq; + } +}); + +var FadeOutTRTilesTest = EffecstsBaseLayer.extend({ + title:function () { + return "FadeOutTRTilesTest"; + }, + code:function () { + return "a = cc.fadeOutTRTiles(duration, gridSize)"; + }, + getEffect:function(duration) { + var action = cc.fadeOutTRTiles( duration, cc.size(16,12)); + var delay = cc.delayTime(0.5); + var back = action.reverse(); + var seq = cc.sequence( action, delay, back); + return seq; + } +}); + +var FadeOutBLTilesTest = EffecstsBaseLayer.extend({ + title:function () { + return "FadeOutBLTilesTest"; + }, + code:function () { + return "a = cc.fadeOutBLTiles(duration, gridSize)"; + }, + getEffect:function(duration) { + var action = cc.fadeOutBLTiles( duration, cc.size(16,12)); + var delay = cc.delayTime(0.5); + var back = action.reverse(); + var seq = cc.sequence( action, delay, back); + return seq; + } +}); + +var FadeOutUpTilesTest = EffecstsBaseLayer.extend({ + title:function () { + return "FadeOutUpTilesTest"; + }, + code:function () { + return "a = cc.fadeOutUpTiles(duration, gridSize)"; + }, + getEffect:function(duration) { + var action = cc.fadeOutUpTiles( duration, cc.size(16,12)); + var delay = cc.delayTime(0.5); + var back = action.reverse(); + var seq = cc.sequence( action, delay, back); + return seq; + } +}); + +var FadeOutDownTilesTest = EffecstsBaseLayer.extend({ + title:function () { + return "FadeOutDownTilesTest"; + }, + code:function () { + return "a = cc.fadeOutDownTiles(duration, gridSize)"; + }, + getEffect:function(duration) { + var action = cc.fadeOutDownTiles( duration, cc.size(16,12)); + var delay = cc.delayTime(0.5); + var back = action.reverse(); + var seq = cc.sequence( action, delay, back); + return seq; + } +}); + +var TurnOffTilesTest = EffecstsBaseLayer.extend({ + title:function () { + return "TurnOffTiles"; + }, + code:function () { + return "a = cc.turnOffTiles(duration, gridSize, seed)"; + }, + getEffect:function(duration) { + var action = cc.turnOffTiles( duration, cc.size(48,32), 25); + var delay = cc.delayTime(0.5); + var back = action.reverse(); + var seq = cc.sequence( action, delay, back); + return seq; + } +}); + +var WavesTiles3DTest = EffecstsBaseLayer.extend({ + title:function () { + return "WavesTiles3D"; + }, + code:function () { + return "a = cc.wavesTiles3D(duration, gridSize, waves, amplitude)"; + }, + getEffect:function(duration) { + var action = cc.wavesTiles3D( duration, cc.size(16,12), 4, 120); + return action; + } +}); + + +var JumpTiles3DTest = EffecstsBaseLayer.extend({ + title:function () { + return "JumpTiles3D"; + }, + code:function () { + return "a = cc.jumpTiles3D(duration, gridSize, jumps, amplitude)"; + }, + getEffect:function(duration) { + var action = cc.jumpTiles3D(duration, cc.size(16,12), 2, 30); + return action; + } +}); + +var SplitRowsTest = EffecstsBaseLayer.extend({ + title:function () { + return "SplitRows"; + }, + code:function () { + return "a = cc.splitRows(duration, rows)"; + }, + getEffect:function(duration) { + var action = cc.splitRows(duration, 9); + var delay = cc.delayTime(0.5); + var back = action.reverse(); + var seq = cc.sequence( action, delay, back); + return seq; + } +}); + +var SplitColsTest = EffecstsBaseLayer.extend({ + title:function () { + return "SplitCols"; + }, + code:function () { + return "a = cc.splitCols(duration, cols)"; + }, + getEffect:function(duration) { + var action = cc.splitCols(duration, 9); + var delay = cc.delayTime(0.5); + var back = action.reverse(); + var seq = cc.sequence( action, delay, back); + return seq; + } +}); + +var PageTurn3DTest = EffecstsBaseLayer.extend({ + title:function () { + return "PageTurn3D"; + }, + code:function () { + return "a = cc.pageTurn3D(duration, gridSize)"; + }, + getEffect:function(duration) { + var action = cc.pageTurn3D(duration, cc.size(15,10)); + return action; + } +}); + +// +// Order of tests +// +var EffectsTestScene = TestScene.extend({ + runThisTest:function (num) { + effectsTestSceneIdx = (num || num == 0) ? (num - 1) : -1; + var layer = nextEffectsTest(); + this.addChild(layer); + + director.runScene(this); + } +}); + +// +// Flow control +// +var arrayOfEffectsTest = [ + Shaky3DTest, + Waves3DTest, + FlipXTest, + FlipYTest, + Lens3DTest, + Ripple3DTest, + LiquidTest, + WavesTest, + TwirlTest, + ShakyTiles3DTest, + ShatteredTiles3DTest, + ShuffleTilesTest, + FadeOutTRTilesTest, + FadeOutBLTilesTest, + FadeOutUpTilesTest, + FadeOutDownTilesTest, + TurnOffTilesTest, + WavesTiles3DTest, + JumpTiles3DTest, + SplitRowsTest, + SplitColsTest, + PageTurn3DTest +]; + +var nextEffectsTest = function () { + effectsTestSceneIdx++; + effectsTestSceneIdx = effectsTestSceneIdx % arrayOfEffectsTest.length; + + if(window.sideIndexBar){ + effectsTestSceneIdx = window.sideIndexBar.changeTest(effectsTestSceneIdx, 14); + } + + return new arrayOfEffectsTest[effectsTestSceneIdx](); +}; +var previousEffectsTest = function () { + effectsTestSceneIdx--; + if (effectsTestSceneIdx < 0) + effectsTestSceneIdx += arrayOfEffectsTest.length; + + if(window.sideIndexBar){ + effectsTestSceneIdx = window.sideIndexBar.changeTest(effectsTestSceneIdx, 14); + } + + return new arrayOfEffectsTest[effectsTestSceneIdx](); +}; +var restartEffectsTest = function () { + return new arrayOfEffectsTest[effectsTestSceneIdx](); +}; diff --git a/tests/js-tests/src/EventTest/EventTest.js b/tests/js-tests/src/EventTest/EventTest.js new file mode 100644 index 0000000000..e89b13c1c2 --- /dev/null +++ b/tests/js-tests/src/EventTest/EventTest.js @@ -0,0 +1,505 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var TEXT_INPUT_FONT_NAME = "Thonburi"; +var TEXT_INPUT_FONT_SIZE = 36; + +var sceneIdx = -1; + +/** + @brief EventTest for retain prev, reset, next, main menu buttons. + */ +var EventTest = cc.Layer.extend({ + ctor:function() { + this._super(); + this.init(); + }, + + restartCallback:function (sender) { + var s = new EventTestScene(); + s.addChild(restartEventsTest()); + director.runScene(s); + }, + nextCallback:function (sender) { + var s = new EventTestScene(); + s.addChild(nextEventsTest()); + director.runScene(s); + }, + backCallback:function (sender) { + var s = new EventTestScene(); + s.addChild(previousEventsTest()); + director.runScene(s); + }, + + title:function () { + return "Event Test"; + }, + + onEnter:function () { + this._super(); + + var s = director.getWinSize(); + + var label = new cc.LabelTTF(this.title(), "Arial", 24); + this.addChild(label); + label.x = s.width / 2; + label.y = s.height - 50; + + var subTitle = this.subtitle(); + if (subTitle && subTitle !== "") { + var l = new cc.LabelTTF(subTitle, "Thonburi", 16); + this.addChild(l, 1); + l.x = s.width / 2; + l.y = s.height - 80; + } + + var item1 = new cc.MenuItemImage(s_pathB1, s_pathB2, this.backCallback, this); + var item2 = new cc.MenuItemImage(s_pathR1, s_pathR2, this.restartCallback, this); + var item3 = new cc.MenuItemImage(s_pathF1, s_pathF2, this.nextCallback, this); + + var menu = new cc.Menu(item1, item2, item3); + menu.x = 0; + menu.y = 0; + item1.x = s.width / 2 - 100; + item1.y = 30; + item2.x = s.width / 2; + item2.y = 30; + item3.x = s.width / 2 + 100; + item3.y = 30; + + this.addChild(menu, 1); + } +}); + +//------------------------------------------------------------------ +// +// OneByOne Touches +// +//------------------------------------------------------------------ +var TouchOneByOneTest = EventTest.extend({ + init:function () { + this._super(); + this.ids = {}; + this.unused_sprites = []; + + if( 'touches' in cc.sys.capabilities ) { + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches: true, + onTouchBegan: this.onTouchBegan, + onTouchMoved: this.onTouchMoved, + onTouchEnded: this.onTouchEnded, + onTouchCancelled: this.onTouchCancelled + }, this); + } else { + cc.log("TOUCH-ONE-BY-ONE test is not supported on desktop"); + } + + for( var i=0; i < 5;i++) { + var sprite = this.sprite = new cc.Sprite(s_pathR2); + this.addChild(sprite,i+10); + sprite.x = 0; + sprite.y = 0; + sprite.scale = 1; + sprite.color = cc.color( Math.random()*200+55, Math.random()*200+55, Math.random()*200+55 ); + this.unused_sprites.push(sprite); + } + }, + subtitle:function () { + return "Touches One by One. Touch the left / right and see console"; + }, + + new_id:function( id, pos) { + var s = this.unused_sprites.pop(); + this.ids[ id ] = s; + s.x = pos.x; + s.y = pos.y; + }, + update_id:function(id, pos) { + var s = this.ids[ id ]; + s.x = pos.x; + s.y = pos.y; + }, + release_id:function(id, pos) { + var s = this.ids[ id ]; + this.ids[ id ] = null; + this.unused_sprites.push( s ); + s.x = 0; + s.y = 0; + }, + + onTouchBegan:function(touch, event) { + var pos = touch.getLocation(); + var id = touch.getID(); + cc.log("onTouchBegan at: " + pos.x + " " + pos.y + " Id:" + id ); + if( pos.x < winSize.width/2) { + event.getCurrentTarget().new_id(id,pos); + return true; + } + return false; + }, + onTouchMoved:function(touch, event) { + var pos = touch.getLocation(); + var id = touch.getID(); + cc.log("onTouchMoved at: " + pos.x + " " + pos.y + " Id:" + id ); + event.getCurrentTarget().update_id(id,pos); + }, + onTouchEnded:function(touch, event) { + var pos = touch.getLocation(); + var id = touch.getID(); + cc.log("onTouchEnded at: " + pos.x + " " + pos.y + " Id:" + id ); + event.getCurrentTarget().release_id(id,pos); + }, + onTouchCancelled:function(touch, event) { + var pos = touch.getLocation(); + var id = touch.getID(); + cc.log("onTouchCancelled at: " + pos.x + " " + pos.y + " Id:" + id ); + event.getCurrentTarget().update_id(id,pos); + } +}); + +//------------------------------------------------------------------ +// +// All At Once Touches +// +//------------------------------------------------------------------ +var TouchAllAtOnce = EventTest.extend({ + init:function () { + this._super(); + + this.ids = {}; + this.unused_sprites = []; + + if( 'touches' in cc.sys.capabilities ) { + // this is the default behavior. No need to set it explicitly. + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesBegan: this.onTouchesBegan, + onTouchesMoved: this.onTouchesMoved, + onTouchesEnded: this.onTouchesEnded, + onTouchesCancelled: this.onTouchesCancelled + }, this); + } else { + cc.log("TOUCHES not supported"); + } + + for( var i=0; i < 5;i++) { + var sprite = this.sprite = new cc.Sprite(s_pathR2); + this.addChild(sprite,i+10); + sprite.x = 0; + sprite.y = 0; + sprite.scale = 1; + sprite.color = cc.color( Math.random()*200+55, Math.random()*200+55, Math.random()*200+55 ); + this.unused_sprites.push(sprite); + } + }, + subtitle:function () { + return "Touches All At Once. Touch and see console"; + }, + + new_id:function( id, pos) { + var s = this.unused_sprites.pop(); + this.ids[ id ] = s; + s.x = pos.x; + s.y = pos.y; + }, + update_id:function(id, pos) { + var s = this.ids[ id ]; + s.x = pos.x; + s.y = pos.y; + }, + release_id:function(id, pos) { + var s = this.ids[ id ]; + this.ids[ id ] = null; + this.unused_sprites.push( s ); + s.x = 0; + s.y = 0; + }, + + onTouchesBegan:function(touches, event) { + var target = event.getCurrentTarget(); + for (var i=0; i < touches.length;i++ ) { + var touch = touches[i]; + var pos = touch.getLocation(); + var id = touch.getID(); + cc.log("Touch #" + i + ". onTouchesBegan at: " + pos.x + " " + pos.y + " Id:" + id); + target.new_id(id,pos); + } + }, + onTouchesMoved:function(touches, event) { + var target = event.getCurrentTarget(); + for (var i=0; i < touches.length;i++ ) { + var touch = touches[i]; + var pos = touch.getLocation(); + var id = touch.getID(); + cc.log("Touch #" + i + ". onTouchesMoved at: " + pos.x + " " + pos.y + " Id:" + id); + target.update_id(id, pos); + } + }, + onTouchesEnded:function(touches, event) { + var target = event.getCurrentTarget(); + for (var i=0; i < touches.length;i++ ) { + var touch = touches[i]; + var pos = touch.getLocation(); + var id = touch.getID(); + cc.log("Touch #" + i + ". onTouchesEnded at: " + pos.x + " " + pos.y + " Id:" + id); + target.release_id(id); + } + }, + onTouchesCancelled:function(touches, event) { + var target = event.getCurrentTarget(); + for (var i=0; i < touches.length;i++ ) { + var touch = touches[i]; + var pos = touch.getLocation(); + var id = touch.getID(); + cc.log("Touch #" + i + ". onTouchesCancelled at: " + pos.x + " " + pos.y + " Id:" + id); + target.release_id(id); + } + } +}); + +//------------------------------------------------------------------ +// +// Accelerometer test +// +//------------------------------------------------------------------ +var AccelerometerTest = EventTest.extend({ + init:function () { + this._super(); + + if( 'accelerometer' in cc.sys.capabilities ) { + // call is called 30 times per second + cc.inputManager.setAccelerometerInterval(1/30); + cc.inputManager.setAccelerometerEnabled(true); + cc.eventManager.addListener({ + event: cc.EventListener.ACCELERATION, + callback: function(accelEvent, event){ + var target = event.getCurrentTarget(); + cc.log('Accel x: '+ accelEvent.x + ' y:' + accelEvent.y + ' z:' + accelEvent.z + ' time:' + accelEvent.timestamp ); + + var w = winSize.width; + var h = winSize.height; + + var x = w * accelEvent.x + w/2; + var y = h * accelEvent.y + h/2; + + // Low pass filter + x = x*0.2 + target.prevX*0.8; + y = y*0.2 + target.prevY*0.8; + + target.prevX = x; + target.prevY = y; + target.sprite.x = x; + target.sprite.y = y ; + } + }, this); + + var sprite = this.sprite = new cc.Sprite(s_pathR2); + this.addChild( sprite ); + sprite.x = winSize.width/2; + sprite.y = winSize.height/2; + + // for low-pass filter + this.prevX = 0; + this.prevY = 0; + } else { + cc.log("ACCELEROMETER not supported"); + } + }, + + onExit: function(){ + this._super(); + if( 'accelerometer' in cc.sys.capabilities ) + cc.inputManager.setAccelerometerEnabled(false); + }, + + subtitle:function () { + return "Accelerometer test. Move device and see console"; + } +}); + +//------------------------------------------------------------------ +// +// Mouse test +// +//------------------------------------------------------------------ +var MouseTest = EventTest.extend({ + init:function () { + this._super(); + var sprite = this.sprite = new cc.Sprite(s_pathR2); + this.addChild(sprite); + sprite.x = 0; + sprite.y = 0; + sprite.scale = 1; + sprite.color = cc.color(Math.random()*200+55, Math.random()*200+55, Math.random()*200+55); + + if( 'mouse' in cc.sys.capabilities ) { + cc.eventManager.addListener({ + event: cc.EventListener.MOUSE, + onMouseDown: function(event){ + var pos = event.getLocation(), target = event.getCurrentTarget(); + if(event.getButton() === cc.EventMouse.BUTTON_RIGHT) + cc.log("onRightMouseDown at: " + pos.x + " " + pos.y ); + else if(event.getButton() === cc.EventMouse.BUTTON_LEFT) + cc.log("onLeftMouseDown at: " + pos.x + " " + pos.y ); + target.sprite.x = pos.x; + target.sprite.y = pos.y; + }, + onMouseMove: function(event){ + var pos = event.getLocation(), target = event.getCurrentTarget(); + cc.log("onMouseMove at: " + pos.x + " " + pos.y ); + target.sprite.x = pos.x; + target.sprite.y = pos.y; + }, + onMouseUp: function(event){ + var pos = event.getLocation(), target = event.getCurrentTarget(); + target.sprite.x = pos.x; + target.sprite.y = pos.y; + cc.log("onMouseUp at: " + pos.x + " " + pos.y ); + } + }, this); + } else { + cc.log("MOUSE Not supported"); + } + }, + subtitle:function () { + return "Mouse test. Move mouse and see console"; + } +}); + +//------------------------------------------------------------------ +// +// Keyboard test +// +//------------------------------------------------------------------ +var KeyboardTest = EventTest.extend({ + init: function () { + this._super(); + var self = this; + var label = new cc.LabelTTF("show key Code"); + var size = cc.director.getWinSize(); + label.setPosition(size.width / 2, size.height / 2); + this.addChild(label); + if ('keyboard' in cc.sys.capabilities) { + cc.eventManager.addListener({ + event: cc.EventListener.KEYBOARD, + onKeyPressed: function (key, event) { + var strTemp = "Key down:" + key; + var keyStr = self.getKeyStr(key); + if (keyStr.length > 0) + { + strTemp += " the key name is:" + keyStr; + } + label.setString(strTemp); + }, + onKeyReleased: function (key, event) { + var strTemp = "Key up:" + key; + var keyStr = self.getKeyStr(key); + if (keyStr.length > 0) + { + strTemp += " the key name is:" + keyStr; + } + label.setString(strTemp); + } + }, this); + } else { + cc.log("KEYBOARD Not supported"); + } + }, + getKeyStr: function (keycode) + { + if (keycode == cc.KEY.none) + { + return ""; + } + + for (var keyTemp in cc.KEY) + { + if (cc.KEY[keyTemp] == keycode) + { + return keyTemp; + } + } + return ""; + }, + subtitle:function () { + return "Keyboard test. Press keyboard and see console"; + }, + + // this callback is only available on JSB + OS X + // Not supported on cocos2d-html5 + onKeyFlagsChanged:function(key) { + cc.log("Key flags changed:" + key); + } +}); + + +var EventTestScene = TestScene.extend({ + runThisTest:function (num) { + sceneIdx = (num || num == 0) ? (num - 1) : -1; + var layer = nextEventsTest(); + // var menu = new EventTest(); + // menu.addKeyboardNotificationLayer( layer ); + + this.addChild(layer); + director.runScene(this); + } +}); + +// +// Flow control +// +var arrayOfEventsTest = [ + TouchOneByOneTest, + TouchAllAtOnce, + AccelerometerTest, + MouseTest, + KeyboardTest +]; + +var nextEventsTest = function () { + sceneIdx++; + sceneIdx = sceneIdx % arrayOfEventsTest.length; + + if(window.sideIndexBar){ + sceneIdx = window.sideIndexBar.changeTest(sceneIdx, 12); + } + + return new arrayOfEventsTest[sceneIdx](); +}; +var previousEventsTest = function () { + sceneIdx--; + if (sceneIdx < 0) + sceneIdx += arrayOfEventsTest.length; + + if(window.sideIndexBar){ + sceneIdx = window.sideIndexBar.changeTest(sceneIdx, 12); + } + + return new arrayOfEventsTest[sceneIdx](); +}; +var restartEventsTest = function () { + return new arrayOfEventsTest[sceneIdx](); +}; + diff --git a/tests/js-tests/src/ExtensionsTest/AssetsManagerTest/AssetsManagerTest.js b/tests/js-tests/src/ExtensionsTest/AssetsManagerTest/AssetsManagerTest.js new file mode 100644 index 0000000000..acd1c664fe --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/AssetsManagerTest/AssetsManagerTest.js @@ -0,0 +1,231 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + + + +var sceneManifests = ["Manifests/AMTestScene1/project.manifest", "Manifests/AMTestScene2/project.manifest", "Manifests/AMTestScene3/project.manifest"]; +var storagePaths = ["JSBTests/AssetsManagerTest/scene1/", "JSBTests/AssetsManagerTest/scene2/", "JSBTests/AssetsManagerTest/scene3"]; +var backgroundPaths = ["Images/assetMgrBackground1.jpg", "Images/assetMgrBackground2.png", "Images/assetMgrBackground3.png"]; + +var currentScene = 0; + +var AssetsManagerTestLayer = BaseTestLayer.extend({ + _background : null, + _spritePath : "", + + ctor : function (spritePath) { + this._super(); + this._spritePath = spritePath; + cc.loader.resPath = "res/"; + }, + + getTitle : function() { + return "AssetsManagerTest"; + }, + + onEnter : function() { + this._super(); + this._background = new cc.Sprite(this._spritePath); + this.addChild(this._background, 1); + this._background.x = cc.winSize.width/2; + this._background.y = cc.winSize.height/2; + }, + + onExit : function(){ + cc.loader.resPath = ""; + this._super(); + }, + + onNextCallback : function () { + if (currentScene < 2) + { + currentScene++; + } + else currentScene = 0; + var scene = new AssetsManagerLoaderScene(); + scene.runThisTest(); + }, + + onBackCallback : function () { + if (currentScene > 0) + { + currentScene--; + } + else currentScene = 2; + var scene = new AssetsManagerLoaderScene(); + scene.runThisTest(); + } +}); + + + +var AssetsManagerTestScene = TestScene.extend({ + _background : "", + + ctor : function (background) { + this._super(); + var layer = new AssetsManagerTestLayer(background); + this.addChild(layer); + } +}); + +var __failCount = 0; + +var AssetsManagerLoaderScene = TestScene.extend({ + _am : null, + _progress : null, + _percent : 0, + _percentByFile : 0, + _loadingBar : null, + _fileLoadingBar : null, + + runThisTest : function () { + var manifestPath = sceneManifests[currentScene]; + var storagePath = ((jsb.fileUtils ? jsb.fileUtils.getWritablePath() : "/") + storagePaths[currentScene]); + cc.log("Storage path for this test : " + storagePath); + + var layer = new cc.Layer(); + this.addChild(layer); + + var icon = new cc.Sprite(s_image_icon); + icon.x = cc.winSize.width/2; + icon.y = cc.winSize.height/2; + layer.addChild(icon); + + this._loadingBar = new ccui.LoadingBar("res/cocosui/sliderProgress.png"); + this._loadingBar.x = cc.visibleRect.center.x; + this._loadingBar.y = cc.visibleRect.top.y - 40; + layer.addChild(this._loadingBar); + + this._fileLoadingBar = new ccui.LoadingBar("res/cocosui/sliderProgress.png"); + this._fileLoadingBar.x = cc.visibleRect.center.x; + this._fileLoadingBar.y = cc.visibleRect.top.y - 80; + layer.addChild(this._fileLoadingBar); + + this._am = new jsb.AssetsManager(manifestPath, storagePath); + this._am.retain(); + + if (!this._am.getLocalManifest().isLoaded()) + { + cc.log("Fail to update assets, step skipped."); + var scene = new AssetsManagerTestScene(backgroundPaths[currentScene]); + cc.director.runScene(scene); + } + else + { + var that = this; + var listener = new jsb.EventListenerAssetsManager(this._am, function(event) { + var scene; + switch (event.getEventCode()) + { + case jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST: + cc.log("No local manifest file found, skip assets update."); + scene = new AssetsManagerTestScene(backgroundPaths[currentScene]); + cc.director.runScene(scene); + break; + case jsb.EventAssetsManager.UPDATE_PROGRESSION: + that._percent = event.getPercent(); + that._percentByFile = event.getPercentByFile(); + + var msg = event.getMessage(); + if (msg) { + cc.log(msg); + } + cc.log(that._percent + "%"); + break; + case jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST: + case jsb.EventAssetsManager.ERROR_PARSE_MANIFEST: + cc.log("Fail to download manifest file, update skipped."); + scene = new AssetsManagerTestScene(backgroundPaths[currentScene]); + cc.director.runScene(scene); + break; + case jsb.EventAssetsManager.ALREADY_UP_TO_DATE: + case jsb.EventAssetsManager.UPDATE_FINISHED: + cc.log("Update finished. " + event.getMessage()); + + // Restart the game to update scripts in scene 3 + if (currentScene == 2) { + // Register the manifest's search path + var searchPaths = that._am.getLocalManifest().getSearchPaths(); + // This value will be retrieved and appended to the default search path during game startup, + // please refer to samples/js-tests/main.js for detailed usage. + // !!! Re-add the search paths in main.js is very important, otherwise, new scripts won't take effect. + cc.sys.localStorage.setItem("Scene3SearchPaths", JSON.stringify(searchPaths)); + // Restart the game to make all scripts take effect. + cc.game.restart(); + } + else { + scene = new AssetsManagerTestScene(backgroundPaths[currentScene]); + cc.director.runScene(scene); + } + break; + case jsb.EventAssetsManager.UPDATE_FAILED: + cc.log("Update failed. " + event.getMessage()); + + __failCount ++; + if (__failCount < 5) + { + that._am.downloadFailedAssets(); + } + else + { + cc.log("Reach maximum fail count, exit update process"); + __failCount = 0; + scene = new AssetsManagerTestScene(backgroundPaths[currentScene]); + cc.director.runScene(scene); + } + break; + case jsb.EventAssetsManager.ERROR_UPDATING: + cc.log("Asset update error: " + event.getAssetId() + ", " + event.getMessage()); + break; + case jsb.EventAssetsManager.ERROR_DECOMPRESS: + cc.log(event.getMessage()); + break; + default: + break; + } + }); + + cc.eventManager.addListener(listener, 1); + + this._am.update(); + + cc.director.runScene(this); + } + + this.schedule(this.updateProgress, 0.5); + }, + + updateProgress : function () { + this._loadingBar.setPercent(this._percent); + this._fileLoadingBar.setPercent(this._percentByFile); + }, + + onExit : function () { + this._am.release(); + this._super(); + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/ExtensionsTest/CCPoolTest/CCPoolTest.js b/tests/js-tests/src/ExtensionsTest/CCPoolTest/CCPoolTest.js new file mode 100644 index 0000000000..c3439c7d0c --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/CCPoolTest/CCPoolTest.js @@ -0,0 +1,190 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + + 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. + ****************************************************************************/ + + +var CCPoolTest = cc.Layer.extend({ + timeList: null, + init: function () { + this.timeList = {}; + var winSize = cc.director.getWinSize(); + + var MARGIN = 40; + var label = new cc.LabelTTF("CCPoolTest", "Arial", 28); + label.setPosition(cc.p(winSize.width / 2, winSize.height - MARGIN)); + this.addChild(label, 0); + + var menuRequest = new cc.Menu(); + menuRequest.setPosition(cc.p(0, 0)); + this.initUI(); + return true; + }, + initUI: function () { + var createLabel = new cc.LabelTTF("click me to create\n 150 sprites directly", "Arial", 23); + var reCreateLabel = new cc.LabelTTF("click me to create\n 150 sprites use pool", "Arial", 23); + reCreateLabel.color = cc.color(255, 255, 255, 255); + createLabel.color = cc.color(255, 255, 255, 255); + var menuItem1 = new cc.MenuItemLabel(createLabel, this.addSpriteByCreate, this); + var menuItem2 = new cc.MenuItemLabel(reCreateLabel, this.addSpriteByPool, this); + var menu = new cc.Menu(menuItem1, menuItem2); + menu.alignItemsHorizontallyWithPadding(150); + this.directLabel = new cc.LabelTTF("create directly cost:", "Arial", 18); + this.poolLabel = new cc.LabelTTF("use pool cost:", "Arial", 18); + this.directLabel.setPosition(cc.pAdd(cc.visibleRect.center, cc.p(-190, -65))); + this.directLabel.anchorY = 0; + this.poolLabel.setPosition(cc.pAdd(cc.visibleRect.center, cc.p(200, -65))); + this.poolLabel.anchorY = 0; + this.addChild(this.directLabel); + this.addChild(this.poolLabel); + this.addChild(menu, 100); + + // Back Menu + var itemBack = new cc.MenuItemFont("Back", this.toExtensionsMainLayer, this); + itemBack.setPosition(cc.p(winSize.width - 50, 25)); + var menuBack = new cc.Menu(itemBack); + menuBack.setPosition(cc.p(0, 0)); + this.addChild(menuBack); + }, + setDirectLabel: function (time) { + if (time == 0) { + time = "<1"; + } + this.directLabel.string = "create directly cost:" + time + "ms"; + }, + setPoolLabel: function (time) { + if (time == 0) { + time = "<1"; + } + this.poolLabel.string = "use pool cost:" + time + "ms"; + + }, + addSpriteByCreate: function () { + this.datalist1 = []; + this.timeStart("directly"); + for (var i = 0; i < 150; i++) { + var sp = MySprite.create(1, 2, 3); + this.datalist1.push(sp); + this.addChild(sp, 100); + sp.x = 50 + 8 * i; + } + this.setDirectLabel(this.timeEnd("directly")); + this.schedule(function () { + for (var i = 0; i < this.datalist1.length; i++) { + this.datalist1[i].removeFromParent(true); + } + this.datalist1 = []; + }, 0, 1, 0.1); + }, + addSpriteByPool: function () { + this.datalist2 = []; + for (var i = 0; i < 150; i++) { + var sp = MySprite.create(1, 2, 3); + this.addChild(sp); + cc.pool.putInPool(sp); + } + this.timeStart("use Pool"); + for (var i = 0; i < 150; i++) { + var sp = MySprite.reCreate(4, 5, 6); + this.datalist2.push(sp); + this.addChild(sp, 100); +// sp.runAction(action); + sp.x = 50 + 8 * i; + } + this.setPoolLabel(this.timeEnd("use Pool")); + this.schedule(function () { + for (var i = 0; i < this.datalist2.length; i++) { + this.datalist2[i].removeFromParent(true); + } + this.datalist2 = []; + cc.pool.drainAllPools(); + }, 0, 1, 0.1); + }, + timeStart: function (name) { + this.timeList[name] = {startTime: Date.now(), EndTime: 0, DeltaTime: 0}; + }, + timeEnd: function (name) { + var obj = this.timeList[name]; + obj.EndTime = Date.now(); + obj.DeltaTime = obj.EndTime - obj.startTime; + return obj.DeltaTime; + }, + toExtensionsMainLayer: function (sender) { + var scene = new ExtensionsTestScene(); + scene.runThisTest(); + } +}); + +CCPoolTest.create = function () { + var retObj = new CCPoolTest(); + if (retObj && retObj.init()) { + return retObj; + } + return null; +}; + + +var runCCPoolTest = function () { + var pScene = cc.Scene.create(); + var pLayer = CCPoolTest.create(); + pScene.addChild(pLayer); + cc.director.runScene(pScene); +}; +var MySprite = cc.Sprite.extend({ + _hp: 0, + _sp: 0, + _mp: 0, + ctor: function (f1, f2, f3) { + this._super(s_grossini); + this.initData(f1, f2, f3); + }, + initData: function (f1, f2, f3) { + this._hp = f1; + this._mp = f2; + this._sp = f3; + }, + unuse: function () { + this._hp = 0; + this._mp = 0; + this._sp = 0; + this.retain();//if in jsb + this.setVisible(false); + this.removeFromParent(true); + }, + reuse: function (f1, f2, f3) { + this.initData(f1, f2, f3); + this.setVisible(true); + } +}); + +MySprite.create = function (f1, f2, f3) { + return new MySprite(f1, f2, f3) +} +MySprite.reCreate = function (f1, f2, f3) { + var pool = cc.pool; + if (pool.hasObject(MySprite)) return pool.getFromPool(MySprite, f1, f2, f3); + return MySprite.create(f1, f2, f3); +} \ No newline at end of file diff --git a/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.js b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.js new file mode 100644 index 0000000000..764e5e06db --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.js @@ -0,0 +1,40 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +cc.BuilderReader.registerController("TestAnimationsLayer", { + "onCCControlButtonIdleClicked" : function(sender, controlEvent) { + this.rootNode.animationManager.runAnimationsForSequenceNamedTweenDuration("Idle", 0.3); + }, + "onCCControlButtonWaveClicked" : function(sender, controlEvent) { + this.rootNode.animationManager.runAnimationsForSequenceNamedTweenDuration("Wave", 0.3); + }, + "onCCControlButtonJumpClicked" : function(sender, controlEvent) { + this.rootNode.animationManager.runAnimationsForSequenceNamedTweenDuration("Jump", 0.3); + }, + "onCCControlButtonFunkyClicked" : function(sender, controlEvent) { + this.rootNode.animationManager.runAnimationsForSequenceNamedTweenDuration("Funky", 0.3); + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.js b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.js new file mode 100644 index 0000000000..fc5df69188 --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.js @@ -0,0 +1,44 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +cc.BuilderReader.registerController("TestButtonsLayer", { + "onCCControlButtonClicked" : function(sender,controlEvent) { + var str = (function(){ + switch(controlEvent) { + case cc.CONTROL_EVENT_TOUCH_DOWN: return "Touch Down."; + case cc.CONTROL_EVENT_TOUCH_DRAG_INSIDE: return "Touch Drag Inside."; + case cc.CONTROL_EVENT_TOUCH_DRAG_OUTSIDE: return "Touch Drag Outside."; + case cc.CONTROL_EVENT_TOUCH_DRAG_ENTER: return "Touch Drag Enter."; + case cc.CONTROL_EVENT_TOUCH_DRAG_EXIT: return "Touch Drag Exit."; + case cc.CONTROL_EVENT_TOUCH_UP_INSIDE: return "Touch Up Inside."; + case cc.CONTROL_EVENT_TOUCH_UP_OUTSIDE: return "Touch Up Outside."; + case cc.CONTROL_EVENT_TOUCH_CANCEL: return "Touch Cancel."; + case cc.CONTROL_EVENT_VALUECHANGED: return "Value Changed."; + } + return ""; + })(); + this["mCCControlEventLabel"].setString(str); + } +}); diff --git a/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.js b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.js new file mode 100644 index 0000000000..2dcbb3b344 --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.js @@ -0,0 +1,39 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var CocosBuilderTestScene = TestScene.extend({ + runThisTest:function(){ + cc.BuilderReader.setResourcePath("res/"); + + var node = cc.BuilderReader.load("res/ccb/HelloCocosBuilder.ccbi", this); + + if(node != null) { + this.addChild(node); + } + + cc.director.runScene(this); + } +}); diff --git a/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.js b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.js new file mode 100644 index 0000000000..66bd4aaceb --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.js @@ -0,0 +1,69 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +cc.BuilderReader.registerController("HelloCocosBuilderLayer", { + _openTest : function(ccbFileName) { + cc.BuilderReader.setResourcePath("res/"); + var node = cc.BuilderReader.load(ccbFileName, this); + + this["mTestTitleLabelTTF"].setString(ccbFileName); + var scene = new cc.Scene(); + if(node != null) + scene.addChild(node); + + /* Push the new scene with a fancy transition. */ + cc.director.pushScene(new cc.TransitionFade(0.5, scene, cc.color(0, 0, 0))); + }, + + "onMenuTestClicked" : function() { + this._openTest("res/ccb/ccb/TestMenus.ccbi"); + }, + + "onSpriteTestClicked" : function() { + this._openTest("res/ccb/ccb/TestSprites.ccbi"); + }, + + "onButtonTestClicked" : function() { + this._openTest("res/ccb/ccb/TestButtons.ccbi"); + }, + + "onAnimationsTestClicked" : function() { + this._openTest("res/ccb/ccb/TestAnimations.ccbi"); + }, + + "onParticleSystemTestClicked" : function() { + this._openTest("res/ccb/ccb/TestParticleSystems.ccbi"); + }, + + "onScrollViewTestClicked" : function() { + this._openTest("res/ccb/ccb/TestScrollViews.ccbi"); + }, + + "onTimelineCallbackSoundClicked" : function() { + this._openTest("res/ccb/ccb/TestTimelineCallback.ccbi"); + } +}); + diff --git a/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/LabelTest/LabelTestLayer.js b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/LabelTest/LabelTestLayer.js new file mode 100644 index 0000000000..b640dd6840 --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/LabelTest/LabelTestLayer.js @@ -0,0 +1,26 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +cc.BuilderReader.registerController("TestLabelsLayer", {}); \ No newline at end of file diff --git a/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.js b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.js new file mode 100644 index 0000000000..e9193fe818 --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.js @@ -0,0 +1,39 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +cc.BuilderReader.registerController("TestMenusLayer", { + "onMenuItemAClicked" : function(sender) { + this["mMenuItemStatusLabelBMFont"].setString("Menu Item A clicked."); + }, + + "onMenuItemBClicked" : function(sender) { + this["mMenuItemStatusLabelBMFont"].setString("Menu Item B clicked."); + }, + + "onMenuItemCClicked" : function(sender) { + this["mMenuItemStatusLabelBMFont"].setString("Menu Item C clicked."); + } +}); diff --git a/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/ParticleSystemTest/ParticleSystemTestLayer.js b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/ParticleSystemTest/ParticleSystemTestLayer.js new file mode 100644 index 0000000000..3b2f7328da --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/ParticleSystemTest/ParticleSystemTestLayer.js @@ -0,0 +1,27 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +cc.BuilderReader.registerController("TestParticleSystemsLayer", {}); \ No newline at end of file diff --git a/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/ScrollViewTest/ScrollViewTestLayer.js b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/ScrollViewTest/ScrollViewTestLayer.js new file mode 100644 index 0000000000..2f1c48951f --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/ScrollViewTest/ScrollViewTestLayer.js @@ -0,0 +1,27 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +cc.BuilderReader.registerController("TestScrollViewsLayer", {}); \ No newline at end of file diff --git a/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/SpriteTest/SpriteTestLayer.js b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/SpriteTest/SpriteTestLayer.js new file mode 100644 index 0000000000..5565869692 --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/SpriteTest/SpriteTestLayer.js @@ -0,0 +1,28 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +cc.BuilderReader.registerController("TestSpritesLayer", {}); + diff --git a/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.js b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.js new file mode 100644 index 0000000000..412b8d5263 --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.js @@ -0,0 +1,31 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +cc.BuilderReader.registerController("TestHeaderLayer", { + "onBackClicked" : function() { + cc.director.popScene(); + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.js b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.js new file mode 100644 index 0000000000..0049c9169c --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.js @@ -0,0 +1,41 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +cc.BuilderReader.registerController("TestTimelineLayer", { + "onCallback1" : function(sender) { + // Rotate the label when the button is pressed + var label = this["helloLabel"]; + label.runAction(cc.rotateBy(1,360)); + label.setString("Callback 1"); + }, + + "onCallback2" : function(sender) { + // Rotate the label when the button is pressed + var label = this["helloLabel"]; + label.runAction(cc.rotateBy(1,-360)); + label.setString("Callback 2"); + } +}); diff --git a/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.js b/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.js new file mode 100644 index 0000000000..cb30419028 --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.js @@ -0,0 +1,284 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var ControlButtonTest_HelloVariableSize = ControlScene.extend({ + init:function () { + if (this._super()) { + var screenSize = cc.director.getWinSize(); + + // Defines an array of title to create buttons dynamically + var stringArray = ["Hello", "Variable", "Size", "!"]; + + var layer = new cc.Node(); + this.addChild(layer, 1); + + var total_width = 0, height = 0; + + // For each title in the array + for (var i = 0; i < stringArray.length; i++) { + var button = this.standardButtonWithTitle(stringArray[i]); + + if (i == 0) { + button.opacity = 50; + //todo setColor not work in canvas + //button.color = cc.color(0, 255, 0); + } + else if (i == 1) { + button.opacity = 200; + //todo setColor not work in canvas + //button.color = cc.color(0, 255, 0); + } + else if (i == 2) { + button.opacity = 100; + //todo setColor not work in canvas + //button.color = cc.color(0, 0, 255); + } + + button.x = total_width + button.width / 2; + button.y = button.height / 2; + layer.addChild(button); + + // Compute the size of the layer + height = button.height; + total_width += button.width; + } + + layer.anchorX = 0.5; + layer.anchorY = 0.5; + layer.width = total_width; + layer.height = height; + layer.x = screenSize.width / 2.0; + layer.y = screenSize.height / 2.0; + + // Add the black background + var background = new cc.Scale9Sprite(s_extensions_buttonBackground); + background.width = total_width + 14; + background.height = height + 14; + background.x = screenSize.width / 2.0; + background.y = screenSize.height / 2.0; + this.addChild(background); + return true; + } + return false; + }, + // Creates and return a button with a default background and title color. + standardButtonWithTitle:function (title) { + // Creates and return a button with a default background and title color. + var backgroundButton = new cc.Scale9Sprite(s_extensions_button); + var backgroundHighlightedButton = new cc.Scale9Sprite(s_extensions_buttonHighlighted); + + var titleButton = new cc.LabelTTF(title, "Marker Felt", 30); + + titleButton.color = cc.color(159, 168, 176); + + var button = new cc.ControlButton(titleButton, backgroundButton); + button.setBackgroundSpriteForState(backgroundHighlightedButton, cc.CONTROL_STATE_HIGHLIGHTED); + button.setTitleColorForState(cc.color.WHITE, cc.CONTROL_STATE_HIGHLIGHTED); + + return button; + } +}); + +ControlButtonTest_HelloVariableSize.create = function (sceneTitle) { + var scene = new cc.Scene(); + var controlLayer = new ControlButtonTest_HelloVariableSize(); + if (controlLayer && controlLayer.init()) { + controlLayer.getSceneTitleLabel().setString(sceneTitle); + scene.addChild(controlLayer); + } + return scene; +}; + +var ControlButtonTest_Event = ControlScene.extend({ + _displayValueLabel:null, + + init:function () { + if (this._super()) { + var screenSize = cc.director.getWinSize(); + + // Add the button + var backgroundButton = new cc.Scale9Sprite(s_extensions_button); + var backgroundHighlightedButton = new cc.Scale9Sprite(s_extensions_buttonHighlighted); + + // Add a label in which the button events will be displayed + this.setDisplayValueLabel(new cc.LabelTTF("No Event", "Marker Felt", 32)); + this._displayValueLabel.anchorX = 0.5; + this._displayValueLabel.anchorY = -1; + this._displayValueLabel.x = screenSize.width / 2.0; + this._displayValueLabel.y = screenSize.height / 2.0; + this.addChild(this._displayValueLabel, 10); + + var titleButton = new cc.LabelTTF("Touch Me!", "Marker Felt", 30); + titleButton.color = cc.color(159, 168, 176); + + var controlButton = new cc.ControlButton(titleButton, backgroundButton); + controlButton.setBackgroundSpriteForState(backgroundHighlightedButton, cc.CONTROL_STATE_HIGHLIGHTED); + controlButton.setTitleColorForState(cc.color.WHITE, cc.CONTROL_STATE_HIGHLIGHTED); + + controlButton.anchorX = 0.5; + controlButton.anchorY = 1; + controlButton.x = screenSize.width / 2.0; + controlButton.y = screenSize.height / 2.0; + this.addChild(controlButton, 1); + + // Add the black background + var background = new cc.Scale9Sprite(s_extensions_buttonBackground); + background.width = 300; + background.height = 170; + background.x = screenSize.width / 2.0; + background.y = screenSize.height / 2.0; + this.addChild(background); + + // Sets up event handlers + controlButton.addTargetWithActionForControlEvents(this, this.touchDownAction, cc.CONTROL_EVENT_TOUCH_DOWN); + controlButton.addTargetWithActionForControlEvents(this, this.touchDragInsideAction, cc.CONTROL_EVENT_TOUCH_DRAG_INSIDE); + controlButton.addTargetWithActionForControlEvents(this, this.touchDragOutsideAction, cc.CONTROL_EVENT_TOUCH_DRAG_OUTSIDE); + controlButton.addTargetWithActionForControlEvents(this, this.touchDragEnterAction, cc.CONTROL_EVENT_TOUCH_DRAG_ENTER); + controlButton.addTargetWithActionForControlEvents(this, this.touchDragExitAction, cc.CONTROL_EVENT_TOUCH_DRAG_EXIT); + controlButton.addTargetWithActionForControlEvents(this, this.touchUpInsideAction, cc.CONTROL_EVENT_TOUCH_UP_INSIDE); + controlButton.addTargetWithActionForControlEvents(this, this.touchUpOutsideAction, cc.CONTROL_EVENT_TOUCH_UP_OUTSIDE); + controlButton.addTargetWithActionForControlEvents(this, this.touchCancelAction, cc.CONTROL_EVENT_TOUCH_CANCEL); + return true; + } + return false; + }, + + getDisplayValueLabel:function () { + return this._displayValueLabel; + }, + setDisplayValueLabel:function (displayValueLabel) { + this._displayValueLabel = displayValueLabel; + }, + + touchDownAction:function (sender, controlEvent) { + this._displayValueLabel.setString("Touch Down"); + }, + touchDragInsideAction:function (sender, controlEvent) { + this._displayValueLabel.setString("Drag Inside"); + }, + touchDragOutsideAction:function (sender, controlEvent) { + this._displayValueLabel.setString("Drag Outside"); + }, + touchDragEnterAction:function (sender, controlEvent) { + this._displayValueLabel.setString("Drag Enter"); + }, + touchDragExitAction:function (sender, controlEvent) { + this._displayValueLabel.setString("Drag Exit"); + }, + touchUpInsideAction:function (sender, controlEvent) { + this._displayValueLabel.setString("Touch Up Inside."); + }, + touchUpOutsideAction:function (sender, controlEvent) { + this._displayValueLabel.setString("Touch Up Outside."); + }, + touchCancelAction:function (sender, controlEvent) { + this._displayValueLabel.setString("Touch Cancel"); + } +}); + +ControlButtonTest_Event.create = function (sceneTitle) { + var scene = new cc.Scene(); + var controlLayer = new ControlButtonTest_Event(); + if (controlLayer && controlLayer.init()) { + controlLayer.getSceneTitleLabel().setString(sceneTitle); + scene.addChild(controlLayer); + } + return scene; +}; + +var ControlButtonTest_Styling = ControlScene.extend({ + init:function () { + if (this._super()) { + var screenSize = cc.director.getWinSize(); + + var layer = new cc.Node(); + this.addChild(layer, 1); + + var space = 10; // px + + var max_w = 0, max_h = 0; + for (var i = 0; i < 3; i++) { + for (var j = 0; j < 3; j++) { + // Add the buttons + var button = this.standardButtonWithTitle((0 | (Math.random() * 30)) + ""); + button.setAdjustBackgroundImage(false); // Tells the button that the background image must not be adjust + // It'll use the prefered size of the background image + button.x = button.width / 2 + (button.width + space) * i; + button.y = button.height / 2 + (button.height + space) * j; + layer.addChild(button); + + max_w = Math.max(button.width * (i + 1) + space * i, max_w); + max_h = Math.max(button.height * (j + 1) + space * j, max_h); + } + } + + layer.anchorX = 0.5; + layer.anchorY = 0.5; + layer.width = max_w; + layer.height = max_h; + layer.x = screenSize.width / 2.0; + layer.y = screenSize.height / 2.0; + + // Add the black background + var backgroundButton = new cc.Scale9Sprite(s_extensions_buttonBackground); + backgroundButton.width = max_w + 14; + backgroundButton.height = max_h + 14; + backgroundButton.x = screenSize.width / 2.0; + backgroundButton.y = screenSize.height / 2.0; + this.addChild(backgroundButton); + return true; + } + return false; + }, + standardButtonWithTitle:function (title) { + /** Creates and return a button with a default background and title color. */ + var backgroundButton = new cc.Scale9Sprite(s_extensions_button); + backgroundButton.setPreferredSize(cc.size(45, 45)); // Set the prefered size + var backgroundHighlightedButton = new cc.Scale9Sprite(s_extensions_buttonHighlighted); + backgroundHighlightedButton.setPreferredSize(cc.size(45, 45)); // Set the prefered size + + var titleButton = new cc.LabelTTF(title, "Marker Felt", 30); + + titleButton.color = cc.color(159, 168, 176); + + var button = new cc.ControlButton(titleButton, backgroundButton); + button.setBackgroundSpriteForState(backgroundHighlightedButton, cc.CONTROL_STATE_HIGHLIGHTED); + button.setTitleColorForState(cc.color.WHITE, cc.CONTROL_STATE_HIGHLIGHTED); + + return button; + } +}); + +ControlButtonTest_Styling.create = function (sceneTitle) { + var scene = new cc.Scene(); + var controlLayer = new ControlButtonTest_Styling(); + if (controlLayer && controlLayer.init()) { + controlLayer.getSceneTitleLabel().setString(sceneTitle); + scene.addChild(controlLayer); + } + return scene; +}; + diff --git a/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlColourPickerTest/CCControlColourPickerTest.js b/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlColourPickerTest/CCControlColourPickerTest.js new file mode 100644 index 0000000000..f5a834050c --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlColourPickerTest/CCControlColourPickerTest.js @@ -0,0 +1,97 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var ControlColourPickerTest = ControlScene.extend({ + _colorLabel:null, + init:function () { + if (this._super()) { + var screenSize = cc.director.getWinSize(); + + var layer = new cc.Node(); + layer.x = screenSize.width / 2; + layer.y = screenSize.height / 2; + this.addChild(layer, 1); + + var layer_width = 0; + + // Create the colour picker + var colourPicker = new cc.ControlColourPicker(); + colourPicker.color = cc.color(37, 46, 252); + colourPicker.x = colourPicker.width / 2; + colourPicker.y = 0; + + // Add it to the layer + layer.addChild(colourPicker); + + // Add the target-action pair + colourPicker.addTargetWithActionForControlEvents(this,this.colourValueChanged, cc.CONTROL_EVENT_VALUECHANGED); + + + layer_width += colourPicker.width; + + // Add the black background for the text + var background = new cc.Scale9Sprite("res/extensions/buttonBackground.png"); + background.width = 150; + background.height = 50; + background.x = layer_width + background.width / 2.0; + background.y = 0; + layer.addChild(background); + + layer_width += background.width; + + this._colorLabel = new cc.LabelTTF("#color", "Marker Felt", 30); + this._colorLabel.retain(); + + this._colorLabel.x = background.x; + this._colorLabel.y = background.y; + layer.addChild(this._colorLabel); + + // Set the layer size + layer.width = layer_width; + layer.height = 0; + layer.anchorX = 0.5; + layer.anchorY = 0.5; + + // Update the color text + this.colourValueChanged(colourPicker, cc.CONTROL_EVENT_VALUECHANGED); + return true; + } + return false; + }, + colourValueChanged:function (sender, controlEvent) { + // Change value of label. + this._colorLabel.setString(cc.colorToHex(sender.color).toUpperCase()); + } +}); +ControlColourPickerTest.create = function (sceneTitle) { + var scene = new cc.Scene(); + var controlLayer = new ControlColourPickerTest(); + if (controlLayer && controlLayer.init()) { + controlLayer.getSceneTitleLabel().setString(sceneTitle); + scene.addChild(controlLayer); + } + return scene; +}; \ No newline at end of file diff --git a/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.js b/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.js new file mode 100644 index 0000000000..a6d842206f --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.js @@ -0,0 +1,96 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var ControlPotentiometerTest = ControlScene.extend({ + _displayValueLabel:null, + init:function () { + if (this._super()) { + var screenSize = cc.director.getWinSize(); + + var layer = new cc.Node(); + layer.x = screenSize.width / 2; + layer.y = screenSize.height / 2; + this.addChild(layer, 1); + + var layer_width = 0; + + // Add the black background for the text + var background = new cc.Scale9Sprite("res/extensions/buttonBackground.png"); + background.width = 80; + background.height = 50; + background.x = layer_width + background.width / 2.0; + background.y = 0; + layer.addChild(background); + + layer_width += background.width; + + this._displayValueLabel = new cc.LabelTTF("", "HelveticaNeue-Bold", 30); + + this._displayValueLabel.x = background.x; + this._displayValueLabel.y = background.y; + layer.addChild(this._displayValueLabel); + + // Add the slider + var potentiometer = new cc.ControlPotentiometer("res/extensions/potentiometerTrack.png" + , "res/extensions/potentiometerProgress.png" + , "res/extensions/potentiometerButton.png"); + potentiometer.x = layer_width + 10 + potentiometer.width / 2; + potentiometer.y = 0; + + // When the value of the slider will change, the given selector will be call + potentiometer.addTargetWithActionForControlEvents(this, this.valueChanged, cc.CONTROL_EVENT_VALUECHANGED); + + layer.addChild(potentiometer); + + layer_width += potentiometer.width; + + // Set the layer size + layer.width = layer_width; + layer.height = 0; + layer.anchorX = 0.5; + layer.anchorY = 0.5; + + // Update the value label + this.valueChanged(potentiometer, cc.CONTROL_EVENT_VALUECHANGED); + + return true; + } + return false; + }, + valueChanged:function (sender, controlEvent) { + // Change value of label. + this._displayValueLabel.setString(sender.getValue().toFixed(2)); + } +}); +ControlPotentiometerTest.create = function (sceneTitle) { + var scene = new cc.Scene(); + var controlLayer = new ControlPotentiometerTest(); + if (controlLayer && controlLayer.init()) { + controlLayer.getSceneTitleLabel().setString(sceneTitle); + scene.addChild(controlLayer); + } + return scene; +}; \ No newline at end of file diff --git a/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlScene.js b/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlScene.js new file mode 100644 index 0000000000..3f6d2db38b --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlScene.js @@ -0,0 +1,115 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var ControlScene = cc.Layer.extend({ + _sceneTitleLabel:null, + + getSceneTitleLabel:function(){return this._sceneTitleLabel;}, + setSceneTitleLabel:function(sceneTitleLabel){this._sceneTitleLabel = sceneTitleLabel;}, + + init:function(){ + if (this._super()) { + // Get the sceensize + var screensize = cc.director.getWinSize(); + + var pBackItem = new cc.MenuItemFont("Back", this.toExtensionsMainLayer, this); + pBackItem.x = screensize.width - 50; + pBackItem.y = 25; + var pBackMenu = new cc.Menu(pBackItem); + pBackMenu.x = 0; + pBackMenu.y = 0; + this.addChild(pBackMenu, 10); + + // Add the generated background + var background = new cc.Sprite(s_extensions_background); + background.x = screensize.width / 2; + background.y = screensize.height / 2; + var bgRect = background.getTextureRect(); + background.scaleX = screensize.width/bgRect.width; + background.scaleY = screensize.height/bgRect.height; + this.addChild(background); + + // Add the ribbon + var ribbon = new cc.Scale9Sprite(s_extensions_ribbon, cc.rect(1, 1, 48, 55)); + ribbon.width = screensize.width; + ribbon.height = 57; + ribbon.x = screensize.width / 2.0; + ribbon.y = screensize.height - ribbon.height / 2.0; + this.addChild(ribbon); + + // Add the title + this.setSceneTitleLabel(new cc.LabelTTF("Title", "Arial", 12)); + this._sceneTitleLabel.x = screensize.width / 2; + this._sceneTitleLabel.y = screensize.height - this._sceneTitleLabel.height / 2 - 5; + this.addChild(this._sceneTitleLabel, 1); + + // Add the menu + var item1 = new cc.MenuItemImage(s_pathB1, s_pathB2, this.previousCallback, this); + var item2 = new cc.MenuItemImage(s_pathR1, s_pathR2, this.restartCallback, this); + var item3 = new cc.MenuItemImage(s_pathF1, s_pathF2, this.nextCallback, this); + + var menu = new cc.Menu(item1, item3, item2); + menu.x = 0; + menu.y = 0; + item1.x = screensize.width / 2 - 100; + item1.y = 37; + item2.x = screensize.width / 2; + item2.y = 35; + item3.x = screensize.width / 2 + 100; + item3.y = 37; + + this.addChild(menu ,1); + + return true; + } + return false; + }, + + toExtensionsMainLayer:function(sender){ + var pScene = new ExtensionsTestScene(); + pScene.runThisTest(); + }, + + previousCallback:function(sender){ + cc.director.runScene(ControlSceneManager.getInstance().previousControlScene()); + }, + restartCallback:function(sender){ + cc.director.runScene(ControlSceneManager.getInstance().currentControlScene()); + }, + nextCallback:function(sender){ + cc.director.runScene(ControlSceneManager.getInstance().nextControlScene()); + } +}); + +ControlScene.create = function(title){ + var scene = new cc.Scene(); + var controlLayer = new ControlScene(); + if(controlLayer && controlLayer.init()){ + controlLayer.getSceneTitleLabel().setString(title); + scene.addChild(controlLayer); + } + return scene; +}; diff --git a/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.js b/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.js new file mode 100644 index 0000000000..c1ae639f71 --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.js @@ -0,0 +1,120 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var controTestItemNames = [ + { + itemTitle:"ControlSliderTest", + testScene:function () { + return ControlSliderTest.create(this.itemTitle); + } + }, + { + itemTitle:"ControlColourPickerTest", + testScene:function () { + return ControlColourPickerTest.create(this.itemTitle); + } + }, + { + itemTitle:"ControlSwitchTest", + testScene:function () { + return ControlSwitchTest.create(this.itemTitle); + } + }, + { + itemTitle:"ControlButtonTest_HelloVariableSize", + testScene:function () { + return ControlButtonTest_HelloVariableSize.create(this.itemTitle); + } + }, + { + itemTitle:"ControlButtonTest_Event", + testScene:function () { + return ControlButtonTest_Event.create(this.itemTitle); + } + }, + { + itemTitle:"ControlButtonTest_Styling", + testScene:function () { + return ControlButtonTest_Styling.create(this.itemTitle); + } + }, + { + itemTitle:"ControlPotentiometerTest", + testScene:function () { + return ControlPotentiometerTest.create(this.itemTitle); + } + }, + { + itemTitle:"ControlStepperTest", + testScene:function () { + return ControlStepperTest.create(this.itemTitle); + } + } +]; + +var ControlSceneManager = cc.Class.extend({ + _currentControlSceneId:0, + + ctor:function () { + this._currentControlSceneId = 0; + }, + + getCurrentControlSceneId:function () { + return this._currentControlSceneId; + }, + setCurrentControlSceneId:function (currentControlSceneId) { + this._currentControlSceneId = currentControlSceneId + }, + + nextControlScene:function () { + this._currentControlSceneId = (this._currentControlSceneId + 1) % controTestItemNames.length; + return this.currentControlScene(); + }, + + previousControlScene:function () { + this._currentControlSceneId = this._currentControlSceneId - 1; + if (this._currentControlSceneId < 0) { + this._currentControlSceneId = controTestItemNames.length - 1; + } + + return this.currentControlScene(); + }, + + currentControlScene:function () { + return controTestItemNames[this._currentControlSceneId].testScene(); + } +}); + +ControlSceneManager.sharedInstance = null; +/** + * Returns the singleton of the control scene manager. + */ +ControlSceneManager.getInstance = function () { + if (ControlSceneManager.sharedInstance == null) { + ControlSceneManager.sharedInstance = new ControlSceneManager(); + } + return ControlSceneManager.sharedInstance; +}; diff --git a/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.js b/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.js new file mode 100644 index 0000000000..90e6d20ec5 --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.js @@ -0,0 +1,93 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var ControlSliderTest = ControlScene.extend({ + _displayValueLabel:null, + init:function () { + if (this._super()) { + var screenSize = cc.director.getWinSize(); + + // Add a label in which the slider value will be displayed + this._displayValueLabel = new cc.LabelTTF("Move the slider thumb!\nThe lower slider is restricted.", "Marker Felt", 32); + this._displayValueLabel.retain(); + this._displayValueLabel.anchorX = 0.5; + this._displayValueLabel.anchorY = -1.0; + this._displayValueLabel.x = screenSize.width / 1.7; + this._displayValueLabel.y = screenSize.height / 2.0; + this.addChild(this._displayValueLabel); + + // Add the slider + var slider = new cc.ControlSlider("res/extensions/sliderTrack.png", "res/extensions/sliderProgress.png", "res/extensions/sliderThumb.png"); + slider.anchorX = 0.5; + slider.anchorY = 1.0; + slider.setMinimumValue(0.0); // Sets the min value of range + slider.setMaximumValue(5.0); // Sets the max value of range + slider.x = screenSize.width / 2.0; + slider.y = screenSize.height / 2.0 + 16; + slider.tag = 1; + + // When the value of the slider will change, the given selector will be call + slider.addTargetWithActionForControlEvents(this, this.valueChanged, cc.CONTROL_EVENT_VALUECHANGED); + + var restrictSlider = new cc.ControlSlider("res/extensions/sliderTrack.png", "res/extensions/sliderProgress.png", "res/extensions/sliderThumb.png"); + restrictSlider.anchorX = 0.5; + restrictSlider.anchorY = 1.0; + restrictSlider.setMinimumValue(0.0); // Sets the min value of range + restrictSlider.setMaximumValue(5.0); // Sets the max value of range + restrictSlider.setMaximumAllowedValue(4.0); + restrictSlider.setMinimumAllowedValue(1.5); + restrictSlider.setValue(3.0); + restrictSlider.x = screenSize.width / 2.0; + restrictSlider.y = screenSize.height / 2.0 - 24; + restrictSlider.tag = 2; + + //same with restricted + restrictSlider.addTargetWithActionForControlEvents(this, this.valueChanged, cc.CONTROL_EVENT_VALUECHANGED); + + this.addChild(slider); + this.addChild(restrictSlider); + return true; + } + return false; + }, + valueChanged:function (sender, controlEvent) { + // Change value of label. + if (sender.tag == 1) + this._displayValueLabel.setString("Upper slider value = " + sender.getValue().toFixed(2)); + if (sender.tag == 2) + this._displayValueLabel.setString("Lower slider value = " + sender.getValue().toFixed(2)); + } +}); + +ControlSliderTest.create = function (sceneTitle) { + var scene = new cc.Scene(); + var controlLayer = new ControlSliderTest(); + if (controlLayer && controlLayer.init()) { + controlLayer.getSceneTitleLabel().setString(sceneTitle); + scene.addChild(controlLayer); + } + return scene; +}; \ No newline at end of file diff --git a/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.js b/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.js new file mode 100644 index 0000000000..5f4e7708f6 --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.js @@ -0,0 +1,95 @@ +/************************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + + */ + +var ControlStepperTest = ControlScene.extend({ + _displayValueLabel:null, + init:function () { + if (this._super()) { + var screenSize = cc.director.getWinSize(); + + var layer = new cc.Node(); + layer.x = screenSize.width / 2; + layer.y = screenSize.height / 2; + this.addChild(layer, 1); + var layer_width = 0; + + // Add the black background for the text + var background = new cc.Scale9Sprite("res/extensions/buttonBackground.png"); + background.width = 100; + background.height = 50; + background.x = layer_width + background.width / 2.0; + background.y = 0; + layer.addChild(background); + + this._displayValueLabel = new cc.LabelTTF("0", "HelveticaNeue-Bold", 30); + + this._displayValueLabel.x = background.x; + this._displayValueLabel.y = background.y; + layer.addChild(this._displayValueLabel); + + layer_width += background.width; + + var stepper = this.makeControlStepper(); + stepper.x = layer_width + 10 + stepper.width / 2; + stepper.y = 0; + stepper.addTargetWithActionForControlEvents(this, this.valueChanged, cc.CONTROL_EVENT_VALUECHANGED); + layer.addChild(stepper); + + layer_width += stepper.width; + + // Set the layer size + layer.width = layer_width; + layer.height = 0; + layer.anchorX = 0.5; + layer.anchorY = 0.5; + + // Update the value label + this.valueChanged(stepper, cc.CONTROL_EVENT_VALUECHANGED); + return true; + } + return false; + }, + makeControlStepper:function () { + var minusSprite = new cc.Sprite("res/extensions/stepper-minus.png"); + var plusSprite = new cc.Sprite("res/extensions/stepper-plus.png"); + + return new cc.ControlStepper(minusSprite, plusSprite); + }, + + valueChanged:function (sender, controlEvent) { + // Change value of label. + this._displayValueLabel.setString(sender.getValue().toString()); + } +}); + +ControlStepperTest.create = function (sceneTitle) { + var scene = new cc.Scene(); + var controlLayer = new ControlStepperTest(); + if (controlLayer && controlLayer.init()) { + controlLayer.getSceneTitleLabel().setString(sceneTitle); + scene.addChild(controlLayer); + } + return scene; +}; \ No newline at end of file diff --git a/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.js b/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.js new file mode 100644 index 0000000000..c9f76819b0 --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.js @@ -0,0 +1,102 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var ControlSwitchTest = ControlScene.extend({ + init:function () { + if (this._super()) { + var screenSize = cc.director.getWinSize(); + + var layer = new cc.Node(); + layer.x = screenSize.width / 2; + layer.y = screenSize.height / 2; + this.addChild(layer, 1); + + var layer_width = 0; + + // Add the black background for the text + var background = new cc.Scale9Sprite("res/extensions/buttonBackground.png"); + background.width = 80; + background.height = 50; + background.x = layer_width + background.width / 2.0; + background.y = 0; + layer.addChild(background); + + layer_width += background.width; + + this._displayValueLabel = new cc.LabelTTF("#color", "Marker Felt", 30); + this._displayValueLabel.retain(); + + this._displayValueLabel.x = background.x; + this._displayValueLabel.y = background.y; + layer.addChild(this._displayValueLabel); + + // Create the switch + var switchControl = new cc.ControlSwitch + ( + new cc.Sprite("res/extensions/switch-mask.png"), + new cc.Sprite("res/extensions/switch-on.png"), + new cc.Sprite("res/extensions/switch-off.png"), + new cc.Sprite("res/extensions/switch-thumb.png"), + new cc.LabelTTF("On", "Arial-BoldMT", 16), + new cc.LabelTTF("Off", "Arial-BoldMT", 16) + ); + switchControl.x = layer_width + 10 + switchControl.width / 2; + switchControl.y = 0; + layer.addChild(switchControl); + + switchControl.addTargetWithActionForControlEvents(this, this.valueChanged, cc.CONTROL_EVENT_VALUECHANGED); + + // Set the layer size + layer.width = layer_width; + layer.height = 0; + layer.anchorX = 0.5; + layer.anchorY = 0.5; + + // Update the value label + this.valueChanged(switchControl, cc.CONTROL_EVENT_VALUECHANGED); + return true; + } + return false; + }, + valueChanged:function (sender, controlEvent) { + if (sender.isOn()) { + this._displayValueLabel.setString("On"); + } + else { + this._displayValueLabel.setString("Off"); + } + } +}); + +ControlSwitchTest.create = function (sceneTitle) { + var scene = new cc.Scene(); + var controlLayer = new ControlSwitchTest(); + if (controlLayer && controlLayer.init()) { + controlLayer.getSceneTitleLabel().setString(sceneTitle); + scene.addChild(controlLayer); + } + return scene; +}; \ No newline at end of file diff --git a/tests/js-tests/src/ExtensionsTest/EditBoxTest/EditBoxTest.js b/tests/js-tests/src/ExtensionsTest/EditBoxTest/EditBoxTest.js new file mode 100644 index 0000000000..97f87c9b02 --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/EditBoxTest/EditBoxTest.js @@ -0,0 +1,128 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var EditBoxTestLayer = cc.Layer.extend({ + _box1: null, + _box2: null, + _box3: null, + _box4: null, + + ctor: function () { + this._super(); + cc.associateWithNative(this, cc.Layer); + this.init(); + }, + + init: function () { + this._box1 = new cc.EditBox(cc.size(170, 50), new cc.Scale9Sprite("res/extensions/green_edit.png"), new cc.Scale9Sprite("res/extensions/orange_edit.png")); + this._box1.setString("EditBoxs"); + this._box1.x = 220; + this._box1.y = 50; + this._box1.setFontColor(cc.color(251, 250, 0)); + this._box1.setDelegate(this); + this.addChild(this._box1); + + this._box2 = new cc.EditBox(cc.size(130, 40), new cc.Scale9Sprite("res/extensions/green_edit.png")); + this._box2.setString("EditBox Sample"); + this._box2.x = 220; + this._box2.y = 190; + this._box2.setInputFlag(cc.EDITBOX_INPUT_FLAG_PASSWORD); + this._box2.setFontColor(cc.color(255, 250, 0)); + this._box2.setPlaceHolder("please enter password"); + this._box2.setPlaceholderFontColor(cc.color(255, 255, 255)); + this._box2.setDelegate(this); + this.addChild(this._box2); + + this._box3 = new cc.EditBox(cc.size(65, 40), new cc.Scale9Sprite("res/extensions/orange_edit.png")); + this._box3.setString("Image"); + this._box3.x = 220; + this._box3.y = 250; + this._box3.setFontColor(cc.color(15, 250, 245)); + this._box3.setDelegate(this); + this.addChild(this._box3); + + this._box4 = new cc.EditBox(cc.size(180, 40), new cc.Scale9Sprite("res/extensions/yellow_edit.png")); + this._box4.setPlaceholderFontColor(cc.color(255, 0, 0)); + this._box4.setPlaceHolder("Tooltip:"); + this._box4.x = 40; + this._box4.y = -100; + this._box4.setDelegate(this); + this._box4.setFontColor(cc.color(5, 4, 10)); + this._box4.setMaxLength(10); + this._box3.addChild(this._box4); + + var itemBack = new cc.MenuItemFont("Back", this.toExtensionsMainLayer, this); + itemBack.x = winSize.width - 50; + itemBack.y = 25; + var menuBack = new cc.Menu(itemBack); + menuBack.x = 0; + menuBack.y = 0; + this.addChild(menuBack); + + return true; + }, + + toExtensionsMainLayer: function (sender) { + var scene = new ExtensionsTestScene(); + scene.runThisTest(); + }, + + editBoxEditingDidBegin: function (editBox) { + cc.log("editBox " + this._getEditBoxName(editBox) + " DidBegin !"); + }, + + editBoxEditingDidEnd: function (editBox) { + cc.log("editBox " + this._getEditBoxName(editBox) + " DidEnd !"); + }, + + editBoxTextChanged: function (editBox, text) { + cc.log("editBox " + this._getEditBoxName(editBox) + ", TextChanged, text: " + text); + }, + + editBoxReturn: function (editBox) { + cc.log("editBox " + this._getEditBoxName(editBox) + " was returned !"); + }, + + _getEditBoxName :function(editBox){ + if (this._box1 == editBox) { + return "box1"; + } else if (this._box2 == editBox) { + return "box2"; + } else if (this._box3 == editBox) { + return "box3"; + } else if (this._box4 == editBox) { + return "box4"; + } + return "Unknown EditBox"; + } +}); + +var runEditBoxTest = function () { + var pScene = new cc.Scene(); + var pLayer = new EditBoxTestLayer(); + pScene.addChild(pLayer); + cc.director.runScene(pScene); +}; \ No newline at end of file diff --git a/tests/js-tests/src/ExtensionsTest/ExtensionsTest.js b/tests/js-tests/src/ExtensionsTest/ExtensionsTest.js new file mode 100644 index 0000000000..0bdae8491f --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/ExtensionsTest.js @@ -0,0 +1,157 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var LINE_SPACE = 40; +var ITEM_TAG_BASIC = 1000; + +var TEST_NOTIFICATIONCENTER = 0; +var TEST_CCCONTROLBUTTON = 1; +var TEST_COCOSBUILDER = 2; +var TEST_HTTPCLIENT = 3; + +var extensionsTestItemNames = [ + /* { + itemTitle:"NotificationCenterTest", + testScene:function () { + //runNotificationCenterTest(); + cc.log("not implement"); + } + },*/ + { + itemTitle:"CCControlButtonTest", + testScene:function () { + var pManager = ControlSceneManager.getInstance(); + var pScene = pManager.currentControlScene(); + cc.director.runScene(pScene); + } + }, + { + itemTitle:"CocosBuilderTest", + testScene:function () { + var pScene = new CocosBuilderTestScene(); + if (pScene) { + pScene.runThisTest(); + } + } + }, + /* { + itemTitle:"HttpClientTest", + testScene:function () { + //runHttpClientTest(); + cc.log("not implement"); + } + },*/ + { + itemTitle:"TableViewTest", + testScene:function () { + runTableViewTest(); + } + }, + { + itemTitle:"WebSocketTest", + testScene:function () { + runWebSocketTest(); + } + }, + { + itemTitle:"SocketIOTest", + testScene:function () { + runSocketIOTest(); + } + }, + { + itemTitle:"CCPoolTest", + testScene:function () { + runCCPoolTest(); + } + } +]; + +if(!cc.sys.isNative || cc.sys.OS_LINUX !== cc.sys.os){ + extensionsTestItemNames.push({ + itemTitle:"EditBoxTest", + testScene:function () { + runEditBoxTest(); + } + }); +} + +if (cc.sys.isNative && cc.sys.OS_IOS == cc.sys.os) { + extensionsTestItemNames.push({ + itemTitle:"PluginTest", + testScene:function () { + var testScene = pluginXSceneManager.currentPluginXScene(); + cc.director.runScene(testScene); + } + }) +} + +if (cc.sys.isNative && cc.sys.OS_WINDOWS != cc.sys.os) { + extensionsTestItemNames.push({ + itemTitle:"AssetsManagerTest", + testScene:function () { + var testScene = new AssetsManagerLoaderScene(); + if (testScene) { + testScene.runThisTest(); + } + } + }); +} + +var ExtensionsMainLayer = cc.Layer.extend({ + onEnter:function () { + this._super(); + + var winSize = cc.director.getWinSize(); + + var pMenu = new cc.Menu(); + pMenu.x = 0; + pMenu.y = 0; + cc.MenuItemFont.setFontName("Arial"); + cc.MenuItemFont.setFontSize(24); + for (var i = 0; i < extensionsTestItemNames.length; ++i) { + var selItem = extensionsTestItemNames[i]; + var pItem = new cc.MenuItemFont(selItem.itemTitle, this.menuCallback, this); + pItem.x = winSize.width / 2; + pItem.y = winSize.height - (i + 1) * LINE_SPACE; + pMenu.addChild(pItem, ITEM_TAG_BASIC + i); + } + this.addChild(pMenu); + }, + + menuCallback:function (sender) { + var nIndex = sender.zIndex - ITEM_TAG_BASIC; + extensionsTestItemNames[nIndex].testScene(); + } +}); + +var ExtensionsTestScene = TestScene.extend({ + runThisTest:function () { + var pLayer = new ExtensionsMainLayer(); + this.addChild(pLayer); + cc.director.runScene(this); + } +}); diff --git a/tests/js-tests/src/ExtensionsTest/NetworkTest/SocketIOTest.js b/tests/js-tests/src/ExtensionsTest/NetworkTest/SocketIOTest.js new file mode 100644 index 0000000000..57af0589b1 --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/NetworkTest/SocketIOTest.js @@ -0,0 +1,278 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + Created by Chris Hannon 2014 http://www.channon.us + + 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. + ****************************************************************************/ +/** @expose */ +window.io; + +var SocketIO = SocketIO || window.io; + +var SocketIOTestLayer = cc.Layer.extend({ + + _sioClient: null, + _sioEndpoint: null, + _sioClientStatus: null, + + ctor:function () { + this._super(); + this.init(); + }, + + init: function () { + + var winSize = cc.director.getWinSize(); + + var MARGIN = 40; + var SPACE = 35; + + var label = new cc.LabelTTF("SocketIO Test", "Arial", 28); + label.setPosition(cc.p(winSize.width / 2, winSize.height - MARGIN)); + this.addChild(label, 0); + + var menuRequest = new cc.Menu(); + menuRequest.setPosition(cc.p(0, 0)); + this.addChild(menuRequest); + + // Test to create basic client in the default namespace + var labelSIOClient = new cc.LabelTTF("Open SocketIO Client", "Arial", 22); + labelSIOClient.setAnchorPoint(cc.p(0,0)); + var itemSIOClient = new cc.MenuItemLabel(labelSIOClient, this.onMenuSIOClientClicked, this); + itemSIOClient.setPosition(cc.p(labelSIOClient.getContentSize().width / 2 + MARGIN, winSize.height - MARGIN - SPACE)); + menuRequest.addChild(itemSIOClient); + + // Test to create a client at the endpoint '/testpoint' + var labelSIOEndpoint = new cc.LabelTTF("Open SocketIO Endpoint", "Arial", 22); + labelSIOEndpoint.setAnchorPoint(cc.p(0,0)); + var itemSIOEndpoint = new cc.MenuItemLabel(labelSIOEndpoint, this.onMenuSIOEndpointClicked, this); + itemSIOEndpoint.setPosition(cc.p(winSize.width - (labelSIOEndpoint.getContentSize().width / 2 + MARGIN), winSize.height - MARGIN - SPACE)); + menuRequest.addChild(itemSIOEndpoint); + + // Test sending message to default namespace + var labelTestMessage = new cc.LabelTTF("Send Test Message", "Arial", 22); + labelTestMessage.setAnchorPoint(cc.p(0,0)); + var itemTestMessage = new cc.MenuItemLabel(labelTestMessage, this.onMenuTestMessageClicked, this); + itemTestMessage.setPosition(cc.p(labelTestMessage.getContentSize().width / 2 + MARGIN, winSize.height - MARGIN - 2 * SPACE)); + menuRequest.addChild(itemTestMessage); + + // Test sending message to the endpoint '/testpoint' + var labelTestMessageEndpoint = new cc.LabelTTF("Test Endpoint Message", "Arial", 22); + labelTestMessageEndpoint.setAnchorPoint(cc.p(0,0)); + var itemTestMessageEndpoint = new cc.MenuItemLabel(labelTestMessageEndpoint, this.onMenuTestMessageEndpointClicked, this); + itemTestMessageEndpoint.setPosition(cc.p(winSize.width - (labelTestMessageEndpoint.getContentSize().width / 2 + MARGIN), winSize.height - MARGIN - 2 * SPACE)); + menuRequest.addChild(itemTestMessageEndpoint); + + // Test sending event 'echotest' to default namespace + var labelTestEvent = new cc.LabelTTF("Send Test Event", "Arial", 22); + labelTestEvent.setAnchorPoint(cc.p(0,0)); + var itemTestEvent = new cc.MenuItemLabel(labelTestEvent, this.onMenuTestEventClicked, this); + itemTestEvent.setPosition(cc.p(labelTestEvent.getContentSize().width / 2 + MARGIN, winSize.height - MARGIN - 3 * SPACE)); + menuRequest.addChild(itemTestEvent); + + // Test sending event 'echotest' to the endpoint '/testpoint' + var labelTestEventEndpoint = new cc.LabelTTF("Test Endpoint Event", "Arial", 22); + labelTestEventEndpoint.setAnchorPoint(cc.p(0,0)); + var itemTestEventEndpoint = new cc.MenuItemLabel(labelTestEventEndpoint, this.onMenuTestEventEndpointClicked, this); + itemTestEventEndpoint.setPosition(cc.p(winSize.width - (labelTestEventEndpoint.getContentSize().width / 2 + MARGIN), winSize.height - MARGIN - 3 * SPACE)); + menuRequest.addChild(itemTestEventEndpoint); + + // Test disconnecting basic client + var labelTestClientDisconnect = new cc.LabelTTF("Disconnect Socket", "Arial", 22); + labelTestClientDisconnect.setAnchorPoint(cc.p(0,0)); + var itemClientDisconnect = new cc.MenuItemLabel(labelTestClientDisconnect, this.onMenuTestClientDisconnectClicked, this); + itemClientDisconnect.setPosition(cc.p(labelTestClientDisconnect.getContentSize().width / 2 + MARGIN, winSize.height - MARGIN - 4 * SPACE)); + menuRequest.addChild(itemClientDisconnect); + + // Test disconnecting the endpoint '/testpoint' + var labelTestEndpointDisconnect = new cc.LabelTTF("Disconnect Endpoint", "Arial", 22); + labelTestEndpointDisconnect.setAnchorPoint(cc.p(0,0)); + var itemTestEndpointDisconnect = new cc.MenuItemLabel(labelTestEndpointDisconnect, this.onMenuTestEndpointDisconnectClicked, this); + itemTestEndpointDisconnect.setPosition(cc.p(winSize.width - (labelTestEndpointDisconnect.getContentSize().width / 2 + MARGIN), winSize.height - MARGIN - 4 * SPACE)); + menuRequest.addChild(itemTestEndpointDisconnect); + + this._sioClientStatus = new cc.LabelTTF("Not connected...", "Arial", 14); + this._sioClientStatus.setAnchorPoint(cc.p(0, 0)); + this._sioClientStatus.setPosition(cc.p(0,winSize.height * .25)); + this.addChild(this._sioClientStatus); + + // Back Menu + var itemBack = new cc.MenuItemFont("Back", this.toExtensionsMainLayer, this); + itemBack.setPosition(cc.p(winSize.width - 50, 25)); + var menuBack = new cc.Menu(itemBack); + menuBack.setPosition(cc.p(0, 0)); + this.addChild(menuBack); + + return true; + }, + + onExit: function() { + if(this._sioEndpoint) this._sioEndpoint.disconnect(); + if(this._sioClient) this._sioClient.disconnect(); + + this._super(); + }, + + //socket callback for testing + testevent: function(data) { + var msg = this.tag + " says 'testevent' with data: " + data; + this.statusLabel.setString(msg); + cc.log(msg); + }, + + message: function(data) { + var msg = this.tag + " received message: " + data; + this.statusLabel.setString(msg); + cc.log(msg); + }, + + disconnection: function() { + var msg = this.tag + " disconnected!"; + this.statusLabel.setString(msg); + cc.log(msg); + }, + // Menu Callbacks + onMenuSIOClientClicked: function(sender) { + + //create a client by using this static method, url does not need to contain the protocol + var sioclient = SocketIO.connect("ws://tools.itharbors.com:4000", {"force new connection" : true}); + + //if you need to track multiple sockets it is best to store them with tags in your own array for now + sioclient.tag = "Test Client"; + + //attaching the status label to the socketio client + //this is only necessary in javascript due to scope within shared event handlers, + //as 'this' will refer to the socketio client + sioclient.statusLabel = this._sioClientStatus; + + //register event callbacks + //this is an example of a handler declared inline + sioclient.on("connect", function() { + var msg = sioclient.tag + " Connected!"; + this.statusLabel.setString(msg); + cc.log(msg); + sioclient.send(msg); + }); + + //example of a handler that is shared between multiple clients + sioclient.on("message", this.message); + + sioclient.on("echotest", function(data) { + cc.log("echotest 'on' callback fired!"); + var msg = this.tag + " says 'echotest' with data: " + data; + this.statusLabel.setString(msg); + cc.log(msg); + }); + + sioclient.on("testevent", this.testevent); + + sioclient.on("disconnect", this.disconnection); + + this._sioClient = sioclient; + + }, + + onMenuSIOEndpointClicked: function(sender) { + + //repeat the same connection steps for the namespace "testpoint" + var sioendpoint = SocketIO.connect("ws://tools.itharbors.com:4000/testpoint"); + + //a tag to differentiate in shared callbacks + sioendpoint.tag = "Test Endpoint"; + + sioendpoint.statusLabel = this._sioClientStatus; + + sioendpoint.on("connect", function() { + var msg = sioendpoint.tag + " Connected!"; + this.statusLabel.setString(msg); + cc.log(msg); + sioendpoint.send(msg); + }); + + //register event callbacks + sioendpoint.on("echotest", function(data) { + cc.log("echotest 'on' callback fired!"); + var msg = this.tag + " says 'echotest' with data: " + data; + this.statusLabel.setString(msg); + cc.log(msg); + }); + + sioendpoint.on("message", this.message); + + //demonstrating how callbacks can be shared within a delegate + sioendpoint.on("testevent", this.testevent); + + sioendpoint.on("disconnect", this.disconnection); + + this._sioEndpoint = sioendpoint; + + }, + + onMenuTestMessageClicked: function(sender) { + + //check that the socket is != NULL before sending or emitting events + //the client should be NULL either before initialization and connection or after disconnect + if(this._sioClient != null) this._sioClient.send("Hello Socket.IO!"); + + }, + + onMenuTestMessageEndpointClicked: function(sender) { + + if(this._sioEndpoint != null) this._sioEndpoint.send("Hello Socket.IO!"); + + }, + + onMenuTestEventClicked: function(sender) { + + if(this._sioClient != null) this._sioClient.emit("echotest","[{\"name\":\"myname\",\"type\":\"mytype\"}]"); + + }, + + onMenuTestEventEndpointClicked: function(sender) { + + if(this._sioEndpoint != null) this._sioEndpoint.emit("echotest","[{\"name\":\"myname\",\"type\":\"mytype\"}]"); + + }, + + onMenuTestClientDisconnectClicked: function(sender) { + + if(this._sioClient != null) this._sioClient.disconnect(); + + }, + + onMenuTestEndpointDisconnectClicked: function(sender) { + + if(this._sioEndpoint != null) this._sioEndpoint.disconnect(); + + }, + + toExtensionsMainLayer: function (sender) { + var scene = new ExtensionsTestScene(); + scene.runThisTest(); + } +}); + +var runSocketIOTest = function () { + var pScene = new cc.Scene(); + var pLayer = new SocketIOTestLayer(); + pScene.addChild(pLayer); + cc.director.runScene(pScene); +}; \ No newline at end of file diff --git a/tests/js-tests/src/ExtensionsTest/NetworkTest/WebSocketTest.js b/tests/js-tests/src/ExtensionsTest/NetworkTest/WebSocketTest.js new file mode 100644 index 0000000000..4455043a34 --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/NetworkTest/WebSocketTest.js @@ -0,0 +1,264 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + 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. + ****************************************************************************/ + +var WebSocket = WebSocket || window.WebSocket || window.MozWebSocket; + +var WebSocketTestLayer = cc.Layer.extend({ + + _wsiSendText: null, + _wsiSendBinary: null, + _wsiError: null, + + _sendTextStatus: null, + _sendBinaryStatus: null, + _errorStatus: null, + + _sendTextTimes: 0, + _sendBinaryTimes: 0, + + init: function () { + + var winSize = cc.director.getWinSize(); + + var MARGIN = 40; + var SPACE = 35; + + var label = new cc.LabelTTF("WebSocket Test", "Arial", 28); + label.x = winSize.width / 2; + label.y = winSize.height - MARGIN; + this.addChild(label, 0); + + var menuRequest = new cc.Menu(); + menuRequest.x = 0; + menuRequest.y = 0; + this.addChild(menuRequest); + + // Send Text + var labelSendText = new cc.LabelTTF("Send Text", "Arial", 22); + var itemSendText = new cc.MenuItemLabel(labelSendText, this.onMenuSendTextClicked, this); + itemSendText.x = winSize.width / 2; + itemSendText.y = winSize.height - MARGIN - SPACE; + menuRequest.addChild(itemSendText); + + // Send Binary + var labelSendBinary = new cc.LabelTTF("Send Binary", "Arial", 22); + var itemSendBinary = new cc.MenuItemLabel(labelSendBinary, this.onMenuSendBinaryClicked, this); + itemSendBinary.x = winSize.width / 2; + itemSendBinary.y = winSize.height - MARGIN - 2 * SPACE; + menuRequest.addChild(itemSendBinary); + + + // Send Text Status Label + this._sendTextStatus = new cc.LabelTTF("Send Text WS is waiting...", "Arial", 14, cc.size(160, 100), cc.TEXT_ALIGNMENT_CENTER, cc.VERTICAL_TEXT_ALIGNMENT_TOP); + this._sendTextStatus.anchorX = 0; + this._sendTextStatus.anchorY = 0; + this._sendTextStatus.x = 0; + this._sendTextStatus.y = 25; + this.addChild(this._sendTextStatus); + + // Send Binary Status Label + this._sendBinaryStatus = new cc.LabelTTF("Send Binary WS is waiting...", "Arial", 14, cc.size(160, 100), cc.TEXT_ALIGNMENT_CENTER, cc.VERTICAL_TEXT_ALIGNMENT_TOP); + this._sendBinaryStatus.anchorX = 0; + this._sendBinaryStatus.anchorY = 0; + this._sendBinaryStatus.x = 160; + this._sendBinaryStatus.y = 25; + this.addChild(this._sendBinaryStatus); + + // Error Label + this._errorStatus = new cc.LabelTTF("Error WS is waiting...", "Arial", 14, cc.size(160, 100), cc.TEXT_ALIGNMENT_CENTER, cc.VERTICAL_TEXT_ALIGNMENT_TOP); + this._errorStatus.anchorX = 0; + this._errorStatus.anchorY = 0; + this._errorStatus.x = 320; + this._errorStatus.y = 25; + this.addChild(this._errorStatus); + + // Back Menu + var itemBack = new cc.MenuItemFont("Back", this.toExtensionsMainLayer, this); + itemBack.x = winSize.width - 50; + itemBack.y = 25; + var menuBack = new cc.Menu(itemBack); + menuBack.x = 0; + menuBack.y = 0; + this.addChild(menuBack); + + var self = this; + + this._wsiSendText = new WebSocket("ws://echo.websocket.org"); + this._wsiSendText.onopen = function(evt) { + self._sendTextStatus.setString("Send Text WS was opened."); + }; + + this._wsiSendText.onmessage = function(evt) { + self._sendTextTimes++; + var textStr = "response text msg: "+evt.data+", "+self._sendTextTimes; + cc.log(textStr); + + self._sendTextStatus.setString(textStr); + }; + + this._wsiSendText.onerror = function(evt) { + cc.log("sendText Error was fired"); + }; + + this._wsiSendText.onclose = function(evt) { + cc.log("_wsiSendText websocket instance closed."); + self._wsiSendText = null; + }; + + + this._wsiSendBinary = new WebSocket("ws://echo.websocket.org"); + this._wsiSendBinary.binaryType = "arraybuffer"; + this._wsiSendBinary.onopen = function(evt) { + self._sendBinaryStatus.setString("Send Binary WS was opened."); + }; + + this._wsiSendBinary.onmessage = function(evt) { + self._sendBinaryTimes++; + var binary = new Uint16Array(evt.data); + var binaryStr = "response bin msg: "; + + var str = ""; + for (var i = 0; i < binary.length; i++) { + if (binary[i] == 0) + { + str += "\'\\0\'"; + } + else + { + var hexChar = "0x" + binary[i].toString("16").toUpperCase(); + str += String.fromCharCode(hexChar); + } + } + + binaryStr += str + ", " + self._sendBinaryTimes; + cc.log(binaryStr); + self._sendBinaryStatus.setString(binaryStr); + }; + + this._wsiSendBinary.onerror = function(evt) { + cc.log("sendBinary Error was fired"); + }; + + this._wsiSendBinary.onclose = function(evt) { + cc.log("_wsiSendBinary websocket instance closed."); + self._wsiSendBinary = null; + }; + + this._wsiError = new WebSocket("ws://invalid.url.com"); + this._wsiError.onopen = function(evt) {}; + this._wsiError.onmessage = function(evt) {}; + this._wsiError.onerror = function(evt) { + cc.log("Error was fired"); + self._errorStatus.setString("an error was fired"); + }; + this._wsiError.onclose = function(evt) { + cc.log("_wsiError websocket instance closed."); + self._wsiError = null; + }; + + return true; + }, + + onExit: function() { + if (this._wsiSendText) + this._wsiSendText.close(); + + if (this._wsiSendBinary) + this._wsiSendBinary.close(); + + if (this._wsiError) + this._wsiError.close(); + this._super(); + }, + + // Menu Callbacks + onMenuSendTextClicked: function(sender) { + + if (this._wsiSendText.readyState == WebSocket.OPEN) + { + this._sendTextStatus.setString("Send Text WS is waiting..."); + this._wsiSendText.send("Hello WebSocket中文, I'm a text message."); + } + else + { + var warningStr = "send text websocket instance wasn't ready..."; + cc.log(warningStr); + this._sendTextStatus.setString(warningStr); + } + }, + + _stringConvertToArray:function (strData) { + if (!strData) + return null; + + var arrData = new Uint16Array(strData.length); + for (var i = 0; i < strData.length; i++) { + arrData[i] = strData.charCodeAt(i); + } + return arrData; + }, + + onMenuSendBinaryClicked: function(sender) + { + + if (this._wsiSendBinary.readyState == WebSocket.OPEN) + { + this._sendBinaryStatus.setString("Send Binary WS is waiting..."); + var buf = "Hello WebSocket中文,\0 I'm\0 a\0 binary\0 message\0."; + var binary = this._stringConvertToArray(buf); + + this._wsiSendBinary.send(binary.buffer); + } + else + { + var warningStr = "send binary websocket instance wasn't ready..."; + cc.log(warningStr); + this._sendBinaryStatus.setString(warningStr); + } + }, + + toExtensionsMainLayer: function (sender) { + var scene = new ExtensionsTestScene(); + scene.runThisTest(); + } +}); + +WebSocketTestLayer.create = function () { + var retObj = new WebSocketTestLayer(); + if (retObj && retObj.init()) { + return retObj; + } + return null; +}; + + +var runWebSocketTest = function () { + var pScene = new cc.Scene(); + var pLayer = WebSocketTestLayer.create(); + pScene.addChild(pLayer); + cc.director.runScene(pScene); +}; \ No newline at end of file diff --git a/tests/js-tests/src/ExtensionsTest/PluginXTest/AnalyticsTest.js b/tests/js-tests/src/ExtensionsTest/PluginXTest/AnalyticsTest.js new file mode 100644 index 0000000000..3165d79c43 --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/PluginXTest/AnalyticsTest.js @@ -0,0 +1,256 @@ +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies 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. + ****************************************************************************/ + +var g_pAnalytics = null; +var s_strAppKey = ""; +// The app key of flurry +var FLURRY_KEY_IOS = "KMGG7CD9WPK2TW4X9VR8"; +var FLURRY_KEY_ANDROID = "SPKFH8KMPGHMMBWRBT5W"; +var UMENG_KEY_IOS = "50d2b18c5270152187000097"; +var UMENG_KEY_ANDROID = ""; // umeng key for android is setted in AndroidManifest.xml + + +if (!plugin) { + var plugin = {}; +} + +plugin.onApplicationDidEnterBackground = function() { + if (g_pAnalytics != null) { + cc.log("plugin.onApplicationDidEnterBackground."); + g_pAnalytics.stopSession(); + } +}; + + +plugin.onApplicationWillEnterForeground = function() { + if (g_pAnalytics != null) { + cc.log("plugin.onApplicationWillEnterForeground."); + g_pAnalytics.startSession(s_strAppKey); + } +}; + +var loadAnalyticsPlugin = function() { + var langType = cc.sys.language;//cc.Application.getInstance().getCurrentLanguage(); + + var umengKey = ""; + var flurryKey = ""; + + if (cc.sys.os == cc.sys.OS_IOS) + { + umengKey = UMENG_KEY_IOS; + flurryKey = FLURRY_KEY_IOS; + } + else if (cc.sys.os == cc.sys.OS_ANDROID) + { + umengKey = UMENG_KEY_ANDROID; + flurryKey = FLURRY_KEY_ANDROID; + } + + var pluginManager = plugin.PluginManager.getInstance(); + if (cc.LANGUAGE_CHINESE == langType) + { + g_pAnalytics = pluginManager.loadPlugin("AnalyticsUmeng"); + s_strAppKey = umengKey; + } + else + { + g_pAnalytics = pluginManager.loadPlugin("AnalyticsFlurry"); + s_strAppKey = flurryKey; + } + + g_pAnalytics.setDebugMode(true); + g_pAnalytics.startSession(s_strAppKey); + g_pAnalytics.setCaptureUncaughtException(true); + + g_pAnalytics.callFuncWithParam("updateOnlineConfig", null); + g_pAnalytics.callFuncWithParam("setReportLocation", new plugin.PluginParam(plugin.PluginParam.ParamType.TypeBool, true)); + g_pAnalytics.callFuncWithParam("logPageView", null); + g_pAnalytics.callFuncWithParam("setVersionName", new plugin.PluginParam(plugin.PluginParam.ParamType.TypeString, "1.1")); + g_pAnalytics.callFuncWithParam("setAge", new plugin.PluginParam(plugin.PluginParam.ParamType.TypeInt, 20)); + g_pAnalytics.callFuncWithParam("setGender", new plugin.PluginParam(plugin.PluginParam.ParamType.TypeInt, 1)); + g_pAnalytics.callFuncWithParam("setUserId", new plugin.PluginParam(plugin.PluginParam.ParamType.TypeString, "123456")); + g_pAnalytics.callFuncWithParam("setUseHttps", new plugin.PluginParam(plugin.PluginParam.ParamType.TypeBool, false)); +}; + + +TAG_LOG_EVENT_ID = 0; +TAG_LOG_EVENT_ID_KV = 1; +TAG_LOG_ONLINE_CONFIG = 2; +TAG_LOG_EVENT_ID_DURATION = 3; +TAG_LOG_EVENT_BEGIN = 4; +TAG_LOG_EVENT_END = 5; +TAG_MAKE_ME_CRASH = 6; + +var s_EventMenuItem = [ + {id: "OnlineConfig", tag: TAG_LOG_ONLINE_CONFIG}, + {id: "LogEvent-eventId", tag: TAG_LOG_EVENT_ID}, + {id: "LogEvent-eventId-kv", tag: TAG_LOG_EVENT_ID_KV}, + {id: "LogEvent-eventId-Duration", tag: TAG_LOG_EVENT_ID_DURATION}, + {id: "LogEvent-Begin", tag: TAG_LOG_EVENT_BEGIN}, + {id: "LogEvent-End", tag: TAG_LOG_EVENT_END}, + {id: "MakeMeCrash", tag: TAG_MAKE_ME_CRASH} +]; + +var AnalyticsTestLayer = PluginXTest.extend({ + + _title:"Plugin-x Test", + _subtitle: cc.LANGUAGE_CHINESE == cc.sys.language ? "umeng" : "flurry",//cc.Application.getInstance().getCurrentLanguage() ? "umeng" : "flurry", + + onEnter: function() { + this._super(); + var size = cc.director.getWinSize(); + + loadAnalyticsPlugin(); + + var pMenu = new cc.Menu(); + pMenu.setPosition( cc.p(0, 0) ); + this.addChild(pMenu, 1); + + var yPos = 0; + for (var i = 0; i < s_EventMenuItem.length; i++) { + var label = new cc.LabelTTF(s_EventMenuItem[i].id, "Arial", 24); + var pMenuItem = new cc.MenuItemLabel(label, this.eventMenuCallback, this); + pMenu.addChild(pMenuItem, 0, s_EventMenuItem[i].tag); + yPos = size.height - 50*i - 100; + pMenuItem.setPosition( cc.p(size.width / 2, yPos)); + } + + var strName = g_pAnalytics.getPluginName(); + var strVer = g_pAnalytics.getPluginVersion(); + var ret = "Plugin : "+strName+", Ver : "+ strVer; + var pLabel = new cc.LabelTTF(ret, "Arial", 24, cc.size(size.width, 0), cc.TEXT_ALIGNMENT_CENTER); + pLabel.setPosition(cc.p(size.width / 2, yPos - 100)); + this.addChild(pLabel); + + var label = new cc.LabelTTF("reload all plugins", "Arial", 24); + var pMenuItem = new cc.MenuItemLabel(label, this.reloadPluginMenuCallback, this); + pMenuItem.setAnchorPoint(cc.p(0.5, 0)); + pMenu.addChild(pMenuItem, 0); + pMenuItem.setPosition( cc.p(size.width / 2, 0)); + }, + + reloadPluginMenuCallback: function(pSender) { + plugin.PluginManager.getInstance().unloadPlugin("AnalyticsFlurry"); + plugin.PluginManager.getInstance().unloadPlugin("AnalyticsUmeng"); + + loadAnalyticsPlugin(); + }, + + eventMenuCallback: function(pSender) { + switch (pSender.getTag()) + { + case TAG_LOG_EVENT_ID: + { + g_pAnalytics.logEvent("click"); + g_pAnalytics.logEvent("music"); + } + break; + case TAG_LOG_EVENT_ID_KV: + { + var paramMap = {}; + paramMap["type"] = "popular"; + paramMap["artist"] = "JJLin"; + g_pAnalytics.logEvent("music", paramMap); + } + break; + case TAG_LOG_ONLINE_CONFIG: + { + cc.log("Online config = " + g_pAnalytics.callStringFuncWithParam("getConfigParams", new plugin.PluginParam(plugin.PluginParam.ParamType.TypeString, "abc"))); + } + break; + case TAG_LOG_EVENT_ID_DURATION: + { + g_pAnalytics.callFuncWithParam("logEventWithDuration", + new plugin.PluginParam(plugin.PluginParam.ParamType.TypeString, "book"), + new plugin.PluginParam(plugin.PluginParam.ParamType.TypeInt, 12000)); + g_pAnalytics.callFuncWithParam("logEventWithDurationLabel", + new plugin.PluginParam(plugin.PluginParam.ParamType.TypeString, "book"), + new plugin.PluginParam(plugin.PluginParam.ParamType.TypeInt, 23000), + new plugin.PluginParam(plugin.PluginParam.ParamType.TypeString, "chapter1")); + var paramMap = {}; + paramMap["type"] = "popular"; + paramMap["artist"] = "JJLin"; + g_pAnalytics.callFuncWithParam("logEventWithDurationParams", + new plugin.PluginParam(plugin.PluginParam.ParamType.TypeString, "music"), + new plugin.PluginParam(plugin.PluginParam.ParamType.TypeInt, 2330000), + new plugin.PluginParam(plugin.PluginParam.ParamType.TypeStringMap, paramMap)); + } + break; + case TAG_LOG_EVENT_BEGIN: + { + g_pAnalytics.logTimedEventBegin("music"); + + var paramMap = {}; + paramMap["type"] = "popular"; + paramMap["artist"] = "JJLin"; + + g_pAnalytics.callFuncWithParam("logTimedEventWithLabelBegin", + new plugin.PluginParam(plugin.PluginParam.ParamType.TypeString, "music"), + new plugin.PluginParam(plugin.PluginParam.ParamType.TypeString, "one")); + g_pAnalytics.callFuncWithParam("logTimedKVEventBegin", + new plugin.PluginParam(plugin.PluginParam.ParamType.TypeString, "music"), + new plugin.PluginParam(plugin.PluginParam.ParamType.TypeString, "flag0"), + new plugin.PluginParam(plugin.PluginParam.ParamType.TypeStringMap, paramMap)); + + g_pAnalytics.callFuncWithParam("logTimedEventBeginWithParams", + new plugin.PluginParam(plugin.PluginParam.ParamType.TypeString, "music-kv"), + new plugin.PluginParam(plugin.PluginParam.ParamType.TypeStringMap, paramMap)); + } + break; + case TAG_LOG_EVENT_END: + { + g_pAnalytics.logTimedEventEnd("music"); + + g_pAnalytics.callFuncWithParam("logTimedEventWithLabelEnd", + new plugin.PluginParam(plugin.PluginParam.ParamType.TypeString, "music"), + new plugin.PluginParam(plugin.PluginParam.ParamType.TypeString, "one")); + g_pAnalytics.callFuncWithParam("logTimedKVEventEnd", + new plugin.PluginParam(plugin.PluginParam.ParamType.TypeString, "music"), + new plugin.PluginParam(plugin.PluginParam.ParamType.TypeString, "flag0")); + + g_pAnalytics.callFuncWithParam("logTimedEventEnd", new plugin.PluginParam(plugin.PluginParam.ParamType.TypeString, "music-kv")); + } + break; + case TAG_MAKE_ME_CRASH: + { + + } + break; + default: + break; + } + }, + + onNextCallback:function (sender) { + var s = new FacebookTest(); + s.addChild(new FacebookLayer); + director.runScene(s); + }, + onBackCallback:function (sender) { + var s = new FacebookTest(); + s.addChild(new FacebookLayer); + director.runScene(s); + } + +}); diff --git a/tests/js-tests/src/ExtensionsTest/PluginXTest/IOSIAPTest.js b/tests/js-tests/src/ExtensionsTest/PluginXTest/IOSIAPTest.js new file mode 100644 index 0000000000..a0f93437b2 --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/PluginXTest/IOSIAPTest.js @@ -0,0 +1,216 @@ +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies 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. + ****************************************************************************/ + +TAG_SETSERVERMODE = 0; +TAG_GETPRODUCTLIST = 1; +TAG_PAYMENT = 2; +TAG_TOAST = 3; + +TAG_SETSERVERMODE_RESULT = 4; +TAG_GETPRODUCTLIST_RESULT = 5; +TAG_PAYMENT_RESULT = 6; + +var s_IAPFunctionItem = [ + {name: "setServerMode", tag: TAG_SETSERVERMODE}, + {name: "getProductList", tag: TAG_GETPRODUCTLIST}, + {name: "PayForProduct", tag: TAG_PAYMENT} +]; +var s_IAPResultItem = [ + {name: "false", tag: TAG_SETSERVERMODE_RESULT}, + {name: "[ ]", tag: TAG_GETPRODUCTLIST_RESULT}, + {name: "didn't call payFunction yet", tag: TAG_PAYMENT_RESULT} +]; +var IAPTestLayer = PluginXTest.extend({ + _serverMode: false, + onEnter: function () { + this._super(); + this.initPlugin(); + this.addMenuItem(); + this.initToast(); + }, + initPlugin: function () { + var pluginManager = plugin.PluginManager.getInstance(); + this.PluginIAP = pluginManager.loadPlugin("IOSIAP"); + this.PluginIAP.setListener(this); + }, + addMenuItem: function () { + var payMenu = new cc.Menu(); + for (var i = 0; i < s_IAPFunctionItem.length; i++) { + var text = new cc.LabelTTF(s_IAPFunctionItem[i].name, "Arial", 20); + var item = new cc.MenuItemLabel(text, this.menuCallBack, this); + item.tag = s_IAPFunctionItem[i].tag; + item.x = 200; + item.y = cc.winSize.height - 200 - i * 50; + + var resultLabel = new cc.LabelTTF(s_IAPResultItem[i].name, "Arial", 20); + resultLabel.color = cc.color(125, 125, 125); + resultLabel.anchorX = 0; + resultLabel.tag = s_IAPResultItem[i].tag; + resultLabel.x = 300; + resultLabel.y = cc.winSize.height - 200 - i * 50; + payMenu.addChild(item); + this.addChild(resultLabel); + } + payMenu.x = 0; + payMenu.y = 0; + this.addChild(payMenu); + }, + closeFunction: function (sender) { + var scene = new ExtensionsTestScene(); + scene.runThisTest(); + cc.director.runScene(scene); + }, + initToast: function () { + this.toastLayer = new cc.LayerColor(); + var label = new cc.LabelTTF("loading", "Arial", 16); + this.toastLayer.addChild(label); + this.toastLayer.setTag(TAG_TOAST); + label.x = cc.winSize.width / 2; + label.y = cc.winSize.height / 2; + this.toastLayer.retain(); + this.toastLayer.setColor(cc.color(100, 100, 100, 100)); + }, + addTouch: function (bool) { + if (bool) { + var self = this.toastLayer; + this.listener = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches: true, + onTouchBegan: function (touch, event) { + return true; + }, + onTouchMoved: function (touch, event) { + }, + onTouchEnded: function (touch, event) { + }, + onTouchCancelled: function (touch, event) { + } + }); + cc.eventManager.addListener(this.listener, self); + } else { + cc.eventManager.removeListener(this.listener); + } + }, + toggleToast: function (show) { + if (show) { + if (!this.getChildByTag(TAG_TOAST)) { + this.addChild(this.toastLayer); + this.addTouch(true); + } + } else { + this.toastLayer.removeFromParent(true); + this.addTouch(false); + } + }, + menuCallBack: function (sender) { + this.toggleToast(true); + if (sender.tag === TAG_SETSERVERMODE) { + this.PluginIAP.callFuncWithParam("setServerMode"); + var label = this.getChildByTag(TAG_SETSERVERMODE_RESULT); + this._serverMode = true; + if (label) { + label.setString("true"); + this.toggleToast(false); + } + } else if (sender.tag == TAG_GETPRODUCTLIST) { + //replace these ids to your own productIdentifiers + var pidList = ["001", "002"]; + this.PluginIAP.callFuncWithParam("requestProducts", plugin.PluginParam(plugin.PluginParam.ParamType.TypeString, pidList.toString())); + } else if (sender.tag == TAG_PAYMENT) { + if (!this.product) { + var label = this.getChildByTag(TAG_PAYMENT_RESULT); + if (label) { + label.setString("please call requestProducts first"); + this.toggleToast(false); + return; + } + } + this.PluginIAP.payForProduct(this.product[0]); + } + }, + + onPayResult: function (ret, msg, productInfo) { + this.toggleToast(false); + cc.log("onPayResult ret is " + ret); + var str = ""; + if (ret == plugin.ProtocolIAP.PayResultCode.PaySuccess) { + str = "payment Success pid is " + productInfo.productId; + //if you use server mode get the receive message and post to your server + if (this._serverMode && msg) { + str = "payment verify from server"; + cc.log(str); + this.postServerData(msg); + } + } else if (ret == plugin.ProtocolIAP.PayResultCode.PayFail) { + str = "payment fail"; + } + var label = this.getChildByTag(TAG_PAYMENT_RESULT); + if (label) { + label.setString(str); + } + }, + onRequestProductResult: function (ret, productInfo) { + var msgStr = ""; + if (ret == plugin.ProtocolIAP.RequestProductCode.RequestFail) { + msgStr = "request error"; + this.toggleToast(false); + } else if (ret == plugin.ProtocolIAP.RequestProductCode.RequestSuccess) { + cc.log("request RequestSuccees " + productInfo[0].productName); + this.product = productInfo; + msgStr = "list: ["; + for (var i = 0; i < productInfo.length; i++) { + var product = productInfo[i]; + msgStr += product.productName + " "; + } + msgStr += " ]"; + this.toggleToast(false); + } + var label = this.getChildByTag(TAG_GETPRODUCTLIST_RESULT); + if (label) { + label.setString(msgStr); + } + }, + postServerData: function (data) { + var that = this; + var xhr = cc.loader.getXMLHttpRequest(); + + //replace to your own server address + xhr.open("POST", "http://localhost/"); + that.toggleToast(true); + xhr.onreadystatechange = function () { + if (xhr.readyState == 4 && xhr.status == 200) { + that.toggleToast(false); + var result = JSON.parse(xhr.responseText); + that.PluginIAP.callFuncWithParam("finishTransaction", new plugin.PluginParam(plugin.PluginParam.ParamType.TypeString, result.receipt.in_app[0].product_id)); + } + }; + // you can add your data and post them to your server; + var result = {userid: 100, receipt: data}; + xhr.send(JSON.stringify(result)); + }, + onExit: function () { + this._super(); + this.toastLayer.release(); + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/ExtensionsTest/PluginXTest/PluginXTest.js b/tests/js-tests/src/ExtensionsTest/PluginXTest/PluginXTest.js new file mode 100644 index 0000000000..f724f12f7b --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/PluginXTest/PluginXTest.js @@ -0,0 +1,99 @@ +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies 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. + ****************************************************************************/ + +var PluginXTest = cc.Layer.extend({ + _sceneTitleLabel:null, + + getSceneTitleLabel:function(){return this._sceneTitleLabel;}, + setSceneTitleLabel:function(sceneTitleLabel){this._sceneTitleLabel = sceneTitleLabel;}, + + ctor:function(title){ + this._super() + // Get the sceensize + var screensize = cc.winSize; + + var pBackItem = new cc.MenuItemFont("Back", this.toExtensionsMainLayer, this); + pBackItem.x = screensize.width - 50; + pBackItem.y = 25; + var pBackMenu = new cc.Menu(pBackItem); + pBackMenu.x = 0; + pBackMenu.y = 0; + this.addChild(pBackMenu, 10); + + // Add the generated background + var background = new cc.Sprite(s_extensions_background); + background.x = screensize.width / 2; + background.y = screensize.height / 2; + var bgRect = background.getTextureRect(); + background.scaleX = screensize.width/bgRect.width; + background.scaleY = screensize.height/bgRect.height; + this.addChild(background); + + // Add the ribbon + var ribbon = new cc.Scale9Sprite(s_extensions_ribbon, cc.rect(1, 1, 48, 55)); + ribbon.width = screensize.width; + ribbon.height = 57; + ribbon.x = screensize.width / 2.0; + ribbon.y = screensize.height - ribbon.height / 2.0; + this.addChild(ribbon); + + // Add the title + this.setSceneTitleLabel(new cc.LabelTTF(title || "Title", "Arial", 12)); + this._sceneTitleLabel.x = screensize.width / 2; + this._sceneTitleLabel.y = screensize.height - this._sceneTitleLabel.height / 2 - 5; + this.addChild(this._sceneTitleLabel, 1); + + // Add the menu + var item1 = new cc.MenuItemImage(s_pathB1, s_pathB2, this.previousCallback, this); + var item2 = new cc.MenuItemImage(s_pathR1, s_pathR2, this.restartCallback, this); + var item3 = new cc.MenuItemImage(s_pathF1, s_pathF2, this.nextCallback, this); + + var menu = new cc.Menu(item1, item3, item2); + menu.x = 0; + menu.y = 0; + item1.x = screensize.width / 2 - 100; + item1.y = 37; + item2.x = screensize.width / 2; + item2.y = 35; + item3.x = screensize.width / 2 + 100; + item3.y = 37; + + this.addChild(menu ,1); + }, + + toExtensionsMainLayer:function(sender){ + var pScene = new ExtensionsTestScene(); + pScene.runThisTest(); + }, + + previousCallback:function(sender){ + cc.director.runScene(pluginXSceneManager.previousPluginXScene()); + }, + restartCallback:function(sender){ + cc.director.runScene(pluginXSceneManager.currentPluginXScene()); + }, + nextCallback:function(sender){ + cc.director.runScene(pluginXSceneManager.nextPluginXScene()); + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/ExtensionsTest/PluginXTest/PluginXTestsManager.js b/tests/js-tests/src/ExtensionsTest/PluginXTest/PluginXTestsManager.js new file mode 100644 index 0000000000..51c499a6c0 --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/PluginXTest/PluginXTestsManager.js @@ -0,0 +1,74 @@ +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies 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. + ****************************************************************************/ + +var pluginXTestItemNames = []; + +if (cc.sys.isMobile && cc.sys.os == cc.sys.OS_IOS) { + pluginXTestItemNames.push({ + itemTitle: "Analytics Test", + testLayer: function () { + return new AnalyticsTestLayer(this.itemTitle); + } + }); +} +if (cc.sys.isMobile && cc.sys.os == cc.sys.OS_IOS) { + pluginXTestItemNames.push({ + itemTitle: "iOS IAP Test", + testLayer: function () { + return new IAPTestLayer(this.itemTitle); + } + }); +} + +var pluginXSceneManager = { + _currentPluginXSceneId: 0, + + getCurrentPluginXSceneId: function () { + return this._currentPluginXSceneId; + }, + setCurrentPluginXSceneId: function (currentPluginXSceneId) { + this._currentPluginXSceneId = currentPluginXSceneId + }, + + nextPluginXScene: function () { + this._currentPluginXSceneId = (this._currentPluginXSceneId + 1) % pluginXTestItemNames.length; + return this.currentPluginXScene(); + }, + + previousPluginXScene: function () { + this._currentPluginXSceneId = this._currentPluginXSceneId - 1; + if (this._currentPluginXSceneId < 0) { + this._currentPluginXSceneId = pluginXTestItemNames.length - 1; + } + + return this.currentPluginXScene(); + }, + + currentPluginXScene: function () { + var scene = new cc.Scene(); + var layer = pluginXTestItemNames[this._currentPluginXSceneId].testLayer(); + scene.addChild(layer); + return scene; + } +}; \ No newline at end of file diff --git a/tests/js-tests/src/ExtensionsTest/S9SpriteTest/S9SpriteTest.js b/tests/js-tests/src/ExtensionsTest/S9SpriteTest/S9SpriteTest.js new file mode 100644 index 0000000000..b0efb1d6e6 --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/S9SpriteTest/S9SpriteTest.js @@ -0,0 +1,559 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2013 Surith Thekkiam + + 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. + ****************************************************************************/ + +var sceneIdx = -1; + +var spriteFrameCache = cc.spriteFrameCache; + +//------------------------------------------------------------------ +// +// S9SpriteTestDemo +// +//------------------------------------------------------------------ +var S9SpriteTestDemo = cc.LayerGradient.extend({ + _title:"", + _subtitle:"", + + ctor:function() { + this._super(cc.color(0,0,0,255), cc.color(98,99,117,255)); + cc.spriteFrameCache.addSpriteFrames(s_s9s_blocks9_plist); + cc.log('sprite frames added to sprite frame cache...'); + }, + onEnter:function () { + this._super(); + + var label = new cc.LabelTTF(this._title, "Arial", 28); + this.addChild(label, 1); + label.x = winSize.width / 2; + label.y = winSize.height - 50; + + if (this._subtitle !== "") { + var l = new cc.LabelTTF(this._subtitle, "Thonburi", 16); + this.addChild(l, 1); + l.x = winSize.width / 2; + l.y = winSize.height - 80; + } + + var item1 = new cc.MenuItemImage(s_pathB1, s_pathB2, this.onBackCallback, this); + var item2 = new cc.MenuItemImage(s_pathR1, s_pathR2, this.onRestartCallback, this); + var item3 = new cc.MenuItemImage(s_pathF1, s_pathF2, this.onNextCallback, this); + + var menu = new cc.Menu(item1, item2, item3); + + menu.x = 0; + menu.y = 0; + var width = item2.width, height = item2.height; + item1.x = winSize.width/2 - width*2; + item1.y = height/2; + item2.x = winSize.width/2; + item2.y = height/2; + item3.x = winSize.width/2 + width*2; + item3.y = height/2; + + this.addChild(menu, 1); + }, + + onExit:function () { + this._super(); + }, + + onRestartCallback:function (sender) { + var s = new S9SpriteTestScene(); + s.addChild(restartS9SpriteTest()); + director.runScene(s); + }, + onNextCallback:function (sender) { + var s = new S9SpriteTestScene(); + s.addChild(nextS9SpriteTest()); + director.runScene(s); + }, + onBackCallback:function (sender) { + var s = new S9SpriteTestScene(); + s.addChild(previousS9SpriteTest()); + director.runScene(s); + } +}); + +// S9BatchNodeBasic + +var S9BatchNodeBasic = S9SpriteTestDemo.extend({ + + _title:"Scale9Sprite created empty and updated from SpriteBatchNode", + _subtitle:"updateWithBatchNode(); capInsets=full size", + + ctor:function() { + this._super(); + + var x = winSize.width / 2; + var y = 0 + (winSize.height / 2); + + cc.log("S9BatchNodeBasic ..."); + + var batchNode = new cc.SpriteBatchNode("res/Images/blocks9.png"); + cc.log("batchNode created with : " + "res/Images/blocks9.png"); + + var blocks = new cc.Scale9Sprite(); + cc.log("... created"); + + blocks.updateWithBatchNode(batchNode, cc.rect(0, 0, 96, 96), false, cc.rect(0, 0, 96, 96)); + cc.log("... updateWithBatchNode"); + + blocks.x = x; + blocks.y = y; + cc.log("... setPosition"); + + this.addChild(blocks); + cc.log("this..addChild"); + + cc.log("... S9BatchNodeBasic done."); + } +}); + +// S9FrameNameSpriteSheet + +var S9FrameNameSpriteSheet = S9SpriteTestDemo.extend({ + + _title:"Scale9Sprite from sprite sheet", + _subtitle:"createWithSpriteFrameName(); default cap insets", + + ctor:function() { + this._super(); + + var x = winSize.width / 2; + var y = 0 + (winSize.height / 2); + + cc.log("S9FrameNameSpriteSheet ..."); + + var blocks = new cc.Scale9Sprite('blocks9.png'); + cc.log("... created"); + + blocks.x = x; + blocks.y = y; + cc.log("... setPosition"); + + this.addChild(blocks); + cc.log("this..addChild"); + + cc.log("... S9FrameNameSpriteSheet done."); + } +}); + +// S9FrameNameSpriteSheetRotated + +var S9FrameNameSpriteSheetRotated = S9SpriteTestDemo.extend({ + + _title:"Scale9Sprite from sprite sheet (stored rotated)", + _subtitle:"createWithSpriteFrameName(); default cap insets", + + ctor:function() { + this._super(); + + var x = winSize.width / 2; + var y = 0 + (winSize.height / 2); + + cc.log("S9FrameNameSpriteSheetRotated ..."); + + var blocks = new cc.Scale9Sprite('blocks9r.png'); + cc.log("... created"); + + blocks.x = x; + blocks.y = y; + cc.log("... setPosition"); + + this.addChild(blocks); + cc.log("this..addChild"); + + cc.log("... S9FrameNameSpriteSheetRotated done."); + } +}); + +// S9BatchNodeScaledNoInsets + +var S9BatchNodeScaledNoInsets = S9SpriteTestDemo.extend({ + + _title:"Scale9Sprite created empty and updated from SpriteBatchNode", + _subtitle:"updateWithBatchNode(); capInsets=full size; rendered 4 X width, 2 X height", + + ctor:function() { + this._super(); + + var x = winSize.width / 2; + var y = 0 + (winSize.height / 2); + + cc.log("S9BatchNodeScaledNoInsets ..."); + + // scaled without insets + var batchNode_scaled = new cc.SpriteBatchNode("res/Images/blocks9.png"); + cc.log("batchNode_scaled created with : " + "res/Images/blocks9.png"); + + var blocks_scaled = new cc.Scale9Sprite(); + cc.log("... created"); + blocks_scaled.updateWithBatchNode(batchNode_scaled, cc.rect(0, 0, 96, 96), false, cc.rect(0, 0, 96, 96)); + cc.log("... updateWithBatchNode"); + + blocks_scaled.x = x; + blocks_scaled.y = y; + cc.log("... setPosition"); + + blocks_scaled.width = 96 * 4; + blocks_scaled.height = 96*2; + cc.log("... setContentSize"); + + this.addChild(blocks_scaled); + cc.log("this..addChild"); + + cc.log("... S9BtchNodeScaledNoInsets done."); + } +}); + +// S9FrameNameSpriteSheetScaledNoInsets + +var S9FrameNameSpriteSheetScaledNoInsets = S9SpriteTestDemo.extend({ + + _title:"Scale9Sprite from sprite sheet", + _subtitle:"createWithSpriteFrameName(); default cap insets; rendered 4 X width, 2 X height", + + ctor:function() { + this._super(); + + var x = winSize.width / 2; + var y = 0 + (winSize.height / 2); + + cc.log("S9FrameNameSpriteSheetScaledNoInsets ..."); + + var blocks_scaled = new cc.Scale9Sprite('blocks9.png'); + cc.log("... created"); + + blocks_scaled.x = x; + blocks_scaled.y = y; + cc.log("... setPosition"); + + blocks_scaled.width = 96 * 4; + blocks_scaled.height = 96*2; + cc.log("... setContentSize"); + + this.addChild(blocks_scaled); + cc.log("this..addChild"); + + cc.log("... S9FrameNameSpriteSheetScaledNoInsets done."); + } +}); + +// S9FrameNameSpriteSheetRotatedScaledNoInsets + +var S9FrameNameSpriteSheetRotatedScaledNoInsets = S9SpriteTestDemo.extend({ + + _title:"Scale9Sprite from sprite sheet (stored rotated)", + _subtitle:"createWithSpriteFrameName(); default cap insets; rendered 4 X width, 2 X height", + + ctor:function() { + this._super(); + + var x = winSize.width / 2; + var y = 0 + (winSize.height / 2); + + cc.log("S9FrameNameSpriteSheetRotatedScaledNoInsets ..."); + + var blocks_scaled = new cc.Scale9Sprite('blocks9r.png'); + cc.log("... created"); + + blocks_scaled.x = x; + blocks_scaled.y = y; + cc.log("... setPosition"); + + blocks_scaled.width = 96 * 4; + blocks_scaled.height = 96*2; + cc.log("... setContentSize"); + + this.addChild(blocks_scaled); + cc.log("this..addChild"); + + cc.log("... S9FrameNameSpriteSheetRotatedScaledNoInsets done."); + } +}); + + +// S9BatchNodeScaleWithCapInsets + +var S9BatchNodeScaleWithCapInsets = S9SpriteTestDemo.extend({ + + _title:"Scale9Sprite created empty and updated from SpriteBatchNode", + _subtitle:"updateWithBatchNode(); capInsets=(32, 32, 32, 32)", + + ctor:function() { + this._super(); + + var x = winSize.width / 2; + var y = 0 + (winSize.height / 2); + + cc.log("S9BatchNodeScaleWithCapInsets ..."); + + var batchNode_scaled_with_insets = new cc.SpriteBatchNode("res/Images/blocks9.png"); + cc.log("batchNode_scaled_with_insets created with : " + "res/Images/blocks9.png"); + + var blocks_scaled_with_insets = new cc.Scale9Sprite(); + cc.log("... created"); + + blocks_scaled_with_insets.updateWithBatchNode(batchNode_scaled_with_insets, cc.rect(0, 0, 96, 96), false, cc.rect(32, 32, 32, 32)); + cc.log("... updateWithBatchNode"); + + blocks_scaled_with_insets.width = 96 * 4.5; + blocks_scaled_with_insets.height = 96 * 2.5; + cc.log("... setContentSize"); + + blocks_scaled_with_insets.x = x; + blocks_scaled_with_insets.y = y; + cc.log("... setPosition"); + + this.addChild(blocks_scaled_with_insets); + cc.log("this..addChild"); + + cc.log("... S9BatchNodeScaleWithCapInsets done."); + } +}); + +// S9FrameNameSpriteSheetInsets + +var S9FrameNameSpriteSheetInsets = S9SpriteTestDemo.extend({ + + _title:"Scale9Sprite scaled with insets sprite sheet", + _subtitle:"createWithSpriteFrameName(); cap insets=(32, 32, 32, 32)", + + ctor:function() { + this._super(); + + var x = winSize.width / 2; + var y = 0 + (winSize.height / 2); + + cc.log("S9FrameNameSpriteSheetInsets ..."); + + var blocks_with_insets = new cc.Scale9Sprite('blocks9.png', cc.rect(32, 32, 32, 32)); + cc.log("... created"); + + blocks_with_insets.x = x; + blocks_with_insets.y = y; + cc.log("... setPosition"); + + this.addChild(blocks_with_insets); + cc.log("this..addChild"); + + cc.log("... S9FrameNameSpriteSheetInsets done."); + } +}); + +// S9FrameNameSpriteSheetInsetsScaled + +var S9FrameNameSpriteSheetInsetsScaled = S9SpriteTestDemo.extend({ + + _title:"Scale9Sprite scaled with insets sprite sheet", + _subtitle:"createWithSpriteFrameName(); default cap insets; rendered scaled 4.5 X width, 2.5 X height", + + ctor:function() { + this._super(); + + var x = winSize.width / 2; + var y = 0 + (winSize.height / 2); + + cc.log("S9FrameNameSpriteSheetInsetsScaled ..."); + + var blocks_scaled_with_insets = new cc.Scale9Sprite('blocks9.png', cc.rect(32, 32, 32, 32)); + cc.log("... created"); + + blocks_scaled_with_insets.width = 96 * 4.5; + blocks_scaled_with_insets.height = 96 * 2.5; + cc.log("... setContentSize"); + + blocks_scaled_with_insets.x = x; + blocks_scaled_with_insets.y = y; + cc.log("... setPosition"); + + this.addChild(blocks_scaled_with_insets); + cc.log("this..addChild"); + + cc.log("... S9FrameNameSpriteSheetInsetsScaled done."); + } +}); + +// S9FrameNameSpriteSheetRotatedInsets + +var S9FrameNameSpriteSheetRotatedInsets = S9SpriteTestDemo.extend({ + + _title:"Scale9Sprite scaled with insets sprite sheet (stored rotated)", + _subtitle:"createWithSpriteFrameName(); cap insets=(32, 32, 32, 32)", + + ctor:function() { + this._super(); + + var x = winSize.width / 2; + var y = 0 + (winSize.height / 2); + + cc.log("S9FrameNameSpriteSheetRotatedInsets ..."); + + var blocks_with_insets = new cc.Scale9Sprite('blocks9r.png', cc.rect(32, 32, 32, 32)); + cc.log("... created"); + + blocks_with_insets.x = x; + blocks_with_insets.y = y; + cc.log("... setPosition"); + + this.addChild(blocks_with_insets); + cc.log("this..addChild"); + + cc.log("... S9FrameNameSpriteSheetRotatedInsets done."); + } +}); + +// S9_TexturePacker + +var S9_TexturePacker = S9SpriteTestDemo.extend({ + + _title:"Scale9Sprite from a spritesheet created with TexturePacker", + _subtitle:"createWithSpriteFrameName('button_normal.png');createWithSpriteFrameName('button_actived.png');", + + ctor:function() { + this._super(); + cc.spriteFrameCache.addSpriteFrames(s_s9s_ui_plist); + + var x = winSize.width / 4; + var y = 0 + (winSize.height / 2); + + cc.log("S9_TexturePacker ..."); + + var s = new cc.Scale9Sprite('button_normal.png'); + cc.log("... created"); + + s.x = x; + + s.y = y; + cc.log("... setPosition"); + + s.width = 21 * 16; + + s.height = 13 * 16; + cc.log("... setContentSize"); + + this.addChild(s); + cc.log("this..addChild"); + + x = winSize.width * 3/4; + + var s2 = new cc.Scale9Sprite('button_actived.png'); + cc.log("... created"); + + s2.x = x; + s2.y = y; + cc.log("... setPosition"); + + s2.width = 21 * 16; + s2.height = 13 * 16; + cc.log("... setContentSize"); + + this.addChild(s2); + cc.log("this..addChild"); + + cc.log("... S9_TexturePacker done."); + } +}); + +// S9FrameNameSpriteSheetRotatedInsetsScaled + +var S9FrameNameSpriteSheetRotatedInsetsScaled = S9SpriteTestDemo.extend({ + + _title:"Scale9Sprite scaled with insets sprite sheet (stored rotated)", + _subtitle:"createWithSpriteFrameName(); default cap insets; rendered scaled 4.5 X width, 2.5 X height", + + ctor:function() { + this._super(); + + var x = winSize.width / 2; + var y = 0 + (winSize.height / 2); + + cc.log("S9FrameNameSpriteSheetRotatedInsetsScaled ..."); + + var blocks_scaled_with_insets = new cc.Scale9Sprite('blocks9.png', cc.rect(32, 32, 32, 32)); + cc.log("... created"); + + blocks_scaled_with_insets.width = 96 * 4.5; + blocks_scaled_with_insets.height = 96 * 2.5; + cc.log("... setContentSize"); + + blocks_scaled_with_insets.x = x; + blocks_scaled_with_insets.y = y; + cc.log("... setPosition"); + + this.addChild(blocks_scaled_with_insets); + cc.log("this..addChild"); + + cc.log("... S9FrameNameSpriteSheetRotatedInsetsScaled done."); + } +}); + +var S9SpriteTestScene = TestScene.extend({ + runThisTest:function (num) { + sceneIdx = (num || num == 0) ? (num - 1) : -1; + var layer = nextS9SpriteTest(); + this.addChild(layer); + + director.runScene(this); + } +}); + +// +// Flow control +// + +var arrayOfS9SpriteTest = [ + S9BatchNodeBasic, + S9FrameNameSpriteSheet, + S9FrameNameSpriteSheetRotated, + S9BatchNodeScaledNoInsets, + S9FrameNameSpriteSheetScaledNoInsets, + S9FrameNameSpriteSheetRotatedScaledNoInsets, + S9BatchNodeScaleWithCapInsets, + S9FrameNameSpriteSheetInsets, + S9FrameNameSpriteSheetInsetsScaled, + S9FrameNameSpriteSheetRotatedInsets, + S9FrameNameSpriteSheetRotatedInsetsScaled, + S9_TexturePacker +]; + +var nextS9SpriteTest = function () { + sceneIdx++; + sceneIdx = sceneIdx % arrayOfS9SpriteTest.length; + + return new arrayOfS9SpriteTest[sceneIdx](); +}; +var previousS9SpriteTest = function () { + sceneIdx--; + if (sceneIdx < 0) + sceneIdx += arrayOfS9SpriteTest.length; + + return new arrayOfS9SpriteTest[sceneIdx](); +}; +var restartS9SpriteTest = function () { + return new arrayOfS9SpriteTest[sceneIdx](); +}; diff --git a/tests/js-tests/src/ExtensionsTest/TableViewTest/TableViewTestScene.js b/tests/js-tests/src/ExtensionsTest/TableViewTest/TableViewTestScene.js new file mode 100644 index 0000000000..37fdccf0c2 --- /dev/null +++ b/tests/js-tests/src/ExtensionsTest/TableViewTest/TableViewTestScene.js @@ -0,0 +1,137 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var CustomTableViewCell = cc.TableViewCell.extend({ + draw:function (ctx) { + this._super(ctx); + } +}); + +var TableViewTestLayer = cc.Layer.extend({ + + ctor:function () { + this._super(); + this.init(); + }, + + init:function () { + var winSize = cc.director.getWinSize(); + + var tableView = new cc.TableView(this, cc.size(600, 60)); + tableView.setDirection(cc.SCROLLVIEW_DIRECTION_HORIZONTAL); + tableView.x = 20; + tableView.y = winSize.height / 2 - 150; + tableView.setDelegate(this); + this.addChild(tableView); + tableView.reloadData(); + + tableView = new cc.TableView(this, cc.size(60, 350)); + tableView.setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL); + tableView.x = winSize.width - 150; + tableView.y = winSize.height / 2 - 150; + tableView.setDelegate(this); + tableView.setVerticalFillOrder(cc.TABLEVIEW_FILL_TOPDOWN); + this.addChild(tableView); + tableView.reloadData(); + + // Back Menu + var itemBack = new cc.MenuItemFont("Back", this.toExtensionsMainLayer, this); + itemBack.x = winSize.width - 50; + itemBack.y = 25; + var menuBack = new cc.Menu(itemBack); + menuBack.x = 0; + menuBack.y = 0; + this.addChild(menuBack); + + return true; + }, + + toExtensionsMainLayer:function (sender) { + var scene = new ExtensionsTestScene(); + scene.runThisTest(); + }, + + scrollViewDidScroll:function (view) { + }, + scrollViewDidZoom:function (view) { + }, + + tableCellTouched:function (table, cell) { + cc.log("cell touched at index: " + cell.getIdx()); + }, + tableCellTouched2:function () { + cc.log("cell touched at index: "); + }, + + tableCellSizeForIndex:function (table, idx) { + if (idx == 2) { + return cc.size(100, 100); + } + return cc.size(60, 60); + }, + + tableCellAtIndex:function (table, idx) { + var strValue = idx.toFixed(0); + var cell = table.dequeueCell(); + var label; + if (!cell) { + cell = new CustomTableViewCell(); + + + + var sprite = new cc.Sprite(s_image_icon); + sprite.anchorX = 0; + sprite.anchorY = 0; + sprite.x = 0; + sprite.y = 0; + cell.addChild(sprite); + + label = new cc.LabelTTF(strValue, "Helvetica", 20.0); + label.x = 0; + label.y = 0; + label.anchorX = 0; + label.anchorY = 0; + label.tag = 123; + cell.addChild(label); + } else { + label = cell.getChildByTag(123); + label.setString(strValue); + } + + return cell; + }, + + numberOfCellsInTableView:function (table) { + return 25; + } +}); + +var runTableViewTest = function () { + var pScene = new cc.Scene(); + var pLayer = new TableViewTestLayer(); + pScene.addChild(pLayer); + cc.director.runScene(pScene); +}; diff --git a/tests/js-tests/src/FacebookTest/FacebookShareTest.js b/tests/js-tests/src/FacebookTest/FacebookShareTest.js new file mode 100644 index 0000000000..453b459c3a --- /dev/null +++ b/tests/js-tests/src/FacebookTest/FacebookShareTest.js @@ -0,0 +1,406 @@ +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies 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. + ****************************************************************************/ + +var buttons = { + "Share link": "onShareLink", + "Share open graph": "onShareOG", + "Share photo": "onSharePhoto", + "Link message": "onLinkMsg", + "Open graph message": "onOGMsg", + "Photo message": "onPhotoMsg", + "App request": "onRequest" +}; + +var appRequestAction = { + "Invites request": "onInviteRequest", + "Target invite request": "onTargetInviteRequest", + "specific lists of friends": "onSpecificListsFriends", + "Sending gift request": "sendingGiftRequest", + "Turn-based games": "onTurnBasedGamesRequest" +}; +var shareLinkAction = { + "share a simple link": "onShareSimpleLink", + "share a Text link": "onShareTextInfoLink", + "share a Picture link": "onSharePictureInfoLink", + "share a media link": "onShareMediaSource" +}; + +var FacebookShareTest = FacebookTest.extend({ + _title: "Facebook SDK Sharing Test", + _subtitle: "", + _agentManager: null, + _showTips: false, + _secondMenu:null, + ctor: function (title) { + this._super(title); + + window.facebook = window.facebook || (window["plugin"] ? window["plugin"]["FacebookAgent"]["getInstance"]() : null); + + var menu = new cc.Menu(); + menu.setPosition(cc.p(0, 0)); + menu.width = winSize.width; + menu.height = winSize.height; + this.addChild(menu, 1); + + var top = 50; + for (var action in buttons) { + var label = new cc.LabelTTF(action, "Arial", 24); + var item = new cc.MenuItemLabel(label, this[buttons[action]], this); + item.setPosition(winSize.width * 1 / 3, winSize.height - top); + menu.addChild(item); + top += 50; + } + + var logo = new cc.Sprite(s_html5_logo); + logo.setPosition(winSize.width * 2 / 3, winSize.height / 2); + this.addChild(logo); + + this._agentManager = window["plugin"].agentManager; + + this.tipsLabel = new cc.LabelTTF("", "Arial", 20); + this.tipsLabel.setDimensions(cc.size(350, 0)); + this.addChild(this.tipsLabel, 100); + this.tipsLabel.setPosition(cc.pAdd(cc.visibleRect.bottomRight, cc.p(-350 / 2 - 20, 150))); + this.tipsLabel.visible = false; + + this._secondMenu = new cc.Menu(); + this._secondMenu.setPosition(cc.p(340, 0)); + this._secondMenu.width = winSize.width / 2; + this._secondMenu.height = winSize.height; + this.addChild(this._secondMenu, 2); + }, + showSecondMenu: function (buttonActions) { + this._secondMenu.removeAllChildren(); + var top = 50; + for (var action in buttonActions) { + var label = new cc.LabelTTF(action, "Arial", 24); + var item = new cc.MenuItemLabel(label, this[buttonActions[action]], this); + item.setPosition(winSize.width * 1 / 3, winSize.height - top); + this._secondMenu.addChild(item); + top += 50; + } + }, + onShareLink: function () { + this.showSecondMenu(shareLinkAction); + }, + + onShareSimpleLink: function (){ + var map = { + "dialog": "shareLink", + "link": "http://www.cocos2d-x.org" + }; + var self = this; + if(facebook.canPresentDialog(map)){ + facebook.dialog(map,function(errorCode,msg){ + self.showDisableTips(JSON.stringify(msg)); + }); + }else{ + map["dialog"] = "feedDialog"; + facebook.dialog(map,function(errorCode,msg){ + self.showDisableTips(JSON.stringify(msg)); + }); + } + }, + onShareTextInfoLink: function (){ + var map = { + "dialog": "shareLink", + "name": "Cocos2d-JS web site", + "caption": "Cocos2d-JS caption", + "description":"Cocos2d-JS description", + "link": "http://www.cocos2d-x.org" + }; + var self = this; + if(facebook.canPresentDialog(map)){ + facebook.dialog(map,function(errorCode,msg){ + self.showDisableTips(JSON.stringify(msg)); + }); + }else{ + map["dialog"] = "feedDialog"; + facebook.dialog(map,function(errorCode,msg){ + self.showDisableTips(JSON.stringify(msg)); + }); + } + }, + onSharePictureInfoLink: function (){ + var map = { + "dialog": "shareLink", + "name": "Cocos2d-JS web site", + "caption": "Cocos2d-JS caption", + "description":"Cocos2d-JS description", + "to": "100008180737293,100006738453912", + "picture": "http://files.cocos2d-x.org/images/orgsite/logo.png", + "link": "http://www.cocos2d-x.org" + }; + var self = this; + if(facebook.canPresentDialog(map)){ + facebook.dialog(map,function(errorCode,msg){ + self.showDisableTips(JSON.stringify(msg)); + }); + }else{ + map["dialog"] = "feedDialog"; + facebook.dialog(map,function(errorCode,msg){ + self.showDisableTips(JSON.stringify(msg)); + }); + } + }, + onShareMediaSource: function () { + var map = { + "dialog": "shareLink", + "name": "Cocos2d-JS web site", + "caption": "Cocos2d-JS caption", + "description":"Cocos2d-JS description", + "link": "http://www.youtube.com/watch?v=uMnHAHpMtDc&feature=youtu.be" + }; + + var self = this; + // only support in feed dialog + facebook.dialog(map,function(errorCode,msg){ + self.showDisableTips(JSON.stringify(msg)); + }); + }, + showDisableTips: function (msg) { + if (!this._showTips) { + this._showTips = true; + if (msg) { + var preMsg = this.tipsLabel.getString(); + this.tipsLabel.setString(msg); + } + var anim = cc.sequence( + cc.fadeIn(0.2), + cc.delayTime(3), + cc.fadeOut(0.2), + cc.callFunc(function () { + this._showTips = false; + this.tipsLabel.visible = false; + if (preMsg) + this.tipsLabel.setString(preMsg); + }, this) + ); + this.tipsLabel.visible = true; + this.tipsLabel.runAction(anim); + } + }, + onShareOG: function () { + var map = { + "dialog": "shareOpenGraph", + "action_type": "cocostestmyfc:share", + "preview_property_name": "cocos_document", + "title": "Cocos2d-JS Game Engine", + "image": "http://files.cocos2d-x.org/images/orgsite/logo.png", + "url": "http://cocos2d-x.org/docs/manual/framework/html5/en", + "description": "cocos document" + }; + var self = this; + if(facebook.canPresentDialog(map)){ + facebook.dialog(map, function (resultcode, msg) { + self.showDisableTips(JSON.stringify(msg)); + }); + }else{ + self.showDisableTips("Can't open dialog for shareOpenGraph"); + } + + + }, + + onSharePhoto: function () { + var self = this; + if (!cc.sys.isNative) { + self.showDisableTips("This share function is not available on web version of Facebook plugin"); + return; + } + var img = self.screenshot("facebookshare.jpg"); + + var delay = cc.delayTime(2); + var share = cc.callFunc(function () { + var map = { + "dialog": "sharePhoto", + "photo": img + }; + + if(facebook.canPresentDialog(map)){ + facebook.dialog(map, function (resultcode, msg) { + self.showDisableTips(JSON.stringify(msg)); + }); + }else{ + self.showDisableTips("Can't open dialog for sharePhoto"); + } + }); + var seq = cc.sequence(delay, share); + this.runAction(seq); + + }, + + onLinkMsg: function () { + var map = { + "dialog": "messageLink", + "description": "Cocos2d-JS is a great game engine", + "title": "Cocos2d-JS", + "link": "http://www.cocos2d-x.org", + "imageUrl": "http://files.cocos2d-x.org/images/orgsite/logo.png" + }; + if(facebook.canPresentDialog(map)){ + var self = this; + facebook.dialog(map, function (resultcode, msg) { + self.showDisableTips(JSON.stringify(msg)); + }); + }else{ + this.showDisableTips("Can't open dialog for messageLink"); + } + }, + + onOGMsg: function () { + if (!cc.sys.isNative) { + this.showDisableTips("This share function is not available on web version of Facebook plugin"); + return; + } + var map = { + "dialog": "messageOpenGraph", + "action_type": "cocostestmyfc:share", + "preview_property_name": "cocos_document", + "title": "Cocos2d-JS Game Engine", + "image": "http://files.cocos2d-x.org/images/orgsite/logo.png", + "url": "http://cocos2d-x.org/docs/manual/framework/html5/en", + "description": "cocos document" + }; + if(facebook.canPresentDialog(map)){ + var self = this; + facebook.dialog(map, function (resultcode, msg) { + self.showDisableTips(JSON.stringify(msg)); + }); + }else{ + this.showDisableTips("Can't open dialog for messageOpenGraph"); + } + }, + + onPhotoMsg: function () { + var self = this; + if (!cc.sys.isNative) { + self.showDisableTips("This share function is not available on web version of Facebook plugin"); + return; + } + var img = this.screenshot("facebookmessage.jpg"); + + var delay = cc.delayTime(2); + var share = cc.callFunc(function () { + var map = { + "dialog": "messagePhoto", + "photo": img + }; + if(facebook.canPresentDialog(map)){ + facebook.dialog(map, function (resultcode, msg) { + self.showDisableTips(JSON.stringify(msg)); + }); + }else{ + self.showDisableTips("Can't open dialog for messagePhoto"); + } + }); + var seq = cc.sequence(delay, share); + this.runAction(seq); + }, + + onRequest: function () { + this.showSecondMenu(appRequestAction); + }, + + onInviteRequest: function () { + var map = { + "message": "Cocos2d-JS is a great game engine", + "title": "Cocos2d-JS title" + }; + var self = this; + facebook.appRequest(map, function (resultcode, msg) { + self.showDisableTips(JSON.stringify(msg)); + }); + }, + onTargetInviteRequest: function () { + var map = { + "message": "Cocos2d-JS is a great game engine", + "title": "Cocos2d-JS title", + "to": "100006738453912, 10204182777160522" + }; + var self = this; + // android only web view support to + facebook.appRequest(map, function (resultcode, msg) { + self.showDisableTips(JSON.stringify(msg)); + }); + }, + onSpecificListsFriends: function () { + var map = { + "message": "Cocos2d-JS is a great game engine", + "title": "Cocos2d-JS title", + "filters": '[{"name":"company", "user_ids":["100006738453912","10204182777160522"]}]' + }; + var self = this; + // android not support filters + facebook.appRequest(map, function (resultcode, msg) { + self.showDisableTips(JSON.stringify(msg)); + }); + }, + sendingGiftRequest: function () { + var map = { + "message": "Cocos2d-JS is a great game engine", + "to": "100006738453912", + "action_type":"send", + "object_id":"649590015121283"// 191181717736427 1426774790893461 + }; + var self = this; + // android not support action_type + facebook.appRequest(map, function (resultcode, msg) { + self.showDisableTips(JSON.stringify(msg)); + }); + }, + onTurnBasedGamesRequest: function () { + var map = { + "message": "Cocos2d-JS is a great game engine", + "title": "Cocos2d-JS title", + "to": "100006738453912", + "action_type":"turn" + }; + var self = this; + // android not support action_type + facebook.appRequest(map, function (resultcode, msg) { + self.showDisableTips(JSON.stringify(msg)); + }); + }, + + screenshot: function (fileName) { + var tex = new cc.RenderTexture(winSize.width, winSize.height, cc.Texture2D.PIXEL_FORMAT_RGBA8888); + tex.setPosition(cc.p(winSize.width / 2, winSize.height / 2)); + tex.begin(); + cc.director.getRunningScene().visit(); + tex.end(); + + var imgPath = jsb.fileUtils.getWritablePath(); + if (imgPath.length == 0) { + return; + } + var result = tex.saveToFile(fileName, cc.IMAGE_FORMAT_JPEG); + if (result) { + imgPath += fileName; + cc.log("save image:" + imgPath); + return imgPath; + } + return ""; + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/FacebookTest/FacebookTest.js b/tests/js-tests/src/FacebookTest/FacebookTest.js new file mode 100644 index 0000000000..85e6b17f72 --- /dev/null +++ b/tests/js-tests/src/FacebookTest/FacebookTest.js @@ -0,0 +1,98 @@ +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies 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. + ****************************************************************************/ + +var FacebookTest = cc.Layer.extend({ + _sceneTitleLabel:null, + _quit: false, + _title: "", + + ctor:function(title){ + this._super() + // Get the sceensize + var screensize = cc.winSize; + + // Add the generated background + var background = new cc.Sprite(s_extensions_background); + background.x = screensize.width / 2; + background.y = screensize.height / 2; + var bgRect = background.getTextureRect(); + background.scaleX = screensize.width/bgRect.width; + background.scaleY = screensize.height/bgRect.height; + this.addChild(background); + + // Add the ribbon + var ribbon = new cc.Scale9Sprite(s_extensions_ribbon, cc.rect(1, 1, 48, 55)); + ribbon.width = screensize.width; + ribbon.height = 57; + ribbon.x = screensize.width / 2.0; + ribbon.y = screensize.height - ribbon.height / 2.0; + this.addChild(ribbon); + + // Add the title + this._sceneTitleLabel = new cc.LabelTTF(this._title, "Arial", 12); + this._sceneTitleLabel.x = screensize.width / 2; + this._sceneTitleLabel.y = screensize.height - this._sceneTitleLabel.height / 2 - 5; + this.addChild(this._sceneTitleLabel, 1); + + // Add the menu + var item1 = new cc.MenuItemImage(s_pathB1, s_pathB2, this.previousCallback, this); + var item2 = new cc.MenuItemImage(s_pathR1, s_pathR2, this.restartCallback, this); + var item3 = new cc.MenuItemImage(s_pathF1, s_pathF2, this.nextCallback, this); + + var menu = new cc.Menu(item1, item3, item2); + menu.x = 0; + menu.y = 0; + item1.x = screensize.width / 2 - 100; + item1.y = 37; + item2.x = screensize.width / 2; + item2.y = 35; + item3.x = screensize.width / 2 + 100; + item3.y = 37; + + this.addChild(menu ,1); + }, + + restartCallback:function (sender) { + if (this._quit) return; + this._quit = true; + (new FacebookTestScene()).runThisTest(__sceneIdx); + }, + + nextCallback:function (sender) { + if (this._quit) return; + this._quit = true; + __sceneIdx++; + __sceneIdx = __sceneIdx % arrayOfFacebookTest.length; + (new FacebookTestScene()).runThisTest(__sceneIdx); + }, + + previousCallback:function (sender) { + if (this._quit) return; + this._quit = true; + __sceneIdx--; + if (__sceneIdx < 0) + __sceneIdx += arrayOfFacebookTest.length; + (new FacebookTestScene()).runThisTest(__sceneIdx); + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/FacebookTest/FacebookTestsManager.js b/tests/js-tests/src/FacebookTest/FacebookTestsManager.js new file mode 100644 index 0000000000..7de1057755 --- /dev/null +++ b/tests/js-tests/src/FacebookTest/FacebookTestsManager.js @@ -0,0 +1,60 @@ +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies 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. + ****************************************************************************/ + +var facebook_is_canvas = false; +var arrayOfFacebookTest = [ + FacebookShareTest, + FacebookUserTest +]; + +var __sceneIdx = -1; + +var nextFacebookTest = function () { + __sceneIdx++; + __sceneIdx = __sceneIdx % arrayOfFacebookTest.length; + return new arrayOfFacebookTest[__sceneIdx](); +}; + +FacebookTestScene = TestScene.extend({ + runThisTest:function (num) { + var self = this; + __sceneIdx = (num || num == 0) ? (num - 1) : -1; + + if(!cc.sys.isNative) { //browser + cc.loader.loadJs('', [ + "../../frameworks/cocos2d-html5/external/pluginx/platform/facebook_sdk.js", + "../../frameworks/cocos2d-html5/external/pluginx/platform/facebook.js" + ], function() { + var layer = nextFacebookTest(); + self.addChild(layer); + director.runScene(self); + }); + } + else { + var layer = nextFacebookTest(); + self.addChild(layer); + director.runScene(self); + } + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/FacebookTest/FacebookUserTest.js b/tests/js-tests/src/FacebookTest/FacebookUserTest.js new file mode 100644 index 0000000000..d31193d22f --- /dev/null +++ b/tests/js-tests/src/FacebookTest/FacebookUserTest.js @@ -0,0 +1,199 @@ +/**************************************************************************** + Copyright (c) 2014 Chukong Technologies 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. + ****************************************************************************/ + +var button_share = { + "login": "loginClick", + "loginWithPermission": "loginWithPermissionClick", + "logout": "logoutClick", + "getUid": "getUidClick", + "getToken": "getTokenClick", + "getPermissions": "getPermissionClick", + "request API": "requestClick", + "activateApp": "activateAppClick", + "logEvent": "LogEventClick", + "logPurchase": "LogPurchaseClick", + "payment": "paymentClick" +}; +var FacebookUserTest = FacebookTest.extend({ + _title: "Facebook SDK User Test", + _subtitle: "", + _agentManager: null, + _isLogin: false, + ctor: function (title) { + this._super(title); + + window.facebook = window.facebook || (window["plugin"] ? window["plugin"]["FacebookAgent"]["getInstance"]() : null); + + var menu = cc.Menu.create(); + for (var action in button_share) { + var label = new cc.LabelTTF(action, "Arial", 22); + var item = new cc.MenuItemLabel(label, this[button_share[action]], this); + menu.addChild(item); + } + menu.alignItemsVerticallyWithPadding(8); + menu.setPosition(cc.pAdd(cc.visibleRect.left, cc.p(+180, 0))); + this.addChild(menu); + + + this.result = new cc.LabelTTF("You can see the result at this label", "Arial", 22); + this.result.setPosition(cc.pAdd(cc.visibleRect.right, cc.p(-this.result.width / 2 - 30, 0))); + this.result.boundingWidth = this.result.width; + this.addChild(this.result, 1); + }, + activateAppClick: function () { + if (cc.sys.isNative|| facebook_is_canvas) { + facebook.activateApp(); + this.result.setString("activateApp is invoked"); + } + else { + this.result.setString("activateApp is only available for Facebook Canvas App"); + } + }, + LogEventClick: function () { + if (cc.sys.isNative || facebook_is_canvas) { + var parameters = {}; + var floatVal = 888.888; + parameters[window["plugin"].FacebookAgent.AppEventParam.SUCCESS] = window["plugin"].FacebookAgent.AppEventParamValue.VALUE_YES; + // facebook.logEvent(plugin.FacebookAgent.AppEvent.COMPLETED_TUTORIAL); + facebook.logEvent(window["plugin"].FacebookAgent.AppEvent.COMPLETED_TUTORIAL, floatVal); + facebook.logEvent(window["plugin"].FacebookAgent.AppEvent.COMPLETED_TUTORIAL, parameters); + facebook.logEvent(window["plugin"].FacebookAgent.AppEvent.COMPLETED_TUTORIAL, floatVal, parameters); + this.result.setString("logEvent is invoked"); + } + else { + this.result.setString("LogEvent is only available for Facebook Canvas App"); + } + }, + loginClick: function (sender) { + var self = this; + + if (facebook.isLoggedIn()) { + self.result.setString("logged in"); + } + else { + facebook.login(function (type, msg) { + self.result.setString("type is " + type + " msg is " + JSON.stringify(msg)); + }); + } + }, + logoutClick: function (sender) { + var self = this; + facebook.logout(function (type, msg) { + self.result.setString(JSON.stringify(msg)); + }); + }, + getUidClick: function (sender) { + var self = this; + + if (facebook.isLoggedIn()) { + self.result.setString(facebook.getUserID()); + } + else { + self.result.setString("User haven't been logged in"); + } + }, + getTokenClick: function (sender) { + var self = this; + + if (facebook.isLoggedIn()) { + self.result.setString(facebook.getAccessToken()); + } + else { + self.result.setString("User haven't been logged in"); + } + }, + + loginWithPermissionClick: function (sender) { + var self = this; + var permissions = ["create_event", "create_note", "manage_pages", "publish_actions"]; + facebook.login(permissions, function (type, msg) { + if (type == window["plugin"].FacebookAgent.CODE_SUCCEED) { + self.result.setString(msg["permissions"]); + } + }); + }, + getPermissionClick: function (sender) { + var self = this; + facebook.api("/me/permissions", window["plugin"].FacebookAgent.HttpMethod.GET, {}, function (type, data) { + if (type == window["plugin"].FacebookAgent.CODE_SUCCEED) { + data = JSON.stringify(data); + self.result.setString(data); + } + else { + self.result.setString(JSON.stringify(data)); + } + }); + }, + requestClick: function (sender) { + var self = this; + facebook.api("/me/photos", window["plugin"].FacebookAgent.HttpMethod.POST, {"url": "http://files.cocos2d-x.org/images/orgsite/logo.png"}, function (type, msg) { + if (type == window["plugin"].FacebookAgent.CODE_SUCCEED) { + self.result.setString("post_id: " + msg["post_id"]); + } + }); + }, + LogPurchaseClick: function (sender) { + if (cc.sys.isNative || facebook_is_canvas) { + var params = {}; + // All supported parameters are listed here + params[window["plugin"].FacebookAgent.AppEventParam.CURRENCY] = "CNY"; + params[window["plugin"].FacebookAgent.AppEventParam.REGISTRATION_METHOD] = "Facebook"; + params[window["plugin"].FacebookAgent.AppEventParam.CONTENT_TYPE] = "game"; + params[window["plugin"].FacebookAgent.AppEventParam.CONTENT_ID] = "201410102342"; + params[window["plugin"].FacebookAgent.AppEventParam.SEARCH_STRING] = "cocos2djs"; + params[window["plugin"].FacebookAgent.AppEventParam.SUCCESS] = window["plugin"].FacebookAgent.AppEventParamValue.VALUE_YES; + params[window["plugin"].FacebookAgent.AppEventParam.MAX_RATING_VALUE] = "10"; + params[window["plugin"].FacebookAgent.AppEventParam.PAYMENT_INFO_AVAILABLE] = window["plugin"].FacebookAgent.AppEventParamValue.VALUE_YES; + params[window["plugin"].FacebookAgent.AppEventParam.NUM_ITEMS] = "99"; + params[window["plugin"].FacebookAgent.AppEventParam.LEVEL] = "10"; + params[window["plugin"].FacebookAgent.AppEventParam.DESCRIPTION] = "Cocos2d-JS"; + facebook.logPurchase(1.23, "CNY", params); + this.result.setString("Purchase logged."); + } + else { + this.result.setString("LogPurchase is only available for Facebook Canvas App"); + } + }, + paymentClick: function () { + if(facebook_is_canvas){ + var info = { + product: 'https://www.cocos2d-x.org/demo/facebooktest/pay/item1.html' + }; + + var self = this; + facebook.canvas.pay(info, function(code, response){ + if (code == window["plugin"].FacebookAgent.CODE_SUCCEED){ + if (response['status'] === 'completed') + self.result.setString("Payment succeeded: " + response['amount'] + response['currency']); + else + self.result.setString("Payment failed: " + JSON.stringify(response['status'])) + } else { + self.result.setString("Request send failed, error #" + code + ": " + JSON.stringify(response)); + } + }); + }else{ + this.result.setString("canvas.pay is only available for Facebook Canvas App"); + } + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/FontTest/FontTest.js b/tests/js-tests/src/FontTest/FontTest.js new file mode 100644 index 0000000000..fe65ef667b --- /dev/null +++ b/tests/js-tests/src/FontTest/FontTest.js @@ -0,0 +1,159 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var TAG_LABEL1 = 550; +var TAG_LABEL2 = 551; +var TAG_LABEL3 = 552; +var TAG_LABEL4 = 553; + +var fontIdx = 0; + +var fontList = [ + + // System Fonts + "Verdana", + "Lucida Sans Unicode", + "Bookman Old Style", + "Symbol", + "Georgia", + "Trebuchet MS", + "Comic Sans MS", + "Arial Black", + "Tahoma", + "Impact", + + // custom TTF + "American Typewriter", + "Marker Felt", + "A Damn Mess", + "Abberancy", + "Abduction", + "Paint Boy", + "Schwarzwald", + "Scissor Cuts" +]; + + +function nextFontTestAction() { + fontIdx++; + fontIdx = fontIdx % fontList.length; + + if(window.sideIndexBar){ + fontIdx = window.sideIndexBar.changeTest(fontIdx, 16); + } + + return fontList[fontIdx]; +} + +function backFontTestAction() { + fontIdx--; + if (fontIdx < 0) { + fontIdx += fontList.length; + } + + if(window.sideIndexBar){ + fontIdx = window.sideIndexBar.changeTest(fontIdx, 16); + } + + return fontList[fontIdx]; +} + +function restartFontTestAction() { + return fontList[fontIdx]; +} +FontTestScene = TestScene.extend({ + + runThisTest:function (num) { + + fontIdx = num || fontIdx; + + var layer = new FontTest(); + this.addChild(layer); + + director.runScene(this); + } +}); + +var FontTest = BaseTestLayer.extend({ + ctor:function () { + this._super(cc.color(0,0,0,255), cc.color(98,99,117,255)); + + this.showFont(restartFontTestAction()); + + }, + showFont:function (pFont) { + this.removeChildByTag(TAG_LABEL1, true); + this.removeChildByTag(TAG_LABEL2, true); + this.removeChildByTag(TAG_LABEL3, true); + this.removeChildByTag(TAG_LABEL4, true); + + var winSize = director.getWinSize(); + + var top = new cc.LabelTTF(pFont, pFont, 24); + var left = new cc.LabelTTF("alignment left", pFont, 32, cc.size(winSize.width, 50), cc.TEXT_ALIGNMENT_LEFT); + var center = new cc.LabelTTF("alignment center", pFont, 32, cc.size(winSize.width, 50), cc.TEXT_ALIGNMENT_CENTER); + var right = new cc.LabelTTF("alignment right", pFont, 32, cc.size(winSize.width, 50), cc.TEXT_ALIGNMENT_RIGHT); + + top.x = winSize.width / 2; + top.y = winSize.height * 3 / 4; + left.x = winSize.width / 2; + left.y = winSize.height / 2; + center.x = winSize.width / 2; + center.y = winSize.height * 3 / 8; + right.x = winSize.width / 2; + right.y = winSize.height / 4; + + this.addChild(left, 0, TAG_LABEL1); + this.addChild(right, 0, TAG_LABEL2); + this.addChild(center, 0, TAG_LABEL3); + this.addChild(top, 0, TAG_LABEL4); + + }, + + onBackCallback:function (sender) { + this.showFont(backFontTestAction()); + }, + onRestartCallback:function (sender) { + this.showFont(restartFontTestAction()); + }, + onNextCallback:function (sender) { + this.showFont(nextFontTestAction()); + }, + subtitle:function () { + return "Font test"; + }, + title:function () { + return "" + fontList[fontIdx]; + }, + + // automation + numberOfPendingTests:function() { + return ( (fontList.length-1) - fontIdx ); + }, + getTestNumber:function() { + return fontIdx; + } + +}); diff --git a/tests/js-tests/src/GUITest/UIButtonTest/UIButtonTest.js b/tests/js-tests/src/GUITest/UIButtonTest/UIButtonTest.js new file mode 100644 index 0000000000..2596a4f6b5 --- /dev/null +++ b/tests/js-tests/src/GUITest/UIButtonTest/UIButtonTest.js @@ -0,0 +1,568 @@ +/**************************************************************************** + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var UIButtonTest = UIScene.extend({ + init: function () { + if (this._super()) { + //init text + this._topDisplayLabel.setString("No Event"); + this._bottomDisplayLabel.setString("Button"); + + var widgetSize = this._widget.getContentSize(); + // Create the button + var button = new ccui.Button(); + button.setTouchEnabled(true); + button.loadTextures("res/cocosui/animationbuttonnormal.png", "res/cocosui/animationbuttonpressed.png", ""); + button.x = widgetSize.width / 2.0; + button.y = widgetSize.height / 2.0; + button.addTouchEventListener(this.touchEvent, this); + this._mainNode.addChild(button); + + return true; + } + return false; + }, + + touchEvent: function (sender, type) { + switch (type) { + case ccui.Widget.TOUCH_BEGAN: + this._topDisplayLabel.setString("Touch Down"); + break; + + case ccui.Widget.TOUCH_MOVED: + this._topDisplayLabel.setString("Touch Move"); + break; + + case ccui.Widget.TOUCH_ENDED: + this._topDisplayLabel.setString("Touch Up"); + break; + + case ccui.Widget.TOUCH_CANCELED: + this._topDisplayLabel.setString("Touch Cancelled"); + break; + + default: + break; + } + } +}); +var UIButtonTest_Scale9 = UIScene.extend({ + init: function () { + if (this._super()) { + //init text + this._topDisplayLabel.setString("No Event"); + this._bottomDisplayLabel.setString("Button scale9 render"); + + // Create the button + var button = new ccui.Button(); + button.setTouchEnabled(true); + button.setScale9Enabled(true); + button.loadTextures("res/cocosui/button.png", "res/cocosui/buttonHighlighted.png", ""); + button.x = this._widget.width / 2.0; + button.y = this._widget.height / 2.0; + button.setContentSize(cc.size(150, 48)); + button.addTouchEventListener(this.touchEvent ,this); + this._mainNode.addChild(button); + + return true; + } + return false; + }, + + touchEvent: function (sender, type) { + switch (type) { + case ccui.Widget.TOUCH_BEGAN: + this._topDisplayLabel.setString("Touch Down"); + break; + case ccui.Widget.TOUCH_MOVED: + this._topDisplayLabel.setString("Touch Move"); + break; + case ccui.Widget.TOUCH_ENDED: + this._topDisplayLabel.setString("Touch Up"); + break; + case ccui.Widget.TOUCH_CANCELED: + this._topDisplayLabel.setString("Touch Cancelled"); + break; + + default: + break; + } + } +}); + +var UIButtonTest_PressedAction = UIScene.extend({ + init: function () { + if (this._super()) { + //init text + this._topDisplayLabel.setString("No Event"); + this._bottomDisplayLabel.setString("Button Pressed Action"); + + var widgetSize = this._widget.getContentSize(); + // Create the button + var button = new ccui.Button(); + button.setTouchEnabled(true); + button.setPressedActionEnabled(true); + button.loadTextures("res/cocosui/animationbuttonnormal.png", "res/cocosui/animationbuttonpressed.png", ""); + button.x = widgetSize.width / 2; + button.y = widgetSize.height / 2; + button.addTouchEventListener(this.touchEvent ,this); + this._mainNode.addChild(button); + return true; + } + return false; + }, + + touchEvent: function (sender, type) { + switch (type) { + case ccui.Widget.TOUCH_BEGAN: + this._topDisplayLabel.setString("Touch Down"); + break; + case ccui.Widget.TOUCH_MOVED: + this._topDisplayLabel.setString("Touch Move"); + break; + case ccui.Widget.TOUCH_ENDED: + this._topDisplayLabel.setString("Touch Up"); + break; + case ccui.Widget.TOUCH_CANCELED: + this._topDisplayLabel.setString("Touch Cancelled"); + break; + default: + break; + } + } +}); + +var UIButtonTest_Title = UIScene.extend({ + init: function () { + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + //init text + this._topDisplayLabel.setString("No Event"); + this._bottomDisplayLabel.setString("Button with title"); + + // Create the text button + var textButton = new ccui.Button(); + textButton.setTouchEnabled(true); + textButton.loadTextures("res/cocosui/backtotopnormal.png", "res/cocosui/backtotoppressed.png", ""); + textButton.setTitleText("Title Button"); + textButton.x = widgetSize.width / 2.0; + textButton.y = widgetSize.height / 2.0; + textButton.addTouchEventListener(this.touchEvent ,this); + this._mainNode.addChild(textButton); + + return true; + } + return false; + }, + + touchEvent: function (sender, type) { + switch (type) { + case ccui.Widget.TOUCH_BEGAN: + this._topDisplayLabel.setString("Touch Down"); + break; + case ccui.Widget.TOUCH_MOVED: + this._topDisplayLabel.setString("Touch Move"); + break; + case ccui.Widget.TOUCH_ENDED: + this._topDisplayLabel.setString("Touch Up"); + break; + case ccui.Widget.TOUCH_CANCELED: + this._topDisplayLabel.setString("Touch Cancelled"); + break; + default: + break; + } + } +}); + +var UIButtonTestRemoveSelf = UIScene.extend({ + init: function () { + if (this._super()) { + //init text + this._topDisplayLabel.setString("No Event"); + this._bottomDisplayLabel.setString("Remove Self in the Button's Callback shouldn't cause crash!"); + this._bottomDisplayLabel.setFontSize(15); + + var widgetSize = this._widget.getContentSize(); + + var layout = new ccui.Layout(); + layout.setContentSize(widgetSize.width * 0.6, widgetSize.height * 0.6); + layout.setBackGroundColor(cc.color.GREEN); + layout.setBackGroundColorType(ccui.Layout.BG_COLOR_SOLID); + layout.setBackGroundColorOpacity(100); + layout.setPosition(widgetSize.width/2, widgetSize.height/2); + layout.setAnchorPoint(0.5, 0.5); + layout.setTag(12); + this._mainNode.addChild(layout); + + // Create the button + var button = new ccui.Button("res/cocosui/animationbuttonnormal.png", + "res/cocosui/animationbuttonpressed.png"); + button.setPosition(layout.width / 2.0, layout.height / 2.0); + button.addTouchEventListener(this.touchEvent, this); + layout.addChild(button); + return true; + } + return false; + }, + + touchEvent: function(sender, type){ + switch (type) { + case ccui.Widget.TOUCH_BEGAN: + this._topDisplayLabel.setString("Touch Down"); + break; + + case ccui.Widget.TOUCH_MOVED: + this._topDisplayLabel.setString("Touch Move"); + break; + + case ccui.Widget.TOUCH_ENDED: + this._topDisplayLabel.setString("Touch Up"); + var layout = this._mainNode.getChildByTag(12); + layout.removeFromParent(true); + break; + + case ccui.Widget.TOUCH_CANCELED: + this._topDisplayLabel.setString("Touch Cancelled"); + break; + + default: + break; + } + } +}); + +var UIButtonTestSwitchScale9 = UIScene.extend({ + init: function(){ + if (this._super()){ + var widgetSize = this._widget.getContentSize(); + + // Add a label in which the button events will be displayed + this._topDisplayLabel.setString("No Event"); + this._bottomDisplayLabel.setString(""); + + // Create the button + var button = new ccui.Button("res/cocosui/animationbuttonnormal.png", + "res/cocosui/animationbuttonpressed.png"); + button.setPosition(widgetSize.width / 2.0, widgetSize.height / 2.0); + button.addTouchEventListener(this.touchEvent, this); + button.setTitleText("Button Title"); + button.ignoreContentAdaptWithSize(false); + + this._mainNode.addChild(button); + return true; + } + return false; + }, + + touchEvent: function(sender, type){ + switch (type) { + case ccui.Widget.TOUCH_BEGAN: + this._topDisplayLabel.setString("Touch Down"); + break; + + case ccui.Widget.TOUCH_MOVED: + this._topDisplayLabel.setString("Touch Move"); + break; + + case ccui.Widget.TOUCH_ENDED: + this._topDisplayLabel.setString("Touch Up"); + sender.setScale9Enabled(!sender.isScale9Enabled()); + sender.setContentSize(200,100); + break; + + case ccui.Widget.TOUCH_CANCELED: + this._topDisplayLabel.setString("Touch Cancelled"); + break; + + default: + break; + } + } +}); + +var UIButtonTestZoomScale = UIScene.extend({ + init: function(){ + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + + // Add a label in which the button events will be displayed + this._topDisplayLabel.setString("Zoom Scale: -0.5"); + this._bottomDisplayLabel.setString(""); + + // Create the button + var button = new ccui.Button("res/cocosui/animationbuttonnormal.png", "res/cocosui/animationbuttonpressed.png"); + button.setPosition(widgetSize.width / 2.0, widgetSize.height / 2.0 ); + button.setPressedActionEnabled(true); + button.addClickEventListener(function () { + cc.log("Button clicked, position = (" + button.x + ", " + button.y + ")"); + }); + button.setName("button"); + this._mainNode.addChild(button); + button.setZoomScale(-0.5); + + var slider = new ccui.Slider(); + slider.loadBarTexture("res/cocosui/sliderTrack.png"); + slider.loadSlidBallTextures("res/cocosui/sliderThumb.png", "res/cocosui/sliderThumb.png", ""); + slider.loadProgressBarTexture("res/cocosui/sliderProgress.png"); + slider.setPosition(widgetSize.width / 2.0 , widgetSize.height / 2.0 - 50); + slider.addEventListener(this.sliderEvent, this); + slider.setPercent(button.getZoomScale() * 100); + this._mainNode.addChild(slider); + return true; + } + return false; + }, + + sliderEvent: function(slider, type){ + if (type == ccui.Slider.EVENT_PERCENT_CHANGED){ + var percent = slider.getPercent(); + var btn = this._mainNode.getChildByName("button"); + var zoomScale = percent * 0.01; + btn.setZoomScale(zoomScale); + this._topDisplayLabel.setString("Zoom Scale: "+ zoomScale.toFixed(2)); + } + } +}); + +var UIButtonTextOnly = UIScene.extend({ + init: function(){ + if (this._super()) { + // Add a label in which the button events will be displayed + this._topDisplayLabel.setString("Text Only Button"); + this._bottomDisplayLabel.setString(""); + + // Create the button + var button = new ccui.Button(); + button.setNormalizedPosition(0.5, 0.5); + + button.setTitleText("PLAY GAME"); + cc.log("content size should be greater than 0: width = %f, height = %f", button.width, button.height); + button.setZoomScale(0.3); + button.setPressedActionEnabled(true); + button.addClickEventListener(function () { + cc.log("clicked!"); + }); + this.addChild(button); + return true; + } + return false; + } +}); + +var UIButtonIgnoreContentSizeTest = UIScene.extend({ + init: function(){ + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + + // Add a label in which the button events will be displayed + this._topDisplayLabel.setString("Button IgnoreContent Size Test"); + this._bottomDisplayLabel.setString(""); + + // Create the button + var button = new ccui.Button("res/cocosui/animationbuttonnormal.png", "res/cocosui/animationbuttonpressed.png"); + button.ignoreContentAdaptWithSize(false); + button.setContentSize(200,100); + button.setNormalizedPosition(0.3, 0.5); + button.setTitleText("PLAY GAME"); + button.setZoomScale(0.3); + button.setPressedActionEnabled(true); + button.addClickEventListener(function () { + cc.log("clicked!"); + button.setScale(1.2); + }); + this.addChild(button); + + // Create the button + var button2 = new ccui.Button("res/cocosui/animationbuttonnormal.png", "res/cocosui/animationbuttonpressed.png"); + button2.ignoreContentAdaptWithSize(false); + button2.setContentSize(200,100); + button2.setNormalizedPosition(0.8, 0.5); + button2.setTitleText("PLAY GAME"); + button2.setZoomScale(0.3); + button2.setPressedActionEnabled(true); + button2.addClickEventListener(function () { + button2.runAction(cc.scaleTo(1.0, 1.2)); + cc.log("clicked!"); + }); + this.addChild(button2); + + return true; + } + return false; + } +}); + +var UIButtonTitleEffectTest = UIScene.extend({ + init: function(){ + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + + // Add a label in which the button events will be displayed + this._topDisplayLabel.setString("Button Title Effect"); + this._bottomDisplayLabel.setString(""); + + // Create the button + var button = new ccui.Button("res/cocosui/animationbuttonnormal.png", "res/cocosui/animationbuttonpressed.png"); + button.setNormalizedPosition(0.3, 0.5); + button.setTitleText("PLAY GAME"); + //button.setTitleFontName("fonts/Marker Felt.ttf"); + button.setZoomScale(0.3); + button.setScale(2.0); + button.setPressedActionEnabled(true); + var title = button.getTitleRenderer(); + button.setTitleColor(cc.color.RED); + title.enableShadow(cc.color.BLACK, cc.size(2,-2)); + this.addChild(button); + + // Create the button + var button2 = new ccui.Button("res/cocosui/animationbuttonnormal.png", "res/cocosui/animationbuttonpressed.png"); + button2.setNormalizedPosition(0.8, 0.5); + button2.setTitleText("PLAY GAME"); + var title2 = button2.getTitleRenderer(); + title2.enableStroke(cc.color.GREEN, 3); + this.addChild(button2); + return true; + } + return false; + } +}); + +var UIButtonFlipTest = UIScene.extend({ + init: function(){ + if (this._super()) { + + // Add a label in which the button events will be displayed + this._topDisplayLabel.setString(""); + this._bottomDisplayLabel.setString(""); + + // Create the button + var button = new ccui.Button("res/cocosui/animationbuttonnormal.png", "res/cocosui/animationbuttonpressed.png"); + button.setNormalizedPosition(0.3, 0.5); + button.setTitleText("PLAY GAME"); + //button.setTitleFontName("fonts/Marker Felt.ttf"); + button.setZoomScale(0.3); + button.setScale(2.0); + button.setFlippedX(true); + button.setPressedActionEnabled(true); + this.addChild(button); + + var titleLabel = new ccui.Text("Button X flipped", "Arial", 20); + titleLabel.setNormalizedPosition(0.3, 0.7); + this.addChild(titleLabel); + + // Create the button + var button2 = new ccui.Button("res/cocosui/animationbuttonnormal.png", "res/cocosui/animationbuttonpressed.png"); + button2.setNormalizedPosition(0.8, 0.5); + button2.setTitleText("PLAY GAME"); + button2.setFlippedY(true); + this.addChild(button2); + + titleLabel = new ccui.Text("Button Y flipped", "Arial", 20); + titleLabel.setNormalizedPosition(0.8, 0.7); + this.addChild(titleLabel); + return true; + } + return false; + } +}); + +var UIButtonNormalDefaultTest = UIScene.extend({ + init: function(){ + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + + // Add a label in which the button events will be displayed + this._topDisplayLabel.setString(""); + this._bottomDisplayLabel.setString(""); + + // Add the alert + var alert = new ccui.Text("Button should scale when clicked","Arial",20); + alert.setColor(cc.color(159, 168, 176)); + alert.setPosition(widgetSize.width / 2.0, + widgetSize.height / 2.0 - alert.height * 1.75); + this._mainNode.addChild(alert); + + // Create the button + var button = new ccui.Button("res/cocosui/animationbuttonnormal.png"); + button.setPosition(widgetSize.width / 2.0 - 80, widgetSize.height / 2.0 + 40); + button.setZoomScale(0.4); + button.setPressedActionEnabled(true); + this._mainNode.addChild(button); + + // Create the button + var buttonScale9 = new ccui.Button("res/cocosui/button.png"); + // open scale9 render + buttonScale9.setScale9Enabled(true); + buttonScale9.setPosition(widgetSize.width / 2.0 + 50, widgetSize.height / 2.0 + 40); + buttonScale9.setContentSize(150, 70); + buttonScale9.setPressedActionEnabled(true); + this._mainNode.addChild(buttonScale9); + return true; + } + return false; + } +}); + +var UIButtonDisableDefaultTest = UIScene.extend({ + init: function(){ + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + + this._topDisplayLabel.setString(""); + this._bottomDisplayLabel.setString(""); + + // Add the alert + var alert = new ccui.Text("Left button will turn normal when clicked","Arial",20); + alert.setColor(cc.color(159, 168, 176)); + alert.setPosition(widgetSize.width / 2.0, widgetSize.height / 2.0 - alert.height * 1.75); + this._mainNode.addChild(alert); + + // Create the button + var button = new ccui.Button("res/cocosui/animationbuttonnormal.png"); + button.setPosition(widgetSize.width / 2.0 - 80, widgetSize.height / 2.0 + 40); + button.setZoomScale(0.4); + button.setPressedActionEnabled(true); + button.setBright(false); + button.addClickEventListener(function () { + button.setBright(true); + }); + this._mainNode.addChild(button); + + // Create the button + var buttonScale9 = new ccui.Button("res/cocosui/button.png"); + // open scale9 render + buttonScale9.setScale9Enabled(true); + buttonScale9.setPosition(widgetSize.width / 2.0 + 50, widgetSize.height / 2.0 + 40); + buttonScale9.setContentSize(150, 70); + buttonScale9.setPressedActionEnabled(true); + buttonScale9.setEnabled(false); + buttonScale9.setBright(false); + this._mainNode.addChild(buttonScale9); + return true; + } + return false; + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/GUITest/UICheckBoxTest/UICheckBoxTest.js b/tests/js-tests/src/GUITest/UICheckBoxTest/UICheckBoxTest.js new file mode 100644 index 0000000000..4ed941f959 --- /dev/null +++ b/tests/js-tests/src/GUITest/UICheckBoxTest/UICheckBoxTest.js @@ -0,0 +1,120 @@ +/**************************************************************************** + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var UICheckBoxTest = UIScene.extend({ + init: function () { + if (this._super()) { + //init text + this._topDisplayLabel.setString("No Event"); + this._bottomDisplayLabel.setString("CheckBox"); + + var widgetSize = this._widget.getContentSize(); + // Create the checkbox + var checkBox = new ccui.CheckBox(); + checkBox.setTouchEnabled(true); + checkBox.loadTextures("res/cocosui/check_box_normal.png", + "res/cocosui/check_box_normal_press.png", + "res/cocosui/check_box_active.png", + "res/cocosui/check_box_normal_disable.png", + "res/cocosui/check_box_active_disable.png"); + checkBox.x = widgetSize.width / 2.0; + checkBox.y = widgetSize.height / 2.0; + checkBox.addEventListener(this.selectedStateEvent, this); + this._mainNode.addChild(checkBox); + + return true; + } + return false; + }, + + selectedStateEvent: function (sender, type) { + switch (type) { + case ccui.CheckBox.EVENT_UNSELECTED: + this._topDisplayLabel.setString("Unselected"); + break; + case ccui.CheckBox.EVENT_SELECTED: + this._topDisplayLabel.setString("Selected"); + break; + + default: + break; + } + } +}); + +//2015-01-14 +var UICheckBoxDefaultBehaviorTest = UIScene.extend({ + + init: function(){ + if(this._super()){ + var widgetSize = this._widget.getContentSize(); + + // Add a label in which the checkbox events will be displayed + this._displayValueLabel = new ccui.Text("No Event", "Marker Felt", 32); + this._displayValueLabel.setAnchorPoint(cc.p(0.5, -1)); + this._displayValueLabel.setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2)); + this._mainNode.addChild(this._displayValueLabel); + this._bottomDisplayLabel.setString(""); + + // Add the alert + var alert = new ccui.Text("Only left two and the last checkbox can be cliked!","Marker Felt",20 ); + alert.setColor(cc.color(159, 168, 176)); + alert.setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2 - alert.getContentSize().height * 1.75)); + this._mainNode.addChild(alert); + + // Create the checkbox + var checkBox = new ccui.CheckBox("res/cocosui/check_box_normal.png", "res/cocosui/check_box_active.png"); + checkBox.setPosition(cc.p(widgetSize.width / 2 - 50, widgetSize.height / 2)); + + this._mainNode.addChild(checkBox); + + + // Create the checkbox + var checkBox2 = new ccui.CheckBox("res/cocosui/check_box_normal.png", "res/cocosui/check_box_active.png"); + checkBox2.setPosition(cc.p(widgetSize.width / 2 - 150, widgetSize.height / 2)); + checkBox2.ignoreContentAdaptWithSize(false); + checkBox2.setZoomScale(0.5); + checkBox2.setContentSize(cc.size(80,80)); + checkBox2.setName("bigCheckBox"); + this._mainNode.addChild(checkBox2); + + + // Create the checkbox + var checkBoxDisabled = new ccui.CheckBox("res/cocosui/check_box_normal.png", "res/cocosui/check_box_active.png"); + checkBoxDisabled.setPosition(cc.p(widgetSize.width / 2 + 20, widgetSize.height / 2)); + checkBoxDisabled.setEnabled(false); + checkBoxDisabled.setBright(false); + this._mainNode.addChild(checkBoxDisabled); + + var checkBoxDisabled2 = new ccui.CheckBox("res/cocosui/check_box_normal.png", "res/cocosui/check_box_active.png"); + checkBoxDisabled2.setPosition(cc.p(widgetSize.width / 2 + 70, widgetSize.height / 2)); + checkBoxDisabled2.setBright(false); + checkBoxDisabled2.setSelected(true); + this._mainNode.addChild(checkBoxDisabled2); + return true; + } + } + +}); \ No newline at end of file diff --git a/tests/js-tests/src/GUITest/UIFocusTest/UIFocusTest.js b/tests/js-tests/src/GUITest/UIFocusTest/UIFocusTest.js new file mode 100644 index 0000000000..6facfd3db3 --- /dev/null +++ b/tests/js-tests/src/GUITest/UIFocusTest/UIFocusTest.js @@ -0,0 +1,554 @@ +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var UIFocusTestBase = UIScene.extend({ + _dpadMenu: null, + _firstFocusedWidget: null, + _eventListener:null, + + init: function(){ + if (this._super()) { + var root = this._mainNode.getChildByTag(81); + var background = root.getChildByName("background_Panel"); + background.removeFromParent(true); + + this._dpadMenu = new cc.Menu(); + + cc.MenuItemFont.setFontSize(20); + var winSize = cc.director.getVisibleSize(); + var leftItem = new cc.MenuItemFont("Left", this.onLeftKeyPressed, this); + leftItem.setPosition(winSize.width - 100, winSize.height/2); + this._dpadMenu.addChild(leftItem); + + var rightItem = new cc.MenuItemFont("Right", this.onRightKeyPressed, this); + rightItem.setPosition(winSize.width - 30, winSize.height/2); + this._dpadMenu.addChild(rightItem); + + var upItem = new cc.MenuItemFont("Up", this.onUpKeyPressed, this); + upItem.setPosition(winSize.width - 60, winSize.height/2 + 50); + this._dpadMenu.addChild(upItem); + + var downItem = new cc.MenuItemFont("Down", this.onDownKeyPressed, this); + downItem.setPosition(winSize.width - 60, winSize.height/2 - 50); + this._dpadMenu.addChild(downItem); + + this._dpadMenu.setPosition(0, 0); + this.addChild(this._dpadMenu); + + //call this method to enable Dpad focus navigation + ccui.Widget.enableDpadNavigation(true); + + this._eventListener = cc.EventListener.create({ + event: cc.EventListener.FOCUS, //TODO Need add focus event in JSB + onFocusChanged: this.onFocusChanged.bind(this) + }); + cc.eventManager.addListener(this._eventListener, 1); + return true; + } + return false; + }, + + onLeftKeyPressed: function(){ + var event = new cc.EventKeyboard(cc.KEY.dpadLeft, false); + cc.eventManager.dispatchEvent(event); + }, + onRightKeyPressed: function(){ + var event = new cc.EventKeyboard(cc.KEY.dpadRight, false); + cc.eventManager.dispatchEvent(event); + }, + onUpKeyPressed: function(){ + var event = new cc.EventKeyboard(cc.KEY.dpadUp, false); + cc.eventManager.dispatchEvent(event); + }, + onDownKeyPressed: function(){ + var event = new cc.EventKeyboard(cc.KEY.dpadDown, false); + cc.eventManager.dispatchEvent(event); + }, + onFocusChanged: function(widgetLostFocus, widgetGetFocus){ + if (widgetGetFocus && widgetGetFocus.isFocusEnabled()) + widgetGetFocus.setColor(cc.color.RED); + + if (widgetLostFocus && widgetLostFocus.isFocusEnabled()) + widgetLostFocus.setColor(cc.color.WHITE); + + if (widgetLostFocus && widgetGetFocus) + cc.log("on focus change, %d widget get focus, %d widget lose focus", widgetGetFocus.getTag(), widgetLostFocus.getTag()); + }, + + onImageViewClicked: function(widget, touchType){ + if (touchType == ccui.Widget.TOUCH_ENDED) { + if (widget.isFocusEnabled()) { + widget.setFocusEnabled(false); + widget.setColor(cc.color.YELLOW); + }else{ + widget.setFocusEnabled(true); + widget.setColor(cc.color.WHITE); + } + } + } +}); + +var UIFocusTestHorizontal = UIFocusTestBase.extend({ + _horizontalLayout: null, + _loopText: null, + + init: function(){ + if (this._super()) { + var winSize = cc.director.getVisibleSize(); + + this._horizontalLayout = new ccui.HBox(); + this._horizontalLayout.setPosition(winSize.height/2 - 20, winSize.height/2 + 40); + this.addChild(this._horizontalLayout); + + this._horizontalLayout.setFocused(true); + this._horizontalLayout.setLoopFocus(true); + this._horizontalLayout.setTag(100); + this._firstFocusedWidget = this._horizontalLayout; + + var count = 3; + for (var i=0; i 100) { + this._count = 0; + } + + this._loadingBar && this._loadingBar.setPercent(this._count); + }, + + previousCallback: function (sender, type) { + this.unscheduleUpdate(); + this._super(sender, type) + }, + + restartCallback: function (sender, type) { + this.unscheduleUpdate(); + this._super(sender, type) + }, + + nextCallback: function (sender, type) { + this.unscheduleUpdate(); + this._super(sender, type) + } +}); + +var UILoadingBarTest_Left = UILoadingBarTest.extend({ + createLoadingBar: function () { + var widgetSize = this._widget.getContentSize(); + var loadingBar = new ccui.LoadingBar(); + loadingBar.setName("LoadingBar"); + loadingBar.loadTexture("res/cocosui/sliderProgress.png"); + loadingBar.setPercent(0); + loadingBar.x = widgetSize.width / 2; + loadingBar.y = widgetSize.height / 2 + loadingBar.height / 4; + this._mainNode.addChild(loadingBar); + this._loadingBar = loadingBar; + } +}); + +var UILoadingBarTest_Right = UILoadingBarTest.extend({ + createLoadingBar: function () { + var widgetSize = this._widget.getContentSize(); + var loadingBar = new ccui.LoadingBar(); + loadingBar.setName("LoadingBar"); + loadingBar.loadTexture("res/cocosui/sliderProgress.png"); + loadingBar.setDirection(ccui.LoadingBar.TYPE_RIGHT); + loadingBar.setPercent(0); + loadingBar.x = widgetSize.width / 2; + loadingBar.y = widgetSize.height / 2 + loadingBar.height / 4; + this._mainNode.addChild(loadingBar); + this._loadingBar = loadingBar; + } +}); + +var UILoadingBarTest_Fix = UILoadingBarTest.extend({ + createLoadingBar: function () { + var widgetSize = this._widget.getContentSize(); + var loadingBar = new ccui.LoadingBar(); + loadingBar.setName("LoadingBar"); + loadingBar.loadTexture("res/cocosui/sliderProgress.png"); + loadingBar.setDirection(ccui.LoadingBar.TYPE_RIGHT); + loadingBar.setPercent(40); + loadingBar.x = widgetSize.width / 2; + loadingBar.y = widgetSize.height / 2 + loadingBar.height / 4; + this._mainNode.addChild(loadingBar); + this._loadingBar = null; + } +}); + +var UILoadingBarTest_Left_Scale9 = UILoadingBarTest.extend({ + createLoadingBar: function () { + var widgetSize = this._widget.getContentSize(); + var loadingBar = new ccui.LoadingBar(); + loadingBar.setName("LoadingBar"); + loadingBar.setScale9Enabled(true); + loadingBar.loadTexture("res/cocosui/slider_bar_active_9patch.png"); + loadingBar.setCapInsets(cc.rect(0, 0, 0, 0)); + loadingBar.setContentSize(cc.size(300, 30)); + loadingBar.setPercent(0); + loadingBar.x = widgetSize.width / 2; + loadingBar.y = widgetSize.height / 2 + loadingBar.height / 4; + this._mainNode.addChild(loadingBar); + this._loadingBar = loadingBar; + } +}); + +var UILoadingBarTest_Right_Scale9 = UILoadingBarTest.extend({ + createLoadingBar: function () { + var widgetSize = this._widget.getContentSize(); + var loadingBar = new ccui.LoadingBar(); + loadingBar.setName("LoadingBar"); + loadingBar.setScale9Enabled(true); + loadingBar.loadTexture("res/cocosui/slider_bar_active_9patch.png"); + loadingBar.setCapInsets(cc.rect(0, 0, 0, 0)); + loadingBar.setContentSize(cc.size(300, 30)); + loadingBar.setDirection(ccui.LoadingBar.TYPE_RIGHT); + loadingBar.setPercent(0); + loadingBar.x = widgetSize.width / 2; + loadingBar.y = widgetSize.height / 2 + loadingBar.height / 4; + this._mainNode.addChild(loadingBar); + this._loadingBar = loadingBar; + } +}); + +var UILoadingBarTest_Fix_Scale9 = UILoadingBarTest.extend({ + createLoadingBar: function () { + var widgetSize = this._widget.getContentSize(); + var loadingBar = new ccui.LoadingBar(); + loadingBar.setName("LoadingBar"); + loadingBar.setScale9Enabled(true); + loadingBar.loadTexture("res/cocosui/slider_bar_active_9patch.png"); + loadingBar.setPercent(40); + loadingBar.setCapInsets(cc.rect(0, 0, 0, 0)); + loadingBar.setContentSize(cc.size(300, 30)); + loadingBar.setDirection(ccui.LoadingBar.TYPE_RIGHT); + loadingBar.x = widgetSize.width / 2; + loadingBar.y = widgetSize.height / 2 + loadingBar.height / 4; + this._mainNode.addChild(loadingBar); + this._loadingBar = null; + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/GUITest/UINodeContainerTest/UINodeContainerTest.js b/tests/js-tests/src/GUITest/UINodeContainerTest/UINodeContainerTest.js new file mode 100644 index 0000000000..2ed9b344c0 --- /dev/null +++ b/tests/js-tests/src/GUITest/UINodeContainerTest/UINodeContainerTest.js @@ -0,0 +1,49 @@ +/**************************************************************************** + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var UIWidgetAddNodeTest = UIScene.extend({ + init: function () { + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + //init text + this._topDisplayLabel.setString(""); + this._bottomDisplayLabel.setString("NodeContainer"); + + // Create the ui node container + var nodeContainer = new ccui.Widget(); + nodeContainer.x = widgetSize.width / 2; + nodeContainer.y = widgetSize.height / 2; + this._mainNode.addChild(nodeContainer); + + var sprite = new cc.Sprite("res/cocosui/ccicon.png"); + sprite.x = 0; + sprite.y = sprite.getBoundingBox().height / 4; + nodeContainer.addNode(sprite); + + return true; + } + return false; + } +}); diff --git a/tests/js-tests/src/GUITest/UIPageViewTest/UIPageViewTest.js b/tests/js-tests/src/GUITest/UIPageViewTest/UIPageViewTest.js new file mode 100644 index 0000000000..af2fd34854 --- /dev/null +++ b/tests/js-tests/src/GUITest/UIPageViewTest/UIPageViewTest.js @@ -0,0 +1,530 @@ +/**************************************************************************** + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var UIPageViewTest = UIScene.extend({ + init: function () { + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + //init text + this._topDisplayLabel.setString("Move by horizontal direction"); + this._topDisplayLabel.x = widgetSize.width / 2.0; + this._topDisplayLabel.y = widgetSize.height / 2.0 + this._topDisplayLabel.height * 1.5; + this._bottomDisplayLabel.setString("PageView"); + this._bottomDisplayLabel.x = widgetSize.width / 2; + this._bottomDisplayLabel.y = widgetSize.height / 2 - this._bottomDisplayLabel.height * 3; + + var background = this._widget.getChildByName("background_Panel"); + + // Create the page view + var pageView = new ccui.PageView(); + pageView.setTouchEnabled(true); + pageView.setContentSize(cc.size(240, 130)); + pageView.x = (widgetSize.width - background.width) / 2 + (background.width - pageView.width) / 2; + pageView.y = (widgetSize.height - background.height) / 2 + (background.height - pageView.height) / 2; + + for (var i = 0; i < 3; ++i) { + var layout = new ccui.Layout(); + layout.setContentSize(cc.size(240, 130)); + var layoutRect = layout.getContentSize(); + + var imageView = new ccui.ImageView(); + imageView.setTouchEnabled(true); + imageView.setScale9Enabled(true); + imageView.loadTexture("res/cocosui/scrollviewbg.png"); + imageView.setContentSize(cc.size(240, 130)); + imageView.x = layoutRect.width / 2; + imageView.y = layoutRect.height / 2; + layout.addChild(imageView); + + var text = new ccui.Text(); + text.string = "page" + (i + 1); + text.font = "30px 'Marker Felt'"; + text.color = cc.color(192, 192, 192); + text.x = layoutRect.width / 2; + text.y = layoutRect.height / 2; + layout.addChild(text); + + pageView.addPage(layout); + } + pageView.addEventListener(this.pageViewEvent, this); + this._mainNode.addChild(pageView); + + return true; + } + return false; + }, + + pageViewEvent: function (sender, type) { + switch (type) { + case ccui.PageView.EVENT_TURNING: + var pageView = sender; + this._topDisplayLabel.setString("page = " + (pageView.getCurPageIndex().valueOf()-0 + 1)); + break; + default: + break; + } + } +}); + +//2015-01-14 +var UIPageViewButtonTest = UIScene.extend({ + init: function(){ + if (this._super()){ + var widgetSize = this._widget.getContentSize(); + + // Add a label in which the dragpanel events will be displayed + this._topDisplayLabel.setString("Move by horizontal direction"); + this._topDisplayLabel.x = widgetSize.width / 2.0; + this._topDisplayLabel.y = widgetSize.height / 2.0 + this._topDisplayLabel.height * 1.5; + + // Add the black background + this._bottomDisplayLabel.setString("PageView with Buttons"); + this._bottomDisplayLabel.setPosition(widgetSize.width / 2.0, widgetSize.height / 2.0 - this._bottomDisplayLabel.height * 3.075); + + var root = this._mainNode.getChildByTag(81); + var background = root.getChildByName("background_Panel"); + + // Create the page view + var pageView = new ccui.PageView(); + pageView.setContentSize(cc.size(240.0, 130.0)); + var backgroundSize = background.getContentSize(); + pageView.setPosition(cc.p((widgetSize.width - backgroundSize.width) / 2.0 + + (backgroundSize.width - pageView.getContentSize().width) / 2.0, + (widgetSize.height - backgroundSize.height) / 2.0 + + (backgroundSize.height - pageView.getContentSize().height) / 2.0)); + + pageView.removeAllPages(); + + var pageCount = 4; + for (var i = 0; i < pageCount; ++i){ + var outerBox = new ccui.HBox(); + outerBox.setContentSize(cc.size(240.0, 130.0)); + + for (var k = 0; k < 2; ++k) { + var innerBox = new ccui.VBox(); + + for (var j = 0; j < 3; j++) { + var btn = new ccui.Button("res/cocosui/animationbuttonnormal.png", "res/cocosui/animationbuttonpressed.png"); + btn.setName("button " + j); + btn.addTouchEventListener( this.onButtonClicked, this); + innerBox.addChild(btn); + } + + var parameter = new ccui.LinearLayoutParameter(); + parameter.setMargin({left: 0, top: 0, right: 100, bottom: 0}); + innerBox.setLayoutParameter(parameter); + + outerBox.addChild(innerBox); + } + pageView.insertPage(outerBox,i); + } + + pageView.removePageAtIndex(0); + pageView.addEventListener(this.pageViewEvent, this); + this._mainNode.addChild(pageView); + + return true; + } + }, + + onButtonClicked: function(sender, type){ + cc.log("button %s clicked", sender.getName()); + }, + + pageViewEvent: function(pageView, type){ + switch (type){ + case ccui.PageView.EVENT_TURNING: + this._topDisplayLabel.setString("page = " + pageView.getCurPageIndex() + 1); + break; + default: + break; + } + } +}); + +//2015-01-14 +var UIPageViewCustomScrollThreshold = UIScene.extend({ + init: function(){ + if (this._super()){ + var widgetSize = this._widget.getContentSize(); + + // Add a label in which the dragpanel events will be displayed + this._topDisplayLabel.setString("Scroll Threshold"); + this._topDisplayLabel.x = widgetSize.width / 2.0; + this._topDisplayLabel.y = widgetSize.height / 2.0 + this._topDisplayLabel.height * 1.5; + + // Add the black background + this._bottomDisplayLabel.setString("PageView"); + this._bottomDisplayLabel.setPosition(cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0 - this._bottomDisplayLabel.height * 3.075)); + + var root = this._mainNode.getChildByTag(81); + var background = root.getChildByName("background_Panel"); + + // Create the page view + var pageView = new ccui.PageView(); + pageView.setContentSize(cc.size(240.0, 100.0)); + var backgroundSize = background.getContentSize(); + pageView.setPosition(cc.p((widgetSize.width - backgroundSize.width) / 2.0 + + (backgroundSize.width - pageView.getContentSize().width) / 2.0, + (widgetSize.height - backgroundSize.height) / 2.0 + + (backgroundSize.height - pageView.getContentSize().height) / 2.0 + 20)); + + var pageCount = 4; + for (var i = 0; i < pageCount; ++i) { + var layout = new ccui.Layout(); + layout.setContentSize(cc.size(240.0, 130.0)); + + var imageView = new ccui.ImageView("res/cocosui/scrollviewbg.png"); + imageView.setScale9Enabled(true); + imageView.setContentSize(cc.size(240, 130)); + imageView.setPosition(cc.p(layout.getContentSize().width / 2.0, layout.getContentSize().height / 2.0)); + layout.addChild(imageView); + + var label = new ccui.Text("page " + (i+1) , "Marker Felt", 30); + label.setColor(cc.color(192, 192, 192)); + label.setPosition(cc.p(layout.getContentSize().width / 2.0, layout.getContentSize().height / 2.0)); + layout.addChild(label); + + pageView.insertPage(layout,i); + } + + this._mainNode.addChild(pageView); + pageView.setName("pageView"); + + var slider = new ccui.Slider(); + slider.loadBarTexture("res/cocosui/sliderTrack.png"); + slider.loadSlidBallTextures("res/cocosui/sliderThumb.png", "res/cocosui/sliderThumb.png", ""); + slider.loadProgressBarTexture("res/cocosui/sliderProgress.png"); + slider.setPosition(cc.p(widgetSize.width / 2.0 , widgetSize.height / 2.0 - 40)); + slider.addEventListener(this.sliderEvent, this); + slider.setPercent(50); + this._mainNode.addChild(slider); + + return true; + } + }, + + sliderEvent: function(slider, type){ + if (type == ccui.Slider.EVENT_PERCENT_CHANGED){ + var percent = slider.getPercent(); + var pageView = this._mainNode.getChildByName("pageView"); + if (percent == 0) + percent = 1; + pageView.setCustomScrollThreshold(percent * 0.01 * pageView.width); + + this._topDisplayLabel.setString("Scroll Threshold: " + pageView.getCustomScrollThreshold().toFixed(2)); + } + } +}); + +//2015-01-14 +var UIPageViewTouchPropagationTest = UIScene.extend({ + init: function(){ + if (this._super()){ + var widgetSize = this._widget.getContentSize(); + + // Add a label in which the dragpanel events will be displayed + this._topDisplayLabel.setString("Move by horizontal direction"); + this._topDisplayLabel.x = widgetSize.width / 2.0; + this._topDisplayLabel.y = widgetSize.height / 2.0 + this._topDisplayLabel.height * 1.5; + + // Add the black background + this._bottomDisplayLabel.setString("PageView Touch Propagation"); + this._bottomDisplayLabel.setPosition(widgetSize.width / 2.0, widgetSize.height / 2.0 - this._bottomDisplayLabel.height * 3.075); + + var root = this._mainNode.getChildByTag(81); + var background = root.getChildByName("background_Panel"); + + // Create the page view + var pageView = new ccui.PageView(); + pageView.setContentSize(cc.size(240.0, 130.0)); + pageView.setAnchorPoint(cc.p(0.5,0.5)); + var backgroundSize = background.getContentSize(); + pageView.setPosition(cc.p(widgetSize.width / 2.0 ,widgetSize.height / 2.0)); + pageView.setBackGroundColor(cc.color.GREEN); + pageView.setBackGroundColorType(ccui.Layout.BG_COLOR_SOLID); + + var pageCount = 4; + for (var i = 0; i < pageCount; ++i) { + var outerBox = new ccui.HBox(); + outerBox.setContentSize(cc.size(240.0, 130.0)); + + for (var k = 0; k < 2; ++k) { + var innerBox = new ccui.VBox(); + + for (var j = 0; j < 3; j++) { + var btn = new ccui.Button("res/cocosui/animationbuttonnormal.png", "res/cocosui/animationbuttonpressed.png"); + btn.setName("button " + j); + btn.addTouchEventListener(this.onButtonClicked, this); + innerBox.addChild(btn); + } + + var parameter = new ccui.LinearLayoutParameter(); + parameter.setMargin({left: 0, top: 0, right: 100, bottom: 0}); + innerBox.setLayoutParameter(parameter); + + outerBox.addChild(innerBox); + } + pageView.insertPage(outerBox, i); + } + + pageView.addEventListener(this.pageViewEvent, this); + pageView.setName("pageView"); + pageView.addTouchEventListener(function(sender, type){ + if (type == ccui.Widget.TOUCH_BEGAN){ + cc.log("page view touch began"); + }else if(type == ccui.Widget.TOUCH_MOVED){ + cc.log("page view touch moved"); + }else if(type == ccui.Widget.TOUCH_ENDED){ + cc.log("page view touch ended"); + }else{ + cc.log("page view touch cancelled"); + } + }); + this._mainNode.addChild(pageView); + + var propagationText = new ccui.Text("Allow Propagation", "Arial", 10); + propagationText.setAnchorPoint(cc.p(0,0.5)); + propagationText.setTextColor(cc.color.RED); + propagationText.setPosition(cc.p(0, pageView.getPosition().y + 50)); + this._mainNode.addChild(propagationText); + + var swallowTouchText = new ccui.Text("Swallow Touches", "Arial", 10); + swallowTouchText.setAnchorPoint(cc.p(0,0.5)); + swallowTouchText.setTextColor(cc.color.RED); + swallowTouchText.setPosition(cc.p(0, pageView.getPosition().y)); + this._mainNode.addChild(swallowTouchText); + + // Create the checkbox + var checkBox1 = new ccui.CheckBox("res/cocosui/check_box_normal.png", + "res/cocosui/check_box_normal_press.png", + "res/cocosui/check_box_active.png", + "res/cocosui/check_box_normal_disable.png", + "res/cocosui/check_box_active_disable.png"); + var propagationPosition = propagationText.getPosition(); + checkBox1.setPosition( + propagationPosition.x + propagationText.getContentSize().width/2, + propagationPosition.y - 20 + ); + + checkBox1.setName("propagation"); + this._mainNode.addChild(checkBox1); + + // Create the checkbox + var checkBox2 = new ccui.CheckBox("res/cocosui/check_box_normal.png", + "res/cocosui/check_box_normal_press.png", + "res/cocosui/check_box_active.png", + "res/cocosui/check_box_normal_disable.png", + "res/cocosui/check_box_active_disable.png"); + var swallowPosition = swallowTouchText.getPosition(); + checkBox2.setPosition( + swallowPosition.x + swallowTouchText.getContentSize().width/2, + swallowPosition.y - 20 + ); + + checkBox2.setName("swallow"); + this._mainNode.addChild(checkBox2); + +// var eventListener = new cc.EventListenerTouchOneByOne(); +// eventListener.onTouchBegan = function(touch, event){ +// cc.log("layout recieves touches"); +// return true; +// }; +// this._eventDispatcher.addEventListenerWithSceneGraphPriority(eventListener, this); + + return true; + } + }, + + onButtonClicked: function(btn, type){ + var ck1 = this._mainNode.getChildByName("propagation"); + var ck2 = this._mainNode.getChildByName("swallow"); + var pageView = this._mainNode.getChildByName("pageView"); + + if (type == ccui.Widget.TOUCH_BEGAN){ + if (ck1.isSelected()){ + btn.setPropagateTouchEvents(true); + pageView.setPropagateTouchEvents(true); + }else{ + btn.setPropagateTouchEvents(false); + pageView.setPropagateTouchEvents(false); + } + + if (ck2.isSelected()){ + btn.setSwallowTouches(true); + pageView.setSwallowTouches(true); + }else{ + btn.setSwallowTouches(false); + pageView.setSwallowTouches(false); + } + } + if (type == ccui.Widget.TOUCH_ENDED) + cc.log("button clicked"); + }, + + pageViewEvent: function(pageView, type){ + switch (type){ + case ccui.PageView.EVENT_TURNING: + this._topDisplayLabel.setString("page = " + (pageView.getCurPageIndex()-0 + 1)); + break; + default: + break; + } + } +}); + +//2015-01-14 +var UIPageViewDynamicAddAndRemoveTest = UIScene.extend({ + init: function(){ + var self = this; + if (this._super()){ + var widgetSize = this._widget.getContentSize(); + + // Add a label in which the dragpanel events will be displayed + this._topDisplayLabel.setString("Click Buttons on the Left"); + this._topDisplayLabel.x = widgetSize.width / 2.0; + this._topDisplayLabel.y = widgetSize.height / 2.0 + this._topDisplayLabel.height * 1.5; + + // Add the black background + this._bottomDisplayLabel.setString("PageView Dynamic Modification"); + this._bottomDisplayLabel.setPosition(widgetSize.width / 2.0, widgetSize.height / 2.0 - this._bottomDisplayLabel.height * 3.075); + + var root = this._mainNode.getChildByTag(81); + var background = root.getChildByName("background_Panel"); + + // Create the page view + var pageView = new ccui.PageView(); + pageView.setContentSize(cc.size(240.0, 130.0)); + pageView.setAnchorPoint(cc.p(0.5,0.5)); + var backgroundSize = background.getContentSize(); + pageView.setPosition(cc.p(widgetSize.width / 2.0 ,widgetSize.height / 2.0)); + pageView.setBackGroundColor(cc.color.GREEN); + pageView.setBackGroundColorType(ccui.Layout.BG_COLOR_SOLID); + + var pageCount = 4; + for (var i = 0; i < pageCount; ++i){ + var outerBox = new ccui.HBox(); + outerBox.setContentSize(cc.size(240.0, 130.0)); + + for (var k = 0; k < 2; ++k){ + var innerBox = new ccui.VBox(); + for (var j = 0; j < 3; j++){ + var btn = new ccui.Button("res/cocosui/animationbuttonnormal.png", + "res/cocosui/animationbuttonpressed.png"); + btn.setName("button " + j); + innerBox.addChild(btn); + } + + var parameter = new ccui.LinearLayoutParameter(); + parameter.setMargin({left: 0, top: 0, right: 100, bottom:0}); + innerBox.setLayoutParameter(parameter); + + outerBox.addChild(innerBox); + } + pageView.insertPage(outerBox,i); + } + + pageView.addEventListener(this.pageViewEvent, this); + pageView.setName("pageView"); + this._mainNode.addChild(pageView); + + //add buttons + var button = new ccui.Button(); +// button.setNormalizedPosition(cc.p(0.12,0.7)); + button.setPosition(20, 220); + button.setTitleText("Add A Page"); + button.setZoomScale(0.3); + button.setPressedActionEnabled(true); + button.setTitleColor(cc.color.RED); + button.addClickEventListener(function(sender){ + var outerBox = new ccui.HBox(); + outerBox.setContentSize(cc.size(240.0, 130.0)); + + for (var k = 0; k < 2; ++k){ + var innerBox = new ccui.VBox(); + for (var j = 0; j < 3; j++){ + var btn = new ccui.Button("res/cocosui/animationbuttonnormal.png", + "res/cocosui/animationbuttonpressed.png"); + btn.setName("button " + j); + innerBox.addChild(btn); + } + + var parameter = new ccui.LinearLayoutParameter(); + parameter.setMargin({left: 0, top: 0, right: 100, bottom: 0}); + innerBox.setLayoutParameter(parameter); + + outerBox.addChild(innerBox); + } + + pageView.addPage(outerBox); + self._topDisplayLabel.setString("page count = " + pageView.getPages().length); + }); + this._mainNode.addChild(button); + + var button2 = new ccui.Button(); +// button2.setNormalizedPosition(cc.p(0.12,0.5)); + button2.setPosition(20, 180); + button2.setTitleText("Remove A Page"); + button2.setZoomScale(0.3); + button2.setPressedActionEnabled(true); + button2.setTitleColor(cc.color.RED); + button2.addClickEventListener(function(sender){ + if (pageView.getPages().length > 0){ + pageView.removePageAtIndex(pageView.getPages().length-1); + }else{ + cc.log("There is no page to remove!"); + } + self._topDisplayLabel.setString("page count = " + pageView.getPages().length); + + }); + this._mainNode.addChild(button2); + + var button3 = new ccui.Button(); +// button3.setNormalizedPosition(cc.p(0.12,0.3)); + button3.setPosition(cc.p(20, 140)); + button3.setTitleText("Remove All Pages"); + button3.setZoomScale(0.3); + button3.setPressedActionEnabled(true); + button3.setTitleColor(cc.color.RED); + button3.addClickEventListener(function(sender){ + pageView.removeAllPages(); + self._topDisplayLabel.setString("page count = " + pageView.getPages().length); + }); + this._mainNode.addChild(button3); + + return true; + } + }, + + pageViewEvent: function(pageView, type){ + switch (type){ + case ccui.PageView.EVENT_TURNING: + this._topDisplayLabel.setString("page = " + (pageView.getCurPageIndex() + 1)); + break; + default: + break; + } + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/GUITest/UIRichTextTest/UIRichTextTest.js b/tests/js-tests/src/GUITest/UIRichTextTest/UIRichTextTest.js new file mode 100644 index 0000000000..68639ec7b9 --- /dev/null +++ b/tests/js-tests/src/GUITest/UIRichTextTest/UIRichTextTest.js @@ -0,0 +1,91 @@ +/**************************************************************************** + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var UIRichTextTest = UIScene.extend({ + _richText:null, + init: function () { + if (this._super()) { + //init text + this._topDisplayLabel.setString(""); + this._bottomDisplayLabel.setString("RichText"); + + var widgetSize = this._widget.getContentSize(); + var button = new ccui.Button(); + button.setTouchEnabled(true); + button.loadTextures("res/cocosui/animationbuttonnormal.png", "res/cocosui/animationbuttonpressed.png", ""); + button.setTitleText("switch"); + button.setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2 + button.getContentSize().height * 2.5)); + button.addTouchEventListener(this.touchEvent,this); + this._mainNode.addChild(button); + + // RichText + var richText = new ccui.RichText(); + richText.ignoreContentAdaptWithSize(false); + richText.width = 120; + richText.height = 100; + + var re1 = new ccui.RichElementText(1, cc.color.WHITE, 255, "This color is white. ", "Helvetica", 10); + var re2 = new ccui.RichElementText(2, cc.color.YELLOW, 255, "And this is yellow. ", "Helvetica", 10); + var re3 = new ccui.RichElementText(3, cc.color.BLUE, 255, "This one is blue. ", "Helvetica", 10); + var re4 = new ccui.RichElementText(4, cc.color.GREEN, 255, "And green. ", "Helvetica", 10); + var re5 = new ccui.RichElementText(5, cc.color.RED, 255, "Last one is red ", "Helvetica", 10); + + var reimg = new ccui.RichElementImage(6, cc.color.WHITE, 255, "res/cocosui/sliderballnormal.png"); + + ccs.armatureDataManager.addArmatureFileInfo("res/cocosui/100/100.ExportJson"); + var pAr = new ccs.Armature("100"); + pAr.getAnimation().play("Animation1"); + + var recustom = new ccui.RichElementCustomNode(1, cc.color.WHITE, 255, pAr); + var re6 = new ccui.RichElementText(7, cc.color.ORANGE, 255, "Have fun!! ", "Helvetica", 10); + richText.pushBackElement(re1); + richText.insertElement(re2, 1); + richText.pushBackElement(re3); + richText.pushBackElement(re4); + richText.pushBackElement(re5); + richText.insertElement(reimg, 2); + richText.pushBackElement(recustom); + richText.pushBackElement(re6); + + richText.x = widgetSize.width / 2; + richText.y = widgetSize.height / 2; + + this._mainNode.addChild(richText); + this._richText = richText; + return true; + } + return false; + }, + touchEvent: function (sender, type) { + if (type == ccui.Widget.TOUCH_ENDED) { + if (this._richText.isIgnoreContentAdaptWithSize()) { + this._richText.ignoreContentAdaptWithSize(false); + this._richText.setContentSize(cc.size(120, 100)); + } else { + this._richText.ignoreContentAdaptWithSize(true); + } + } + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/GUITest/UIScene.js b/tests/js-tests/src/GUITest/UIScene.js new file mode 100644 index 0000000000..1dc7f590df --- /dev/null +++ b/tests/js-tests/src/GUITest/UIScene.js @@ -0,0 +1,138 @@ +/**************************************************************************** + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +UIScene = cc.Scene.extend({ + _widget: null, + _sceneTitle: null, + _topDisplayLabel:null, + _bottomDisplayLabel:null, + _mainNode:null, + ctor: function () { + cc.Scene.prototype.ctor.call(this); + this._widget = null; + }, + init: function () { + if (this._super()) { + var winSize = cc.director.getWinSize(); + + //add main node + var mainNode = new cc.Node(); + var scale = winSize.height / 320; + mainNode.attr({anchorX: 0, anchorY: 0, scale: scale, x: (winSize.width - 480 * scale) / 2, y: (winSize.height - 320 * scale) / 2}); + this.addChild(mainNode); + + var widget; + if(cocoStudioOldApiFlag == 0){ + var json = ccs.load("res/cocosui/UITest/UITest.json"); + widget = json.node; + }else{ + //old api + widget = ccs.uiReader.widgetFromJsonFile("res/cocosui/UITest/UITest.json"); + } + mainNode.addChild(widget,-1); + + this._sceneTitle = widget.getChildByName("UItest"); + + var back_label = widget.getChildByName("back"); + back_label.addTouchEventListener(this.toExtensionsMainLayer, this); + + var left_button = widget.getChildByName("left_Button"); + left_button.addTouchEventListener(this.previousCallback ,this); + + var middle_button = widget.getChildByName("middle_Button"); + middle_button.addTouchEventListener(this.restartCallback ,this); + + var right_button = widget.getChildByName("right_Button"); + right_button.addTouchEventListener(this.nextCallback ,this); + + //add topDisplayLabel + var widgetSize = widget.getContentSize(); + var topDisplayText = new ccui.Text(); + topDisplayText.attr({ + string: "", + fontName: "Marker Felt", + fontSize: 32, + anchorX: 0.5, + anchorY: -1, + x: widgetSize.width / 2.0, + y: widgetSize.height / 2.0 + }); + mainNode.addChild(topDisplayText); + + //add bottomDisplayLabel + var bottomDisplayText = new ccui.Text(); + bottomDisplayText.attr({ + string: "INIT", + fontName: "Marker Felt", + fontSize: 30, + color: cc.color(159, 168, 176), + x: widgetSize.width / 2.0 + }); + bottomDisplayText.y = widgetSize.height / 2.0 - bottomDisplayText.height * 1.75; + mainNode.addChild(bottomDisplayText); + + this._topDisplayLabel = topDisplayText; + this._bottomDisplayLabel = bottomDisplayText; + this._mainNode = mainNode; + this._widget = widget; + return true; + } + return false; + }, + setSceneTitle: function (title) { + this._sceneTitle.setString(title); + }, + toExtensionsMainLayer: function (sender, type) { + if (type == ccui.Widget.TOUCH_ENDED) { + UISceneManager.purge(); + /* + var scene = new cc.Scene(); + var layer = new TestController(); + scene.addChild(layer); + var transition = new cc.TransitionProgressRadialCCW(0.5,scene); + director.runScene(transition); + */ + GUITestScene.prototype.runThisTest(); + } + }, + + previousCallback: function (sender, type) { + if (type == ccui.Widget.TOUCH_ENDED) { + cc.director.runScene(UISceneManager.getInstance().previousUIScene()); + } + }, + + restartCallback: function (sender, type) { + if (type == ccui.Widget.TOUCH_ENDED) { + cc.director.runScene(UISceneManager.getInstance().currentUIScene()); + } + }, + + nextCallback: function (sender, type) { + if (type == ccui.Widget.TOUCH_ENDED) { + cc.director.runScene(UISceneManager.getInstance().nextUIScene()); + } + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/GUITest/UISceneManager.js b/tests/js-tests/src/GUITest/UISceneManager.js new file mode 100644 index 0000000000..61105998dc --- /dev/null +++ b/tests/js-tests/src/GUITest/UISceneManager.js @@ -0,0 +1,654 @@ +/**************************************************************************** + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +(function(global){ + + var currentTestingArray = null; + + var testingItems = { + "UIButton": [ + { + title: "UIButtonTest", + func: function () { + return new UIButtonTest(); + } + }, + { + title: "UIButtonTest_Scale9", + func: function () { + return new UIButtonTest_Scale9(); + } + }, + { + title: "UIButtonTest_PressedAction", + func: function () { + return new UIButtonTest_PressedAction(); + } + }, + { + title: "UIButtonTest_Title", + func: function () { + return new UIButtonTest_Title(); + } + }, + { + title: "UIButtonTestRemoveSelf", + func: function () { + return new UIButtonTestRemoveSelf(); + } + }, + { + title: "UIButtonTestSwitchScale9", + func: function () { + return new UIButtonTestSwitchScale9(); + } + }, + { + title: "UIButtonTestZoomScale", + func: function () { + return new UIButtonTestZoomScale(); + } + }, + { + title: "UIButtonTextOnly", + func: function () { + return new UIButtonTextOnly(); + } + }, + { + title: "UIButtonIgnoreContentSizeTest", + func: function () { + return new UIButtonIgnoreContentSizeTest(); + } + }, + { + title: "UIButtonTitleEffectTest", + func: function () { + return new UIButtonTitleEffectTest(); + } + }, + { + title: "UIButtonFlipTest", + func: function () { + return new UIButtonFlipTest(); + } + }, + { + title: "UIButtonNormalDefaultTest", + func: function () { + return new UIButtonNormalDefaultTest(); + } + }, + { + title: "UIButtonDisableDefaultTest", + func: function () { + return new UIButtonDisableDefaultTest(); + } + } + ], + "UIFocus": [ + { + title: "UIFocusTestHorizontal", + func: function () { + return new UIFocusTestHorizontal(); + } + }, + { + title: "UIFocusTestVertical", + func: function () { + return new UIFocusTestVertical(); + } + }, + { + title: "UIFocusTestNestedLayout1", + func: function () { + return new UIFocusTestNestedLayout1(); + } + }, + { + title: "UIFocusTestNestedLayout2", + func: function () { + return new UIFocusTestNestedLayout2(); + } + }, + { + title: "UIFocusTestNestedLayout3", + func: function () { + return new UIFocusTestNestedLayout3(); + } + } + /*{ //need test + title: "UIFocusTestListView", + func: function () { + return new UIFocusTestListView(); + } + }*/ + ], + "UICheckBox": [ + { + title: "UICheckBoxTest", + func: function () { + return new UICheckBoxTest(); + } + }, + { + title: "UICheckBoxDefaultBehaviorTest", + func: function(){ + return new UICheckBoxDefaultBehaviorTest(); + } + } + ], + "UISlider": [ + { + title: "UISliderTest", + func: function () { + return new UISliderTest(); + } + }, + { + title: "UISliderTest_Scale9", + func: function () { + return new UISliderTest_Scale9(); + } + }, + { + title: "UISliderNormalDefaultTest", + func: function () { + return new UISliderNormalDefaultTest(); + } + }, + { + title: "UISliderDisabledDefaultTest", + func: function () { + return new UISliderDisabledDefaultTest(); + } + } + ], + "UIImageView": [ + { + title: "UIImageViewTest", + func: function () { + return new UIImageViewTest(); + } + }, + { + title: "UIImageViewTest_Scale9", + func: function () { + return new UIImageViewTest_Scale9(); + } + }, + { + title: "UIImageViewTest_ContentSize", + func: function () { + return new UIImageViewTest_ContentSize(); + } + }, + { + title: "UIImageViewFlipTest", + func: function () { + return new UIImageViewFlipTest(); + } + } + ], + "UILoadingBar": [ + { + title: "UILoadingBarTest_Left", + func: function () { + return new UILoadingBarTest_Left(); + } + }, + { + title: "UILoadingBarTest_Right", + func: function () { + return new UILoadingBarTest_Right(); + } + }, + { + title: "UILoadingBarTest_Fix", + func: function(){ + return new UILoadingBarTest_Fix(); + } + }, + { + title: "UILoadingBarTest_Left_Scale9", + func: function () { + return new UILoadingBarTest_Left_Scale9(); + } + }, + { + title: "UILoadingBarTest_Right_Scale9", + func: function () { + return new UILoadingBarTest_Right_Scale9(); + } + }, + { + title: "UILoadingBarTest_Fix_Scale9", + func: function(){ + return new UILoadingBarTest_Fix_Scale9(); + } + } + ], + "UIText": [ + { + title: "UITextTest", + func: function(){ + return new UITextTest(); + } + }, + { + title: "UITextTest_LineWrap", + func: function(){ + return new UITextTest_LineWrap(); + } + }, + { + title: "UILabelTest_Effect", + func: function(){ + return new UILabelTest_Effect(); + } + }, + { + title: "UITextTest_TTF", + func: function(){ + return new UITextTest_TTF(); + } + }, + { + title: "UITextTest_IgnoreConentSize", + func: function(){ + return new UITextTest_IgnoreConentSize(); + } + }, + { + title: "UILabelAtlasTest", + func: function () { + return new UILabelAtlasTest(); + } + }, + { + title: "UILabelTest", + func: function () { + return new UILabelTest(); + } + }, + { + title: "UILabelTest_LineWrap", + func: function () { + return new UILabelTest_LineWrap(); + } + }, + { + title: "UILabelBMFontTest", + func: function () { + return new UILabelBMFontTest(); + } + }, + { + title: "UILabelTest_TTF", + func: function () { + return new UILabelTest_TTF(); + } + } + ], + "UITextFiled": [ + { + title: "UITextFieldTest", + func: function () { + return new UITextFieldTest(); + } + }, + { + title: "UITextFieldTest_MaxLength", + func: function () { + return new UITextFieldTest_MaxLength(); + } + }, + { + title: "UITextFieldTest_Password", + func: function () { + return new UITextFieldTest_Password(); + } + }, + { + title: "UITextFieldTest_LineWrap", + func: function () { + return new UITextFieldTest_LineWrap(); + } + }, + { + title: "UITextFieldTest_TrueTypeFont", + func: function () { + return new UITextFieldTest_TrueTypeFont(); + } + }, + { + title: "UITextFieldTest_PlaceHolderColor", + func: function () { + return new UITextFieldTest_PlaceHolderColor(); + } + } + ], + "UILayout": [ + { + title: "UILayoutTest", + func: function () { + return new UILayoutTest(); + } + }, + { + title: "UILayoutTest_Color", + func: function () { + return new UILayoutTest_Color(); + } + }, + { + title: "UILayoutTest_Gradient", func: function () { + return new UILayoutTest_Gradient(); + } + }, + { + title: "UILayoutTest_BackGroundImage", + func: function () { + return new UILayoutTest_BackGroundImage(); + } + }, + { + title: "UILayoutTest_BackGroundImage_Scale9", + func: function () { + return new UILayoutTest_BackGroundImage_Scale9(); + } + }, + { + title: "UILayoutTest_Layout_Linear_Vertical", + func: function () { + return new UILayoutTest_Layout_Linear_Vertical(); + } + }, + { + title: "UILayoutTest_Layout_Linear_Horizontal", + func: function () { + return new UILayoutTest_Layout_Linear_Horizontal(); + } + }, + { + title: "UILayoutTest_Layout_Relative", + func: function () { + return new UILayoutTest_Layout_Relative(); + } + }, + { + title: "UILayoutTest_Layout_Relative_Align_Parent", + func: function () { + return new UILayoutTest_Layout_Relative_Align_Parent(); + } + }, + { + title: "UILayoutTest_Layout_Relative_Location", + func: function () { + return new UILayoutTest_Layout_Relative_Location(); + } + }, + { + title: "UILayoutComponent_Berth_Test", + func: function () { + return new UILayoutComponent_Berth_Test(); + } + }, + { + title: "UILayoutComponent_Berth_Stretch_Test", + func: function () { + return new UILayoutComponent_Berth_Stretch_Test(); + } + } + ], + "UIScrollView": [ + { + title: "UIScrollViewTest_Vertical", + func: function () { + return new UIScrollViewTest_Vertical(); + } + }, + { + title: "UIScrollViewTest_Horizontal", + func: function () { + return new UIScrollViewTest_Horizontal(); + } + }, + { + title: "UIScrollViewTest_Both", + func: function () { + return new UIScrollViewTest_Both(); + } + }, + { + title: "UIScrollViewTest_ScrollToPercentBothDirection", + func: function () { + return new UIScrollViewTest_ScrollToPercentBothDirection(); + } + }, + { + title: "UIScrollViewTest_ScrollToPercentBothDirection_Bounce", + func: function () { + return new UIScrollViewTest_ScrollToPercentBothDirection_Bounce(); + } + }, + { + title: "UIScrollViewNestTest", + func: function () { + return new UIScrollViewNestTest(); + } + }, + { + title: "UIScrollViewRotated", + func: function () { + return new UIScrollViewRotated(); + } + } + ], + "UIPageView": [ + { + title: "UIPageViewTest", + func: function () { + return new UIPageViewTest(); + } + }, + { + title: "UIPageViewButtonTest", + func: function () { + return new UIPageViewButtonTest(); + } + }, + { + title: "UIPageViewCustomScrollThreshold", + func: function () { + return new UIPageViewCustomScrollThreshold(); + } + }, + { + title: "UIPageViewTouchPropagationTest", + func: function () { + return new UIPageViewTouchPropagationTest(); + } + }, + { + title: "UIPageViewDynamicAddAndRemoveTest", + func: function () { + return new UIPageViewDynamicAddAndRemoveTest(); + } + } + ], + "UIListView": [ + { + title: "UIListViewTest_Vertical", + func: function () { + return new UIListViewTest_Vertical(); + } + }, + { + title: "UIListViewTest_Horizontal", + func: function () { + return new UIListViewTest_Horizontal(); + } + } + ], + "UIWidget": [ + { + title: "UIWidgetAddNodeTest", + func: function () { + return new UIWidgetAddNodeTest(); + } + } + ], + "UIRichText": [ + { + title: "UIRichTextTest", + func: function () { + return new UIRichTextTest(); + } + } + ] + }; + + global.GUITestScene = cc.Class.extend({ + + runThisTest: function(){ + cc.director.runScene(new listScene); + } + + }); + + var listScene = TestScene.extend({ + + onEnter: function(){ + TestScene.prototype.onEnter.call(this); + + var menu = new cc.Menu(); + menu.x = 0; + menu.y = 0; + var index = 0; + for(var p in testingItems){ + (function(name, list){ + var label = new cc.LabelTTF(name, "Arial", 24); + var menuItem = new cc.MenuItemLabel(label, function(){ + currentTestingArray = list; + var manager = global.UISceneManager.getInstance(); + var scene = manager.currentUIScene(); + cc.director.runScene(scene); + }, this); + menuItem.x = winSize.width / 2; + menuItem.y = (winSize.height - (index++ + 1) * 25); + index++; + menu.addChild(menuItem); + })(p, testingItems[p]); + } + + this._menu = menu; + this.addChild(menu); + + if ('touches' in cc.sys.capabilities) + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesMoved: function (touches, event) { + var target = event.getCurrentTarget(); + var delta = touches[0].getDelta(); + target.moveMenu(delta); + return true; + } + }, this); + else if ('mouse' in cc.sys.capabilities) { + cc.eventManager.addListener({ + event: cc.EventListener.MOUSE, + onMouseMove: function (event) { + if (event.getButton() == cc.EventMouse.BUTTON_LEFT) + event.getCurrentTarget().moveMenu(event.getDelta()); + }, + onMouseScroll: function (event) { + var delta = cc.sys.isNative ? event.getScrollY() * 6 : -event.getScrollY(); + event.getCurrentTarget().moveMenu({y: delta}); + return true; + } + }, this); + } + + this._length = 0; + for(var p in testingItems){ + this._length++; + } + }, + + moveMenu: function(delta){ + var newY = this._menu.y + delta.y; + if (newY < 0 ) + newY = 0; + + if( newY > ((this._length + 1) * 49 - winSize.height)) + newY = ((this._length + 1) * 49 - winSize.height); + + this._menu.y = newY; + } + }); + + global.UISceneManager = { + + _currentUISceneId: 0, + + ctor: function () { + this._currentUISceneId = 0; + }, + + nextUIScene: function () { + this._currentUISceneId++; + if (this._currentUISceneId > currentTestingArray.length - 1) { + this._currentUISceneId = 0; + } + return this.currentUIScene(); + }, + + previousUIScene: function () { + this._currentUISceneId--; + if (this._currentUISceneId < 0) { + this._currentUISceneId = currentTestingArray.length - 1; + } + return this.currentUIScene(); + }, + + currentUIScene: function () { + var test = currentTestingArray[this._currentUISceneId]; + var sence = test.func(); + sence.init(); + sence.setSceneTitle(test.title); + return sence; + } + }; + + global.UISceneManager.getInstance = function () { + return this; + }; + + global.UISceneManager.purge = function (){ + this._currentUISceneId = 0; + }; + +})(window); \ No newline at end of file diff --git a/tests/js-tests/src/GUITest/UIScrollViewTest/UIScrollViewTest.js b/tests/js-tests/src/GUITest/UIScrollViewTest/UIScrollViewTest.js new file mode 100644 index 0000000000..0db6aa93fe --- /dev/null +++ b/tests/js-tests/src/GUITest/UIScrollViewTest/UIScrollViewTest.js @@ -0,0 +1,415 @@ +/**************************************************************************** + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var UIScrollViewTest_Vertical = UIScene.extend({ + init: function () { + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + //init text + this._topDisplayLabel.setString("Move by vertical direction"); + this._topDisplayLabel.x = widgetSize.width / 2.0; + this._topDisplayLabel.y = widgetSize.height / 2.0 + this._topDisplayLabel.height * 1.5; + this._bottomDisplayLabel.setString("ScrollView"); + this._bottomDisplayLabel.x = widgetSize.width / 2; + this._bottomDisplayLabel.y = widgetSize.height / 2 - this._bottomDisplayLabel.height * 3; + + var background = this._widget.getChildByName("background_Panel"); + + // Create the scrollview + var scrollView = new ccui.ScrollView(); + scrollView.setDirection(ccui.ScrollView.DIR_VERTICAL); + scrollView.setTouchEnabled(true); + scrollView.setContentSize(cc.size(280, 150)); + + scrollView.x = (widgetSize.width - background.width) / 2 + (background.width - scrollView.width) / 2; + scrollView.y = (widgetSize.height - background.height) / 2 + (background.height - scrollView.height) / 2; + this._mainNode.addChild(scrollView); + + var imageView = new ccui.ImageView(); + imageView.loadTexture("res/cocosui/ccicon.png"); + + var innerWidth = scrollView.width; + var innerHeight = scrollView.height + imageView.height; + + scrollView.setInnerContainerSize(cc.size(innerWidth, innerHeight)); + + var button = new ccui.Button(); + button.setTouchEnabled(true); + button.loadTextures("res/cocosui/animationbuttonnormal.png", "res/cocosui/animationbuttonpressed.png", ""); + button.x = innerWidth / 2; + button.y = scrollView.getInnerContainerSize().height - button.height / 2; + scrollView.addChild(button); + + var textButton = new ccui.Button(); + textButton.setTouchEnabled(true); + textButton.loadTextures("res/cocosui/backtotopnormal.png", "res/cocosui/backtotoppressed.png", ""); + textButton.setTitleText("Text Button"); + textButton.x = innerWidth / 2; + textButton.y = button.getBottomBoundary() - button.height; + scrollView.addChild(textButton); + + var button_scale9 = new ccui.Button(); + button_scale9.setTouchEnabled(true); + button_scale9.setScale9Enabled(true); + button_scale9.loadTextures("res/cocosui/button.png", "res/cocosui/buttonHighlighted.png", ""); + button_scale9.width = 100; + button_scale9.height = 32; + button_scale9.x = innerWidth / 2; + button_scale9.y = textButton.getBottomBoundary() - textButton.height; + scrollView.addChild(button_scale9); + + imageView.x = innerWidth / 2; + imageView.y = imageView.height / 2; + scrollView.addChild(imageView); + + return true; + } + return false; + } +}); + +var UIScrollViewTest_Horizontal = UIScene.extend({ + init: function () { + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + //init text + this._topDisplayLabel.setString("Move by horizontal direction"); + this._topDisplayLabel.x = widgetSize.width / 2.0; + this._topDisplayLabel.y = widgetSize.height / 2.0 + this._topDisplayLabel.height * 1.5; + this._bottomDisplayLabel.setString("ScrollView"); + this._bottomDisplayLabel.x = widgetSize.width / 2; + this._bottomDisplayLabel.y = widgetSize.height / 2 - this._bottomDisplayLabel.height * 3; + + var background = this._widget.getChildByName("background_Panel"); + + // Create the scrollview + var scrollView = new ccui.ScrollView(); + scrollView.setDirection(ccui.ScrollView.DIR_HORIZONTAL); + scrollView.setTouchEnabled(true); + scrollView.setContentSize(cc.size(280, 150)); + var scrollViewRect = scrollView.getContentSize(); + scrollView.setInnerContainerSize(cc.size(scrollViewRect.width,scrollViewRect.height)); + + scrollView.x = (widgetSize.width - background.width) / 2 + (background.width - scrollViewRect.width) / 2; + scrollView.y = (widgetSize.height - background.height) / 2 + (background.height - scrollViewRect.height) / 2; + this._mainNode.addChild(scrollView); + + var imageView = new ccui.ImageView(); + imageView.loadTexture("res/cocosui/ccicon.png"); + + var innerWidth = scrollViewRect.width + imageView.getContentSize().width; + var innerHeight = scrollViewRect.height; + + scrollView.setInnerContainerSize(cc.size(innerWidth, innerHeight)); + + var button = new ccui.Button(); + button.setTouchEnabled(true); + button.loadTextures("res/cocosui/animationbuttonnormal.png", "res/cocosui/animationbuttonpressed.png", ""); + button.x = button.width / 2; + button.y = scrollView.getInnerContainerSize().height - button.height / 2; + scrollView.addChild(button); + + var textButton = new ccui.Button(); + textButton.setTouchEnabled(true); + textButton.loadTextures("res/cocosui/backtotopnormal.png", "res/cocosui/backtotoppressed.png", ""); + textButton.setTitleText("Text Button"); + textButton.x = button.getRightBoundary() + button.width / 2; + textButton.y = button.getBottomBoundary() - button.height; + scrollView.addChild(textButton); + + var button_scale9 = new ccui.Button(); + button_scale9.setTouchEnabled(true); + button_scale9.setScale9Enabled(true); + button_scale9.loadTextures("res/cocosui/button.png", "res/cocosui/buttonHighlighted.png", ""); + button_scale9.width = 100; + button_scale9.height = 32; + button_scale9.x = textButton.getRightBoundary() + textButton.width / 2; + button_scale9.y = textButton.getBottomBoundary() - textButton.height; + scrollView.addChild(button_scale9); + + imageView.x = innerWidth - imageView.width / 2; + imageView.y = button_scale9.getBottomBoundary() - button_scale9.height / 2; + scrollView.addChild(imageView); + + return true; + } + return false; + } +}); + +var UIScrollViewTest_Both = UIScene.extend({ + init: function () { + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + //init text + this._topDisplayLabel.setString("Move by any direction"); + this._topDisplayLabel.x = widgetSize.width / 2.0; + this._topDisplayLabel.y = widgetSize.height / 2.0 + this._topDisplayLabel.height * 1.5; + this._bottomDisplayLabel.setString("ScrollView both"); + this._bottomDisplayLabel.x = widgetSize.width / 2; + this._bottomDisplayLabel.y = widgetSize.height / 2 - this._bottomDisplayLabel.height * 3; + + var background = this._widget.getChildByName("background_Panel"); + + // Create the scrollview + var scrollView = new ccui.ScrollView(); + scrollView.setDirection(ccui.ScrollView.DIR_BOTH); + scrollView.setTouchEnabled(true); + scrollView.setBounceEnabled(true); + scrollView.setBackGroundImageScale9Enabled(true); + scrollView.setBackGroundImage("res/cocosui/green_edit.png"); + scrollView.setContentSize(cc.size(210, 122)); + var scrollViewSize = scrollView.getContentSize(); + + scrollView.x = (widgetSize.width - background.width) / 2 + (background.width - scrollViewSize.width) / 2; + scrollView.y = (widgetSize.height - background.height) / 2 + (background.height - scrollViewSize.height) / 2; + this._mainNode.addChild(scrollView); + + var imageView = new ccui.ImageView(); + imageView.loadTexture("res/cocosui/b11.png"); + scrollView.addChild(imageView); + + scrollView.setInnerContainerSize(cc.size(imageView.width, imageView.height)); + imageView.x = imageView.width/2; + imageView.y = imageView.height/2; + + return true; + } + return false; + } +}); + +var UIScrollViewTest_ScrollToPercentBothDirection = UIScene.extend({ + init: function () { + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + //init text + this._topDisplayLabel.setString(""); + this._bottomDisplayLabel.setString("ScrollView scroll to percent both directrion"); + this._bottomDisplayLabel.x = widgetSize.width / 2; + this._bottomDisplayLabel.y = widgetSize.height / 2 - this._bottomDisplayLabel.height * 3; + + var background = this._widget.getChildByName("background_Panel"); + + // Create the scrollview + var scrollView = new ccui.ScrollView(); + scrollView.setTouchEnabled(true); + scrollView.setBackGroundColor(cc.color.GREEN); + scrollView.setBackGroundColorType(ccui.Layout.BG_COLOR_SOLID); + scrollView.setDirection(ccui.ScrollView.DIR_BOTH); + scrollView.setInnerContainerSize(cc.size(480, 320)); + scrollView.setContentSize(cc.size(100, 100)); + var scrollViewSize = scrollView.getContentSize(); + + scrollView.x = (widgetSize.width - background.width) / 2 + (background.width - scrollViewSize.width) / 2; + scrollView.y = (widgetSize.height - background.height) / 2 + (background.height - scrollViewSize.height) / 2; + scrollView.scrollToPercentBothDirection(cc.p(50, 50), 1, true); + + this._mainNode.addChild(scrollView); + + var imageView = new ccui.ImageView(); + imageView.loadTexture("res/cocosui/Hello.png"); + imageView.x = 240; + imageView.y = 160; + scrollView.addChild(imageView); + + return true; + } + return false; + } +}); + +var UIScrollViewTest_ScrollToPercentBothDirection_Bounce = UIScene.extend({ + init: function () { + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + //init text + this._topDisplayLabel.setString(""); + this._bottomDisplayLabel.setString("ScrollView scroll to percent both directrion bounce"); + this._bottomDisplayLabel.x = widgetSize.width / 2; + this._bottomDisplayLabel.y = widgetSize.height / 2 - this._bottomDisplayLabel.height * 3; + + var background = this._widget.getChildByName("background_Panel"); + + // Create the scrollview + var scrollView = new ccui.ScrollView(); + scrollView.setTouchEnabled(true); + scrollView.setBounceEnabled(true); + scrollView.setBackGroundColor(cc.color.GREEN); + scrollView.setBackGroundColorType(ccui.Layout.BG_COLOR_SOLID); + scrollView.setDirection(ccui.ScrollView.DIR_BOTH); + scrollView.setInnerContainerSize(cc.size(480, 320)); + scrollView.setContentSize(cc.size(100, 100)); + var scrollViewSize = scrollView.getContentSize(); + + scrollView.x = (widgetSize.width - background.width) / 2 + (background.width - scrollViewSize.width) / 2; + scrollView.y = (widgetSize.height - background.height) / 2 + (background.height - scrollViewSize.height) / 2; + scrollView.scrollToPercentBothDirection(cc.p(50, 50), 1, true); + + this._mainNode.addChild(scrollView); + + var imageView = new ccui.ImageView(); + imageView.loadTexture("res/cocosui/Hello.png"); + imageView.x = 240; + imageView.y = 160; + scrollView.addChild(imageView); + + return true; + } + return false; + } +}); + +//2015-01-14 +var UIScrollViewNestTest = UIScene.extend({ + init: function(){ + if(this._super()){ + var widgetSize = this._widget.getContentSize(); + + // Add a label in which the scrollview alert will be displayed + this._topDisplayLabel.setString("Move by vertical direction"); + + // Add the alert + this._bottomDisplayLabel.setString("ScrollView vertical"); + this._bottomDisplayLabel.setPosition(widgetSize.width / 2.0, widgetSize.height / 2.0 - this._bottomDisplayLabel.height * 3.075); + + var root = this._mainNode.getChildByTag(81); + + var background = root.getChildByName("background_Panel"); + + // Create the scrollview by vertical + var scrollView = new ccui.ScrollView(); + scrollView.setContentSize(cc.size(280.0, 150.0)); + scrollView.setDirection(ccui.ScrollView.DIR_BOTH); + var backgroundSize = background.getContentSize(); + scrollView.setPosition(cc.p((widgetSize.width - backgroundSize.width) / 2.0 + + (backgroundSize.width - scrollView.getContentSize().width) / 2.0, + (widgetSize.height - backgroundSize.height) / 2.0 + + (backgroundSize.height - scrollView.getContentSize().height) / 2.0)); + this._mainNode.addChild(scrollView); + + var imageView = new ccui.ImageView("res/cocosui/ccicon.png"); + + var innerWidth = scrollView.getContentSize().width; + var innerHeight = scrollView.getContentSize().height + imageView.getContentSize().height; + + scrollView.setInnerContainerSize(cc.size(innerWidth, innerHeight)); + + var button = new ccui.Button("res/cocosui/animationbuttonnormal.png", "res/cocosui/animationbuttonpressed.png"); + button.setPosition(cc.p(innerWidth / 2.0, scrollView.getInnerContainerSize().height - button.getContentSize().height / 2.0)); + scrollView.addChild(button); + + var titleButton = new ccui.Button("res/cocosui/backtotopnormal.png", "res/cocosui/backtotoppressed.png"); + titleButton.setTitleText("Title Button"); + titleButton.setPosition(cc.p(innerWidth / 2.0, button.getBottomBoundary() - button.getContentSize().height)); + scrollView.addChild(titleButton); + + var button_scale9 = new ccui.Button("res/cocosui/button.png", "res/cocosui/buttonHighlighted.png"); + button_scale9.setScale9Enabled(true); + button_scale9.setContentSize(cc.size(100.0, button_scale9.getVirtualRendererSize().height)); + button_scale9.setPosition(cc.p(innerWidth / 2.0, titleButton.getBottomBoundary() - titleButton.getContentSize().height)); + scrollView.addChild(button_scale9); + + imageView.setPosition(cc.p(innerWidth / 2.0, imageView.getContentSize().height / 2.0)); + scrollView.addChild(imageView); + + // Create the scrollview by horizontal + var sc = new ccui.ScrollView(); + sc.setBackGroundColor(cc.color.GREEN); + sc.setBackGroundColorType(ccui.Layout.BG_COLOR_SOLID); + sc.setBounceEnabled(true); + sc.setDirection(ccui.ScrollView.DIR_BOTH); + sc.setInnerContainerSize(cc.size(480, 320)); + sc.setContentSize(cc.size(100,100)); + sc.setPropagateTouchEvents(false); + sc.setPosition(cc.p(180,100)); + sc.scrollToPercentBothDirection(cc.p(50, 50), 1, true); + var iv = new ccui.ImageView("res/cocosui/Hello.png"); + iv.setPosition(cc.p(240, 160)); + sc.addChild(iv); + scrollView.addChild(sc); + + return true; + } + } + +}); + +//2015-01-14 +var UIScrollViewRotated = UIScene.extend({ + init: function(){ + if(this._super()){ + var widgetSize = this._widget.getContentSize(); + + // Add a label in which the scrollview alert will be displayed + this._topDisplayLabel.setString("Move by vertical direction"); + + // Add the alert + this._bottomDisplayLabel.setString("ScrollView vertical"); + this._bottomDisplayLabel.setPosition(widgetSize.width / 2.0, widgetSize.height / 2.0 - this._bottomDisplayLabel.height * 3.075); + + var root = this._mainNode.getChildByTag(81); + var background = root.getChildByName("background_Panel"); + + // Create the scrollview by vertical + var scrollView = new ccui.ScrollView(); + scrollView.setContentSize(cc.size(280.0, 150.0)); + scrollView.setDirection(ccui.ScrollView.DIR_BOTH); + var backgroundSize = background.getContentSize(); + scrollView.setPosition(cc.p((widgetSize.width - backgroundSize.width) / 2.0 + + (backgroundSize.width - scrollView.getContentSize().width) / 2.0, + (widgetSize.height - backgroundSize.height) / 2.0 + + (backgroundSize.height - scrollView.getContentSize().height) / 2.0 + 100) ); + scrollView.setRotation(45); + this._mainNode.addChild(scrollView); + + var imageView = new ccui.ImageView("res/cocosui/ccicon.png"); + + var innerWidth = scrollView.getContentSize().width; + var innerHeight = scrollView.getContentSize().height + imageView.getContentSize().height; + scrollView.setInnerContainerSize(cc.size(innerWidth, innerHeight)); + + var button = new ccui.Button("res/cocosui/animationbuttonnormal.png", "res/cocosui/animationbuttonpressed.png"); + button.setPosition(cc.p(innerWidth / 2.0, scrollView.getInnerContainerSize().height - button.getContentSize().height / 2.0)); + scrollView.addChild(button); + + var titleButton = new ccui.Button("res/cocosui/backtotopnormal.png", "res/cocosui/backtotoppressed.png"); + titleButton.setTitleText("Title Button"); + titleButton.setPosition(cc.p(innerWidth / 2.0, button.getBottomBoundary() - button.getContentSize().height)); + scrollView.addChild(titleButton); + + var button_scale9 = new ccui.Button("res/cocosui/button.png", "res/cocosui/buttonHighlighted.png"); + button_scale9.setScale9Enabled(true); + button_scale9.setContentSize(cc.size(100.0, button_scale9.getVirtualRendererSize().height)); + button_scale9.setPosition(cc.p(innerWidth / 2.0, titleButton.getBottomBoundary() - titleButton.getContentSize().height)); + scrollView.addChild(button_scale9); + + imageView.setPosition(cc.p(innerWidth / 2.0, imageView.getContentSize().height / 2.0)); + scrollView.addChild(imageView); + + return true; + } + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/GUITest/UISliderTest/UISliderTest.js b/tests/js-tests/src/GUITest/UISliderTest/UISliderTest.js new file mode 100644 index 0000000000..551c4c9911 --- /dev/null +++ b/tests/js-tests/src/GUITest/UISliderTest/UISliderTest.js @@ -0,0 +1,175 @@ +/**************************************************************************** + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var UISliderTest = UIScene.extend({ + init: function () { + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + //init text + this._topDisplayLabel.setString("Move the slider thumb"); + this._bottomDisplayLabel.setString("Slider"); + + // Create the slider + var slider = new ccui.Slider(); + slider.setTouchEnabled(true); + slider.loadBarTexture("res/cocosui/sliderTrack.png"); + slider.loadSlidBallTextures("res/cocosui/sliderThumb.png", "res/cocosui/sliderThumb.png", ""); + slider.loadProgressBarTexture("res/cocosui/sliderProgress.png"); + slider.x = widgetSize.width / 2.0; + slider.y = widgetSize.height / 2.0; + slider.addEventListener(this.sliderEvent, this); + this._mainNode.addChild(slider); + + return true; + } + return false; + }, + + sliderEvent: function (sender, type) { + switch (type) { + case ccui.Slider.EVENT_PERCENT_CHANGED: + var slider = sender; + var percent = slider.getPercent(); + this._topDisplayLabel.setString("Percent " + percent.toFixed(0)); + break; + default: + break; + } + } +}); + +var UISliderTest_Scale9 = UIScene.extend({ + init: function () { + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + //init text + this._topDisplayLabel.setString("Move the slider thumb"); + this._bottomDisplayLabel.setString("Slider scale9 render"); + + // Create the slider + var slider = new ccui.Slider(); + slider.setTouchEnabled(true); + slider.setScale9Enabled(true); + slider.loadBarTexture("res/cocosui/sliderTrack2.png"); + slider.loadSlidBallTextures("res/cocosui/sliderThumb.png", "res/cocosui/sliderThumb.png", ""); + slider.loadProgressBarTexture("res/cocosui/slider_bar_active_9patch.png"); + slider.setCapInsets(cc.rect(0, 0, 0, 0)); + slider.setContentSize(cc.size(250, 10)); + slider.x = widgetSize.width / 2.0; + slider.y = widgetSize.height / 2.0; + slider.addEventListener(this.sliderEvent, this); + this._mainNode.addChild(slider); + + return true; + } + return false; + }, + + sliderEvent: function (sender, type) { + switch (type) { + case ccui.Slider.EVENT_PERCENT_CHANGED: + var slider = sender; + var percent = slider.getPercent(); + this._topDisplayLabel.setString("Percent " + percent.toFixed(0)); + break; + default: + break; + } + } +}); + +//2015-01-14 +var UISliderNormalDefaultTest = UIScene.extend({ + init: function () { + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + + this._bottomDisplayLabel.setString(""); + + // Add the alert + var alert = new ccui.Text("when pressed, the slider ball should scale","Marker Felt",20); + alert.setColor(cc.color(159, 168, 176)); + alert.setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2 - alert.height * 3.75)); + this._mainNode.addChild(alert); + + // Create the slider + var slider = new ccui.Slider(); + slider.loadBarTexture("res/cocosui/sliderTrack.png"); + slider.loadSlidBallTextures("res/cocosui/sliderThumb.png"); + slider.setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2 + 50)); + this._mainNode.addChild(slider); + + var sliderScale9 = new ccui.Slider("res/cocosui/sliderTrack2.png", "res/cocosui/sliderThumb.png"); + sliderScale9.setScale9Enabled(true); + sliderScale9.setCapInsets(cc.rect(0, 0, 0, 0)); + sliderScale9.setZoomScale(1); + sliderScale9.setContentSize(cc.size(250, 19)); + sliderScale9.setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2 - 20)); + this._mainNode.addChild(sliderScale9); + + + return true; + } + return false; + } +}); + +//2015-01-14 +var UISliderDisabledDefaultTest = UIScene.extend({ + init: function () { + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + + this._bottomDisplayLabel.setString(""); + + // Add the alert + var alert = new ccui.Text("slider ball should be gray.","Marker Felt",20); + alert.setColor(cc.color(159, 168, 176)); + alert.setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2 - alert.height * 3.75)); + this._mainNode.addChild(alert); + + // Create the slider + var slider = new ccui.Slider(); + slider.loadBarTexture("res/cocosui/slidbar.png"); + slider.loadSlidBallTextureNormal("res/cocosui/sliderballnormal.png"); + slider.setEnabled(false); + slider.setBright(false); + slider.setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2 + 50)); + this._mainNode.addChild(slider); + + var sliderScale9 = new ccui.Slider("res/cocosui/slidbar.png", "res/cocosui/sliderballnormal.png"); + sliderScale9.setScale9Enabled(true); + sliderScale9.setEnabled(false); + sliderScale9.setBright(false); + sliderScale9.setCapInsets(cc.rect(0, 0, 0, 0)); + sliderScale9.setContentSize(cc.size(250, 10)); + sliderScale9.setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2 - 20)); + this._mainNode.addChild(sliderScale9); + + return true; + } + return false; + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/GUITest/UITextFieldTest/UITextFieldTest.js b/tests/js-tests/src/GUITest/UITextFieldTest/UITextFieldTest.js new file mode 100644 index 0000000000..bffd3c4adb --- /dev/null +++ b/tests/js-tests/src/GUITest/UITextFieldTest/UITextFieldTest.js @@ -0,0 +1,329 @@ +/**************************************************************************** + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var UITextFieldTest = UIScene.extend({ + init: function () { + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + //init text + this._topDisplayLabel.setString("No Event"); + this._bottomDisplayLabel.setString("TextField"); + + // Create the textfield + var textField = new ccui.TextField("PlaceHolder", "Marker Felt", 30); + textField.x = widgetSize.width / 2.0; + textField.y = widgetSize.height / 2.0; + textField.addEventListener(this.textFieldEvent, this); + this._mainNode.addChild(textField); + + return true; + } + return false; + }, + + textFieldEvent: function (textField, type) { + switch (type) { + case ccui.TextField.EVENT_ATTACH_WITH_IME: + var widgetSize = this._widget.getContentSize(); + textField.runAction(cc.moveTo(0.225, + cc.p(widgetSize.width / 2, widgetSize.height / 2 + textField.height / 2))); + this._topDisplayLabel.setString("attach with IME"); + break; + case ccui.TextField.EVENT_DETACH_WITH_IME: + var widgetSize = this._widget.getContentSize(); + textField.runAction(cc.moveTo(0.175, cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0))); + this._topDisplayLabel.setString("detach with IME"); + break; + case ccui.TextField.EVENT_INSERT_TEXT: + this._topDisplayLabel.setString("insert words"); + break; + case ccui.TextField.EVENT_DELETE_BACKWARD: + this._topDisplayLabel.setString("delete word"); + break; + default: + break; + } + } +}); + +var UITextFieldTest_MaxLength = UIScene.extend({ + init: function () { + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + //init text + this._topDisplayLabel.setString("No Event"); + this._bottomDisplayLabel.setString("TextField max length"); + + // Create the textfield + var textField = new ccui.TextField(); + textField.setMaxLengthEnabled(true); + textField.setMaxLength(3); + textField.setTouchEnabled(true); + textField.fontName = "Marker Felt"; + textField.fontSize = 30; + textField.placeHolder = "input words here"; + textField.x = widgetSize.width / 2.0; + textField.y = widgetSize.height / 2.0; + textField.addEventListener(this.textFieldEvent, this); + this._mainNode.addChild(textField); + + return true; + } + return false; + }, + + textFieldEvent: function (sender, type) { + var textField = sender; + var widgetSize = this._widget.getContentSize(); + switch (type) { + case ccui.TextField.EVENT_ATTACH_WITH_IME: + textField.runAction(cc.moveTo(0.225, + cc.p(widgetSize.width / 2, widgetSize.height / 2 + textField.height / 2))); + this._topDisplayLabel.setString("attach with IME max length:" + textField.getMaxLength()); + break; + case ccui.TextField.EVENT_DETACH_WITH_IME: + textField.runAction(cc.moveTo(0.175, cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0))); + this._topDisplayLabel.setString("detach with IME max length:" + textField.getMaxLength()); + break; + case ccui.TextField.EVENT_INSERT_TEXT: + this._topDisplayLabel.setString("insert with IME max length:" + textField.getMaxLength()); + break; + case ccui.TextField.EVENT_DELETE_BACKWARD: + this._topDisplayLabel.setString("delete with IME max length:" + textField.getMaxLength()); + break; + default: + break; + } + } +}); + +var UITextFieldTest_Password = UIScene.extend({ + init: function () { + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + //init text + this._topDisplayLabel.setString("No Event"); + this._bottomDisplayLabel.setString("TextField max length"); + + // Create the textfield + var textField = new ccui.TextField(); + textField.setPasswordEnabled(true); + textField.setPasswordStyleText("*"); + textField.setTouchEnabled(true); + textField.fontName = "Marker Felt"; + textField.fontSize = 30; + textField.placeHolder = "input password here"; + textField.x = widgetSize.width / 2.0; + textField.y = widgetSize.height / 2.0; + textField.addEventListener(this.textFieldEvent, this); + this._mainNode.addChild(textField); + + return true; + } + return false; + }, + + textFieldEvent: function (textField, type) { + var widgetSize = this._widget.getContentSize(); + switch (type) { + case ccui.TextField.EVENT_ATTACH_WITH_IME: + textField.runAction(cc.moveTo(0.225, + cc.p(widgetSize.width / 2, widgetSize.height / 2 + textField.height / 2))); + this._topDisplayLabel.setString("attach with IME IME password"); + break; + case ccui.TextField.EVENT_DETACH_WITH_IME: + textField.runAction(cc.moveTo(0.175, cc.p(widgetSize.width / 2.0, widgetSize.height / 2.0))); + this._topDisplayLabel.setString("detach with IME password"); + break; + case ccui.TextField.EVENT_INSERT_TEXT: + this._topDisplayLabel.setString("insert with IME password"); + break; + case ccui.TextField.EVENT_DELETE_BACKWARD: + this._topDisplayLabel.setString("delete with IME password"); + break; + default: + break; + } + } +}); + +//2015-01-14 +var UITextFieldTest_LineWrap = UIScene.extend({ + + init: function(){ + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + + // Add a label in which the textfield events will be displayed + this._topDisplayLabel.setString("No Event"); + this._topDisplayLabel.setPosition(widgetSize.width / 2, widgetSize.height / 2 + this._topDisplayLabel.height * 1.5); + this._bottomDisplayLabel.setString(""); + + // Add the alert + var alert = new ccui.Text("TextField line wrap","Marker Felt",30); + alert.setColor(cc.color(159, 168, 176)); + alert.setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2 - alert.height * 3.075)); + this._mainNode.addChild(alert); + + // Create the textfield + var textField = new ccui.TextField("input words here", "Marker Felt",30); + textField.ignoreContentAdaptWithSize(false); + //textField.getVirtualRenderer().setLineBreakWithoutSpace(true); + textField.setContentSize(240, 120); + textField.setString("input words here"); + textField.setTextHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER); + textField.setTextVerticalAlignment(cc.TEXT_ALIGNMENT_CENTER); + textField.setPosition(widgetSize.width / 2, widgetSize.height / 2); + textField.addEventListener(this.textFieldEvent, this); + this._mainNode.addChild(textField); + return true; + } + }, + + textFieldEvent: function(textField, type){ + var widgetSize = this._widget.getContentSize(); + switch (type){ + case ccui.TextField.EVENT_ATTACH_WITH_IME: + textField.runAction(cc.moveTo(0.225, cc.p(widgetSize.width / 2, widgetSize.height / 2 + 30))); + textField.setTextHorizontalAlignment(cc.TEXT_ALIGNMENT_LEFT); + textField.setTextVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_TOP); + this._topDisplayLabel.setString("attach with IME"); + break; + case ccui.TextField.EVENT_DETACH_WITH_IME: + textField.runAction(cc.moveTo(0.175, cc.p(widgetSize.width / 2, widgetSize.height / 2))); + textField.setTextHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER); + textField.setTextVerticalAlignment(cc.TEXT_ALIGNMENT_CENTER); + this._topDisplayLabel.setString("detach with IME"); + break; + case ccui.TextField.EVENT_INSERT_TEXT: + this._topDisplayLabel.setString("insert words"); + break; + case ccui.TextField.EVENT_DELETE_BACKWARD: + this._topDisplayLabel.setString("delete word"); + break; + default: + break; + } + } +}); + +//2015-01-14 +var UITextFieldTest_TrueTypeFont = UIScene.extend({ + init: function(){ + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + + // Add a label in which the textfield events will be displayed + this._topDisplayLabel.setString("True Type Font Test - No Event"); + this._topDisplayLabel.setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2 + this._topDisplayLabel.height * 1.5)); + + // Add the alert + this._bottomDisplayLabel.setString("TextField"); + this._bottomDisplayLabel.setPosition(widgetSize.width / 2, widgetSize.height / 2 - this._bottomDisplayLabel.height * 3.075); + + // Create the textfield + var textField = new ccui.TextField("input words here","Marker Felt",30); + textField.setPosition(widgetSize.width / 2, widgetSize.height / 2); + textField.addEventListener(this.textFieldEvent, this); + this._mainNode.addChild(textField); + return true; + } + }, + + textFieldEvent: function(textField, type){ + var widgetSize = this._widget.getContentSize(); + switch (type){ + case ccui.TextField.EVENT_ATTACH_WITH_IME: + textField.runAction(cc.moveTo(0.225, cc.p(widgetSize.width / 2, widgetSize.height / 2 + textField.height / 2))); + this._topDisplayLabel.setString("attach with IME"); + break; + + case ccui.TextField.EVENT_DETACH_WITH_IME: + textField.runAction(cc.moveTo(0.175, cc.p(widgetSize.width / 2, widgetSize.height / 2))); + this._topDisplayLabel.setString("detach with IME"); + break; + + case ccui.TextField.EVENT_INSERT_TEXT: + this._topDisplayLabel.setString("insert words"); + break; + + case ccui.TextField.EVENT_DELETE_BACKWARD: + this._topDisplayLabel.setString("delete word"); + break; + + default: + break; + } + } +}); + +//2015-01-14 +var UITextFieldTest_PlaceHolderColor = UIScene.extend({ + init: function(){ + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + + // Add a label in which the textfield events will be displayed + this._topDisplayLabel.setString("Set place hold color"); + this._topDisplayLabel.setPosition(widgetSize.width / 2, widgetSize.height / 2 + this._topDisplayLabel.height * 1.5); + + // Add the alert + this._bottomDisplayLabel.setString("TextField"); + this._bottomDisplayLabel.setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2 - this._bottomDisplayLabel.height * 3.075)); + + // Create the textfield + var textField = new ccui.TextField("input words here","Arial",30); + textField.setPlaceHolder("input text here"); + textField.setPlaceHolderColor(cc.color.GREEN); + textField.setTextColor(cc.color.RED); + textField.setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2)); + textField.addEventListener(this.textFieldEvent, this); + this._mainNode.addChild(textField); + return true; + } + }, + + textFieldEvent: function(textField, type){ + var widgetSize = this._widget.getContentSize(); + switch (type){ + case ccui.TextField.EVENT_ATTACH_WITH_IME: + textField.runAction(cc.moveTo(0.225, cc.p(widgetSize.width / 2, widgetSize.height / 2 + textField.height / 2))); + this._topDisplayLabel.setString("attach with IME"); + break; + case ccui.TextField.EVENT_DETACH_WITH_IME: + textField.runAction(cc.moveTo(0.175, cc.p(widgetSize.width / 2, widgetSize.height / 2))); + this._topDisplayLabel.setString("detach with IME"); + break; + case ccui.TextField.EVENT_INSERT_TEXT: + this._topDisplayLabel.setString("insert words"); + break; + case ccui.TextField.EVENT_DELETE_BACKWARD: + this._topDisplayLabel.setString("delete word"); + break; + default: + break; + } + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/GUITest/UITextTest/UITextTest.js b/tests/js-tests/src/GUITest/UITextTest/UITextTest.js new file mode 100644 index 0000000000..e6c5f84ec6 --- /dev/null +++ b/tests/js-tests/src/GUITest/UITextTest/UITextTest.js @@ -0,0 +1,182 @@ +/**************************************************************************** + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +//2015-01-14 +var UITextTest = UIScene.extend({ + init: function(){ + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + + this._bottomDisplayLabel.setString("Text"); + + // Create the text + var text = new ccui.Text("Text", "AmericanTypewriter", 30); + text.setPosition(cc.p(widgetSize.width / 2, widgetSize.height / 2 + text.height / 4)); + this._mainNode.addChild(text); + + return true; + } + } +}); + +//2015-01-14 +var UITextTest_LineWrap = UIScene.extend({ + init: function(){ + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + + this._bottomDisplayLabel.setString("Text line wrap"); + + // Create the line wrap + var text = new ccui.Text("TextArea Widget can line wrap","AmericanTypewriter",32); + text.ignoreContentAdaptWithSize(false); + text.setContentSize(cc.size(280, 150)); + text.setTextHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER); + text.setTouchScaleChangeEnabled(true); + text.setTouchEnabled(true); + text.addTouchEventListener(function(sender, type){ + if (type == ccui.Widget.TOUCH_ENDED){ + if (text.width == 280){ + text.setContentSize(cc.size(380,100)); + }else { + text.setContentSize(cc.size(280, 150)); + } + } + }); + text.setPosition(widgetSize.width / 2, widgetSize.height / 2 - text.height / 8); + this._mainNode.addChild(text); + + return true; + } + } +}); + +//2015-01-14 +var UILabelTest_Effect = UIScene.extend({ + init: function(){ + if (this._super()) { + var widgetSize = this._widget.getContentSize(); + + this._bottomDisplayLabel.setString(""); + + var alert = new ccui.Text(); + alert.setString("Label Effect"); + alert.setFontName("Marker Felt"); + alert.setFontSize(30); + alert.setColor(cc.color(159, 168, 176)); + alert.setPosition(widgetSize.width / 2, widgetSize.height / 2 - alert.height * 3.05); + this._mainNode.addChild(alert); + + // create the shadow only label + var shadow_label = new ccui.Text(); + + shadow_label.enableShadow(cc.color.GRAY, cc.p(10, -10)); + shadow_label.setString("Shadow"); + shadow_label.setPosition(widgetSize.width / 2, widgetSize.height / 2 + shadow_label.height); + + this._mainNode.addChild(shadow_label); + + // create the stroke only label + var glow_label = new ccui.Text(); + glow_label.setFontName("Marker Felt"); + glow_label.setString("Glow"); + glow_label.enableGlow(cc.color.RED); + glow_label.setPosition(widgetSize.width / 2, widgetSize.height / 2); + this._mainNode.addChild(glow_label); + + // create the label stroke and shadow + var outline_label = new ccui.Text(); + outline_label.enableOutline(cc.color.BLUE, 2); + outline_label.setString("Outline"); + outline_label.setPosition(widgetSize.width / 2, widgetSize.height / 2 - shadow_label.height); + + this._mainNode.addChild(outline_label); + + return true; + } + } +}); + +//2015-01-14 +var UITextTest_TTF = UIScene.extend({ + init: function(){ + if(this._super()){ + var widgetSize = this._widget.getContentSize(); + + this._bottomDisplayLabel.setString("Text set TTF font"); + + // Create the text, and set font with .ttf + var text = new ccui.Text("Text","A Damn Mess",30); + text.setPosition(widgetSize.width / 2, widgetSize.height / 2 + text.height / 4); + this._mainNode.addChild(text); + + return true; + } + } +}); + +//2015-01-14 +var UITextTest_IgnoreConentSize = UIScene.extend({ + + init: function(){ + if(this._super()){ + var widgetSize = this._widget.getContentSize(); + + this._bottomDisplayLabel.setString(""); + + var leftText = new ccui.Text("ignore conent", "Marker Felt",10); + leftText.setPosition(cc.p(widgetSize.width / 2 - 50, + widgetSize.height / 2)); + leftText.ignoreContentAdaptWithSize(false); + leftText.setTextAreaSize(cc.size(60,60)); + leftText.setString("Text line with break\nText line with break\nText line with break\nText line with break\n"); + leftText.setTouchScaleChangeEnabled(true); + leftText.setTouchEnabled(true); + this._mainNode.addChild(leftText); + + var rightText = new ccui.Text("ignore conent", "Marker Felt",10); + rightText.setPosition(cc.p(widgetSize.width / 2 + 50, + widgetSize.height / 2)); + rightText.setString("Text line with break\nText line with break\nText line with break\nText line with break\n"); + //note: setTextAreaSize must be used with ignoreContentAdaptWithSize(false) + rightText.setTextAreaSize(cc.size(100,30)); + rightText.ignoreContentAdaptWithSize(false); + this._mainNode.addChild(rightText); + + var halighButton = new ccui.Button(); + halighButton.setTitleText("Alignment Right"); + halighButton.addClickEventListener(function(){ + leftText.setTextHorizontalAlignment(cc.TEXT_ALIGNMENT_RIGHT); + rightText.setTextHorizontalAlignment(cc.TEXT_ALIGNMENT_RIGHT); + }); + halighButton.setPosition(cc.p(widgetSize.width/2 - 50, + widgetSize.height/2 - 50)); + this._mainNode.addChild(halighButton); + + return true; + } + } + +}); \ No newline at end of file diff --git a/tests/js-tests/src/IntervalTest/IntervalTest.js b/tests/js-tests/src/IntervalTest/IntervalTest.js new file mode 100644 index 0000000000..99a3813c4a --- /dev/null +++ b/tests/js-tests/src/IntervalTest/IntervalTest.js @@ -0,0 +1,156 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + + + +var IntervalLayer = cc.LayerGradient.extend({ + + label0:null, + label1:null, + label2:null, + label3:null, + label4:null, + + time0:null, + time1:null, + time2:null, + time3:null, + time4:null, + + ctor:function () { + this._super(cc.color(0,0,0,255), cc.color(98,99,117,255)); + + this.time0 = this.time1 = this.time2 = this.time3 = this.time4 = 0.0; + + var s = director.getWinSize(); + // sun + var sun = new cc.ParticleSun(); + sun.texture = cc.textureCache.addImage(s_fire); + sun.x = s.width - 32; + sun.y = s.height - 32; + + sun.setTotalParticles(130); + sun.setLife(0.6); + this.addChild(sun); + + // timers + this.label0 = new cc.LabelTTF("0", "Arial", 24); + this.label1 = new cc.LabelTTF("0", "Arial", 24); + this.label2 = new cc.LabelTTF("0", "Arial", 24); + this.label3 = new cc.LabelTTF("0", "Arial", 24); + this.label4 = new cc.LabelTTF("0", "Arial", 24); + + this.scheduleUpdate(); + this.schedule(this.step1); + this.schedule(this.step2, 0); + this.schedule(this.step3, 1.0); + this.schedule(this.step4, 2.0); + + this.label0.x = s.width * 1 / 6; + this.label0.y = s.height / 2; + this.label1.x = s.width * 2 / 6; + this.label1.y = s.height / 2; + this.label2.x = s.width * 3 / 6; + this.label2.y = s.height / 2; + this.label3.x = s.width * 4 / 6; + this.label3.y = s.height / 2; + this.label4.x = s.width * 5 / 6; + this.label4.y = s.height / 2; + + this.addChild(this.label0); + this.addChild(this.label1); + this.addChild(this.label2); + this.addChild(this.label3); + this.addChild(this.label4); + + // Sprite + var sprite = new cc.Sprite(s_pathGrossini); + sprite.x = 40; + sprite.y = 50; + + var jump = cc.jumpBy(3, cc.p(s.width - 80, 0), 50, 4); + + this.addChild(sprite); + sprite.runAction(cc.sequence(jump, jump.reverse()).repeatForever()); + + // pause button + var item1 = new cc.MenuItemFont("Pause", this.onPause, this); + var menu = new cc.Menu(item1); + menu.x = s.width / 2; + menu.y = s.height - 50; + + this.addChild(menu); + + }, + + onPause:function (sender) { + if (director.isPaused()) { + director.resume(); + } else { + director.pause(); + } + }, + + onExit:function () { + if (director.isPaused()) { + director.resume(); + } + this._super(); + }, + + step1:function (dt) { + this.time1 += dt; + this.label1.setString(this.time1.toFixed(1)); + }, + step2:function (dt) { + this.time2 += dt; + this.label2.setString(this.time2.toFixed(1)); + }, + step3:function (dt) { + this.time3 += dt; + this.label3.setString(this.time3.toFixed(1)); + }, + step4:function (dt) { + this.time4 += dt; + this.label4.setString(this.time4.toFixed(1)); + }, + update:function (dt) { + this.time0 += dt; + + this.label0.setString(this.time0.toFixed(1)); + } + + //CREATE_NODE(IntervalLayer); +}); + +var IntervalTestScene = TestScene.extend({ + + runThisTest:function () { + var layer = new IntervalLayer(); + this.addChild(layer); + director.runScene(this); + } +}); diff --git a/tests/js-tests/src/LabelTest/LabelTest.js b/tests/js-tests/src/LabelTest/LabelTest.js new file mode 100644 index 0000000000..d873cdc368 --- /dev/null +++ b/tests/js-tests/src/LabelTest/LabelTest.js @@ -0,0 +1,2080 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var TAG_LABEL = 1; +var TAG_LABEL_SPRITE_MANAGER = 1; +var TAG_ANIMATION1 = 1; +var TAG_BITMAP_ATLAS1 = 1; +var TAG_BITMAP_ATLAS2 = 2; +var TAG_BITMAP_ATLAS3 = 3; + +var TAG_LABEL_SPRITE1 = 660; +var TAG_LABEL_SPRITE12 = 661; +var TAG_LABEL_SPRITE13 = 662; +var TAG_LABEL_SPRITE14 = 663; +var TAG_LABEL_SPRITE15 = 664; +var TAG_LABEL_SPRITE16 = 665; +var TAG_LABEL_SPRITE17 = 666; +var TAG_LABEL_SPRITE18 = 667; + +var labelTestIdx = -1; + +var LabelTestScene = TestScene.extend({ + runThisTest:function (num) { + labelTestIdx = (num || num == 0) ? (num - 1) : -1; + this.addChild(nextLabelTest()); + director.runScene(this); + } +}); + +var AtlasDemo = BaseTestLayer.extend({ + + title:function () { + return "No title"; + }, + subtitle:function () { + return ""; + }, + onRestartCallback:function (sender) { + var s = new LabelTestScene(); + s.addChild(restartLabelTest()); + director.runScene(s); + + }, + onNextCallback:function (sender) { + var s = new LabelTestScene(); + s.addChild(nextLabelTest()); + director.runScene(s); + + }, + onBackCallback:function (sender) { + var s = new LabelTestScene(); + s.addChild(previousLabelTest()); + director.runScene(s); + }, + + // automation + numberOfPendingTests:function() { + return ( (arrayOfLabelTest.length-1) - labelTestIdx ); + }, + + getTestNumber:function() { + return labelTestIdx; + } + +}); + +//------------------------------------------------------------------ +// +// LabelAtlasOpacityTest +// +//------------------------------------------------------------------ +var LabelAtlasOpacityTest = AtlasDemo.extend({ + time:null, + ctor:function () { + //----start0----ctor + this._super(); + this.time = 0; + + var label1 = new cc.LabelAtlas("123 Test", s_resprefix + "fonts/tuffy_bold_italic-charmap.plist"); + this.addChild(label1, 0, TAG_LABEL_SPRITE1); + label1.x = 10; + label1.y = 100; + label1.opacity = 200; + + var label2 = new cc.LabelAtlas("0123456789", s_resprefix + "fonts/tuffy_bold_italic-charmap.plist"); + this.addChild(label2, 0, TAG_LABEL_SPRITE12); + label2.x = 10; + label2.y = 200; + label2.opacity = 32; + + this.schedule(this.step); + //----end0---- + }, + step:function (dt) { + //----start0----step + this.time += dt; + + var label1 = this.getChildByTag(TAG_LABEL_SPRITE1); + var string1 = this.time.toFixed(2) + " Test"; + label1.setString(string1); + + var label2 = this.getChildByTag(TAG_LABEL_SPRITE12); + var string2 = parseInt(this.time, 10).toString(); + label2.setString(string2); + //----end0---- + }, + title:function () { + return "LabelAtlas Opacity"; + }, + subtitle:function () { + return "Updating label should be fast"; + }, + + // + // Automation + // + getExpectedResult:function() { + // yellow, red, green, blue, yellow + var ret = [200,32]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = []; + var tags = [TAG_LABEL_SPRITE1, TAG_LABEL_SPRITE12]; + + for( var i in tags ) { + var t = tags[i]; + ret.push( this.getChildByTag(t).opacity ); + } + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// LabelAtlasOpacityColorTest +// +//------------------------------------------------------------------ +var LabelAtlasOpacityColorTest = AtlasDemo.extend({ + time:null, + ctor:function () { + //----start1----ctor + this._super(); + var label1 = new cc.LabelAtlas("123 Test", s_resprefix + "fonts/tuffy_bold_italic-charmap.png", 48, 64, ' '); + this.addChild(label1, 0, TAG_LABEL_SPRITE1); + label1.x = 10; + label1.y = 100; + label1.opacity = 200; + + var label2 = new cc.LabelAtlas("0123456789", s_resprefix + "fonts/tuffy_bold_italic-charmap.png", 48, 64, ' '); + this.addChild(label2, 0, TAG_LABEL_SPRITE12); + label2.x = 10; + label2.y = 200; + label2.color = cc.color(255, 0, 0); + + var fade = cc.fadeOut(1.0); + var fade_in = fade.reverse(); + var delay = cc.delayTime(0.25); + var seq = cc.sequence(fade, delay, fade_in, delay.clone()); + var repeat = seq.repeatForever(); + label2.runAction(repeat); + + this.time = 0; + + this.schedule(this.step); + //----end1---- + }, + step:function (dt) { + //----start1----step + this.time += dt; + var string1 = this.time.toFixed(2) + " Test"; + var label1 = this.getChildByTag(TAG_LABEL_SPRITE1); + label1.setString(string1); + + var label2 = this.getChildByTag(TAG_LABEL_SPRITE12); + var string2 = parseInt(this.time, 10).toString(); + label2.setString(string2); + //----end1---- + }, + title:function () { + return "LabelAtlas Opacity Color"; + }, + subtitle:function () { + return "Opacity + Color should work at the same time"; + }, + + // + // Automation + // + testDuration:1, + getExpectedResult:function() { + // yellow, red, green, blue, yellow + var ret = [200,{"r":255,"g":255,"b":255},0,{"r":255,"g":0,"b":0}]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = []; + var tags = [TAG_LABEL_SPRITE1, TAG_LABEL_SPRITE12]; + + for( var i in tags ) { + var t = tags[i]; + ret.push( this.getChildByTag(t).opacity ); + ret.push( this.getChildByTag(t).color ); + } + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// LabelAtlasHD +// +//------------------------------------------------------------------ +var LabelAtlasHD = AtlasDemo.extend({ + ctor:function () { + //----start2----ctor + this._super(); + var s = director.getWinSize(); + + // cc.LabelBMFont + var label1 = new cc.LabelAtlas("TESTING RETINA DISPLAY", s_resprefix + "fonts/larabie-16.plist"); + label1.anchorX = 0.5; + label1.anchorY = 0.5; + + this.addChild(label1); + label1.x = s.width / 2; + label1.y = s.height / 2; + //----end2---- + }, + title:function () { + return "LabelAtlas with Retina Display"; + }, + subtitle:function () { + return "loading larabie-16 / larabie-16-hd"; + }, + + + // + // Automation + // + + pixel: {"0": 255, "1": 255, "2": 255, "3": 255}, + + getExpectedResult:function() { + + // var ret = [{"0":0,"1":0,"2":226,"3":255},{"0":47,"1":0,"2":0,"3":255},{"0":0,"1":47,"2":0,"3":255}]; + var s = director.getWinSize(); + var ret = {"center": "yes"}; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + + var s = director.getWinSize(); + var ret2 = this.readPixels(s.width/2, s.height/2, 100, 100); + + var ret = {"center": this.containsPixel(ret2, this.pixel) ? "yes" : "no"}; + + return JSON.stringify(ret); + } +}); + + +//------------------------------------------------------------------ +// +// BMFontOpacityColorAlignmentTest +// +//------------------------------------------------------------------ +var BMFontOpacityColorAlignmentTest = AtlasDemo.extend({ + time:0, + ctor:function () { + //----start3----ctor + this._super(); + var col = new cc.LayerColor(cc.color(128, 128, 128, 255)); + this.addChild(col, -10); + + var label1 = new cc.LabelBMFont("Test", s_resprefix + "fonts/bitmapFontTest2.fnt"); + + // testing anchors + label1.anchorX = 0; + label1.anchorY = 0; + this.addChild(label1, 0, TAG_BITMAP_ATLAS1); + var fade = cc.fadeOut(1.0); + var fade_in = fade.reverse(); + var seq = cc.sequence(fade, cc.delayTime(0.25), fade_in); + var repeat = seq.repeatForever(); + label1.runAction(repeat); + + // VERY IMPORTANT + // color and opacity work OK because bitmapFontAltas2 loads a BMP image (not a PNG image) + // If you want to use both opacity and color, it is recommended to use NON premultiplied images like BMP images + // Of course, you can also tell XCode not to compress PNG images, but I think it doesn't work as expected + var label2 = new cc.LabelBMFont("Test", s_resprefix + "fonts/bitmapFontTest2.fnt"); + // testing anchors + label2.anchorX = 0.5; + label2.anchorY = 0.5; + label2.color = cc.color.RED ; + this.addChild(label2, 0, TAG_BITMAP_ATLAS2); + label2.runAction(repeat.clone()); + + var label3 = new cc.LabelBMFont("Test", s_resprefix + "fonts/bitmapFontTest2.fnt"); + // testing anchors + label3.anchorX = 1; + label3.anchorY = 1; + this.addChild(label3, 0, TAG_BITMAP_ATLAS3); + + var s = director.getWinSize(); + label1.x = 0; + label1.y = 0; + label2.x = s.width / 2; + label2.y = s.height / 2; + label3.x = s.width; + label3.y = s.height; + + this.schedule(this.step); + //----end3---- + }, + step:function (dt) { + //----start3----step + this.time += dt; + //var string; + var string = this.time.toFixed(2) + "Test j"; + + var label1 = this.getChildByTag(TAG_BITMAP_ATLAS1); + label1.setString(string); + + var label2 = this.getChildByTag(TAG_BITMAP_ATLAS2); + label2.setString(string); + + var label3 = this.getChildByTag(TAG_BITMAP_ATLAS3); + label3.setString(string); + //----end3---- + }, + + title:function () { + return "cc.LabelBMFont"; + }, + subtitle:function () { + return "Testing alignment. Testing opacity + tint"; + }, + + + // + // Automation + // + testDuration:1.1, + getExpectedResult:function() { + // yellow, red, green, blue, yellow + var ret = [0,{"r":255,"g":255,"b":255},0,{"r":255,"g":0,"b":0}]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = []; + var tags = [TAG_BITMAP_ATLAS1, TAG_BITMAP_ATLAS2]; + + for( var i in tags ) { + var t = tags[i]; + ret.push( this.getChildByTag(t).opacity ); + ret.push( this.getChildByTag(t).color ); + } + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// BMFontSubSpriteTest +// +//------------------------------------------------------------------ +var BMFontSubSpriteTest = AtlasDemo.extend({ + time:null, + ctor:function () { + //----start4----ctor + this._super(); + this.time = 0; + + var s = director.getWinSize(); + + var drawNode = new cc.DrawNode(); + this.addChild(drawNode); + drawNode.setDrawColor(cc.color(255,0,0,128)); + drawNode.drawSegment(cc.p(0, s.height / 2), cc.p(s.width, s.height / 2), 2); + drawNode.drawSegment(cc.p(s.width / 2, 0), cc.p(s.width / 2, s.height), 2); + + // Upper Label + var label = new cc.LabelBMFont("Bitmap Font Atlas", s_resprefix + "fonts/bitmapFontTest.fnt"); + this.labelObj = label; + this.addChild(label); + + label.x = s.width / 2; + label.y = s.height / 2; + label.anchorX = 0.5; + label.anchorY = 0.5; + + var BChar = label.getChildByTag(0); + var FChar = label.getChildByTag(7); + var AChar = label.getChildByTag(12); + + if(autoTestEnabled) { + var jump = cc.jumpBy(0.5, cc.p(0,0), 60, 1); + var jump_4ever = cc.sequence(jump, cc.delayTime(0.25)).repeatForever(); + var fade_out = cc.fadeOut(0.5); + var rotate = cc.rotateBy(0.5, 180); + var rot_4ever = cc.sequence(rotate, cc.delayTime(0.25), rotate.clone()).repeatForever(); + + var scale = cc.scaleBy(0.5, 1.5); + } else { + var jump = cc.jumpBy(4, cc.p(0,0), 60, 1); + var jump_4ever = jump.repeatForever(); + var fade_out = cc.fadeOut(1); + var rotate = cc.rotateBy(2, 360); + var rot_4ever = rotate.repeatForever(); + + var scale = cc.scaleBy(2, 1.5); + } + + var scale_back = scale.reverse(); + var scale_seq = cc.sequence(scale, cc.delayTime(0.25), scale_back); + var scale_4ever = scale_seq.repeatForever(); + + var fade_in = cc.fadeIn(1); + var seq = cc.sequence(fade_out, cc.delayTime(0.25), fade_in); + var fade_4ever = seq.repeatForever(); + + BChar.runAction(rot_4ever); + BChar.runAction(scale_4ever); + FChar.runAction(jump_4ever); + AChar.runAction(fade_4ever); + + // Bottom Label + var label2 = new cc.LabelBMFont("00.0", s_resprefix + "fonts/bitmapFontTest.fnt"); + this.addChild(label2, 0, TAG_BITMAP_ATLAS2); + label2.x = s.width / 2.0; + label2.y = 80; + + var lastChar = label2.getChildByTag(3); + lastChar.runAction(rot_4ever.clone()); + + this.schedule(this.step, 0.1); + //----end4---- + }, + step:function (dt) { + //----start4----step + this.time += dt; + var string = this.time.toFixed(1); + string = (string < 10) ? "0" + string : string; + var label1 = this.getChildByTag(TAG_BITMAP_ATLAS2); + label1.setString(string); + //----end4---- + }, + title:function () { + return "cc.LabelBMFont BMFontSubSpriteTest"; + }, + subtitle:function () { + return "Using fonts as cc.Sprite objects. Some characters should rotate."; + }, + + // + // Automation + // + testDuration:0.6, + getExpectedResult:function() { + // yellow, red, green, blue, yellow + var ret = {"rotate": 180, "scale": 1.5, "opacity": 0}; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + + var s = this.labelObj.getChildByTag(0).scale; + var r = this.labelObj.getChildByTag(0).rotation; + var o = this.labelObj.getChildByTag(12).opacity; + var ret = {"rotate": r, "scale": s, "opacity": o}; + + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// BMFontPaddingTest +// +//------------------------------------------------------------------ +var BMFontPaddingTest = AtlasDemo.extend({ + ctor:function () { + //----start5---- + this._super(); + var label = new cc.LabelBMFont("abcdefg", s_resprefix + "fonts/bitmapFontTest4.fnt"); + this.addChild(label); + + var s = director.getWinSize(); + + label.x = s.width / 2; + label.y = s.height / 2; + label.anchorX = 0.5; + label.anchorY = 0.5; + //----end5---- + }, + title:function () { + return "cc.LabelBMFont BMFontPaddingTest"; + }, + subtitle:function () { + return "Testing padding"; + }, + + + // + // Automation + // + pixel: {"0": 255, "1": 255, "2": 255, "3": 255}, + + getExpectedResult:function() { + + // var ret = [{"0":0,"1":0,"2":226,"3":255},{"0":47,"1":0,"2":0,"3":255},{"0":0,"1":47,"2":0,"3":255}]; + var s = director.getWinSize(); + var ret = {"center": "yes"}; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + + var s = director.getWinSize(); + var ret2 = this.readPixels(s.width/2, s.height/2, 100, 100); + var ret = {"center": this.containsPixel(ret2, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// BMFontOffsetTest +// +//------------------------------------------------------------------ +var BMFontOffsetTest = AtlasDemo.extend({ + ctor:function () { + //----start6----ctor + this._super(); + var s = director.getWinSize(); + + var label = null; + label = new cc.LabelBMFont("FaFeFiFoFu", s_resprefix + "fonts/bitmapFontTest5.fnt"); + this.addChild(label); + label.x = s.width / 2; + label.y = s.height / 2 + 50; + label.anchorX = 0.5; + label.anchorY = 0.5; + + label = new cc.LabelBMFont("fafefifofu", s_resprefix + "fonts/bitmapFontTest5.fnt"); + this.addChild(label); + label.x = s.width / 2; + label.y = s.height / 2; + label.anchorX = 0.5; + label.anchorY = 0.5; + + label = new cc.LabelBMFont("aeiou", s_resprefix + "fonts/bitmapFontTest5.fnt"); + this.addChild(label); + label.x = s.width / 2; + label.y = s.height / 2 - 50; + label.anchorX = 0.5; + label.anchorY = 0.5; + //----end6---- + }, + title:function () { + return "cc.LabelBMFont"; + }, + subtitle:function () { + return "Rendering should be OK. Testing offset"; + }, + + // + // Automation + // + + pixel: {"0":150,"1":150,"2":150,"3":255}, + getExpectedResult:function() { + var ret = {"top": "yes", "center": "yes", "bottom": "yes"}; + + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + + var s = director.getWinSize(); + var ret1 = this.readPixels(s.width/2, s.height/2-50, 50, 50); + var ret2 = this.readPixels(s.width/2, s.height/2, 50, 50); + var ret3 = this.readPixels(s.width/2, s.height/2+50, 50, 50); + var ret = {"top": this.containsPixel(ret1, this.pixel, true, 140) ? "yes" : "no", + "center": this.containsPixel(ret2, this.pixel, true, 140) ? "yes" : "no", + "bottom": this.containsPixel(ret3, this.pixel, true, 140) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// BMFontTintTest +// +//------------------------------------------------------------------ +var BMFontTintTest = AtlasDemo.extend({ + ctor:function () { + //----start7----ctor + this._super(); + var s = director.getWinSize(); + + var label = null; + label = new cc.LabelBMFont("Blue", s_resprefix + "fonts/bitmapFontTest5.fnt"); + label.color = cc.color(0, 0, 255); + this.addChild(label); + label.x = s.width / 2; + label.y = s.height / 4; + label.anchorX = 0.5; + label.anchorY = 0.5; + + label = new cc.LabelBMFont("Red", s_resprefix + "fonts/bitmapFontTest5.fnt"); + this.addChild(label); + label.x = s.width / 2; + label.y = 2 * s.height / 4; + label.anchorX = 0.5; + label.anchorY = 0.5; + label.color = cc.color(255, 0, 0); + + label = new cc.LabelBMFont("G", s_resprefix + "fonts/bitmapFontTest5.fnt"); + this.addChild(label); + label.x = s.width / 2; + label.y = 3 * s.height / 4; + label.anchorX = 0.5; + label.anchorY = 0.5; + label.color = cc.color(0, 255, 0); + label.setString("Green"); + //----end7---- + }, + title:function () { + return "cc.LabelBMFont BMFontTintTest"; + }, + subtitle:function () { + return "Testing color"; + }, + + // + // Automation + // + + pixel1: {"0":0,"1":0,"2":255,"3":255}, + pixel2: {"0":255,"1":0,"2":0,"3":255}, + pixel3: {"0":0,"1":255,"2":0,"3":255}, + getExpectedResult:function() { + var ret = {"left": "yes", "center": "yes", "right": "yes"}; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + + var s = director.getWinSize(); + var ret1 = this.readPixels(s.width/2, s.height/4, 50, 50); + var ret2 = this.readPixels(s.width/2, 2 * s.height/4, 50, 50); + var ret3 = this.readPixels(s.width/2, 3 * s.height/4, 50, 50); + var ret = {"left": this.containsPixel(ret1, this.pixel1, true, 100) ? "yes" : "no", + "center": this.containsPixel(ret2, this.pixel2, true, 100) ? "yes" : "no", + "right": this.containsPixel(ret3, this.pixel3, true, 100) ? "yes" : "no"} + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// BMFontSpeedTest +// +//------------------------------------------------------------------ +var BMFontSpeedTest = AtlasDemo.extend({ + ctor:function () { + //----start8----ctor + this._super(); + // Upper Label + for (var i = 0; i < 100; i++) { + var str = "-" + i + "-"; + var label = new cc.LabelBMFont(str, s_resprefix + "fonts/bitmapFontTest.fnt"); + this.addChild(label); + + var s = director.getWinSize(); + + var p = cc.p(Math.random() * s.width, Math.random() * s.height); + label.setPosition(p); + label.anchorX = 0.5; + label.anchorY = 0.5; + } + //----end8---- + }, + title:function () { + return "cc.LabelBMFont"; + }, + subtitle:function () { + return "Creating several cc.LabelBMFont with the same .fnt file should be fast"; + } +}); + +//------------------------------------------------------------------ +// +// BMFontMultiLineTest +// +//------------------------------------------------------------------ +var BMFontMultiLineTest = AtlasDemo.extend({ + ctor:function () { + //----start9----ctor + this._super(); + + // Left + var label1 = new cc.LabelBMFont("Multi line\nLeft", s_resprefix + "fonts/bitmapFontTest3.fnt"); + label1.anchorX = 0; + label1.anchorY = 0; + this.addChild(label1, 0, TAG_BITMAP_ATLAS1); + cc.log("content size:" + label1.width + "," + label1.height); + + + // Center + var label2 = new cc.LabelBMFont("Multi line\nCenter", s_resprefix + "fonts/bitmapFontTest3.fnt"); + label2.anchorX = 0.5; + label2.anchorY = 0.5; + this.addChild(label2, 0, TAG_BITMAP_ATLAS2); + cc.log("content size:" + label2.width + "," + label2.height); + + // right + var label3 = new cc.LabelBMFont("Multi line\nRight\nThree lines Three", s_resprefix + "fonts/bitmapFontTest3.fnt"); + label3.anchorX = 1; + label3.anchorY = 1; + this.addChild(label3, 0, TAG_BITMAP_ATLAS3); + cc.log("content size:" + label3.width + "," + label3.height); + + var s = director.getWinSize(); + label1.x = 0; + label1.y = 0; + label2.x = s.width / 2; + label2.y = s.height / 2; + label3.x = s.width; + label3.y = s.height; + //----end9---- + }, + title:function () { + return "cc.LabelBMFont BMFontMultiLineTest"; + }, + subtitle:function () { + return "Multiline + anchor point"; + }, + + // Automation + + pixel: {"0": 255, "1": 186, "2": 33, "3": 255}, + + getExpectedResult:function() { + + // var ret = [{"0":0,"1":0,"2":226,"3":255},{"0":47,"1":0,"2":0,"3":255},{"0":0,"1":47,"2":0,"3":255}]; + var s = director.getWinSize(); + var ret = {"left": "yes", "center": "yes", "right": "yes"}; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + + var s = director.getWinSize(); + var ret1 = this.readPixels(0, 0, 100, 100); + var ret2 = this.readPixels(s.width/2, s.height/2, 100, 100); + var ret3 = this.readPixels(s.width - 100, s.height - 100, 100, 100); + + + var ret = {"left": this.containsPixel(ret1, this.pixel) ? "yes" : "no", + "center": this.containsPixel(ret2, this.pixel) ? "yes" : "no", + "right": this.containsPixel(ret3, this.pixel) ? "yes" : "no"} + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// BMFontMultiLine2Test +// +//------------------------------------------------------------------ +var BMFontMultiLine2Test = AtlasDemo.extend({ + ctor:function () { + //----start10----ctor + this._super(); + + // Left + var label1 = new cc.LabelBMFont("Multi line\n\nAligned to the left", s_resprefix + "fonts/bitmapFontTest3.fnt"); + label1.anchorX = 0; + label1.anchorY = 0; + label1.textAlign = cc.TEXT_ALIGNMENT_LEFT; + label1.boundingWidth = 400; + this.addChild(label1, 0, TAG_BITMAP_ATLAS1); + cc.log("content size:" + label1.width + "," + label1.height); + + + // Center + var label2 = new cc.LabelBMFont("Error\n\nSome error message", s_resprefix + "fonts/bitmapFontTest3.fnt"); + label2.anchorX = 0.5; + label2.anchorY = 0.5; + label2.textAlign = cc.TEXT_ALIGNMENT_CENTER; + label2.boundingWidth = 290; + this.addChild(label2, 0, TAG_BITMAP_ATLAS2); + cc.log("content size:" + label2.width + "," + label2.height); + + // right + var label3 = new cc.LabelBMFont("Multi line\n\nAligned to the right", s_resprefix + "fonts/bitmapFontTest3.fnt"); + label3.anchorX = 1; + label3.anchorY = 1; + label3.textAlign = cc.TEXT_ALIGNMENT_RIGHT; + label3.boundingWidth = 400; + this.addChild(label3, 0, TAG_BITMAP_ATLAS3); + cc.log("content size:" + label3.width + "," + label3.height); + + var s = director.getWinSize(); + label1.x = 0; + label1.y = 0; + label2.x = s.width / 2; + label2.y = s.height / 2; + label3.x = s.width; + label3.y = s.height; + //----end10---- + }, + title:function () { + return "cc.LabelBMFont BMFontMultiLine2Test"; + }, + subtitle:function () { + return "Multiline with 2 new lines. All characters should appear"; + }, + // Automation + + pixel: {"0": 255, "1": 186, "2": 33, "3": 255}, + + getExpectedResult:function() { + + // var ret = [{"0":0,"1":0,"2":226,"3":255},{"0":47,"1":0,"2":0,"3":255},{"0":0,"1":47,"2":0,"3":255}]; + var s = director.getWinSize(); + var ret = {"left": "yes", "center": "yes", "right": "yes"}; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var s = director.getWinSize(); + var ret1 = this.readPixels(0, 0, 100, 100); + var ret2 = this.readPixels(s.width/2, s.height/2, 100, 100); + var ret3 = this.readPixels(s.width - 100, s.height - 100, 100, 100); + + var ret = {"left": this.containsPixel(ret1, this.pixel) ? "yes" : "no", + "center": this.containsPixel(ret2, this.pixel) ? "yes" : "no", + "right": this.containsPixel(ret3, this.pixel) ? "yes" : "no"} + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// LabelsEmpty +// +//------------------------------------------------------------------ +var LabelsEmpty = AtlasDemo.extend({ + setEmpty:null, + ctor:function () { + //----start25----ctor + this._super(); + + + // cc.LabelBMFont + var label1 = new cc.LabelBMFont("", s_resprefix + "fonts/bitmapFontTest3.fnt"); + this.addChild(label1, 0, TAG_BITMAP_ATLAS1); + label1.x = winSize.width / 2; + label1.y = winSize.height - 100; + + // cc.LabelTTF + var label2 = new cc.LabelTTF("", "Arial", 24); + this.addChild(label2, 0, TAG_BITMAP_ATLAS2); + label2.x = winSize.width / 2; + label2.y = winSize.height / 2; + + // cc.LabelAtlas + var label3 = new cc.LabelAtlas("", s_resprefix + "fonts/tuffy_bold_italic-charmap.png", 48, 64, ' '); + this.addChild(label3, 0, TAG_BITMAP_ATLAS3); + label3.x = winSize.width / 2; + label3.y = 0 + 100; + + this.schedule(this.onUpdateStrings, 1.0); + + this.setEmpty = false; + //----end25---- + }, + onUpdateStrings:function (dt) { + //----start25----onUpdateStrings + var label1 = this.getChildByTag(TAG_BITMAP_ATLAS1); + var label2 = this.getChildByTag(TAG_BITMAP_ATLAS2); + var label3 = this.getChildByTag(TAG_BITMAP_ATLAS3); + + if (!this.setEmpty) { + label1.setString("not empty"); + label2.setString("not empty"); + label3.setString("hi"); + + this.setEmpty = true; + } + else { + label1.setString(""); + label2.setString(""); + label3.setString(""); + + this.setEmpty = false; + } + //----end25---- + }, + title:function () { + return "Testing empty labels"; + }, + subtitle:function () { + return "3 empty labels: LabelAtlas, LabelTTF and LabelBMFont"; + } +}); + +//------------------------------------------------------------------ +// +// BMFontHDTest +// +//------------------------------------------------------------------ +var BMFontHDTest = AtlasDemo.extend({ + ctor:function () { + //----start16----ctor + this._super(); + var s = director.getWinSize(); + + // cc.LabelBMFont + var label1 = new cc.LabelBMFont("TESTING RETINA DISPLAY", s_resprefix + "fonts/konqa32.fnt"); + this.addChild(label1); + label1.x = s.width / 2; + label1.y = s.height / 2; + //----end16---- + }, + title:function () { + return "Testing Retina Display BMFont"; + }, + subtitle:function () { + return "loading arista16 or arista16-hd"; + }, + + // + // Automation + // + + pixel: {"0": 255, "1": 255, "2": 255, "3": 255}, + + getExpectedResult:function() { + + // var ret = [{"0":0,"1":0,"2":226,"3":255},{"0":47,"1":0,"2":0,"3":255},{"0":0,"1":47,"2":0,"3":255}]; + var s = director.getWinSize(); + var ret = {"center": "yes"}; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + + var s = director.getWinSize(); + var ret2 = this.readPixels(s.width/2, s.height/2, 100, 100); + + var ret = {"center": this.containsPixel(ret2, this.pixel) ? "yes" : "no"}; + + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// BMFontGlyphDesignerTest +// +//------------------------------------------------------------------ +var BMFontGlyphDesignerTest = AtlasDemo.extend({ + ctor:function () { + //----start17----ctor + this._super(); + var s = director.getWinSize(); + + var layer = new cc.LayerColor(cc.color(128, 128, 128, 255)); + this.addChild(layer, -10); + + // cc.LabelBMFont + var label1 = new cc.LabelBMFont("Testing Glyph Designer", s_resprefix + "fonts/futura-48.fnt"); + this.addChild(label1); + label1.x = s.width / 2; + label1.y = s.height / 2; + //----end17---- + }, + title:function () { + return "Testing Glyph Designer"; + }, + subtitle:function () { + return "You should see a font with shawdows and outline"; + }, + + // + // Automation + // + + pixel: {"0": 240, "1": 201, "2": 108, "3": 255}, + + getExpectedResult:function() { + + // var ret = [{"0":0,"1":0,"2":226,"3":255},{"0":47,"1":0,"2":0,"3":255},{"0":0,"1":47,"2":0,"3":255}]; + var s = director.getWinSize(); + var ret = {"center": "yes"}; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + + var s = director.getWinSize(); + var ret2 = this.readPixels(s.width/2, s.height/2, 100, 100); + + var ret = {"center": this.containsPixel(ret2, this.pixel) ? "yes" : "no"}; + + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// LabelTTFTest +// +//------------------------------------------------------------------ + +var LabelTTFStrokeShadowTest = AtlasDemo.extend({ + _labelShadow: null, + _labelStroke: null, + _labelStrokeShadow: null, + + ctor: function () { + //----start26----ctor + this._super(); + this.updateLabels(); + //----end26---- + }, + + updateLabels: function () { + //----start26----updateLabels + var blockSize = cc.size(400, 100); + var s = director.getWinSize(); + + // colors + var redColor = cc.color(255, 0, 0); + var yellowColor = cc.color(255, 255, 0); + var blueColor = cc.color(0, 0, 255); + + // shadow offset + var shadowOffset = cc.p(12, -12); + + // positioning stuff + var posX = s.width / 2 - (blockSize.width / 2); + var posY_5 = s.height / 7; + + // font definition + var fontDefRedShadow = new cc.FontDefinition(); + fontDefRedShadow.fontName = "Arial"; + fontDefRedShadow.fontSize = 32; + fontDefRedShadow.textAlign = cc.TEXT_ALIGNMENT_CENTER; + fontDefRedShadow.verticalAlign = cc.VERTICAL_TEXT_ALIGNMENT_TOP; + fontDefRedShadow.fillStyle = redColor; + fontDefRedShadow.boundingWidth = blockSize.width; + fontDefRedShadow.boundingHeight = blockSize.height; + // shadow + fontDefRedShadow.shadowEnabled = true; + fontDefRedShadow.shadowOffsetX = shadowOffset.x; + fontDefRedShadow.shadowOffsetY = shadowOffset.y; + + // create the label using the definition + this._labelShadow = new cc.LabelTTF("Shadow Only", fontDefRedShadow); + this._labelShadow.anchorX = 0; + this._labelShadow.anchorY = 0; + this._labelShadow.x = posX; + this._labelShadow.y = posY_5; + + // font definition + var fontDefBlueStroke = new cc.FontDefinition(); + fontDefBlueStroke.fontName = "Arial"; + fontDefBlueStroke.fontSize = 32; + fontDefBlueStroke.textAlign = cc.TEXT_ALIGNMENT_CENTER; + fontDefBlueStroke.verticalAlign = cc.VERTICAL_TEXT_ALIGNMENT_TOP; + fontDefBlueStroke.fillStyle = blueColor; + fontDefBlueStroke.boundingWidth = blockSize.width; + fontDefBlueStroke.boundingHeight = blockSize.height; + // stroke + fontDefBlueStroke.strokeEnabled = true; + fontDefBlueStroke.strokeStyle = yellowColor; + + this._labelStroke = new cc.LabelTTF("Stroke Only", fontDefBlueStroke); + this._labelStroke.anchorX = 0; + this._labelStroke.anchorY = 0; + this._labelStroke.x = posX; + this._labelStroke.y = posY_5 * 2; + + // font definition + var fontDefRedStrokeShadow = new cc.FontDefinition(); + fontDefRedStrokeShadow.fontName = "Arial"; + fontDefRedStrokeShadow.fontSize = 32; + fontDefRedStrokeShadow.textAlign = cc.TEXT_ALIGNMENT_CENTER; + fontDefRedStrokeShadow.verticalAlign = cc.VERTICAL_TEXT_ALIGNMENT_TOP; + fontDefRedStrokeShadow.fillStyle = blueColor; + fontDefRedStrokeShadow.boundingWidth = blockSize.width; + fontDefRedStrokeShadow.boundingHeight = blockSize.height; + // stroke + fontDefRedStrokeShadow.strokeEnabled = true; + fontDefRedStrokeShadow.strokeStyle = redColor; + // shadow + fontDefRedStrokeShadow.shadowEnabled = true; + fontDefRedStrokeShadow.shadowOffsetX = -12; + fontDefRedStrokeShadow.shadowOffsetY = 12; //shadowOffset; + + this._labelStrokeShadow = new cc.LabelTTF("Stroke + Shadow\n New Line", fontDefRedStrokeShadow); + this._labelStrokeShadow.anchorX = 0; + this._labelStrokeShadow.anchorY = 0; + this._labelStrokeShadow.x = posX; + this._labelStrokeShadow.y = posY_5 * 3; + + // add all the labels + this.addChild(this._labelShadow); + this.addChild(this._labelStroke); + this.addChild(this._labelStrokeShadow); + //----end26---- + }, + + title: function () { + return "Testing cc.LabelTTF + shadow and stroke"; + }, + + subtitle: function () { + return ""; + } +}); + +var LabelTTFTest = AtlasDemo.extend({ + _label:null, + _horizAlign:null, + _vertAlign:null, + ctor:function () { + //----start19----ctor + this._super(); + var blockSize = cc.size(200, 160); + var s = director.getWinSize(); + + var colorLayer = new cc.LayerColor(cc.color(100, 100, 100, 255), blockSize.width, blockSize.height); + colorLayer.anchorX = 0; + colorLayer.anchorY = 0; + colorLayer.x = (s.width - blockSize.width) / 2; + colorLayer.y = (s.height - blockSize.height) / 2; + + this.addChild(colorLayer); + + cc.MenuItemFont.setFontSize(30); + var menu = new cc.Menu( + new cc.MenuItemFont("Left", this.setAlignmentLeft, this), + new cc.MenuItemFont("Center", this.setAlignmentCenter, this), + new cc.MenuItemFont("Right", this.setAlignmentRight, this)); + menu.alignItemsVerticallyWithPadding(4); + menu.x = 50; + menu.y = s.height / 2 - 20; + this.addChild(menu); + + menu = new cc.Menu( + new cc.MenuItemFont("Top", this.setAlignmentTop, this), + new cc.MenuItemFont("Middle", this.setAlignmentMiddle, this), + new cc.MenuItemFont("Bottom", this.setAlignmentBottom, this)); + menu.alignItemsVerticallyWithPadding(4); + menu.x = s.width - 50; + menu.y = s.height / 2 - 20; + this.addChild(menu); + + this._label = null; + this._horizAlign = cc.TEXT_ALIGNMENT_LEFT; + this._vertAlign = cc.VERTICAL_TEXT_ALIGNMENT_TOP; + + this.updateAlignment(); + //----end19---- + }, + updateAlignment:function () { + //----start19----updateAlignment + var blockSize = cc.size(200, 160); + var s = director.getWinSize(); + + if (this._label) { + this._label.removeFromParent(); + } + + this._label = new cc.LabelTTF(this.getCurrentAlignment(), "Arial", 32, blockSize, this._horizAlign, this._vertAlign); + + this._label.anchorX = 0; + this._label.anchorY = 0; + this._label.x = (s.width - blockSize.width) / 2; + this._label.y = (s.height - blockSize.height) / 2; + + this.addChild(this._label); + //----end19---- + }, + setAlignmentLeft:function (sender) { + this._horizAlign = cc.TEXT_ALIGNMENT_LEFT; + this.updateAlignment(); + }, + setAlignmentCenter:function (sender) { + this._horizAlign = cc.TEXT_ALIGNMENT_CENTER; + this.updateAlignment(); + }, + setAlignmentRight:function (sender) { + this._horizAlign = cc.TEXT_ALIGNMENT_RIGHT; + this.updateAlignment(); + }, + setAlignmentTop:function (sender) { + this._vertAlign = cc.VERTICAL_TEXT_ALIGNMENT_TOP; + this.updateAlignment(); + }, + setAlignmentMiddle:function (sender) { + this._vertAlign = cc.VERTICAL_TEXT_ALIGNMENT_CENTER; + this.updateAlignment(); + }, + setAlignmentBottom:function (sender) { + this._vertAlign = cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM; + this.updateAlignment(); + }, + getCurrentAlignment:function () { + //----start19----getCurrentAlignment + var vertical = null; + var horizontal = null; + switch (this._vertAlign) { + case cc.VERTICAL_TEXT_ALIGNMENT_TOP: + vertical = "Top"; + break; + case cc.VERTICAL_TEXT_ALIGNMENT_CENTER: + vertical = "Middle"; + break; + case cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM: + vertical = "Bottom"; + break; + } + switch (this._horizAlign) { + case cc.TEXT_ALIGNMENT_LEFT: + horizontal = "Left"; + break; + case cc.TEXT_ALIGNMENT_CENTER: + horizontal = "Center"; + break; + case cc.TEXT_ALIGNMENT_RIGHT: + horizontal = "Right"; + break; + } + + return "Alignment " + vertical + " " + horizontal; + //----end19---- + }, + title:function () { + return "Testing cc.LabelTTF"; + }, + subtitle:function () { + return "Select the buttons on the sides to change alignment"; + } +}); + +var LabelTTFMultiline = AtlasDemo.extend({ + ctor:function () { + //----start20----ctor + this._super(); + var s = director.getWinSize(); + + // cc.LabelBMFont + var center = new cc.LabelTTF("word wrap \"testing\" (bla0) bla1 'bla2' [bla3] (bla4) {bla5} {bla6} [bla7] (bla8) [bla9] 'bla0' \"bla1\"", + "Arial", 32, cc.size(s.width / 2, 200), cc.TEXT_ALIGNMENT_CENTER, cc.VERTICAL_TEXT_ALIGNMENT_TOP); + center.setDimensions(s.width / 2, 200); + center.x = s.width / 2; + center.y = 150; + + this.addChild(center); + //----end20---- + }, + title:function () { + return "Testing cc.LabelTTF Word Wrap"; + }, + subtitle:function () { + return "Word wrap using cc.LabelTTF"; + }, + + // + // Automation + // + + pixel: {"0": 255, "1": 255, "2": 255, "3": 255}, + + getExpectedResult:function() { + + // var ret = [{"0":0,"1":0,"2":226,"3":255},{"0":47,"1":0,"2":0,"3":255},{"0":0,"1":47,"2":0,"3":255}]; + var s = director.getWinSize(); + var ret = {"center": "yes"}; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + + var s = director.getWinSize(); + var ret2 = this.readPixels(s.width/2, 125, 100, 100); + + var ret = {"center": this.containsPixel(ret2, this.pixel) ? "yes" : "no"}; + + return JSON.stringify(ret); + } +}); + +var LabelTTFChinese = AtlasDemo.extend({ + ctor:function () { + //----start21----ctor + this._super(); + var size = director.getWinSize(); + var fontname = (cc.sys.os === cc.sys.OS_WP8 ) ? "fonts/arialuni.ttf" : (cc.sys.os == cc.sys.OS_WINRT) ? "DengXian" : "Microsoft Yahei"; + var label = new cc.LabelTTF("中国", fontname, 30); + label.x = size.width / 2; + label.y = size.height / 3 * 2; + this.addChild(label); + + // Test UTF8 string from native to jsval. + var label2 = new cc.LabelTTF("string from native:"+label.getString(), fontname, 30); + label2.x = size.width / 2; + label2.y = size.height / 3; + this.addChild(label2); + //----end21---- + }, + title:function () { + return "Testing cc.LabelTTF with Chinese character"; + } +}); + +var BMFontChineseTest = AtlasDemo.extend({ + ctor:function () { + //----start18----ctor + this._super(); + var size = director.getWinSize(); + var label = new cc.LabelBMFont("中国", s_resprefix + "fonts/bitmapFontChinese.fnt"); + label.x = size.width / 2; + label.y = size.height / 2; + this.addChild(label); + //----end18---- + }, + title:function () { + return "Testing cc.LabelBMFont with Chinese character"; + }, + + // + // Automation + // + + pixel: {"0": 255, "1": 0, "2": 142, "3": 255}, + + getExpectedResult:function() { + + // var ret = [{"0":0,"1":0,"2":226,"3":255},{"0":47,"1":0,"2":0,"3":255},{"0":0,"1":47,"2":0,"3":255}]; + var s = director.getWinSize(); + var ret = {"center": "yes"}; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + + var s = director.getWinSize(); + var ret2 = this.readPixels(s.width/2, s.height / 2, 100, 100); + + var ret = {"center": this.containsPixel(ret2, this.pixel) ? "yes" : "no"}; + + return JSON.stringify(ret); + } +}); + +var LongSentencesExample = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; +var chineseExampleText = "美好的一天美好的一天美好的一天美好的一天美好的一天美好的一天美好的一天美好的一天美好的一天美好的一天美好的一天"; +var chineseMixEnglishText = "美好的一天bdgpy美b好b的d一b天d美好bd的p一g天美好b的d一d天bdgpybdgpybdgpybdg美好的一天bdgpy美好的一天美好的一天"; +var mixAllLanguageText = "美好良い一日を一Buen díabdgpy美b好b的d一b天d美Buen い一日を好b的d一d天Buen py美好的一天bdgpy美好的一天美好的一天"; +var LineBreaksExample = "Lorem ipsum dolor\nsit amet\nconsectetur adipisicing elit\nblah\nblah"; +var MixedExample = "ABC\nLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt\nDEF"; + +var ArrowsMax = 0.95; +var ArrowsMin = 0.7; + +var LeftAlign = 0; +var CenterAlign = 1; +var RightAlign = 2; + +var LongSentences = 0; +var LineBreaks = 1; +var Mixed = 2; +var chineseText = 3; +var chineseMixEnglish = 4; +var mixAllLanguage = 5; + +var alignmentItemPadding = 40; +var menuItemPaddingCenter = 80; + +var BMFontMultiLineAlignmentTest = AtlasDemo.extend({ + labelShouldRetain:null, + arrowsBarShouldRetain:null, + arrowsShouldRetain:null, + lastSentenceItem:null, + lastAlignmentItem:null, + lineBreakFlag:false, + ctor:function () { + //----start11----ctor + this._super(); + + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesBegan: this.onTouchesBegan.bind(this), + onTouchesMoved: this.onTouchesMoved.bind(this), + onTouchesEnded: this.onTouchesEnded.bind(this) + }, this); + if ('touches' in cc.sys.capabilities){ + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesBegan: this.onTouchesBegan.bind(this), + onTouchesMoved: this.onTouchesMoved.bind(this), + onTouchesEnded: this.onTouchesEnded.bind(this) + }, this); + } else if ('mouse' in cc.sys.capabilities) + cc.eventManager.addListener({ + event: cc.EventListener.MOUSE, + onMouseDown: this.onMouseDown.bind(this), + onMouseMove: this.onMouseMove.bind(this), + onMouseUp: this.onMouseUp.bind(this) + }, this); + + // ask director the the window size + var size = director.getWinSize(); + + // create and initialize a Label + this.labelShouldRetain = new cc.LabelBMFont(LongSentencesExample, s_resprefix + "fonts/markerFelt.fnt", size.width / 2, cc.TEXT_ALIGNMENT_CENTER, cc.p(0, 0)); + this.arrowsBarShouldRetain = new cc.Sprite(s_resprefix + "Images/arrowsBar.png"); + this.arrowsShouldRetain = new cc.Sprite(s_resprefix + "Images/arrows.png"); + + cc.MenuItemFont.setFontSize(20); + var longSentences = new cc.MenuItemFont("Long Flowing Sentences", this.onStringChanged, this); + var lineBreaks = new cc.MenuItemFont("Short Sentences With Intentional Line Breaks", this.onStringChanged, this); + var mixed = new cc.MenuItemFont("Long Sentences Mixed With Intentional Line Breaks", this.onStringChanged.bind(this)); // another way to pass 'this' + var changeChineseItem = new cc.MenuItemFont("change chinese", this.onStringChanged, this); + var mixEnglishItem = new cc.MenuItemFont("change chinesemixEnglish", this.onStringChanged, this); + var mixAllLanItem = new cc.MenuItemFont("change mixAllLan", this.onStringChanged, this); + + var stringMenu = new cc.Menu(longSentences, lineBreaks, mixed, changeChineseItem,mixEnglishItem, mixAllLanItem); + stringMenu.alignItemsVertically(); + + var setLineBreakItem = new cc.MenuItemFont("setLineBreakWithoutSpace", this.onLineBreakChanged, this); + var setScale = new cc.MenuItemFont("setScale", this.onScaleChange, this); + var lineBreakMenu = new cc.Menu(setLineBreakItem, setScale); + lineBreakMenu.x = 100; + lineBreakMenu.y = winSize.height / 2; + lineBreakMenu.alignItemsVertically(); + + longSentences.color = cc.color(255, 0, 0); + this.lastSentenceItem = longSentences; + longSentences.tag = LongSentences; + lineBreaks.tag = LineBreaks; + mixed.tag = Mixed; + changeChineseItem.tag = chineseText; + mixEnglishItem.tag = chineseMixEnglish; + mixAllLanItem.tag = mixAllLanguage; + + cc.MenuItemFont.setFontSize(30); + + var left = new cc.MenuItemFont("Left", this.onAlignmentChanged, this); + var center = new cc.MenuItemFont("Center", this.onAlignmentChanged, this); + var right = new cc.MenuItemFont("Right", this.onAlignmentChanged.bind(this)); // another way to pass 'this' + var alignmentMenu = new cc.Menu(left, center, right); + alignmentMenu.alignItemsHorizontallyWithPadding(alignmentItemPadding); + + center.color = cc.color(255, 0, 0); + this.lastAlignmentItem = center; + left.tag = LeftAlign; + center.tag = CenterAlign; + right.tag = RightAlign; + + // position the label on the center of the screen + this.labelShouldRetain.x = size.width / 2; + this.labelShouldRetain.y = size.height / 2; + + this.arrowsBarShouldRetain.visible = false; + + var arrowsWidth = (ArrowsMax - ArrowsMin) * size.width; + this.arrowsBarShouldRetain.scaleX = arrowsWidth / this.arrowsBarShouldRetain.width; + this.arrowsBarShouldRetain.anchorX = 0; + this.arrowsBarShouldRetain.anchorY = 0.5; + this.arrowsBarShouldRetain.x = ArrowsMin * size.width; + this.arrowsBarShouldRetain.y = this.labelShouldRetain.y; + + this.arrowsShouldRetain.x = this.arrowsBarShouldRetain.x; + this.arrowsShouldRetain.y = this.arrowsBarShouldRetain.y; + + stringMenu.x = size.width / 2; + stringMenu.y = size.height - menuItemPaddingCenter; + alignmentMenu.x = size.width / 2; + alignmentMenu.y = menuItemPaddingCenter + 15; + + this.addChild(this.labelShouldRetain); + this.addChild(this.arrowsBarShouldRetain); + this.addChild(this.arrowsShouldRetain); + this.addChild(stringMenu); + this.addChild(alignmentMenu); + this.addChild(lineBreakMenu); + + + //----end11---- + }, + __title: function(){ + return 'The scroll bar'; + }, + title:function () { + return ""; + }, + subtitle:function () { + return ""; + }, + + onScaleChange:function(sener){ + if (this.labelShouldRetain.getScale() > 1) + { + this.labelShouldRetain.setScale(1.0); + } + else + { + this.labelShouldRetain.setScale(2.0); + } + + }, + onLineBreakChanged:function(sender){ + this.lineBreakFlag = !this.lineBreakFlag; + this.labelShouldRetain.setLineBreakWithoutSpace(this.lineBreakFlag); + }, + onStringChanged:function (sender) { + this.lastSentenceItem.color = cc.color(255, 255, 255); + sender.color = cc.color(255, 0, 0); + this.lastSentenceItem = sender; + + switch (sender.tag) { + case LongSentences: + this.labelShouldRetain.setString(LongSentencesExample); + this.labelShouldRetain.setFntFile(s_resprefix + "fonts/markerFelt.fnt"); + break; + case LineBreaks: + this.labelShouldRetain.setString(LineBreaksExample); + this.labelShouldRetain.setFntFile(s_resprefix + "fonts/markerFelt.fnt"); + break; + case Mixed: + this.labelShouldRetain.setString(MixedExample); + this.labelShouldRetain.setFntFile(s_resprefix + "fonts/markerFelt.fnt"); + break; + case chineseText: + this.labelShouldRetain.setFntFile(s_resprefix + "fonts/arial-unicode-26.fnt"); + this.labelShouldRetain.setString(chineseExampleText); + break; + case chineseMixEnglish: + this.labelShouldRetain.setFntFile(s_resprefix + "fonts/arial-unicode-26.fnt"); + this.labelShouldRetain.setString(chineseMixEnglishText); + break; + case mixAllLanguage: + this.labelShouldRetain.setFntFile(s_resprefix + "fonts/arial-unicode-26.fnt"); + this.labelShouldRetain.setString(mixAllLanguageText); + break; + default: + break; + } + + this.snapArrowsToEdge(); + }, + onAlignmentChanged:function (sender) { + var item = sender; + this.lastAlignmentItem.color = cc.color(255, 255, 255); + item.color = cc.color(255, 0, 0); + this.lastAlignmentItem = item; + + switch (item.tag) { + case LeftAlign: + this.labelShouldRetain.textAlign = cc.TEXT_ALIGNMENT_LEFT; + break; + case CenterAlign: + this.labelShouldRetain.textAlign = cc.TEXT_ALIGNMENT_CENTER; + break; + case RightAlign: + this.labelShouldRetain.textAlign = cc.TEXT_ALIGNMENT_RIGHT; + break; + default: + break; + } + + this.snapArrowsToEdge(); + }, + onTouchesBegan:function (touches) { + var touch = touches[0]; + var location = touch.getLocation(); + + if (cc.rectContainsPoint(this.arrowsShouldRetain.getBoundingBox(), location)) { + this.arrowsBarShouldRetain.visible = true; + } + }, + onTouchesEnded:function () { + this.arrowsBarShouldRetain.visible = false; + }, + onTouchesMoved:function (touches) { + var touch = touches[0]; + var location = touch.getLocation(); + + var winSize = director.getWinSize(); + + this.arrowsShouldRetain.x = Math.max(Math.min(location.x, ArrowsMax * winSize.width), ArrowsMin * winSize.width); + + this.labelShouldRetain.boundingWidth = Math.abs(this.arrowsShouldRetain.getPosition().x - this.labelShouldRetain.getPosition().x) * 2; + }, + + onMouseDown:function (event) { + var location = event.getLocation(); + + if (cc.rectContainsPoint(this.arrowsShouldRetain.getBoundingBox(), location)) { + this.arrowsBarShouldRetain.visible = true; + } + }, + onMouseMove:function (event) { + if(!event.getButton || event.getButton() != cc.EventMouse.BUTTON_LEFT) + return; + + var location = event.getLocation(); + var winSize = director.getWinSize(); + + this.arrowsShouldRetain.x = Math.max(Math.min(location.x, ArrowsMax * winSize.width), ArrowsMin * winSize.width); + this.labelShouldRetain.boundingWidth = Math.abs(this.arrowsShouldRetain.x - this.labelShouldRetain.x) * 2; + }, + onMouseUp:function (event) { + //this.snapArrowsToEdge(); + this.arrowsBarShouldRetain.visible = false; + }, + + snapArrowsToEdge:function () { + var winSize = director.getWinSize(); + this.arrowsShouldRetain.x = ArrowsMin * winSize.width; + this.arrowsShouldRetain.y = this.arrowsBarShouldRetain.y; + } +}); + +/// LabelTTFA8Test +var LabelTTFA8Test = AtlasDemo.extend({ + ctor:function () { + //----start22----ctor + this._super(); + var s = director.getWinSize(); + + var layer = new cc.LayerColor(cc.color(128, 128, 128, 255)); + this.addChild(layer, -10); + + // cc.LabelBMFont + var label1 = new cc.LabelTTF("Testing A8 Format", "Arial", 48); + this.addChild(label1); + label1.color = cc.color(255, 0, 0); + label1.x = s.width / 2; + label1.y = s.height / 2; + + var fadeOut = cc.fadeOut(2); + var fadeIn = cc.fadeIn(2); + var seq = cc.sequence(fadeOut, fadeIn); + var forever = seq.repeatForever(); + label1.runAction(forever); + //----end22---- + }, + title:function () { + return "Testing A8 Format"; + }, + subtitle:function () { + return "RED label, fading In and Out in the center of the screen"; + } +}); + +/// BMFontOneAtlas +var BMFontOneAtlas = AtlasDemo.extend({ + ctor:function () { + //----start12----ctor + this._super(); + var s = director.getWinSize(); + + var label1 = new cc.LabelBMFont("This is Helvetica", s_resprefix + "fonts/helvetica-32.fnt", cc.LabelAutomaticWidth, cc.TEXT_ALIGNMENT_LEFT, cc.p(0, 0)); + this.addChild(label1); + label1.x = s.width / 2; + label1.y = s.height * 2 / 3; + + var label2 = new cc.LabelBMFont("And this is Geneva", s_resprefix + "fonts/geneva-32.fnt", cc.LabelAutomaticWidth, cc.TEXT_ALIGNMENT_LEFT, cc.p(0, 128)); + this.addChild(label2); + label2.x = s.width / 2; + label2.y = s.height / 3; + //----end12---- + }, + + title:function () { + return "cc.LabelBMFont with one texture"; + }, + + subtitle:function () { + return "Using 2 .fnt definitions that share the same texture atlas."; + } +}); + +/// BMFontUnicode +var BMFontUnicode = AtlasDemo.extend({ + ctor:function () { + //----start13----ctor + this._super(); + var chinese = "美好的一天"; + var japanese = "良い一日を"; + var spanish = "Buen día"; + + var label1 = new cc.LabelBMFont(spanish, s_resprefix + "fonts/arial-unicode-26.fnt", 200, cc.TEXT_ALIGNMENT_LEFT); + this.addChild(label1); + label1.x = winSize.width / 2; + label1.y = winSize.height / 4; + + var label2 = new cc.LabelBMFont(chinese, s_resprefix + "fonts/arial-unicode-26.fnt"); + this.addChild(label2); + label2.x = winSize.width / 2; + label2.y = winSize.height / 2.2; + + var label3 = new cc.LabelBMFont(japanese, s_resprefix + "fonts/arial-unicode-26.fnt"); + this.addChild(label3); + label3.x = winSize.width / 2; + label3.y = winSize.height / 1.5; + //----end13---- + }, + title:function () { + return "cc.LabelBMFont with Unicode support"; + }, + subtitle:function () { + return "You should see 3 different labels: In Spanish, Chinese and Korean"; + } +}); + +// BMFontInit +var BMFontInit = AtlasDemo.extend({ + ctor:function () { + //----start14----ctor + this._super(); + + var bmFont = new cc.LabelBMFont(); + bmFont.setFntFile(s_resprefix + "fonts/helvetica-32.fnt"); + bmFont.setString("It is working!"); + this.addChild(bmFont); + bmFont.x = winSize.width / 2; + bmFont.y = winSize.height / 2; + //----end14---- + }, + title:function () { + return "cc.LabelBMFont init"; + }, + subtitle:function () { + return "Test for support of init method without parameters."; + } +}); + +// LabelTTFFontInitTest +var LabelTTFFontInitTest = AtlasDemo.extend({ + ctor:function () { + //----start23----ctor + this._super(); + var font = new cc.LabelTTF(); + font.font = "48px 'Courier New'"; + //font.setFontName("Arial"); + font.string = "It is working!"; + this.addChild(font); + font.x = winSize.width / 2; + font.y = winSize.height / 2; + //----end23---- + }, + title:function () { + return "cc.LabelTTF init"; + }, + subtitle:function () { + return "Test for support of init method without parameters."; + } +}); + + +var LabelTTFAlignment = AtlasDemo.extend({ + ctor:function () { + //----start24----ctor + this._super(); + var s = director.getWinSize(); + var ttf0 = new cc.LabelTTF("Alignment 0\nnew line", "Arial", 12, cc.size(256, 32), cc.TEXT_ALIGNMENT_LEFT); + ttf0.x = s.width / 2; + ttf0.y = (s.height / 6) * 2; + ttf0.anchorX = 0.5; + ttf0.anchorY = 0.5; + this.addChild(ttf0); + + var ttf1 = new cc.LabelTTF("Alignment 1\nnew line", "Arial", 12, cc.size(256, 32), cc.TEXT_ALIGNMENT_CENTER); + ttf1.x = s.width / 2; + ttf1.y = (s.height / 6) * 3; + ttf1.anchorX = 0.5; + ttf1.anchorY = 0.5; + this.addChild(ttf1); + + var ttf2 = new cc.LabelTTF("Alignment 2\nnew line", "Arial", 12, cc.size(256, 32), cc.TEXT_ALIGNMENT_RIGHT); + ttf2.x = s.width / 2; + ttf2.y = (s.height / 6) * 4; + ttf2.anchorX = 0.5; + ttf2.anchorY = 0.5; + this.addChild(ttf2); + //----end24---- + }, + title:function () { + return "cc.LabelTTF alignment"; + }, + subtitle:function () { + return "Tests alignment values"; + }, + + // + // Automation + // + getExpectedResult:function() { + // yellow, red, green, blue, yellow + var ret = [{"r":255,"g":255,"b":0},{"r":255,"g":0,"b":0},{"r":0,"g":255,"b":0},{"r":0,"g":0,"b":255},{"r":255,"g":255,"b":0}]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = []; + for( var i=0; i<5; i++) { + var ch = this.label.getChildByTag(i).getDisplayedColor(); + ret.push(ch); + } + + return JSON.stringify(ret); + } + +}); + +var BMFontColorParentChild = AtlasDemo.extend({ + ctor:function () { + //----start15----ctor + this._super(); + + this.label = new cc.LabelBMFont("YRGB", s_resprefix + "fonts/konqa32.fnt"); + this.addChild(this.label); + this.label.x = winSize.width / 2; + this.label.y = winSize.height / 2; + this.label.color = cc.color.YELLOW; + + // R + var letter = this.label.getChildByTag(1); + letter.color = cc.color.RED; + + // G + letter = this.label.getChildByTag(2); + letter.color = cc.color.GREEN; + + // B + letter = this.label.getChildByTag(3); + letter.color = cc.color.BLUE; + + this.scheduleUpdate(); + + this.accum = 0; + //----end15---- + }, + + update:function(dt){ + //----start15----update + this.accum += dt; + + this.label.setString("YRGB " + parseInt(this.accum,10).toString() ); + //----end15---- + }, + + title:function () { + return "cc.LabelBMFont color parent / child"; + }, + subtitle:function () { + return "Yellow Red Green Blue and numbers in Yellow"; + }, + + // + // Automation + // + getExpectedResult:function() { + // yellow, red, green, blue, yellow + var ret = [{"r":255,"g":255,"b":0},{"r":255,"g":0,"b":0},{"r":0,"g":255,"b":0},{"r":0,"g":0,"b":255},{"r":255,"g":255,"b":0}]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = []; + for( var i=0; i<5; i++) { + var ch = this.label.getChildByTag(i).getDisplayedColor(); + ret.push(ch); + } + + return JSON.stringify(ret); + } +}); + +var WrapAlgorithmTest = AtlasDemo.extend({ + ctor: function(){ + this._super(); + var self = this; + + var normalText = [ + "这里是中文测试例", + "测试带有符号,换行", + "测试中带有符号,换行", + "", + "Here is the English test", + "aaaaaaaaaaaaaaaaa", + "test test test aaa, tt", + "test test test aa, tt", + "こは日本語テスト", + "符号のテストに,ついて" + ]; + + normalText.forEach(function(text, i){ + var LabelTTF = new cc.LabelTTF(); + LabelTTF.setString(text); + LabelTTF.setPosition(30 + 150 * (i/4|0), 300 - (i%4) * 60); + LabelTTF.setAnchorPoint(0,1); + LabelTTF.boundingWidth = 120; + LabelTTF.boundingHeight = 0; + LabelTTF.enableStroke(cc.color(0, 0, 0, 1), 3.0); + if (cc.sys.os === cc.sys.OS_WP8) + LabelTTF.setFontName("fonts/arialuni.ttf"); + else if(cc.sys.os === cc.sys.OS_WINRT) + LabelTTF.setFontName("DengXian"); + self.addChild(LabelTTF); + }); + + //Extreme test + var extremeText = [ + "测", + "\n", + "\r\n", + "、", + ",", + "W", + "7" + ]; + + extremeText.forEach(function(text, i){ + var LabelTTF = new cc.LabelTTF(); + LabelTTF.setString(text); + LabelTTF.setPosition(480 + i * 25, 300); + LabelTTF.setAnchorPoint(0,1); + LabelTTF.boundingWidth = 3; + LabelTTF.boundingHeight = 0; + LabelTTF.enableStroke(cc.color(0, 0, 0, 1), 3.0); + if (cc.sys.os === cc.sys.OS_WP8) + LabelTTF.setFontName("fonts/arialuni.ttf"); + else if(cc.sys.os === cc.sys.OS_WINRT) + LabelTTF.setFontName("DengXian"); + self.addChild(LabelTTF); + }); + + //Combinatorial testing + var combinatorialText = [ + "中英混排English", + "中日混排テスト", + "日本語テストEnglish" + ]; + + combinatorialText.forEach(function(text, i){ + var LabelTTF = new cc.LabelTTF(); + LabelTTF.setString(text); + LabelTTF.setPosition(480 + 100 * (i/3|0), 240 - (i%3) * 60); + LabelTTF.setAnchorPoint(0,1); + LabelTTF.boundingWidth = 90; + LabelTTF.boundingHeight = 0; + LabelTTF.enableStroke(cc.color(0, 0, 0, 1), 3.0); + if (cc.sys.os === cc.sys.OS_WP8) + LabelTTF.setFontName("fonts/arialuni.ttf"); + else if(cc.sys.os === cc.sys.OS_WINRT) + LabelTTF.setFontName("DengXian"); + self.addChild(LabelTTF); + }); + + }, + title: function(){ + return "Wrap algorithm test"; + }, + subtitle: function(){ + return "Wrap effect under various circumstances"; + }, + onEnter: function(){ + this._super(); + cc.SPRITE_DEBUG_DRAW = 1; + }, + onExit: function(){ + this._super(); + cc.SPRITE_DEBUG_DRAW = 0; + } +}); + +// +// Flow control +// +var arrayOfLabelTest = [ + LabelAtlasOpacityTest, + LabelAtlasOpacityColorTest, + LabelAtlasHD, + + BMFontOpacityColorAlignmentTest, + BMFontSubSpriteTest, + BMFontPaddingTest, + BMFontOffsetTest, + BMFontTintTest, + BMFontSpeedTest, + BMFontMultiLineTest, + BMFontMultiLine2Test, + BMFontMultiLineAlignmentTest, + BMFontOneAtlas, + BMFontUnicode, + BMFontInit, + BMFontColorParentChild, + BMFontHDTest, + BMFontGlyphDesignerTest, + BMFontChineseTest, + + LabelTTFTest, + LabelTTFMultiline, + LabelTTFChinese, + LabelTTFA8Test, + LabelTTFFontInitTest, + LabelTTFAlignment, + + LabelsEmpty, + LabelTTFStrokeShadowTest +]; + +if (!cc.sys.isNative || cc.sys.isMobile) { + arrayOfLabelTest.push(WrapAlgorithmTest); +} + +var nextLabelTest = function () { + labelTestIdx++; + labelTestIdx = labelTestIdx % arrayOfLabelTest.length; + + if(window.sideIndexBar){ + labelTestIdx = window.sideIndexBar.changeTest(labelTestIdx, 19); + } + + return new arrayOfLabelTest[labelTestIdx](); +}; +var previousLabelTest = function () { + labelTestIdx--; + if (labelTestIdx < 0) + labelTestIdx += arrayOfLabelTest.length; + + if(window.sideIndexBar){ + labelTestIdx = window.sideIndexBar.changeTest(labelTestIdx, 19); + } + + return new arrayOfLabelTest[labelTestIdx](); +}; +var restartLabelTest = function () { + return new arrayOfLabelTest[labelTestIdx](); +}; diff --git a/tests/js-tests/src/LayerTest/LayerTest.js b/tests/js-tests/src/LayerTest/LayerTest.js new file mode 100644 index 0000000000..6d129c6b3c --- /dev/null +++ b/tests/js-tests/src/LayerTest/LayerTest.js @@ -0,0 +1,579 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +cc.TAG_LAYER = 1; + +var layerTestSceneIdx = -1; +var LAYERTEST2_LAYER1_TAG = 1; +var LAYERTEST2_LAYER2_TAG = 2; + +var LayerTestScene = TestScene.extend({ + runThisTest:function (num) { + layerTestSceneIdx = (num || num == 0) ? (num - 1) : -1; + this.addChild(nextLayerTest()); + director.runScene(this); + } +}); + +//------------------------------------------------------------------ +// +// LayerTest +// +//------------------------------------------------------------------ +var LayerTest = BaseTestLayer.extend({ + _title:null, + + + title:function () { + return "No title"; + }, + subtitle:function () { + return ""; + }, + + onRestartCallback:function (sender) { + var s = new LayerTestScene(); + s.addChild(restartLayerTest()); + director.runScene(s); + + }, + onNextCallback:function (sender) { + var s = new LayerTestScene(); + s.addChild(nextLayerTest()); + director.runScene(s); + + }, + onBackCallback:function (sender) { + var s = new LayerTestScene(); + s.addChild(previousLayerTest()); + director.runScene(s); + + }, + // automation + numberOfPendingTests:function() { + return ( (arrayOfLayerTest.length-1) - layerTestSceneIdx ); + }, + + getTestNumber:function() { + return layerTestSceneIdx; + } + +}); + +//------------------------------------------------------------------ +// +// LayerTest1 +// +//------------------------------------------------------------------ +var LayerTest1 = LayerTest.extend({ + onEnter:function () { + //----start0----onEnter + this._super(); + + if( 'touches' in cc.sys.capabilities ) + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesMoved:function (touches, event) { + event.getCurrentTarget().updateSize(touches[0].getLocation()); + } + }, this); + else if ('mouse' in cc.sys.capabilities ) + cc.eventManager.addListener({ + event: cc.EventListener.MOUSE, + onMouseMove: function(event){ + if(event.getButton() == cc.EventMouse.BUTTON_LEFT) + event.getCurrentTarget().updateSize(event.getLocation()); + } + }, this); + + var s = director.getWinSize(); + var layer = new cc.LayerColor(cc.color(255, 0, 0, 128)); + + layer.ignoreAnchor = false; + layer.anchorX = 0.5; + layer.anchorY = 0.5; + layer.setContentSize(200, 200); + layer.x = s.width / 2; + layer.y = s.height / 2; + this.addChild(layer, 1, cc.TAG_LAYER); + //----end0---- + }, + title:function () { + return "ColorLayer resize (tap & move)"; + }, + + updateSize:function (location) { + //----start0----updateSize + var l = this.getChildByTag(cc.TAG_LAYER); + + l.width = Math.abs(location.x - winSize.width / 2) * 2; + l.height = Math.abs(location.y - winSize.height / 2) * 2; + //----end0---- + }, + + // + // Automation + // + pixel: {"0": 190, "1": 0, "2": 0, "3": 128}, + + getExpectedResult:function() { + + var s = director.getWinSize(); + var ret = {"center": "yes"}; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + + var s = director.getWinSize(); + var ret2 = this.readPixels(s.width/2, s.height/2, 5, 5); + var ret = {"center": this.containsPixel(ret2, this.pixel, true, 100) ? "yes" : "no"}; + + return JSON.stringify(ret); + } +}); + +var IgnoreAnchorpointTest1 = LayerTest.extend({ + onEnter:function () { + //----start3----onEnter + this._super(); + //create layer + var ws = director.getWinSize(); + var layer1 = new cc.LayerColor(cc.color(255, 100, 100, 128), ws.width / 2, ws.height / 2); + layer1.ignoreAnchorPointForPosition(true); + var layer2 = new cc.LayerColor(cc.color(100, 255, 100, 128), ws.width / 4, ws.height / 4); + layer2.ignoreAnchorPointForPosition(true); + layer1.addChild(layer2); + layer1.x = ws.width / 2; + layer1.y = ws.height / 2; + this.addChild(layer1); + //----end3---- + }, + title:function () { + return "ignore Anchorpoint Test #1"; + }, + subtitle:function () { + return "red:true green:true"; + }, + + + // + // Automation + // + + pixel1: {"0": 100, "1": 150, "2": 100, "3": 200}, + pixel2: {"0": 100, "1": 50, "2": 50, "3": 200}, + + getExpectedResult:function() { + + var s = director.getWinSize(); + var ret = {"big": "yes", "small": "yes"}; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + + var s = director.getWinSize(); + var ret2 = this.readPixels(s.width/2 + s.width/5, s.height/2 + s.height/5, 5, 5); + var ret3 = this.readPixels(s.width - 50, s.height - 50, 50, 50); + var ret = {"big": this.containsPixel(ret2, this.pixel1, true, 100) ? "yes" : "no", + "small": this.containsPixel(ret3, this.pixel2, true, 100) ? "yes" : "no"}; + + return JSON.stringify(ret); + } +}); +var IgnoreAnchorpointTest2 = LayerTest.extend({ + onEnter:function () { + //----start4----onEnter + this._super(); + //create layer + var ws = director.getWinSize(); + var layer1 = new cc.LayerColor(cc.color(255, 100, 100, 128), ws.width / 2, ws.height / 2); + layer1.ignoreAnchorPointForPosition(true); + var layer2 = new cc.LayerColor(cc.color(100, 255, 100, 128), ws.width / 4, ws.height / 4); + layer2.ignoreAnchorPointForPosition(false); + layer1.addChild(layer2); + layer1.x = ws.width / 2; + layer1.y = ws.height / 2; + this.addChild(layer1); + //----end4---- + }, + title:function () { + return "ignore Anchorpoint Test #2"; + }, + subtitle:function () { + return "red:true green:false"; + }, + + + // + // Automation + // + + pixel1: {"0": 50, "1": 100, "2": 50, "3": 200}, + pixel2: {"0": 100, "1": 50, "2": 50, "3": 200}, + + getExpectedResult:function() { + + var s = director.getWinSize(); + var ret = {"big": "yes", "small": "yes"}; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + + var s = director.getWinSize(); + var ret2 = this.readPixels(s.width/2 - 50, s.height/2 - 50, 5, 5); + var ret3 = this.readPixels(s.width - 50, s.height - 50, 5, 5); + var ret = {"big": this.containsPixel(ret2, this.pixel1, true, 100) ? "yes" : "no", + "small": this.containsPixel(ret3, this.pixel2, true, 100) ? "yes" : "no"}; + + return JSON.stringify(ret); + } +}); + +var IgnoreAnchorpointTest3 = LayerTest.extend({ + onEnter:function () { + //----start5----onEnter + this._super(); + //create layer + var ws = director.getWinSize(); + var layer1 = new cc.LayerColor(cc.color(255, 100, 100, 128), ws.width / 2, ws.height / 2); + layer1.ignoreAnchorPointForPosition(false); + var layer2 = new cc.LayerColor(cc.color(100, 255, 100, 128), ws.width / 4, ws.height / 4); + layer2.ignoreAnchorPointForPosition(false); + layer1.addChild(layer2); + layer1.x = ws.width / 2; + layer1.y = ws.height / 2; + this.addChild(layer1); + //----end5---- + }, + title:function () { + return "ignore Anchorpoint Test #3"; + }, + subtitle:function () { + return "red:false green:false"; + } +}); + +var IgnoreAnchorpointTest4 = LayerTest.extend({ + onEnter:function () { + //----start6----onEnter + this._super(); + //create layer + var ws = director.getWinSize(); + var layer1 = new cc.LayerColor(cc.color(255, 100, 100, 128), ws.width / 2, ws.height / 2); + layer1.ignoreAnchorPointForPosition(false); + var layer2 = new cc.LayerColor(cc.color(100, 255, 100, 128), ws.width / 4, ws.height / 4); + layer2.ignoreAnchorPointForPosition(true); + layer1.addChild(layer2); + layer1.x = ws.width / 2; + layer1.y = ws.height / 2; + this.addChild(layer1); + //----end6---- + }, + title:function () { + return "ignore Anchorpoint Test #4"; + }, + subtitle:function () { + return "red:false green:true"; + } + +}); + +//------------------------------------------------------------------ +// +// LayerTest2 +// +//------------------------------------------------------------------ +var LayerTest2 = LayerTest.extend({ + + onEnter:function () { + //----start1----onEnter + this._super(); + + var s = director.getWinSize(); + var layer1 = new cc.LayerColor(cc.color(255, 255, 0, 80), 100, 300); + layer1.x = s.width / 3; + layer1.y = s.height / 2; + layer1.ignoreAnchorPointForPosition(false); + this.addChild(layer1, 1, LAYERTEST2_LAYER1_TAG); + + var layer2 = new cc.LayerColor(cc.color(0, 0, 255, 255), 100, 300); + layer2.x = (s.width / 3) * 2; + layer2.y = s.height / 2; + layer2.ignoreAnchorPointForPosition(false); + this.addChild(layer2, 2, LAYERTEST2_LAYER2_TAG); + + var actionTint = cc.tintBy(2, -255, -127, 0); + var actionTintBack = actionTint.reverse(); + + var actionFade = cc.fadeOut(2.0); + var actionFadeBack = actionFade.reverse(); + + if (autoTestEnabled) { + var seq1 = cc.sequence(actionTint, cc.delayTime(0.25), actionTintBack); + var seq2 = cc.sequence(actionFade, cc.delayTime(0.25), actionFadeBack); + } else { + var seq1 = cc.sequence(actionTint, actionTintBack); + var seq2 = cc.sequence(actionFade, actionFadeBack); + } + + layer1.runAction(seq1); + layer2.runAction(seq2); + //----end1---- + }, + title:function () { + return "ColorLayer: fade and tint"; + }, + + // + // Automation + // + + testDuration: 2.1, + tintTest: {"r": 0, "g": 128, "b": 60}, + getExpectedResult:function() { + var ret = {"tint": "yes", "opacity": 0}; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var abs = function (a) { + return (a > 0) ? a : a * -1; + }; + + var inColorRange = function (pix1, pix2) { + // Color on iOS comes as 0,128,128 and on web as 0,128,0 + if (abs(pix1.r - pix2.r) < 50 && abs(pix1.g - pix2.g) < 50 && + abs(pix1.b - pix2.b) < 90) { + return true; + } + return false; + }; + var s = director.getWinSize(); + var tint = this.getChildByTag(LAYERTEST2_LAYER1_TAG).color; + var op = this.getChildByTag(LAYERTEST2_LAYER2_TAG).opacity; + var ret = {"tint": inColorRange(tint, this.tintTest) ? "yes" : "no", + "opacity": op}; + + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// LayerTestBlend +// +//------------------------------------------------------------------ +var LayerTestBlend = LayerTest.extend({ + _blend:true, + + ctor:function () { + //----start2----ctor + this._super(); + var layer1 = new cc.LayerColor(cc.color(255, 255, 255, 80)); + + var sister1 = new cc.Sprite(s_pathSister1); + var sister2 = new cc.Sprite(s_pathSister2); + + this.addChild(sister1); + this.addChild(sister2); + this.addChild(layer1, 100, cc.TAG_LAYER); + + sister1.x = winSize.width/3; + + sister1.y = winSize.height / 2; + sister2.x = winSize.width/3 * 2; + sister2.y = winSize.height / 2; + + if (!cc.sys.isNative && !("opengl" in cc.sys.capabilities)) { + var label = new cc.LabelTTF("Not supported on HTML5-canvas", "Times New Roman", 30); + this.addChild(label); + label.x = winSize.width / 2; + label.y = winSize.height / 2; + } + + this.schedule(this.onNewBlend, 1.0); + this._blend = true; + //----end2---- + }, + onNewBlend:function (dt) { + //----start2----onNewBlend + var layer = this.getChildByTag(cc.TAG_LAYER); + + var src; + var dst; + + if (this._blend) { + src = cc.SRC_ALPHA; + dst = cc.ONE_MINUS_SRC_ALPHA; + } else { + src = cc.ONE_MINUS_DST_COLOR; + dst = cc.ZERO; + } + layer.setBlendFunc( src, dst ); + this._blend = ! this._blend; + //----end2---- + }, + title:function () { + return "ColorLayer: blend"; + } +}); + +//------------------------------------------------------------------ +// +// LayerGradient +// +//------------------------------------------------------------------ +var LayerGradient = LayerTest.extend({ + _isPressed:false, + ctor:function () { + //----start7----onEnter + this._super(); + var layer1 = new cc.LayerGradient(cc.color(255, 0, 0, 255), cc.color(0, 255, 0, 255), cc.p(0.9, 0.9)); + this.addChild(layer1, 0, cc.TAG_LAYER); + + if( 'touches' in cc.sys.capabilities ){ + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesBegan:function(touches, event){ + event.getCurrentTarget().updateGradient(touches[0].getLocation()); + }, + onTouchesMoved:function (touches, event) { + event.getCurrentTarget().updateGradient(touches[0].getLocation()); + } + }, this); + } else if ('mouse' in cc.sys.capabilities ){ + cc.eventManager.addListener({ + event: cc.EventListener.MOUSE, + onMouseDown: function(event){ + event.getCurrentTarget().updateGradient(event.getLocation()); + }, + onMouseMove: function(event){ + if(event.getButton() == cc.EventMouse.BUTTON_LEFT) + event.getCurrentTarget().updateGradient(event.getLocation()); + } + }, this); + } + + var label1 = new cc.LabelTTF("Compressed Interpolation: Enabled", "Marker Felt", 26); + var label2 = new cc.LabelTTF("Compressed Interpolation: Disabled", "Marker Felt", 26); + var item1 = new cc.MenuItemLabel(label1); + var item2 = new cc.MenuItemLabel(label2); + var item = new cc.MenuItemToggle(item1, item2, this.onToggleItem, this); + + var menu = new cc.Menu(item); + this.addChild(menu); + menu.x = winSize.width / 2; + menu.y = 100; + //----end7---- + }, + + updateGradient:function(pos) { + //----start7----updateGradient + var diff = cc.pSub(cc.p(winSize.width / 2, winSize.height / 2), pos); + diff = cc.pNormalize(diff); + + var gradient = this.getChildByTag(1); + gradient.setVector(diff); + //----end7---- + }, + + onToggleItem:function (sender) { + //----start7----onToggleItem + var gradient = this.getChildByTag(cc.TAG_LAYER); + gradient.setCompressedInterpolation(!gradient.isCompressedInterpolation()); + //----end7---- + }, + + title:function () { + return "LayerGradient"; + }, + subtitle:function () { + return "Touch the screen and move your finger"; + }, + + // + // Automation + // + + pixel1: {"0": 255, "1": 0, "2": 0, "3": 255}, + pixel2: {"0": 0, "1": 255, "2": 0, "3": 255}, + + getExpectedResult:function() { + + var s = director.getWinSize(); + var ret = {"bottomleft": "yes", "topright": "yes"}; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + + var s = director.getWinSize(); + var ret2 = this.readPixels(50, 50, 50, 50); + var ret3 = this.readPixels(s.width - 50, s.height - 50, 50, 50); + var ret = {"bottomleft": this.containsPixel(ret2, this.pixel1) ? "yes" : "no", + "topright": this.containsPixel(ret3, this.pixel2) ? "yes" : "no"}; + + return JSON.stringify(ret); + } +}); + +var arrayOfLayerTest = [ + LayerTest1, + LayerTest2, + LayerGradient, + LayerTestBlend, + IgnoreAnchorpointTest1, + IgnoreAnchorpointTest2, + IgnoreAnchorpointTest3, + IgnoreAnchorpointTest4 +]; + +var nextLayerTest = function () { + layerTestSceneIdx++; + layerTestSceneIdx = layerTestSceneIdx % arrayOfLayerTest.length; + + if(window.sideIndexBar){ + layerTestSceneIdx = window.sideIndexBar.changeTest(layerTestSceneIdx, 20); + } + + return new arrayOfLayerTest[layerTestSceneIdx](); +}; +var previousLayerTest = function () { + layerTestSceneIdx--; + if (layerTestSceneIdx < 0) + layerTestSceneIdx += arrayOfLayerTest.length; + + if(window.sideIndexBar){ + layerTestSceneIdx = window.sideIndexBar.changeTest(layerTestSceneIdx, 20); + } + + return new arrayOfLayerTest[layerTestSceneIdx](); +}; +var restartLayerTest = function () { + return new arrayOfLayerTest[layerTestSceneIdx](); +}; diff --git a/tests/js-tests/src/LightTest/LightTest.js b/tests/js-tests/src/LightTest/LightTest.js new file mode 100644 index 0000000000..b4825fdca0 --- /dev/null +++ b/tests/js-tests/src/LightTest/LightTest.js @@ -0,0 +1,321 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var LightTestIdx = -1; + +var LightTestDemo = cc.Layer.extend({ + _title:"", + _subtitle:"", + + ctor:function () { + this._super(); + }, + + // + // Menu + // + onEnter:function () { + this._super(); + + var label = new cc.LabelTTF(this._title, "Arial", 28); + this.addChild(label, 100, BASE_TEST_TITLE_TAG); + label.x = winSize.width / 2; + label.y = winSize.height - 50; + + var label2 = new cc.LabelTTF(this._subtitle, "Thonburi", 16); + this.addChild(label2, 101, BASE_TEST_SUBTITLE_TAG); + label2.x = winSize.width / 2; + label2.y = winSize.height - 80; + + var item1 = new cc.MenuItemImage(s_pathB1, s_pathB2, this.onBackCallback, this); + var item2 = new cc.MenuItemImage(s_pathR1, s_pathR2, this.onRestartCallback, this); + var item3 = new cc.MenuItemImage(s_pathF1, s_pathF2, this.onNextCallback, this); + + item1.tag = BASE_TEST_MENUITEM_PREV_TAG; + item2.tag = BASE_TEST_MENUITEM_RESET_TAG; + item3.tag = BASE_TEST_MENUITEM_NEXT_TAG; + + var menu = new cc.Menu(item1, item2, item3); + + menu.x = 0; + menu.y = 0; + var width = item2.width, height = item2.height; + item1.x = winSize.width/2 - width*2; + item1.y = height/2 ; + item2.x = winSize.width/2; + item2.y = height/2 ; + item3.x = winSize.width/2 + width*2; + item3.y = height/2 ; + + this.addChild(menu, 102, BASE_TEST_MENU_TAG); + }, + + onRestartCallback:function (sender) { + var s = new LightTestScene(); + s.addChild(restartLightTest()); + director.runScene(s); + }, + + onNextCallback:function (sender) { + var s = new LightTestScene(); + s.addChild(nextLightTest()); + director.runScene(s); + }, + + onBackCallback:function (sender) { + var s = new LightTestScene(); + s.addChild(previousLightTest()); + director.runScene(s); + }, +}); + +var LightTestScene = cc.Scene.extend({ + ctor:function () { + this._super(); + + var label = new cc.LabelTTF("Main Menu", "Arial", 20); + var menuItem = new cc.MenuItemLabel(label, this.onMainMenuCallback, this); + + var menu = new cc.Menu(menuItem); + menu.x = 0; + menu.y = 0; + menuItem.x = winSize.width - 50; + menuItem.y = 25; + this.addChild(menu); + }, + onMainMenuCallback:function () { + var scene = new cc.Scene(); + var layer = new TestController(); + scene.addChild(layer); + director.runScene(scene); + }, + runThisTest:function (num) { + LightTestIdx = (num || num == 0) ? (num - 1) : -1; + var layer = nextLightTest(); + this.addChild(layer); + + director.runScene(this); + } +}); + +var LightTest = LightTestDemo.extend({ + _title:"Light Test", + _subtitle:"", + _ambientLight:null, + _directionalLight:null, + _pointLight:null, + _spotLight:null, + _ambientLightLabel:null, + _directionalLightLabel:null, + _pointLightLabel:null, + _spotLightLabel:null, + _angle:0, + + ctor:function(){ + this._super(); + + this.addSprite(); + this.addLights(); + this.scheduleUpdate(); + + var s = cc.winSize; + var camera = cc.Camera.createPerspective(60, s.width/s.height, 1, 1000); + camera.setCameraFlag(cc.CameraFlag.USER1); + camera.setPosition3D(cc.math.vec3(0, 100, 100)); + camera.lookAt(cc.math.vec3(0, 0, 0), cc.math.vec3(0, 1, 0)); + this.addChild(camera); + + this._ambientLightLabel = new cc.LabelTTF("Ambient Light ON", "Arial", 15); + var item1 = new cc.MenuItemLabel(this._ambientLightLabel, this.switchLight, this); + item1.setPosition(cc.p(100, 100 + item1.getContentSize().height * 8)); + item1.setUserData(cc.LightType.AMBIENT); + + this._directionalLightLabel = new cc.LabelTTF("Directional Light OFF", "Arial", 15); + var item2 = new cc.MenuItemLabel(this._directionalLightLabel, this.switchLight, this); + item2.setPosition(cc.p(100, 100 + item2.getContentSize().height * 6)); + item2.setUserData(cc.LightType.DIRECTIONAL); + + this._pointLightLabel = new cc.LabelTTF("Point Light OFF", "Arial", 15); + var item3 = new cc.MenuItemLabel(this._pointLightLabel, this.switchLight, this); + item3.setPosition(cc.p(100, 100 + item3.getContentSize().height * 4)); + item3.setUserData(cc.LightType.POINT); + + this._spotLightLabel = new cc.LabelTTF("Spot Light OFF", "Arial", 15); + var item4 = new cc.MenuItemLabel(this._spotLightLabel, this.switchLight, this); + item4.setPosition(cc.p(100, 100 + item4.getContentSize().height * 2)); + item4.setUserData(cc.LightType.SPOT); + + var menu = new cc.Menu(item1, item2, item3, item4); + this.addChild(menu); + menu.setPosition(cc.p(0, 0)); + + }, + + addSprite:function(){ + var s = cc.winSize; + + var orc = new jsb.Sprite3D("Sprite3DTest/orc.c3b"); + orc.setRotation3D(cc.math.vec3(0, 180, 0)); + orc.setPosition(cc.p(0, 0)); + orc.setScale(2.0); + var axe = new jsb.Sprite3D("Sprite3DTest/axe.c3b"); + orc.getAttachNode("Bip001 R Hand").addChild(axe); + var animation = jsb.Animation3D.create("Sprite3DTest/orc.c3b"); + if(animation){ + var animate = jsb.Animate3D.create(animation); + orc.runAction(cc.repeatForever(animate)); + } + this.addChild(orc); + orc.setCameraMask(2); + + var sphere1 = new jsb.Sprite3D("Sprite3DTest/sphere.c3b"); + sphere1.setPosition(cc.p(30, 0)); + this.addChild(sphere1); + sphere1.setCameraMask(2); + + var sphere2 = new jsb.Sprite3D("Sprite3DTest/sphere.c3b"); + sphere2.setPosition(cc.p(-50, 0)); + sphere2.setScale(0.5); + this.addChild(sphere2); + sphere2.setCameraMask(2); + + var sphere3 = new jsb.Sprite3D("Sprite3DTest/sphere.c3b"); + sphere3.setPosition(cc.p(-30, 0)); + sphere3.setScale(0.5); + this.addChild(sphere3); + sphere3.setCameraMask(2); + }, + + addLights:function(){ + this._ambientLight = jsb.AmbientLight.create(cc.color(200, 200, 200)); + this._ambientLight.setEnabled(true); + this.addChild(this._ambientLight); + this._ambientLight.setCameraMask(2); + + this._directionalLight = jsb.DirectionLight.create(cc.math.vec3(-1, -1, 0), cc.color(200, 200, 200)); + this._directionalLight.setEnabled(false); + this.addChild(this._directionalLight); + this._directionalLight.setCameraMask(2); + + this._pointLight = jsb.PointLight.create(cc.math.vec3(0, 0, 0), cc.color(200, 200, 200), 10000); + this._pointLight.setEnabled(false); + this.addChild(this._pointLight); + this._pointLight.setCameraMask(2); + + this._spotLight = jsb.SpotLight.create(cc.math.vec3(-1, -1, 0), cc.math.vec3(0, 0, 0), cc.color(200, 200, 200), 0, 0.5, 10000); + this._spotLight.setEnabled(false); + this.addChild(this._spotLight); + this._spotLight.setCameraMask(2); + + var seq1 = cc.sequence(cc.tintTo(4, 0, 0, 255), cc.tintTo(4, 0, 255, 0), cc.tintTo(4, 255, 0, 0), cc.tintTo(4, 255, 255, 255)); + this._ambientLight.runAction(seq1.repeatForever()); + + var seq2 = cc.sequence(cc.tintTo(4, 255, 0, 0), cc.tintTo(4, 0, 255, 0), cc.tintTo(4, 0, 0, 255), cc.tintTo(4, 255, 255, 255)); + this._directionalLight.runAction(seq2.repeatForever()); + + var seq3 = cc.sequence(cc.tintTo(4, 255, 0, 0), cc.tintTo(4, 0, 255, 0), cc.tintTo(4, 0, 0, 255), cc.tintTo(4, 255, 255, 255)); + this._pointLight.runAction(seq3.repeatForever()); + + var seq4 = cc.sequence(cc.tintTo(4, 255, 0, 0), cc.tintTo(4, 0, 255, 0), cc.tintTo(4, 0, 0, 255), cc.tintTo(4, 255, 255, 255)); + this._spotLight.runAction(seq4.repeatForever()); + }, + + update:function(dt){ + if(this._directionalLight) + this._directionalLight.setRotation3D(cc.math.vec3(-45, -cc.radiansToDegrees(this._angle), 0)); + + if(this._pointLight) + this._pointLight.setPosition3D(cc.math.vec3(100*Math.cos(this._angle+2*dt), 100, 100*Math.sin(this._angle+2*dt))); + + if(this._spotLight){ + this._spotLight.setPosition3D(cc.math.vec3(100*Math.cos(this._angle+4*dt), 100, 100*Math.sin(this._angle+4*dt))); + this._spotLight.setDirection(cc.math.vec3(-Math.cos(this._angle + 4 * dt), -1, -Math.sin(this._angle + 4*dt))); + } + }, + + switchLight:function(sender){ + var lightType = sender.getUserData(); + switch(lightType){ + case cc.LightType.AMBIENT: + var isAmbientOn = !this._ambientLight.isEnabled(); + this._ambientLight.setEnabled(isAmbientOn); + this._ambientLightLabel.setString("Ambient Light " + (isAmbientOn ? "ON" : "OFF")); + break; + + case cc.LightType.DIRECTIONAL: + var isDirectionalOn = !this._directionalLight.isEnabled(); + this._directionalLight.setEnabled(isDirectionalOn); + this._directionalLightLabel.setString("Directional Light " + (isDirectionalOn ? "ON" : "OFF")); + break; + + case cc.LightType.POINT: + var isPointOn = !this._pointLight.isEnabled(); + this._pointLight.setEnabled(isPointOn); + this._pointLightLabel.setString("Point Light " + (isPointOn ? "ON" : "OFF")); + break; + + case cc.LightType.SPOT: + var isSpotOn = !this._spotLight.isEnabled(); + this._spotLight.setEnabled(isSpotOn); + this._spotLightLabel.setString("Spot Light " + (isSpotOn ? "ON" : "OFF")); + break; + + default: + break; + } + } +}); + +// +// Flow control +// +var arrayOfLightTest = [ + LightTest +]; + +var nextLightTest = function () { + LightTestIdx++; + LightTestIdx = LightTestIdx % arrayOfLightTest.length; + + if(window.sideIndexBar){ + LightTestIdx = window.sideIndexBar.changeTest(LightTestIdx, 36); + } + + return new arrayOfLightTest[LightTestIdx ](); +}; +var previousLightTest = function () { + LightTestIdx--; + if (LightTestIdx < 0) + LightTestIdx += arrayOfLightTest.length; + + if(window.sideIndexBar){ + LightTestIdx = window.sideIndexBar.changeTest(LightTestIdx, 36); + } + + return new arrayOfLightTest[LightTestIdx ](); +}; +var restartLightTest = function () { + return new arrayOfLightTest[LightTestIdx ](); +}; diff --git a/tests/js-tests/src/LoaderTest/LoaderTest.js b/tests/js-tests/src/LoaderTest/LoaderTest.js new file mode 100644 index 0000000000..4893f2a823 --- /dev/null +++ b/tests/js-tests/src/LoaderTest/LoaderTest.js @@ -0,0 +1,94 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +//------------------------------------------------------------------ +// +// LoaderTestLayer +// +//------------------------------------------------------------------ +var LoaderTestLayer = BaseTestLayer.extend({ + _title:"Loader Test", + _subtitle:"", + + ctor:function() { + var self = this; + self._super(cc.color(0,0,0,255), cc.color(98,99,117,255)); + + var winSize = cc.winSize; + cc.loader.load(s_helloWorld, function(err, results){ + if(err){ + cc.log("Failed to load %s.", s_helloWorld); + return; + } + cc.log(s_helloWorld + "--->"); + cc.log(results[0]); + var bg = new cc.Sprite(s_helloWorld); + self.addChild(bg); + bg.x = winSize.width/2; + bg.y = winSize.height/2; + }); + + cc.loader.load([s_Cowboy_plist, s_Cowboy_png], function(err, results){ + if(err){ + cc.log("Failed to load %s, %s .", s_Cowboy_plist, s_Cowboy_png); + return; + } + + cc.log(s_Cowboy_plist + "--->"); + cc.log(results[0]); + cc.log(s_Cowboy_png + "--->"); + cc.log(results[1]); + cc.spriteFrameCache.addSpriteFrames(s_Cowboy_plist); + var frame = new cc.Sprite("#testAnimationResource/1.png"); + self.addChild(frame); + frame.x = winSize.width/4; + frame.y = winSize.height/4; + }); + + + var str; + if(cc.sys.isNative) { + str = s_lookup_desktop_plist; + } else if(cc.sys.isMobile) { + str = s_lookup_mobile_plist; + } else { + str = s_lookup_html5_plist; + } + + cc.loader.loadAliases(str, function(){ + var sprite = new cc.Sprite("grossini.bmp"); + self.addChild( sprite ); + sprite.x = winSize.width/2; + sprite.y = winSize.height/2; + }); + + } +}); + +var LoaderTestScene = TestScene.extend({ + runThisTest:function () { + this.addChild(new LoaderTestLayer()); + director.runScene(this); + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/MenuTest/MenuTest.js b/tests/js-tests/src/MenuTest/MenuTest.js new file mode 100644 index 0000000000..074a6b4bc4 --- /dev/null +++ b/tests/js-tests/src/MenuTest/MenuTest.js @@ -0,0 +1,533 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + + +var TAG_MENU = 77771; +var TAG_MENU0 = 77770; +var TAG_MENU1 = 77771; + +//------------------------------------------------------------------ +// +// LayerMainMenu +// +//------------------------------------------------------------------ +var MenuLayerMainMenu = cc.Layer.extend({ + _disabledItem:null, + _touchListener: null, + + ctor:function () { + //----start0----ctor + this._super(); + + // Font Item + var spriteNormal = new cc.Sprite(s_menuItem, cc.rect(0,23*2,115,23)); + var spriteSelected = new cc.Sprite(s_menuItem, cc.rect(0,23,115,23)); + var spriteDisabled = new cc.Sprite(s_menuItem, cc.rect(0,0,115,23)); + + var item1 = new cc.MenuItemSprite(spriteNormal, spriteSelected, spriteDisabled, this.onMenuCallback, this); + + // Image Item + var sendScoreSF = new cc.SpriteFrame(s_sendScore, cc.rect(0, 0, 145, 26)); + cc.spriteFrameCache.addSpriteFrame(sendScoreSF, "send_score_sf"); + var item2 = new cc.MenuItemImage("#send_score_sf", s_pressSendScore, this.onMenuCallback2, this); + + // Label Item (LabelAtlas) + var labelAtlas = new cc.LabelAtlas("0123456789", s_fpsImages, 16, 24, '.'); + var item3 = new cc.MenuItemLabel(labelAtlas, this.onMenuCallbackDisabled, this ); + item3.setDisabledColor( cc.color(32,32,64) ); + item3.color = cc.color(200,200,255); + + // Font Item + var item4 = new cc.MenuItemFont("I toggle enable items", function(sender) { + this._disabledItem.enabled = !this._disabledItem.enabled; + }, this); + + item4.fontSize = 20; + item4.fontName = "Arial"; + + // Label Item (LabelBMFont) + var label = new cc.LabelBMFont("configuration", s_bitmapFontTest3_fnt); + var item5 = new cc.MenuItemLabel(label, this.onMenuCallbackConfig, this); + + // Testing issue #500 + item5.scale = 0.8; + + // Events + cc.MenuItemFont.setFontName("Arial"); + + // Bugs Item + var item7 = new cc.MenuItemFont("Bugs", this.onMenuCallbackBugsTest, this); + + // Font Item + var item8 = new cc.MenuItemFont("Quit", this.onQuit, this); + + var item9 = new cc.MenuItemFont("Remove menu item when moving", this.onMenuMovingCallback, this); + + var color_action = cc.tintBy(0.5, 0, -255, -255); + var color_back = color_action.reverse(); + var seq = cc.sequence(color_action, color_back); + item8.runAction(seq.repeatForever()); + + var menu = new cc.Menu( item1, item2, item3, item4, item5, item7, item8, item9); + menu.alignItemsVertically(); + + // elastic effect + var winSize = cc.director.getWinSize(); + + var locChildren = menu.children; + var dstPoint = cc.p(0,0); + for(var i = 0; i < locChildren.length; i++){ + var selChild = locChildren[i]; + if(selChild){ + dstPoint.x = selChild.x; + dstPoint.y = selChild.y; + var offset = 0|(winSize.width/2 + 50); + if( i % 2 == 0) + offset = -offset; + + selChild.x = dstPoint.x + offset; + selChild.y = dstPoint.y; + selChild.runAction(cc.moveBy(2, cc.p(dstPoint.x - offset,0)).easing(cc.easeElasticOut(0.35))); + } + } + this._disabledItem = item3; + this._disabledItem.enabled = false; + this.addChild(menu); + menu.x = winSize.width/2; + menu.y = winSize.height/2; + //----end0---- + }, + + onMenuCallback:function (sender) { + this.parent.switchTo(1); + }, + + onMenuCallbackConfig:function (sender) { + this.parent.switchTo(3); + }, + + onAllowTouches:function (dt) { + cc.eventManager.setPriority(this._touchListener, 1); + this.unscheduleAllCallbacks(); + cc.log("TOUCHES ALLOWED AGAIN"); + }, + + onMenuCallbackDisabled:function (sender) { + // hijack all touch events for 5 seconds + cc.eventManager.setPriority(this._touchListener, -1); + this.schedule(this.onAllowTouches, 5.0); + cc.log("TOUCHES DISABLED FOR 5 SECONDS"); + }, + + onMenuCallback2:function (sender) { + this.parent.switchTo(2); + }, + + onEnter: function() { + this._super(); + this._touchListener = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches: true, + onTouchBegan:function () { + return true; + } + }); + cc.eventManager.addListener(this._touchListener, 1); + }, + + onExit: function() { + this._super(); + cc.eventManager.removeListener(this._touchListener); + }, + + onQuit:function (sender) { + cc.log("Quit called"); + }, + + onMenuCallbackBugsTest:function(sender){ + this.parent.switchTo(4); + }, + + onMenuMovingCallback:function(sender){ + this.parent.switchTo(5); + } +}); + +//------------------------------------------------------------------ +// +// MenuLayer2 +// +//------------------------------------------------------------------ +var MenuLayer2 = cc.Layer.extend({ + _centeredMenu:null, + _alignedH:false, + + ctor:function () { + this._super(); + for (var i = 0; i < 2; i++) { + var item1 = new cc.MenuItemImage(s_playNormal, s_playSelect, this.onMenuCallback, this); + var item2 = new cc.MenuItemImage(s_highNormal, s_highSelect, this.onMenuCallbackOpacity, this); + var item3 = new cc.MenuItemImage(s_aboutNormal, s_aboutSelect, this.onMenuCallbackAlign, this); + + item1.scaleX = 1.5; + item2.scaleX = 0.5; + item3.scaleX = 0.5; + + var menu = new cc.Menu(item1, item2, item3); + var winSize = director.getWinSize(); + + menu.tag = TAG_MENU; + menu.x = winSize.width / 2; + menu.y = winSize.height / 2; + + this.addChild(menu, 0, 100 + i); + + this._centeredMenu = cc.p(menu.x, menu.y); + } + this._alignedH = true; + this.alignMenuH(); + }, + init:function () { + this._super(); + + }, + alignMenuH:function () { + for (var i = 0; i < 2; i++) { + var menu = this.getChildByTag(100 + i); + menu.x = this._centeredMenu.x; + menu.y = this._centeredMenu.y; + if (i === 0) { + menu.alignItemsHorizontally(); + menu.y += 30; + } else { + menu.alignItemsHorizontallyWithPadding(40); + menu.y -= 30; + } + } + }, + alignMenusV:function () { + for (var i = 0; i < 2; i++) { + var menu = this.getChildByTag(100 + i); + menu.x = this._centeredMenu.x; + menu.y = this._centeredMenu.y; + if (i === 0) { + menu.alignItemsVertically(); + menu.x += 100; + } else { + menu.alignItemsVerticallyWithPadding(40); + menu.x -= 100; + } + } + }, + // callbacks + onMenuCallback:function (sender) { + this.parent.switchTo(0); + }, + onMenuCallbackOpacity:function (sender) { + var menu = sender.parent; + var opacity = menu.opacity; + if (opacity == 128) + menu.opacity = 255; + else + menu.opacity = 128; + }, + onMenuCallbackAlign:function (sender) { + this._alignedH = !this._alignedH; + if (this._alignedH) + this.alignMenuH(); + else + this.alignMenusV(); + } +}); + +//------------------------------------------------------------------ +// +// MenuLayer3 +// +//------------------------------------------------------------------ +var MenuLayer3 = cc.Layer.extend({ + _disabledItem:null, + + ctor:function () { + this._super(); + this.init(); + }, + init:function () { + this._super(); + cc.MenuItemFont.setFontName("Marker Felt"); + cc.MenuItemFont.setFontSize(28); + + var label = new cc.LabelBMFont("Enable AtlasItem", s_bitmapFontTest3_fnt); + var item1 = new cc.MenuItemLabel(label, function(sender){ + this._disabledItem.enabled = !this._disabledItem.enabled; + this._disabledItem.stopAllActions(); + }, this); + var item2 = new cc.MenuItemFont("--- Go Back ---", function(sender){ + this.parent.switchTo(0); + }, this); + + var spriteNormal = new cc.Sprite(s_menuItem, cc.rect(0, 23 * 2, 115, 23)); + var spriteSelected = new cc.Sprite(s_menuItem, cc.rect(0, 23, 115, 23)); + var spriteDisabled = new cc.Sprite(s_menuItem, cc.rect(0, 0, 115, 23)); + + var item3 = new cc.MenuItemSprite(spriteNormal, spriteSelected, spriteDisabled, function(sender){ + cc.log("sprite clicked!"); + }, this); + this._disabledItem = item3; + this._disabledItem.enabled = false; + + var menu = new cc.Menu(item1, item2, item3); + menu.x = 0; + menu.y = 0; + + var s = director.getWinSize(); + + item1.x = s.width / 2 - 150; + item1.y = s.height / 2; + item2.x = s.width / 2 - 200; + item2.y = s.height / 2; + item3.x = s.width / 2; + item3.y = s.height / 2 - 100; + + var jump = cc.jumpBy(3, cc.p(400, 0), 50, 4); + item2.runAction(cc.sequence(jump, jump.reverse()).repeatForever()); + var spin1 = cc.rotateBy(3, 360); + var spin2 = spin1.clone(); + var spin3 = spin1.clone(); + + item1.runAction(spin1.repeatForever()); + item2.runAction(spin2.repeatForever()); + item3.runAction(spin3.repeatForever()); + + this.addChild(menu); + menu.x = 0; + menu.y = 0; + } +}); + +var MenuLayer4 = cc.Layer.extend({ + ctor:function () { + this._super(); + this.init(); + }, + init:function () { + //this._super(); + cc.MenuItemFont.setFontName("American Typewriter"); + cc.MenuItemFont.setFontSize(18); + + var title1 = new cc.MenuItemFont("Sound"); + title1.enabled = false; + cc.MenuItemFont.setFontName("Marker Felt"); + cc.MenuItemFont.setFontSize(34); + + // you can create a ToggleItem by passing the items + // and later setting the callback + var item1 = new cc.MenuItemToggle( + new cc.MenuItemFont("On"), + new cc.MenuItemFont("Off")); + item1.setCallback(this.onMenuCallback, this); + + cc.MenuItemFont.setFontName("American Typewriter"); + cc.MenuItemFont.setFontSize(18); + var title2 = new cc.MenuItemFont("Music"); + title2.enabled = false; + cc.MenuItemFont.setFontName("Marker Felt"); + cc.MenuItemFont.setFontSize(34); + + // or you can create a ToggleItem by passing the items + // an the callback at the last arguments. + var item2 = new cc.MenuItemToggle( + new cc.MenuItemFont("Off"), + new cc.MenuItemFont("On"), + this.onMenuCallback.bind(this) + ); + + cc.MenuItemFont.setFontName("American Typewriter"); + cc.MenuItemFont.setFontSize(18); + var title3 = new cc.MenuItemFont("Quality"); + title3.enabled = false; + cc.MenuItemFont.setFontName("Marker Felt"); + cc.MenuItemFont.setFontSize(34); + var item3 = new cc.MenuItemToggle( + new cc.MenuItemFont("High"), + new cc.MenuItemFont("Low"), + this.onMenuCallback, this + ); + + cc.MenuItemFont.setFontName("American Typewriter"); + cc.MenuItemFont.setFontSize(18); + var title4 = new cc.MenuItemFont("Orientation"); + title4.enabled = false; + cc.MenuItemFont.setFontName("Marker Felt"); + cc.MenuItemFont.setFontSize(34); + var item4 = new cc.MenuItemToggle( + new cc.MenuItemFont("Off"), + new cc.MenuItemFont("33%"), + new cc.MenuItemFont("66%"), + new cc.MenuItemFont("100%"), + this.onMenuCallback, this + ); + + // you can change the one of the items by doing this + item4.setSelectedIndex(2); + + cc.MenuItemFont.setFontName("Marker Felt"); + cc.MenuItemFont.setFontSize(34); + + var label = new cc.LabelBMFont("go back", s_bitmapFontTest3_fnt); + var back = new cc.MenuItemLabel(label, this.onBackCallback, this); + + var menu = new cc.Menu( + title1, title2, + item1, item2, + title3, title4, + item3, item4, + back); // 9 items. + + menu.alignItemsInColumns(2, 2, 2, 2, 1); + + this.addChild(menu); + + var winSize = director.getWinSize(); + menu.x = winSize.width / 2; + menu.y = winSize.height / 2; + }, + onMenuCallback:function (sender) { + cc.log("Callback called"); + }, + onBackCallback:function (sender) { + this.parent.switchTo(0); + } +}); + +var MenuBugsTest = cc.Layer.extend({ + ctor:function(){ + this._super(); + + var issue1410 = new cc.MenuItemFont("Issue 1410", this.onIssue1410MenuCallback, this); + var issue1410_2 = new cc.MenuItemFont("Issue 1410 #2", this.onIssue1410v2MenuCallback, this); + var back = new cc.MenuItemFont("Back", this.onBackMenuCallback, this); + + var menu = new cc.Menu(issue1410, issue1410_2, back); + this.addChild(menu); + menu.alignItemsVertically(); + + var s = cc.director.getWinSize(); + menu.x = s.width/2; + menu.y = s.height/2; + }, + + onIssue1410MenuCallback:function(sender){ + var menu = sender.parent; + menu.setEnabled(false); + menu.setEnabled(true); + + cc.log("NO CRASHES"); + }, + + onIssue1410v2MenuCallback:function(sender){ + var menu = sender.parent; + menu.setEnabled(true); + menu.setEnabled(false); + + cc.log("NO CRASHES. AND MENU SHOULD STOP WORKING"); + }, + + onBackMenuCallback:function(sender){ + this.parent.switchTo(0); + } +}); + +var RemoveMenuItemWhenMove = cc.Layer.extend({ + _item:null, + _touchListener: null, + ctor: function(){ + this._super(); + + var s = cc.director.getWinSize(); + + var label = new cc.LabelTTF("click item and move, should not crash", "Arial", 20); + label.x = s.width/2; + label.y = s.height - 30; + this.addChild(label); + + this._item = new cc.MenuItemFont("item 1"); + + var back = new cc.MenuItemFont("go back", this.goBack, this); + + var menu = new cc.Menu(this._item, back); + this.addChild(menu); + menu.alignItemsVertically(); + + menu.x = s.width/2; + menu.y = s.height/2; + }, + + onEnter: function() { + this._super(); + this._touchListener = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches: false, + onTouchBegan:function(touch, event){ + return true; + }, + onTouchMoved: function(touch, event){ + if (this._item){ + this._item.removeFromParent(true); + this._item = null; + } + }.bind(this) + }); + cc.eventManager.addListener(this._touchListener, -129); + }, + + onExit: function() { + this._super(); + cc.eventManager.removeListener(this._touchListener); + }, + + goBack: function(sender){ + this.parent.switchTo(0); + } +}); + +var MenuTestScene = TestScene.extend({ + runThisTest:function () { + var layer1 = new MenuLayerMainMenu(); + var layer2 = new MenuLayer2(); + var layer3 = new MenuLayer3(); + var layer4 = new MenuLayer4(); + var layer5 = new MenuBugsTest(); + var layer6 = new RemoveMenuItemWhenMove(); + + var layer = new cc.LayerMultiplex(layer1, layer2, layer3, layer4, layer5, layer6); + this.addChild(layer, 0); + + director.runScene(this); + } +}); + +var arrayOfMenuTest = [MenuTestScene]; diff --git a/tests/js-tests/src/MotionStreakTest/MotionStreakTest.js b/tests/js-tests/src/MotionStreakTest/MotionStreakTest.js new file mode 100644 index 0000000000..38cc58be7a --- /dev/null +++ b/tests/js-tests/src/MotionStreakTest/MotionStreakTest.js @@ -0,0 +1,269 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2008-2009 Jason Booth + + 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. + ****************************************************************************/ + +var TAG_LABEL = 1; +var TAG_SPRITE1 = 2; +var TAG_SPRITE2 = 3; + +var sceneIdx = -1; + +var MotionStreakTest = cc.Layer.extend({ + _streak:null, + + title:function () { + return "No title"; + }, + subtitle:function () { + return ""; + }, + + onEnter:function () { + this._super(); + + var winSize = cc.director.getWinSize(); + + var label = new cc.LabelTTF(this.title(), "Arial", 32); + this.addChild(label, 0, TAG_LABEL); + label.x = winSize.width / 2; + label.y = winSize.height - 50; + + var subTitle = this.subtitle(); + if (subTitle.length > 0) { + var l = new cc.LabelTTF(subTitle, "Arial", 16); + this.addChild(l, 1); + l.x = winSize.width / 2; + l.y = winSize.height - 80; + } + + var item1 = new cc.MenuItemImage(s_pathB1, s_pathB2, this.backCallback, this); + var item2 = new cc.MenuItemImage(s_pathR1, s_pathR2, this.restartCallback, this); + var item3 = new cc.MenuItemImage(s_pathF1, s_pathF2, this.nextCallback, this); + + var menu = new cc.Menu(item1, item2, item3); + + menu.x = 0; + menu.y = 0; + item1.x = cc.visibleRect.center.x - item2.width * 2; + item1.y = cc.visibleRect.bottom.y + item2.height / 2; + item2.x = cc.visibleRect.center.x; + item2.y = cc.visibleRect.bottom.y + item2.height / 2; + item3.x = cc.visibleRect.center.x + item2.width * 2; + item3.y = cc.visibleRect.bottom.y + item2.height / 2; + + this.addChild(menu, 1); + + var itemMode = new cc.MenuItemToggle(new cc.MenuItemFont("Use High Quality Mode"), + new cc.MenuItemFont("Use Fast Mode"), this.modeCallback, this); + + var menuMode = new cc.Menu(itemMode); + this.addChild(menuMode); + + menuMode.x = winSize.width / 2; + menuMode.y = winSize.height / 4; + }, + + restartCallback:function (sender) { + var scene = new MotionStreakTestScene(); + scene.addChild(restartMotionAction()); + cc.director.runScene(scene); + }, + + nextCallback:function (sender) { + var scene = new MotionStreakTestScene(); + scene.addChild(nextMotionAction()); + cc.director.runScene(scene); + }, + + backCallback:function (sender) { + var scene = new MotionStreakTestScene; + scene.addChild(backMotionAction()); + cc.director.runScene(scene); + }, + + modeCallback:function (sender) { + var fastMode = this._streak.fastMode; + this._streak.fastMode = !fastMode; + } +}); + +var MotionStreakTest1 = MotionStreakTest.extend({ + _root:null, + _target:null, + + onEnter:function () { + this._super(); + + var winSize = cc.director.getWinSize(); + // the root object just rotates around + this._root = new cc.Sprite(s_pathR1); + this.addChild(this._root, 1); + this._root.x = winSize.width / 2; + this._root.y = winSize.height / 2; + + // the target object is offset from root, and the streak is moved to follow it + this._target = new cc.Sprite(s_pathR1); + this._root.addChild(this._target); + this._target.x = winSize.width / 4; + this._target.y = 0; + + // create the streak object and add it to the scene + this._streak = new cc.MotionStreak(2, 3, 32, cc.color.GREEN, s_streak); + this.addChild(this._streak); + // schedule an update on each frame so we can syncronize the streak with the target + this.schedule(this.onUpdate); + + var a1 = cc.rotateBy(2, 360); + + var action1 = a1.repeatForever(); + var motion = cc.moveBy(2, cc.p(100, 0)); + this._root.runAction(cc.sequence(motion, motion.reverse()).repeatForever()); + this._root.runAction(action1); + + var colorAction = cc.sequence( + cc.tintTo(0.2, 255, 0, 0), + cc.tintTo(0.2, 0, 255, 0), + cc.tintTo(0.2, 0, 0, 255), + cc.tintTo(0.2, 0, 255, 255), + cc.tintTo(0.2, 255, 255, 0), + cc.tintTo(0.2, 255, 0, 255), + cc.tintTo(0.2, 255, 255, 255) + ).repeatForever(); + + this._streak.runAction(colorAction); + }, + + onUpdate:function (delta) { + var pos = this._target.convertToWorldSpace(cc.p(this._target.width/2, 0)); + this._streak.x = pos.x; + this._streak.y = pos.y; + }, + + title:function () { + return "MotionStreak test 1"; + } +}); + +var MotionStreakTest2 = MotionStreakTest.extend({ + _root:null, + _target:null, + + onEnter:function () { + this._super(); + + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesMoved:function (touches, event) { + if (touches.length == 0) + return; + + var touch = touches[0]; + var touchLocation = touch.getLocation(); + var streak = event.getCurrentTarget()._streak; + streak.x = touchLocation.x; + streak.y = touchLocation.y; + } + }, this); + var winSize = cc.director.getWinSize(); + // create the streak object and add it to the scene + this._streak = new cc.MotionStreak(3, 3, 64, cc.color.WHITE, s_streak); + this.addChild(this._streak); + this._streak.x = winSize.width / 2; + this._streak.y = winSize.height / 2; + }, + + title:function () { + return "MotionStreak test"; + } +}); + +var Issue1358 = MotionStreakTest.extend({ + _center:null, + _radius:0, + _angle:0, + title:function () { + return "Issue 1358"; + }, + + subtitle:function () { + return "The tail should use the texture"; + }, + + onEnter:function () { + this._super(); + + // ask director the the window size + var size = cc.director.getWinSize(); + this._streak = new cc.MotionStreak(2.0, 1.0, 50.0, cc.color(255, 255, 0), s_image_icon); + this.addChild(this._streak); + + this._center = cc.p(size.width / 2, size.height / 2); + this._radius = size.width / 3; + this._angle = 0.0; + this.schedule(this.update, 0); + }, + + update:function (dt) { + this._angle += 1.0; + this._streak.x = this._center.x + Math.cos(this._angle / 180 * Math.PI) * this._radius; + this._streak.y = this._center.y + Math.sin(this._angle / 180 * Math.PI) * this._radius; + } +}); + +var arrayOfMotionStreakTest = [ + MotionStreakTest1, + MotionStreakTest2, + Issue1358 +]; + +var nextMotionAction = function () { + sceneIdx++; + sceneIdx = sceneIdx % arrayOfMotionStreakTest.length; + return new arrayOfMotionStreakTest[sceneIdx](); +}; + +var backMotionAction = function () { + sceneIdx--; + if (sceneIdx < 0) + sceneIdx += arrayOfMotionStreakTest.length; + return new arrayOfMotionStreakTest[sceneIdx](); +}; + +var restartMotionAction = function () { + return new arrayOfMotionStreakTest[sceneIdx](); +}; + +var MotionStreakTestScene = TestScene.extend({ + runThisTest:function (num) { + sceneIdx = (num || num == 0) ? (num - 1) : -1; + var pLayer = nextMotionAction(); + this.addChild(pLayer); + cc.director.runScene(this); + } +}); + + + diff --git a/tests/js-tests/src/NewEventManagerTest/NewEventManagerTest.js b/tests/js-tests/src/NewEventManagerTest/NewEventManagerTest.js new file mode 100644 index 0000000000..55e57a0aff --- /dev/null +++ b/tests/js-tests/src/NewEventManagerTest/NewEventManagerTest.js @@ -0,0 +1,1301 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var eventDispatcherSceneIdx = -1; + +var EventDispatcherTestDemo = BaseTestLayer.extend({ + ctor:function() { + this._super(cc.color(0,0,0,255), cc.color(160,32,32,255)); + }, + + title:function () { + return "No title"; + }, + + subtitle:function () { + return ""; + }, + + onBackCallback:function (sender) { + var s = new EventDispatcherTestScene(); + s.addChild(previousDispatcherTest()); + director.runScene(s); + }, + + onRestartCallback:function (sender) { + var s = new EventDispatcherTestScene(); + s.addChild(restartDispatcherTest()); + director.runScene(s); + }, + + onNextCallback:function (sender) { + var s = new EventDispatcherTestScene(); + s.addChild(nextDispatcherTest()); + director.runScene(s); + }, + // varmation + numberOfPendingTests:function() { + return ( (arrayOfEventDispatcherTest.length-1) - eventDispatcherSceneIdx ); + }, + + getTestNumber:function() { + return eventDispatcherSceneIdx; + } +}); + +var TouchableSpriteTest = EventDispatcherTestDemo.extend({ + onEnter:function(){ + //----start0----onEnter + this._super(); + + var origin = director.getVisibleOrigin(); + var size = director.getVisibleSize(); + + var containerForSprite1 = new cc.Node(); + var sprite1 = new cc.Sprite("res/Images/CyanSquare.png"); + sprite1.setPosition(origin.x + size.width/2 - 80, origin.y + size.height/2 + 80); + containerForSprite1.addChild(sprite1); + this.addChild(containerForSprite1, 10); + + var sprite2 = new cc.Sprite("res/Images/MagentaSquare.png"); + sprite2.setPosition(origin.x + size.width/2, origin.y + size.height/2); + this.addChild(sprite2, 20); + + var sprite3 = new cc.Sprite("res/Images/YellowSquare.png"); + sprite3.setPosition(0,0); + sprite2.addChild(sprite3, 1); + + // Make sprite1 touchable + var listener1 = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches: true, + onTouchBegan: function (touch, event) { + var target = event.getCurrentTarget(); + + var locationInNode = target.convertToNodeSpace(touch.getLocation()); + var s = target.getContentSize(); + var rect = cc.rect(0, 0, s.width, s.height); + + if (cc.rectContainsPoint(rect, locationInNode)) { + cc.log("sprite began... x = " + locationInNode.x + ", y = " + locationInNode.y); + target.opacity = 180; + return true; + } + return false; + }, + onTouchMoved: function (touch, event) { + var target = event.getCurrentTarget(); + var delta = touch.getDelta(); + target.x += delta.x; + target.y += delta.y; + }, + onTouchEnded: function (touch, event) { + var target = event.getCurrentTarget(); + cc.log("sprite onTouchesEnded.. "); + target.setOpacity(255); + if (target == sprite2) { + containerForSprite1.setLocalZOrder(100); + } else if (target == sprite1) { + containerForSprite1.setLocalZOrder(0); + } + } + }); + + cc.eventManager.addListener(listener1, sprite1); + cc.eventManager.addListener(listener1.clone(), sprite2); + cc.eventManager.addListener(listener1.clone(), sprite3); + var selfPointer = this; + + var removeAllTouchItem = new cc.MenuItemFont("Remove All Touch Listeners", function(senderItem){ + senderItem.setString("Only Next item could be clicked"); + + cc.eventManager.removeListeners(cc.EventListener.TOUCH_ONE_BY_ONE); + + var nextItem = new cc.MenuItemFont("Next", function(sender){ + selfPointer.onNextCallback(); + }); + + nextItem.fontSize = 16; + nextItem.x = cc.visibleRect.right.x -100; + nextItem.y = cc.visibleRect.right.y - 30; + + var menu2 = new cc.Menu(nextItem); + menu2.setPosition(0, 0); + menu2.setAnchorPoint(0, 0); + selfPointer.addChild(menu2); + }); + + removeAllTouchItem.fontSize = 16; + removeAllTouchItem.x = cc.visibleRect.right.x -removeAllTouchItem.width/2-20; + removeAllTouchItem.y = cc.visibleRect.right.y; + + var menu = new cc.Menu(removeAllTouchItem); + menu.setPosition(0, 0); + menu.setAnchorPoint(0, 0); + this.addChild(menu); + //----end0---- + }, + + title:function(){ + return "Touchable Sprite Test"; + }, + + subtitle:function(){ + return "Please drag the blocks"; + } +}); + +TouchableSpriteTest.create = function(){ + var test = new TouchableSpriteTest(); + test.init(); + return test; +}; + +var TouchableSprite = cc.Sprite.extend({ + _listener:null, + _fixedPriority:0, + _removeListenerOnTouchEnded: false, + + ctor: function(priority){ + this._super(); + this._fixedPriority = priority || 0; + }, + + setPriority:function(fixedPriority){ + this._fixedPriority = fixedPriority; + }, + + onEnter:function(){ + this._super(); + + var selfPointer = this; + var listener = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches: true, + onTouchBegan: function (touch, event) { + var locationInNode = selfPointer.convertToNodeSpace(touch.getLocation()); + var s = selfPointer.getContentSize(); + var rect = cc.rect(0, 0, s.width, s.height); + + if (cc.rectContainsPoint(rect, locationInNode)) { + selfPointer.setColor(cc.color.RED); + return true; + } + return false; + }, + onTouchMoved: function (touch, event) { + //this.setPosition(this.getPosition() + touch.getDelta()); + }, + onTouchEnded: function (touch, event) { + selfPointer.setColor(cc.color.WHITE); + if(selfPointer._removeListenerOnTouchEnded) { + cc.eventManager.removeListener(selfPointer._listener); + selfPointer._listener = null; + } + } + }); + + if(this._fixedPriority != 0) + cc.eventManager.addListener(listener, this._fixedPriority); + else + cc.eventManager.addListener(listener, this); + this._listener = listener; + }, + + onExit: function(){ + this._listener && cc.eventManager.removeListener(this._listener); + this._super(); + }, + + removeListenerOnTouchEnded: function(toRemove){ + this._removeListenerOnTouchEnded = toRemove; + }, + + getListener: function() { + return this._listener; + } +}); + +TouchableSprite.create = function(priority){ + var test = new TouchableSprite(priority); + test.init(); + return test; +}; + +var FixedPriorityTest = EventDispatcherTestDemo.extend({ + onEnter:function(){ + //----start1----onEnter + this._super(); + + var origin = director.getVisibleOrigin(); + var size = director.getVisibleSize(); + + var sprite1 = TouchableSprite.create(30); + sprite1.setTexture("res/Images/CyanSquare.png"); + sprite1.x = origin.x + size.width / 2 - 80; + sprite1.y = origin.y + size.height / 2 + 40; + this.addChild(sprite1, 10); + + var sprite2 = TouchableSprite.create(20); + sprite2.setTexture("res/Images/MagentaSquare.png"); + sprite2.x = origin.x + size.width / 2; + sprite2.y = origin.y + size.height / 2; + this.addChild(sprite2, 20); + + var sprite3 = TouchableSprite.create(10); + sprite3.setTexture("res/Images/YellowSquare.png"); + sprite3.x = 0; + sprite3.y = 0; + sprite2.addChild(sprite3, 1); + //----end1---- + }, + + title:function(){ + return "Fixed priority test"; + }, + + subtitle:function(){ + return "Fixed Priority, Blue: 30, Red: 20, Yellow: 10\n The lower value the higher priority will be."; + } +}); + +FixedPriorityTest.create = function(){ + var test = new FixedPriorityTest(); + test.init(); + return test; +}; + +var RemoveListenerWhenDispatching = EventDispatcherTestDemo.extend({ + onEnter:function(){ + //----start2----onEnter + this._super(); + + var origin = director.getVisibleOrigin(); + var size = director.getVisibleSize(); + + var sprite1 = new cc.Sprite("res/Images/CyanSquare.png"); + sprite1.setPosition(origin.x + size.width/2, origin.y + size.height/2); + this.addChild(sprite1, 10); + + // Make sprite1 touchable + var listener1 = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches: true, + onTouchBegan: function (touch, event) { + var locationInNode = sprite1.convertToNodeSpace(touch.getLocation()); + var s = sprite1.getContentSize(); + var rect = cc.rect(0, 0, s.width, s.height); + + if (cc.rectContainsPoint(rect, locationInNode)) { + sprite1.setColor(cc.color.RED); + return true; + } + return false; + }, + onTouchEnded: function (touch, event) { + sprite1.setColor(cc.color.WHITE); + } + }); + this.setUserObject(listener1); + + cc.eventManager.addListener(listener1, sprite1); + + var statusLabel = new cc.LabelTTF("The sprite could be touched!", "", 20); + statusLabel.setPosition(origin.x + size.width/2, origin.y + size.height-90 ); + this.addChild(statusLabel); + + var enable = true; + + // Enable/Disable item + var toggleItem = new cc.MenuItemToggle(new cc.MenuItemFont("Enabled"), new cc.MenuItemFont("Disabled"), + function (sender) { + if (enable) { + cc.eventManager.removeListener(listener1); + statusLabel.setString("The sprite could not be touched!"); + enable = false; + } else { + cc.eventManager.addListener(listener1, sprite1); + statusLabel.setString("The sprite could be touched!"); + enable = true; + } + }); + + toggleItem.setPosition(origin.x + size.width/2, origin.y + 80); + var menu = new cc.Menu(toggleItem); + menu.setPosition(0, 0); + menu.setAnchorPoint(0, 0); + this.addChild(menu, 1); + //----end2---- + }, + + title:function(){ + return "Add and remove listener\n when dispatching event"; + }, + + subtitle:function(){ + return ""; + } +}); + +RemoveListenerWhenDispatching.create = function(){ + var test = new RemoveListenerWhenDispatching(); + test.init(); + return test; +}; + +var CustomEventTest = EventDispatcherTestDemo.extend({ + _listener1: null, + _listener2: null, + _item1Count: 0, + _item2Count: 0, + + onEnter:function(){ + //----start3----onEnter + this._super(); + + var origin = director.getVisibleOrigin(), size = director.getVisibleSize(), selfPointer = this; + + cc.MenuItemFont.setFontSize(20); + + var statusLabel = new cc.LabelTTF("No custom event 1 received!", "", 20); + statusLabel.setPosition(origin.x + size.width / 2, origin.y + size.height - 90); + this.addChild(statusLabel); + + this._listener1 = cc.EventListener.create({ + event: cc.EventListener.CUSTOM, + eventName: "game_custom_event1", + callback: function(event){ + statusLabel.setString("Custom event 1 received, " + event.getUserData() + " times"); + } + }); + cc.eventManager.addListener(this._listener1, 1); + + var sendItem = new cc.MenuItemFont("Send Custom Event 1", function(sender){ + ++selfPointer._item1Count; + var event = new cc.EventCustom("game_custom_event1"); + event.setUserData(selfPointer._item1Count.toString()); + cc.eventManager.dispatchEvent(event); + }); + sendItem.setPosition(origin.x + size.width/2, origin.y + size.height/2); + + var statusLabel2 = new cc.LabelTTF("No custom event 2 received!", "", 20); + statusLabel2.setPosition(origin.x + size.width/2, origin.y + size.height-120); + this.addChild(statusLabel2); + + this._listener2 = cc.EventListener.create({ + event: cc.EventListener.CUSTOM, + eventName: "game_custom_event2", + callback: function(event){ + statusLabel2.setString("Custom event 2 received, " + event.getUserData() + " times"); + } + }); + + cc.eventManager.addListener(this._listener2, 1); + var sendItem2 = new cc.MenuItemFont("Send Custom Event 2", function(sender){ + ++selfPointer._item2Count; + var event = new cc.EventCustom("game_custom_event2"); + event.setUserData(selfPointer._item2Count.toString()); + cc.eventManager.dispatchEvent(event); + }); + sendItem2.setPosition(origin.x + size.width/2, origin.x + size.height/2 - 40); + + var menu = new cc.Menu(sendItem, sendItem2); + menu.setPosition(0, 0); + menu.setAnchorPoint(0, 0); + this.addChild(menu, 1); + //----end3---- + }, + + onExit:function(){ + //----start3----onExit + cc.eventManager.removeListener(this._listener1); + cc.eventManager.removeListener(this._listener2); + this._super(); + //----end3---- + }, + + title:function(){ + return "Send custom event"; + }, + + subtitle:function(){ + return ""; + } +}); + +CustomEventTest.create = function(){ + var test = new CustomEventTest(); + test.init(); + return test; +}; + +var LabelKeyboardEventTest = EventDispatcherTestDemo.extend({ + onEnter:function(){ + //----start4----onEnter + this._super(); + + var origin = director.getVisibleOrigin(); + var size = director.getVisibleSize(); + + var statusLabel = new cc.LabelTTF("No keyboard event received!", "", 20); + statusLabel.setPosition(origin.x + size.width/2, origin.x + size.height/2); + this.addChild(statusLabel); + + var that = this; + cc.eventManager.addListener({ + event: cc.EventListener.KEYBOARD, + onKeyPressed: function(keyCode, event){ + var label = event.getCurrentTarget(); + label.setString("Key " + (cc.sys.isNative ? that.getNativeKeyName(keyCode) : String.fromCharCode(keyCode) ) + "(" + keyCode.toString() + ") was pressed!"); + }, + onKeyReleased: function(keyCode, event){ + var label = event.getCurrentTarget(); + label.setString("Key " + (cc.sys.isNative ? that.getNativeKeyName(keyCode) : String.fromCharCode(keyCode) ) + "(" + keyCode.toString() + ") was released!"); + } + }, statusLabel); + //----end4---- + }, + + getNativeKeyName:function(keyCode) { + var allCode = Object.getOwnPropertyNames(cc.KEY); + var keyName = ""; + for(var x in allCode){ + if(cc.KEY[allCode[x]] == keyCode){ + keyName = allCode[x]; + break; + } + } + return keyName; + }, + + title:function(){ + return "Label Receives Keyboard Event"; + }, + + subtitle:function(){ + return "Please click keyboard\n(Only available on Desktop and Android)"; + } +}); + +LabelKeyboardEventTest.create = function(){ + var test = new LabelKeyboardEventTest(); + test.init(); + return test; +}; + +var SpriteAccelerationEventTest = EventDispatcherTestDemo.extend({ + onEnter:function(){ + //----start5----onEnter + this._super(); + + var origin = director.getVisibleOrigin(); + var size = director.getVisibleSize(); + + cc.inputManager.setAccelerometerEnabled(true); + + var sprite = new cc.Sprite("res/Images/ball.png"); + sprite.setPosition(origin.x + size.width/2, origin.y + size.height/2); + this.addChild(sprite); + + cc.eventManager.addListener({ + event: cc.EventListener.ACCELERATION, + callback: function(acc, event){ + var target = event.getCurrentTarget(); + var ballSize = target.getContentSize(); + var ptNow = target.getPosition(); + + //cc.log("acc: x = " + acc.x + ", y = " + acc.y); + + target.x = SpriteAccelerationEventTest._fix_pos(ptNow.x + acc.x * 9.81, + (cc.visibleRect.left.x + ballSize.width / 2.0), (cc.visibleRect.right.x - ballSize.width / 2.0)); + target.y = SpriteAccelerationEventTest._fix_pos(ptNow.y + acc.y * 9.81, + (cc.visibleRect.bottom.y + ballSize.height / 2.0), (cc.visibleRect.top.y - ballSize.height / 2.0)); + } + }, sprite); + //----end5---- + }, + + onExit:function(){ + //----start5----onEnter + cc.inputManager.setAccelerometerEnabled(false); + this._super(); + //----end---- + }, + + title:function(){ + return "Sprite Receives Acceleration Event"; + }, + + subtitle:function(){ + return "Please move your device\n(Only available on mobile)"; + } +}); + +SpriteAccelerationEventTest._fix_pos = function(pos, min, max){ + var ret = pos; + if(pos < min) + ret = min; + else if(pos > max) + ret = max; + return ret; +}; + +SpriteAccelerationEventTest.create = function(){ + var test = new SpriteAccelerationEventTest(); + test.init(); + return test; +}; + +var RemoveAndRetainNodeTest = EventDispatcherTestDemo.extend({ + _sprite:null, + _spriteSaved:false, + + onEnter:function(){ + //----start6----onEnter + this._super(); + + var origin = director.getVisibleOrigin(); + var size = director.getVisibleSize(); + + this._sprite = new cc.Sprite("res/Images/CyanSquare.png"); + this._sprite.setPosition(origin.x + size.width/2, origin.y + size.height/2); + this.addChild(this._sprite, 10); + + // Make sprite1 touchable + var listener1 = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches: true, + onTouchBegan: function (touch, event) { + var target = event.getCurrentTarget(); + + var locationInNode = target.convertToNodeSpace(touch.getLocation()); + var s = target.getContentSize(); + var rect = cc.rect(0, 0, s.width, s.height); + + if (cc.rectContainsPoint(rect, locationInNode)) { + cc.log("sprite began... x = " + locationInNode.x + ", y = " + locationInNode.y); + target.opacity = 180; + return true; + } + return false; + }, + onTouchMoved: function (touch, event) { + var target = event.getCurrentTarget(); + var delta = touch.getDelta(); + target.x += delta.x; + target.y += delta.y; + }, + onTouchEnded: function (touch, event) { + var target = event.getCurrentTarget(); + cc.log("sprite onTouchesEnded.. "); + target.opacity = 255; + } + }); + cc.eventManager.addListener(listener1, this._sprite); + + this.runAction(cc.sequence(cc.delayTime(5.0), + cc.callFunc(function () { + this._spriteSaved = true; + this._sprite.retain(); + this._sprite.removeFromParent(); + }, this), + cc.delayTime(5.0), + cc.callFunc(function () { + this._spriteSaved = false; + this.addChild(this._sprite); + if(!cc.sys.isNative) + cc.eventManager.addListener(listener1, this._sprite); + this._sprite.release(); + }, this) + )); + //----end6---- + }, + + onExit:function(){ + //----start6----onExit + this._super(); + if (this._spriteSaved) + this._sprite.release(); + //----end6---- + }, + + title:function(){ + return "RemoveAndRetainNodeTest"; + }, + + subtitle:function(){ + return "Sprite should be removed after 5s, add to scene again after 5s"; + } +}); + +RemoveAndRetainNodeTest.create = function(){ + var test = new RemoveAndRetainNodeTest(); + test.init(); + return test; +}; + +var RemoveListenerAfterAddingTest = EventDispatcherTestDemo.extend({ + onEnter:function(){ + //----start7----onEnter + this._super(); + var selfPointer = this; + var item1 = new cc.MenuItemFont("Click Me 1", function(sender){ + var listener = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + onTouchBegan: function (touch, event) { + cc.assert(false, "Should not come here!"); + return true; + } + }); + cc.eventManager.addListener(listener, -1); + cc.eventManager.removeListener(listener); + }); + var vCenter = cc.visibleRect.center; + item1.setPosition(vCenter.x, vCenter.y + 80); + + var addNextButton = function(){ + var next = new cc.MenuItemFont("Please Click Me To Reset!", function(sender){ + selfPointer.onRestartCallback(); + }); + next.setPosition(vCenter.x, vCenter.y - 40); + + var menu = new cc.Menu(next); + menu.setPosition(cc.visibleRect.bottomLeft); + menu.setAnchorPoint(0,0); + selfPointer.addChild(menu); + }; + + var item2 = new cc.MenuItemFont("Click Me 2", function(sender){ + var listener = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + onTouchBegan: function(touch, event){ + cc.assert("Should not come here!"); + return true; + } + }); + cc.eventManager.addListener(listener, -1); + cc.eventManager.removeListeners(cc.EventListener.TOUCH_ONE_BY_ONE); + addNextButton(); + }, this); + item2.setPosition(vCenter.x, vCenter.y + 40); + + var item3 = new cc.MenuItemFont("Click Me 3", function(sender){ + var listener = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + onTouchBegan: function(touch, event){ + cc.assert(false, "Should not come here!"); + return true; + } + }); + cc.eventManager.addListener(listener, -1); + cc.eventManager.removeAllListeners(); + addNextButton(); + }, this); + item3.setPosition(cc.visibleRect.center); + + var menu = new cc.Menu(item1, item2, item3); + menu.setPosition(cc.visibleRect.bottomLeft); + menu.setAnchorPoint(0, 0); + this.addChild(menu); + //----end7---- + }, + + title:function(){ + return "RemoveListenerAfterAddingTest"; + }, + + subtitle:function(){ + return "Should not crash!"; + } +}); + +RemoveListenerAfterAddingTest.create = function(){ + var test = new RemoveListenerAfterAddingTest(); + test.init(); + return test; +}; + +var DirectorEventTest = EventDispatcherTestDemo.extend({ + _count1:0, + _count2:0, + _count3:0, + _count4:0, + _label1:null, + _label2:null, + _label3:null, + _label4:null, + _event1:null, + _event2:null, + _event3:null, + _event4:null, + _time:0, + + onEnter:function(){ + //----start8----onEnter + this._super(); + var s = director.getWinSize(), selfPointer = this; + + this._label1 = new cc.LabelTTF("Update: 0", "Arial", 20); + this._label1.setPosition(80,s.height/2 + 60); + this.addChild(this._label1); + + this._label2 = new cc.LabelTTF("Visit: 0", "Arial", 20); + this._label2.setPosition(80,s.height/2 + 20); + this.addChild(this._label2); + + this._label3 = new cc.LabelTTF("Draw: 0", "Arial", 20); + this._label3.setPosition(80,s.height/2 - 20); + this.addChild(this._label3); + + this._label4 = new cc.LabelTTF("Projection: 0", "Arial", 20); + this._label4.setPosition(80,s.height/2 - 60); + this.addChild(this._label4); + + var dispatcher = cc.eventManager; + + this._event1 = dispatcher.addCustomListener(cc.Director.EVENT_AFTER_UPDATE, this.onEvent1.bind(this)); + this._event2 = dispatcher.addCustomListener(cc.Director.EVENT_AFTER_VISIT, this.onEvent2.bind(this)); + this._event3 = dispatcher.addCustomListener(cc.Director.EVENT_AFTER_DRAW, function(event) { + selfPointer._label3.setString("Draw: " + selfPointer._count3++); + }); + this._event4 = dispatcher.addCustomListener(cc.Director.EVENT_PROJECTION_CHANGED, function(event) { + selfPointer._label4.setString("Projection: " + selfPointer._count4++); + }); + + this._event1.retain(); + this._event2.retain(); + this._event3.retain(); + this._event4.retain(); + + this.scheduleUpdate(); + }, + + onExit:function(){ + //----start8----onExit + this._super(); + + var eventManager = cc.eventManager; + eventManager.removeListener(this._event1); + eventManager.removeListener(this._event2); + eventManager.removeListener(this._event3); + eventManager.removeListener(this._event4); + + this._event1.release(); + this._event2.release(); + this._event3.release(); + this._event4.release(); + //----end8---- + }, + + update:function(dt){ + //----start8----update + this._time += dt; + if(this._time > 0.5) { + cc.director.setProjection(cc.Director.PROJECTION_2D); + this._time = 0; + } + //----end8---- + }, + + onEvent1:function(event){ + //----start8----onExit + this._label1.setString("Update: " + this._count1++); + //----end8---- + }, + + onEvent2:function(event){ + //----start8----onExit + this._label2.setString("Visit: " + this._count2++); + //----end8---- + }, + + title:function(){ + return "Testing Director Events"; + }, + + subtitle:function(){ + return "after visit, after draw, after update, projection changed"; + } +}); + +DirectorEventTest.create = function(){ + var test = new DirectorEventTest(); + test.init(); + return test; +}; + +var GlobalZTouchTest = EventDispatcherTestDemo.extend({ + _sprite:null, + _accum:null, + + ctor: function(){ + this._super(); + + var listener = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches:true, + onTouchBegan: function(touch, event){ + var target = event.getCurrentTarget(); + + var locationInNode = target.convertToNodeSpace(touch.getLocation()); + var s = target.getContentSize(); + var rect = cc.rect(0, 0, s.width, s.height); + + if (cc.rectContainsPoint(rect, locationInNode)) { + cc.log("sprite began... x = %f, y = %f", locationInNode.x, locationInNode.y); + target.setOpacity(180); + return true; + } + return false; + }, + onTouchMoved: function(touch, event){ + var target = event.getCurrentTarget(), delta = touch.getDelta(); + target.x += delta.x; + target.y += delta.y; + }, + onTouchEnded: function(touch, event){ + cc.log("sprite onTouchesEnded.. "); + event.getCurrentTarget().setOpacity(255); + } + }); + + var SPRITE_COUNT = 8, sprite; + for (var i = 0; i < SPRITE_COUNT; i++) { + if(i==4) { + sprite = new cc.Sprite("res/Images/CyanSquare.png"); + this._sprite = sprite; + this._sprite.setGlobalZOrder(-1); + } else + sprite = new cc.Sprite("res/Images/YellowSquare.png"); + + cc.eventManager.addListener(listener.clone(), sprite); + this.addChild(sprite); + + var visibleSize = cc.director.getVisibleSize(); + sprite.x = cc.visibleRect.left.x + visibleSize.width / (SPRITE_COUNT - 1) * i; + sprite.y = cc.visibleRect.center.y; + } + + this.scheduleUpdate(); + }, + + update: function(dt){ + this._accum += dt; + if( this._accum > 2.0) { + var z = this._sprite.getGlobalZOrder(); + this._sprite.setGlobalZOrder(-z); + this._accum = 0; + } + }, + + title: function(){ + return "Global Z Value, Try touch blue sprite"; + }, + + subtitle: function() { + return "Blue Sprite should change go from foreground to background"; + } +}); + +GlobalZTouchTest.create = function(){ + var test = new GlobalZTouchTest(); + test.init(); + return test; +}; + +var StopPropagationTest = EventDispatcherTestDemo.extend({ + ctor:function(){ + //----start9----ctor + this._super(); + + var touchOneByOneListener = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches:true, + onTouchBegan: function(touch, event){ + // Skip if don't touch top half screen. + if (!this._isPointInTopHalfAreaOfScreen(touch.getLocation())) + return false; + + var target = event.getCurrentTarget(); + if(target.getTag() != StopPropagationTest._TAG_BLUE_SPRITE) + cc.log("Yellow blocks shouldn't response event."); + + if (this._isPointInNode(touch.getLocation(), target)) { + target.setOpacity(180); + return true; + } + + // Stop propagation, so yellow blocks will not be able to receive event. + event.stopPropagation(); + return false; + }.bind(this), + onTouchEnded: function(touch, event){ + event.getCurrentTarget().setOpacity(255); + } + }); + + var touchAllAtOnceListener = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesBegan: function(touches, event){ + // Skip if don't touch top half screen. + if (this._isPointInTopHalfAreaOfScreen(touches[0].getLocation())) + return; + + var target = event.getCurrentTarget(); + if(target.getTag() != StopPropagationTest._TAG_BLUE_SPRITE2) + cc.log("Yellow blocks shouldn't response event."); + + if (this._isPointInNode(touches[0].getLocation(), target)) + target.setOpacity(180); + // Stop propagation, so yellow blocks will not be able to receive event. + event.stopPropagation(); + }.bind(this), + onTouchesEnded: function(touches, event){ + // Skip if don't touch top half screen. + if (this._isPointInTopHalfAreaOfScreen(touches[0].getLocation())) + return; + + var target = event.getCurrentTarget(); + if(target.getTag() != StopPropagationTest._TAG_BLUE_SPRITE2) + cc.log("Yellow blocks shouldn't response event."); + + if (this._isPointInNode(touches[0].getLocation(), target)) + target.setOpacity(255); + // Stop propagation, so yellow blocks will not be able to receive event. + event.stopPropagation(); + }.bind(this) + }); + + var keyboardEventListener = cc.EventListener.create({ + event: cc.EventListener.KEYBOARD, + onKeyPressed: function(key, event){ + var target = event.getCurrentTarget(); + if(!(target.getTag() == StopPropagationTest._TAG_BLUE_SPRITE || target.getTag() == StopPropagationTest._TAG_BLUE_SPRITE2)){ + cc.log("Yellow blocks shouldn't response event."); + } + // Stop propagation, so yellow blocks will not be able to receive event. + event.stopPropagation(); + } + }); + + var SPRITE_COUNT = 8, sprite1, sprite2; + + for (var i = 0; i < SPRITE_COUNT; i++) { + if(i==4) { + sprite1 = new cc.Sprite("res/Images/CyanSquare.png"); + sprite1.setTag(StopPropagationTest._TAG_BLUE_SPRITE); + this.addChild(sprite1, 100); + + sprite2 = new cc.Sprite("res/Images/CyanSquare.png"); + sprite2.setTag(StopPropagationTest._TAG_BLUE_SPRITE2); + this.addChild(sprite2, 100); + } else { + sprite1 = new cc.Sprite("res/Images/YellowSquare.png"); + this.addChild(sprite1, 0); + sprite2 = new cc.Sprite("res/Images/YellowSquare.png"); + this.addChild(sprite2, 0); + } + + + cc.eventManager.addListener(touchOneByOneListener.clone(), sprite1); + cc.eventManager.addListener(keyboardEventListener.clone(), sprite1); + + cc.eventManager.addListener(touchAllAtOnceListener.clone(), sprite2); + cc.eventManager.addListener(keyboardEventListener.clone(), sprite2); + + + var visibleSize = cc.director.getVisibleSize(); + sprite1.x = cc.visibleRect.left.x + visibleSize.width / (SPRITE_COUNT - 1) * i; + sprite1.y = cc.visibleRect.center.y + sprite2.getContentSize().height / 2 + 10; + sprite2.x = cc.visibleRect.left.x + visibleSize.width / (SPRITE_COUNT - 1) * i; + sprite2.y = cc.visibleRect.center.y - sprite2.getContentSize().height / 2 - 10; + } + //----end9---- + }, + + _isPointInNode: function (pt, node) { + //----start9----_isPointInNode + var s = node.getContentSize(); + return cc.rectContainsPoint(cc.rect(0, 0, s.width, s.height), node.convertToNodeSpace(pt)); + //----end9---- + }, + + _isPointInTopHalfAreaOfScreen: function(pt){ + //----start9----_isPointInTopHalfAreaOfScreen + var winSize = cc.director.getWinSize(); + return (pt.y >= winSize.height/2); + //----end9---- + }, + + title: function(){ + return "Stop Propagation Test"; + }, + + subtitle: function() { + return "Shouldn't crash and only blue block could be clicked"; + } +}); +StopPropagationTest._TAG_BLUE_SPRITE = 101; +StopPropagationTest._TAG_BLUE_SPRITE2 = 102; + +StopPropagationTest.create = function(){ + var test = new StopPropagationTest(); + test.init(); + return test; +}; + +var Issue4160 = EventDispatcherTestDemo.extend({ + ctor: function(){ + //----start10----ctor + this._super(); + var origin = cc.director.getVisibleOrigin(); + var size = cc.director.getVisibleSize(); + + var sprite1 = TouchableSprite.create(-30); + sprite1.setTexture("res/Images/CyanSquare.png"); + sprite1.x = origin.x + (size.width/2) - 80; + sprite1.y = origin.y + (size.height/2) + 40; + this.addChild(sprite1, 5); + + var sprite2 = TouchableSprite.create(-20); + sprite2.setTexture("res/Images/MagentaSquare.png"); + sprite2.removeListenerOnTouchEnded(true); + sprite2.x = origin.x + (size.width/2); + sprite2.y = origin.y + (size.height/2); + this.addChild(sprite2, 10); + + var sprite3 = TouchableSprite.create(-10); + sprite3.setTexture("res/Images/YellowSquare.png"); + sprite3.x = 0; + sprite3.y = 0; + sprite2.addChild(sprite3, 21); + //----end10---- + }, + + title: function(){ + return "Issue 4160: Out of range exception"; + }, + + subtitle: function() { + return "Touch the red block twice \n should not crash and the red one couldn't be touched"; + } +}); + +Issue4160.create = function(){ + var test = new Issue4160(); + test.init(); + return test; +}; + +var PauseResumeTargetTest = EventDispatcherTestDemo.extend({ + ctor: function () { + //----start11----ctor + this._super(); + + var origin = cc.director.getVisibleOrigin(); + var size = cc.director.getVisibleSize(); + + var sprite1 = TouchableSprite.create(); + sprite1.setTexture("res/Images/CyanSquare.png"); + sprite1.x = origin.x + size.width / 2 - 180; + sprite1.y = origin.y + size.height / 2 + 40; + this.addChild(sprite1, 10); + + var sprite2 = TouchableSprite.create(); + sprite2.setTexture("res/Images/MagentaSquare.png"); + sprite2.x = origin.x + size.width / 2 - 100; + sprite2.y = origin.y + size.height / 2; + this.addChild(sprite2, 1); + + var sprite3 = TouchableSprite.create(100); // Sprite3 uses fixed priority listener + sprite3.setTexture("res/Images/YellowSquare.png"); + sprite3.x = 0; + sprite3.y = 0; + sprite2.addChild(sprite3, -1); + + var _this = this; + var popup = new cc.MenuItemFont("Popup", function(sender){ + sprite3.getListener().setEnabled(false); + cc.eventManager.pauseTarget(_this, true); + var colorLayer = new cc.LayerColor(cc.color(0, 0, 255, 100)); + _this.addChild(colorLayer, 999); //set colorLayer to top + + // Add the button + var backgroundButton = new cc.Scale9Sprite(s_extensions_button); + var backgroundHighlightedButton = new cc.Scale9Sprite(s_extensions_buttonHighlighted); + + var titleButton = new cc.LabelTTF("Close Dialog", "Marker Felt", 26); + titleButton.color = cc.color(159, 168, 176); + + var controlButton = new cc.ControlButton(titleButton, backgroundButton); + controlButton.setBackgroundSpriteForState(backgroundHighlightedButton, cc.CONTROL_STATE_HIGHLIGHTED); + controlButton.setTitleColorForState(cc.color.WHITE, cc.CONTROL_STATE_HIGHLIGHTED); + + controlButton.anchorX = 0.5; + controlButton.anchorY = 1; + controlButton.x = size.width / 2 + 50; + controlButton.y = size.height / 2; + colorLayer.addChild(controlButton, 1); + controlButton.addTargetWithActionForControlEvents(this, function(){ + colorLayer.removeFromParent(); + cc.eventManager.resumeTarget(_this, true); + sprite3.getListener().setEnabled(true); + }, cc.CONTROL_EVENT_TOUCH_UP_INSIDE); + + // Add the black background + var background = new cc.Scale9Sprite(s_extensions_buttonBackground); + background.width = 300; + background.height = 170; + background.x = size.width / 2.0 + 50; + background.y = size.height / 2.0; + colorLayer.addChild(background); + }); + + popup.setAnchorPoint(1,0.5); + popup.setPosition(cc.visibleRect.right); + + var menu = new cc.Menu(popup); + menu.setAnchorPoint(0, 0); + menu.setPosition(0, 0); + + this.addChild(menu); + //----end11---- + }, + + title: function(){ + return "PauseResumeTargetTest"; + }, + + subtitle: function() { + return "Yellow block uses fixed priority"; + } +}); + +PauseResumeTargetTest.create = function(){ + var test = new Issue4160(); + test.init(); + return test; +}; + +var Issue9898 = EventDispatcherTestDemo.extend({ + + title: function(){ + return "Issue9898"; + }, + + subtitle: function(){ + return "Should not crash if dispatch event after remove\n event listener in callback"; + }, + + ctor: function(){ + this._super(); + //----start12----ctor + + var origin = cc.director.getVisibleOrigin(); + var size = cc.director.getVisibleSize(); + + var node = new cc.Node(); + this.addChild(node); + + var _listener = cc.EventListener.create({ + event: cc.EventListener.CUSTOM, + eventName: "Issue9898", + callback: function(event){ + cc.eventManager.removeListener(_listener); + event = new cc.EventCustom("Issue9898"); + cc.eventManager.dispatchEvent(event); + } + }); + cc.eventManager.addListener(_listener, 1); + var menuItem = new cc.MenuItemFont("Dispatch Custom Event1", function(sender){ + var event = new cc.EventCustom("Issue9898"); + cc.eventManager.dispatchEvent(event); + }); + menuItem.setPosition(origin.x + size.width/2, origin.y + size.height/2); + + var menu = new cc.Menu(menuItem); + menu.setPosition(0, 0); + this.addChild(menu); + //----end12---- + } + +}); + +Issue9898.create = function(){ + var test = new Issue9898(); + test.init(); + return test; +}; + +var EventDispatcherTestScene = TestScene.extend({ + runThisTest:function (num) { + eventDispatcherSceneIdx = (num || num == 0) ? (num - 1) : -1; + this.addChild(nextDispatcherTest()); + director.runScene(this); + } +}); + +var arrayOfEventDispatcherTest = [ + TouchableSpriteTest, + FixedPriorityTest, + RemoveListenerWhenDispatching, + CustomEventTest, + LabelKeyboardEventTest, + SpriteAccelerationEventTest, + RemoveAndRetainNodeTest, + RemoveListenerAfterAddingTest, + DirectorEventTest, + //GlobalZTouchTest, + StopPropagationTest, + Issue4160, + PauseResumeTargetTest, + Issue9898 +]; + +var nextDispatcherTest = function () { + eventDispatcherSceneIdx++; + eventDispatcherSceneIdx = eventDispatcherSceneIdx % arrayOfEventDispatcherTest.length; + + if(window.sideIndexBar){ + eventDispatcherSceneIdx = window.sideIndexBar.changeTest(eventDispatcherSceneIdx, 11); + } + + return new arrayOfEventDispatcherTest[eventDispatcherSceneIdx](); +}; +var previousDispatcherTest = function () { + eventDispatcherSceneIdx--; + if (eventDispatcherSceneIdx < 0) + eventDispatcherSceneIdx += arrayOfEventDispatcherTest.length; + + if(window.sideIndexBar){ + eventDispatcherSceneIdx = window.sideIndexBar.changeTest(eventDispatcherSceneIdx, 11); + } + + return new arrayOfEventDispatcherTest[eventDispatcherSceneIdx](); +}; +var restartDispatcherTest = function () { + return new arrayOfEventDispatcherTest[eventDispatcherSceneIdx](); +}; \ No newline at end of file diff --git a/tests/js-tests/src/OpenGLTest/OpenGLTest.js b/tests/js-tests/src/OpenGLTest/OpenGLTest.js new file mode 100644 index 0000000000..bae9d902e8 --- /dev/null +++ b/tests/js-tests/src/OpenGLTest/OpenGLTest.js @@ -0,0 +1,1361 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var OpenGLTestIdx = -1; + +// the class inherit from TestScene +// every Scene each test used must inherit from TestScene, +// make sure the test have the menu item for back to main menu +var OpenGLTestScene = TestScene.extend({ + runThisTest:function (num) { + OpenGLTestIdx = (num || num == 0) ? (num - 1) : -1; + this.addChild(nextOpenGLTest()); + director.runScene(this); + } +}); + +cc.GLNode = cc.GLNode || cc.Node.extend({ + ctor:function(){ + this._super(); + this.init(); + }, + init:function(){ + this._renderCmd._needDraw = true; + this._renderCmd.rendering = function(ctx){ + cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW); + cc.kmGLPushMatrix(); + cc.kmGLLoadMatrix(this._stackMatrix); + + this._node.draw(ctx); + + cc.kmGLPopMatrix(); + }; + }, + draw:function(ctx){ + this._super(ctx); + } +}); + +var OpenGLTestLayer = BaseTestLayer.extend({ + _grossini:null, + _tamara:null, + _kathia:null, + _code:null, + + ctor:function() { + this._super(cc.color(0,0,0,255), cc.color(98,99,117,255) ); + }, + + title:function () { + return "OpenGLTest"; + }, + subtitle:function () { + return ""; + }, + onBackCallback:function (sender) { + var s = new OpenGLTestScene(); + s.addChild(previousOpenGLTest()); + director.runScene(s); + }, + onRestartCallback:function (sender) { + var s = new OpenGLTestScene(); + s.addChild(restartOpenGLTest()); + director.runScene(s); + }, + onNextCallback:function (sender) { + var s = new OpenGLTestScene(); + s.addChild(nextOpenGLTest()); + director.runScene(s); + }, + + // automation + numberOfPendingTests:function() { + return ( (arrayOfOpenGLTest.length-1) - OpenGLTestIdx ); + }, + + getTestNumber:function() { + return OpenGLTestIdx; + } +}); + +//------------------------------------------------------------------ +// +// ReadPixelsTest +// +//------------------------------------------------------------------ +var GLReadPixelsTest = OpenGLTestLayer.extend({ + + ctor:function() { + this._super(); + + if( 'opengl' in cc.sys.capabilities ) { + var x = winSize.width; + var y = winSize.height; + + var blue = new cc.LayerColor(cc.color(0, 0, 255, 255)); + var red = new cc.LayerColor(cc.color(255, 0, 0, 255)); + var green = new cc.LayerColor(cc.color(0, 255, 0, 255)); + var white = new cc.LayerColor(cc.color(255, 255, 255, 255)); + + blue.scale = 0.5; + blue.x = -x / 4; + blue.y = -y / 4; + + red.scale = 0.5; + red.x = x / 4; + red.y = -y / 4; + + green.scale = 0.5; + green.x = -x / 4; + green.y = y / 4; + + white.scale = 0.5; + white.x = x / 4; + white.y = y / 4; + + this.addChild(blue,10); + this.addChild(white,11); + this.addChild(green,12); + this.addChild(red,13); + } + }, + + title:function () { + return "gl.ReadPixels()"; + }, + subtitle:function () { + return "Tests ReadPixels. See console"; + }, + + // + // Automation + // + getExpectedResult:function() { + // red, green, blue, white + var ret = [{"0":255,"1":0,"2":0,"3":255},{"0":0,"1":255,"2":0,"3":255},{"0":0,"1":0,"2":255,"3":255},{"0":255,"1":255,"2":255,"3":255}]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var x = winSize.width; + var y = winSize.height; + + var rPixels = new Uint8Array(4); + var gPixels = new Uint8Array(4); + var bPixels = new Uint8Array(4); + var wPixels = new Uint8Array(4); + + // blue + gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, bPixels); + + // red + gl.readPixels(x-1, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, rPixels); + + // green + gl.readPixels(0, y-1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, gPixels); + + // white + gl.readPixels(x-1, y-1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, wPixels); + + var ret = [ rPixels, gPixels, bPixels, wPixels]; + return JSON.stringify(ret); + } + +}); + + +//------------------------------------------------------------------ +// +// GLClearTest +// +//------------------------------------------------------------------ +var GLClearTest = OpenGLTestLayer.extend({ + + ctor:function() { + this._super(); + + if( 'opengl' in cc.sys.capabilities ) { + + var blue = new cc.LayerColor(cc.color(0, 0, 255, 255)); + this.addChild( blue, 1 ); + + var node = new cc.GLNode(); + node.init(); + node.draw = function() { + gl.clear( gl.COLOR_BUFFER_BIT ); + }; + + this.addChild( node, 10 ); + node.x = winSize.width/2; + node.y = winSize.height/2 ; + } + }, + + title:function () { + return "gl.clear(gl.COLOR_BUFFER_BIT)"; + }, + subtitle:function () { + return "Testing gl.clear() with cc.GLNode"; + }, + + // + // Automation + // + getExpectedResult:function() { + // black pixel, not a blue pixel + var ret = {"0":0,"1":0,"2":0,"3":255}; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = this.readPixels(winSize.width/2, winSize.height/2, 1, 1); + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// GLNodeWebGLAPITest +// +//------------------------------------------------------------------ +var GLNodeWebGLAPITest = OpenGLTestLayer.extend({ + + ctor:function() { + this._super(); + + if( 'opengl' in cc.sys.capabilities ) { + + // simple shader example taken from: + // http://learningwebgl.com/blog/?p=134 + var vsh = "\n" + + "attribute vec3 aVertexPosition;\n" + + "attribute vec4 aVertexColor;\n" + + "uniform mat4 uMVMatrix;\n" + + "uniform mat4 uPMatrix;\n" + + "varying vec4 vColor;\n" + + "void main(void) {\n" + + " gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);\n" + + " vColor = aVertexColor;\n" + + "}\n"; + + var fsh = "\n" + + "#ifdef GL_ES\n" + + "precision mediump float;\n" + + "#endif\n" + + "varying vec4 vColor;\n" + + "void main(void) {\n"+ + " gl_FragColor = vColor;\n" + + "}\n"; + + var fshader = this.compileShader(fsh, 'fragment'); + var vshader = this.compileShader(vsh, 'vertex'); + + var shaderProgram = this.shader = gl.createProgram(); + + gl.attachShader(shaderProgram, vshader); + gl.attachShader(shaderProgram, fshader); + gl.linkProgram(shaderProgram); + + if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { + throw("Could not initialise shaders"); + } + + gl.useProgram(shaderProgram); + + shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition"); + gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute); + + shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor"); + gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute); + + shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix"); + shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix"); + + this.initBuffers(); + + var glnode = new cc.GLNode(); + this.addChild(glnode,10); + this.glnode = glnode; + + glnode.draw = function() { + var pMatrix = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]; + this.pMatrix = pMatrix = new Float32Array(pMatrix); + + var mvMatrix = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]; + this.mvMatrix = mvMatrix = new Float32Array(mvMatrix); + + gl.useProgram(this.shader); + gl.uniformMatrix4fv(this.shader.pMatrixUniform, false, this.pMatrix); + gl.uniformMatrix4fv(this.shader.mvMatrixUniform, false, this.mvMatrix); + + gl.enableVertexAttribArray(this.shader.vertexPositionAttribute); + gl.enableVertexAttribArray(this.shader.vertexColorAttribute); + + // Draw fullscreen Square + gl.bindBuffer(gl.ARRAY_BUFFER, this.squareVertexPositionBuffer); + gl.vertexAttribPointer(this.shader.vertexPositionAttribute, this.squareVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.squareVertexColorBuffer); + gl.vertexAttribPointer(this.shader.vertexColorAttribute, this.squareVertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0); + + this.setMatrixUniforms(); + gl.drawArrays(gl.TRIANGLE_STRIP, 0, this.squareVertexPositionBuffer.numItems); + + // Draw fullscreen Triangle + gl.bindBuffer(gl.ARRAY_BUFFER, this.triangleVertexPositionBuffer); + gl.vertexAttribPointer(this.shader.vertexPositionAttribute, this.triangleVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.triangleVertexColorBuffer); + gl.vertexAttribPointer(this.shader.vertexColorAttribute, this.triangleVertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0); + + gl.drawArrays(gl.TRIANGLES, 0, this.triangleVertexPositionBuffer.numItems); + + gl.bindBuffer(gl.ARRAY_BUFFER, null); + + }.bind(this); + + } + }, + + setMatrixUniforms:function() { + gl.uniformMatrix4fv(this.shader.pMatrixUniform, false, this.pMatrix); + gl.uniformMatrix4fv(this.shader.mvMatrixUniform, false, this.mvMatrix); + }, + + initBuffers:function() { + var triangleVertexPositionBuffer = this.triangleVertexPositionBuffer = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer); + var vertices = [ + 0.0, 1.0, 0.0, + -1.0, -1.0, 0.0, + 1.0, -1.0, 0.0 + ]; + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); + triangleVertexPositionBuffer.itemSize = 3; + triangleVertexPositionBuffer.numItems = 3; + + var triangleVertexColorBuffer = this.triangleVertexColorBuffer = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexColorBuffer); + var colors = [ + 1.0, 0.0, 0.0, 1.0, + 1.0, 0.0, 0.0, 1.0, + 1.0, 0.0, 0.0, 1.0 + ]; + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW); + triangleVertexColorBuffer.itemSize = 4; + triangleVertexColorBuffer.numItems = 3; + + + var squareVertexPositionBuffer = this.squareVertexPositionBuffer = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexPositionBuffer); + vertices = [ + 1.0, 1.0, 0.0, + -1.0, 1.0, 0.0, + 1.0, -1.0, 0.0, + -1.0, -1.0, 0.0 + ]; + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); + squareVertexPositionBuffer.itemSize = 3; + squareVertexPositionBuffer.numItems = 4; + + var squareVertexColorBuffer = this.squareVertexColorBuffer = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexColorBuffer); + colors = [ + 0.0, 0.0, 1.0, 1.0, + 0.0, 0.0, 1.0, 1.0, + 0.0, 0.0, 1.0, 1.0, + 0.0, 0.0, 1.0, 1.0 + ]; + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW); + squareVertexColorBuffer.itemSize = 4; + squareVertexColorBuffer.numItems = 4; + + gl.bindBuffer(gl.ARRAY_BUFFER, null); + }, + + compileShader:function(source, type) { + var shader; + if( type == 'fragment' ) + shader = gl.createShader(gl.FRAGMENT_SHADER); + else + shader = gl.createShader(gl.VERTEX_SHADER); + gl.shaderSource(shader, source); + gl.compileShader(shader); + if( !gl.getShaderParameter(shader, gl.COMPILE_STATUS) ) { + cc.log( gl.getShaderInfoLog(shader) ); + throw("Could not compile " + type + " shader"); + } + return shader; + }, + + title:function () { + return "GLNode + WebGL API"; + }, + subtitle:function () { + return "blue background with a red triangle in the middle"; + }, + + // + // Automation + // + getExpectedResult:function() { + // blue, red, blue + var ret = [{"0":0,"1":0,"2":255,"3":255},{"0":0,"1":0,"2":255,"3":255},{"0":255,"1":0,"2":0,"3":255}]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret1 = this.readPixels(10, winSize.height-1, 1, 1); + var ret2 = this.readPixels(winSize.width-10, winSize.height-1, 1, 1); + var ret3 = this.readPixels(winSize.width/2, winSize.height/2, 1, 1); + + return JSON.stringify([ret1,ret2,ret3]); + } +}); + +//------------------------------------------------------------------ +// +// GLNodeCCAPITest +// +//------------------------------------------------------------------ +var GLNodeCCAPITest = OpenGLTestLayer.extend({ + + ctor:function() { + this._super(); + + if( 'opengl' in cc.sys.capabilities ) { + + + var glnode = new cc.GLNode(); + this.addChild(glnode,10); + this.glnode = glnode; + + this.shader = cc.shaderCache.getProgram("ShaderPositionColor"); + this.initBuffers(); + + glnode.draw = function() { + + this.shader.use(); + this.shader.setUniformsForBuiltins(); + cc.glEnableVertexAttribs( cc.VERTEX_ATTRIB_FLAG_COLOR | cc.VERTEX_ATTRIB_FLAG_POSITION); + + // Draw fullscreen Square + gl.bindBuffer(gl.ARRAY_BUFFER, this.squareVertexPositionBuffer); + gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.squareVertexColorBuffer); + gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.FLOAT, false, 0, 0); + + gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); + + // Draw fullscreen Triangle + gl.bindBuffer(gl.ARRAY_BUFFER, this.triangleVertexPositionBuffer); + gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.triangleVertexColorBuffer); + gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.FLOAT, false, 0, 0); + + gl.drawArrays(gl.TRIANGLE_STRIP, 0, 3); + + gl.bindBuffer(gl.ARRAY_BUFFER, null); + + }.bind(this); + + } + }, + + initBuffers:function() { + // + // Triangle + // + var triangleVertexPositionBuffer = this.triangleVertexPositionBuffer = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer); + var vertices = [ + winSize.width/2, winSize.height, + 0, 0, + winSize.width, 0 + ]; + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); + + var triangleVertexColorBuffer = this.triangleVertexColorBuffer = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexColorBuffer); + var colors = [ + 1.0, 0.0, 0.0, 1.0, + 1.0, 0.0, 0.0, 1.0, + 1.0, 0.0, 0.0, 1.0 + ]; + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW); + + // + // Square + // + var squareVertexPositionBuffer = this.squareVertexPositionBuffer = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexPositionBuffer); + vertices = [ + winSize.width, winSize.height, + 0, winSize.height, + winSize.width, 0, + 0, 0 + ]; + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); + + var squareVertexColorBuffer = this.squareVertexColorBuffer = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexColorBuffer); + colors = [ + 0.0, 0.0, 1.0, 1.0, + 0.0, 0.0, 1.0, 1.0, + 0.0, 0.0, 1.0, 1.0, + 0.0, 0.0, 1.0, 1.0 + ]; + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW); + gl.bindBuffer(gl.ARRAY_BUFFER, null); + }, + title:function () { + return "GLNode + cocos2d API"; + }, + subtitle:function () { + return "blue background with a red triangle in the middle"; + }, + + // + // Automation + // + getExpectedResult:function() { + // blue, red, blue + var ret = [{"0":0,"1":0,"2":255,"3":255},{"0":0,"1":0,"2":255,"3":255},{"0":255,"1":0,"2":0,"3":255}]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret1 = this.readPixels(10, winSize.height-1, 1, 1); + var ret2 = this.readPixels(winSize.width-10, winSize.height-1, 1, 1); + var ret3 = this.readPixels(winSize.width/2, winSize.height/2, 1, 1); + + return JSON.stringify([ret1,ret2,ret3]); + } +}); + +//------------------------------------------------------------------ +// +// ShaderNode +// +//------------------------------------------------------------------ +var ShaderNode = cc.GLNode.extend({ + ctor:function(vertexShader, framentShader) { + this._super(); + this.init(); + + if( 'opengl' in cc.sys.capabilities ) { + this.width = 256; + this.height = 256; + this.anchorX = 0.5; + this.anchorY = 0.5; + + this.shader = cc.GLProgram.create(vertexShader, framentShader); + this.shader.retain(); + this.shader.addAttribute("aVertex", cc.VERTEX_ATTRIB_POSITION); + this.shader.link(); + this.shader.updateUniforms(); + + var program = this.shader.getProgram(); + this.uniformCenter = gl.getUniformLocation( program, "center"); + this.uniformResolution = gl.getUniformLocation( program, "resolution"); + this.initBuffers(); + + this.scheduleUpdate(); + this._time = 0; + } + }, + draw:function() { + this.shader.use(); + this.shader.setUniformsForBuiltins(); + + // + // Uniforms + // + var frameSize = cc.view.getFrameSize(); + this.shader.setUniformLocationF32( this.uniformCenter, frameSize.width/2, frameSize.height/2); + this.shader.setUniformLocationF32( this.uniformResolution, 256, 256); + + cc.glEnableVertexAttribs( cc.VERTEX_ATTRIB_FLAG_POSITION ); + + // Draw fullscreen Square + gl.bindBuffer(gl.ARRAY_BUFFER, this.squareVertexPositionBuffer); + gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0); + gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); + + gl.bindBuffer(gl.ARRAY_BUFFER, null); + }, + + update:function(dt) { + this._time += dt; + }, + initBuffers:function() { + + // + // Square + // + var squareVertexPositionBuffer = this.squareVertexPositionBuffer = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexPositionBuffer); + vertices = [ + 256, 256, + 0, 256, + 256, 0, + 0, 0 + ]; + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); + gl.bindBuffer(gl.ARRAY_BUFFER, null); + } +}); +//------------------------------------------------------------------ +// +// ShaderHeartTest +// +//------------------------------------------------------------------ +var ShaderHeartTest = OpenGLTestLayer.extend({ + ctor:function() { + this._super(); + + if( 'opengl' in cc.sys.capabilities ) { + var shaderNode = new ShaderNode("res/Shaders/example_Heart.vsh", "res/Shaders/example_Heart.fsh"); + this.addChild(shaderNode,10); + shaderNode.x = winSize.width/2; + shaderNode.y = winSize.height/2; + } + }, + + title:function () { + return "Shader Heart Test"; + }, + subtitle:function () { + return "You should see a heart in the center"; + }, + + // + // Automation + // + getExpectedResult:function() { + // redish pixel + var ret = {"0":255,"1":0,"2":0,"3":255}; + return JSON.stringify(ret); + }, + getCurrentResult:function() { + var ret = this.readPixels(winSize.width/2, winSize.height/2, 1, 1); + ret[0] = ret[0] > 240 ? 255 : 0; + ret[3] = ret[3] > 240 ? 255 : 0; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// ShaderMandelbrotTest +// +//------------------------------------------------------------------ +var ShaderMandelbrotTest = OpenGLTestLayer.extend({ + ctor:function() { + this._super(); + + if( 'opengl' in cc.sys.capabilities ) { + var shaderNode = new ShaderNode("res/Shaders/example_Mandelbrot.vsh", "res/Shaders/example_Mandelbrot.fsh"); + this.addChild(shaderNode,10); + shaderNode.x = winSize.width/2; + shaderNode.y = winSize.height/2; + } + }, + + title:function () { + return "Shader Mandelbrot Test"; + }, + subtitle:function () { + return "Mandelbrot shader with Zoom"; + }, + + // + // Automation + // + getExpectedResult:function() { + throw "Automation Test Not implemented yet"; + }, + getCurrentResult:function() { + throw "Automation Test Not implemented yet"; + } +}); + +//------------------------------------------------------------------ +// +// ShaderMonjoriTest +// +//------------------------------------------------------------------ +var ShaderMonjoriTest = OpenGLTestLayer.extend({ + ctor:function() { + this._super(); + + if( 'opengl' in cc.sys.capabilities ) { + var shaderNode = new ShaderNode("res/Shaders/example_Monjori.vsh", "res/Shaders/example_Monjori.fsh"); + this.addChild(shaderNode,10); + shaderNode.x = winSize.width/2; + shaderNode.y = winSize.height/2; + } + }, + + title:function () { + return "Shader Monjori Test"; + }, + subtitle:function () { + return "Monjori plane deformations"; + }, + + // + // Automation + // + getExpectedResult:function() { + throw "Automation Test Not implemented yet"; + }, + getCurrentResult:function() { + throw "Automation Test Not implemented yet"; + } +}); + +//------------------------------------------------------------------ +// +// ShaderPlasmaTest +// +//------------------------------------------------------------------ +var ShaderPlasmaTest = OpenGLTestLayer.extend({ + ctor:function() { + this._super(); + + if( 'opengl' in cc.sys.capabilities ) { + var shaderNode = new ShaderNode("res/Shaders/example_Plasma.vsh", "res/Shaders/example_Plasma.fsh"); + this.addChild(shaderNode,10); + shaderNode.x = winSize.width/2; + shaderNode.y = winSize.height/2; + } + }, + title:function () { + return "Shader Plasma Test"; + }, + subtitle:function () { + return "You should see a plasma in the center"; + }, + + // + // Automation + // + getExpectedResult:function() { + // redish pixel + return JSON.stringify(true); + }, + getCurrentResult:function() { + var ret = this.readPixels(winSize.width/2, winSize.height/2, 1, 1); + var sum = ret[0] + ret[1] + ret[2]; + return JSON.stringify(sum>300); + } +}); + +//------------------------------------------------------------------ +// +// ShaderFlowerTest +// +//------------------------------------------------------------------ +var ShaderFlowerTest = OpenGLTestLayer.extend({ + + ctor:function() { + this._super(); + + if( 'opengl' in cc.sys.capabilities ) { + + var shaderNode = new ShaderNode("res/Shaders/example_Flower.vsh", "res/Shaders/example_Flower.fsh"); + this.addChild(shaderNode,10); + shaderNode.x = winSize.width/2; + shaderNode.y = winSize.height/2; + } + }, + title:function () { + return "Shader Flower Test"; + }, + subtitle:function () { + return "You should see a moving Flower in the center"; + }, + + // + // Automation + // + getExpectedResult:function() { + // redish pixel + return JSON.stringify(true); + }, + getCurrentResult:function() { + var ret = this.readPixels(winSize.width/2, winSize.height/2, 1, 1); + var sum = ret[0] + ret[1] + ret[2]; + return JSON.stringify(sum<30); + } +}); + +//------------------------------------------------------------------ +// +// ShaderJuliaTest +// +//------------------------------------------------------------------ +var ShaderJuliaTest = OpenGLTestLayer.extend({ + + ctor:function() { + this._super(); + + if( 'opengl' in cc.sys.capabilities ) { + + var shaderNode = new ShaderNode("res/Shaders/example_Julia.vsh", "res/Shaders/example_Julia.fsh"); + this.addChild(shaderNode,10); + shaderNode.x = winSize.width/2; + shaderNode.y = winSize.height/2; + } + }, + title:function () { + return "Shader Julia Test"; + }, + subtitle:function () { + return "You should see Julia effect"; + }, + + // + // Automation + // + getExpectedResult:function() { + // redish pixel + return JSON.stringify(true); + }, + getCurrentResult:function() { + var ret = this.readPixels(winSize.width/2, winSize.height/2, 1, 1); + var sum = ret[0] + ret[1] + ret[2]; + return JSON.stringify(sum>300); + } +}); + +//------------------------------------------------------------------ +// +// ShaderOutline +// +//------------------------------------------------------------------ +//FIX ME: +//The renderers of webgl and opengl is quite different now, so we have to use different shader and different js code +//This is a bug, need to be fixed in the future +var ShaderOutlineEffect = OpenGLTestLayer.extend({ + ctor:function() { + this._super(); + + if( 'opengl' in cc.sys.capabilities ) { + if(cc.sys.isNative){ + this.shader = new cc.GLProgram("res/Shaders/example_Outline_noMVP.vsh", "res/Shaders/example_Outline.fsh"); + this.shader.link(); + this.shader.updateUniforms(); + } + else{ + this.shader = new cc.GLProgram("res/Shaders/example_Outline.vsh", "res/Shaders/example_Outline.fsh"); + this.shader.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); + this.shader.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); + this.shader.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR); + + this.shader.link(); + this.shader.updateUniforms(); + this.shader.use(); + this.shader.setUniformLocationWith1f(this.shader.getUniformLocationForName('u_threshold'), 1.75); + this.shader.setUniformLocationWith3f(this.shader.getUniformLocationForName('u_outlineColor'), 0 / 255, 255 / 255, 0 / 255); + } + + this.sprite = new cc.Sprite('res/Images/grossini.png'); + this.sprite.attr({ + x: winSize.width / 2, + y: winSize.height / 2 + }); + this.sprite.runAction(cc.sequence(cc.rotateTo(1.0, 10), cc.rotateTo(1.0, -10)).repeatForever()); + + if(cc.sys.isNative){ + var glProgram_state = cc.GLProgramState.getOrCreateWithGLProgram(this.shader); + glProgram_state.setUniformFloat("u_threshold", 1.75); + glProgram_state.setUniformVec3("u_outlineColor", {x: 0/255, y: 255/255, z: 0/255}); + this.sprite.setGLProgramState(glProgram_state); + }else{ + this.sprite.shaderProgram = this.shader; + } + + this.addChild(this.sprite); + + this.scheduleUpdate(); + } + }, + update:function(dt) { + if( 'opengl' in cc.sys.capabilities ) { + if(cc.sys.isNative){ + this.sprite.getGLProgramState().setUniformFloat("u_radius", Math.abs(this.sprite.getRotation() / 500)); + }else{ + this.shader.use(); + this.shader.setUniformLocationWith1f(this.shader.getUniformLocationForName('u_radius'), Math.abs(this.sprite.getRotation() / 500)); + this.shader.updateUniforms(); + } + } + }, + title:function () { + return "Shader Outline Effect"; + }, + subtitle:function () { + return "Should see rotated image with animated outline effect"; + } + + // + // Automation + // +}); + +//------------------------------------------------------------------ +// +// ShaderRetro +// +//------------------------------------------------------------------ + +// Fix me: +// The implemetation of LabelBMFont is quite defferent between html5 and native +// That is why we use 'if (cc.sys.isNative){...}else{...}' in this test case +// It should be fixed in the future. +var ShaderRetroEffect = OpenGLTestLayer.extend({ + ctor:function() { + this._super(); + + if( 'opengl' in cc.sys.capabilities ) { + var program = new cc.GLProgram("res/Shaders/example_ColorBars.vsh", "res/Shaders/example_ColorBars.fsh"); + program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); + program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); + program.link(); + program.updateUniforms(); + + var label = new cc.LabelBMFont("RETRO EFFECT","res/fonts/west_england-64.fnt"); + + if(cc.sys.isNative) + label.children[0].shaderProgram = program; + else + label.shaderProgram = program; + + label.x = winSize.width/2; + + label.y = winSize.height/2; + this.addChild(label); + + this.scheduleUpdate(); + + this.label = label; + this.accum = 0; + } + }, + update:function(dt) { + this.accum += dt; + + if(cc.sys.isNative){ + var letters = this.label.children[0]; + for(var i = 0; i< letters.getStringLength(); ++i){ + var sprite = letters.getLetter(i); + sprite.y = Math.sin( this.accum * 2 + i/2.0) * 20; + sprite.scaleY = ( Math.sin( this.accum * 2 + i/2.0 + 0.707) ); + } + }else{ + var children = this.label.children; + + for( var i in children ) { + var sprite = children[i]; + sprite.y = Math.sin( this.accum * 2 + i/2.0) * 20; + + // add fabs() to prevent negative scaling + var scaleY = ( Math.sin( this.accum * 2 + i/2.0 + 0.707) ); + + sprite.scaleY = scaleY; + } + } + }, + title:function () { + return "Shader Retro Effect"; + }, + subtitle:function () { + return "Should see moving colors, and a sin effect on the letters"; + } + + // + // Automation + // +}); +//------------------------------------------------------------------ +// +// GLGetActiveTest +// +//------------------------------------------------------------------ +var GLGetActiveTest = OpenGLTestLayer.extend({ + + ctor:function() { + this._super(); + + if( 'opengl' in cc.sys.capabilities ) { + var sprite = this.sprite = new cc.Sprite("res/Images/grossini.png"); + sprite.x = winSize.width/2; + sprite.y = winSize.height/2; + this.addChild( sprite ); + + // after auto test + this.scheduleOnce( this.onTest, 0.5 ); + } + }, + + onTest:function(dt) { + cc.log( this.getCurrentResult() ); + }, + + title:function () { + return "gl.getActive***"; + }, + subtitle:function () { + return "Tests gl.getActiveUniform / getActiveAttrib. See console"; + }, + + // + // Automation + // + getExpectedResult:function() { + // redish pixel + var ret = [{"size":1,"type":35666,"name":"a_position"},{"size":1,"type":35678,"name":"CC_Texture"},[2,3]]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = []; + var p = this.sprite.shaderProgram.getProgram(); + ret.push( gl.getActiveAttrib( p, 0 ) ); + ret.push( gl.getActiveUniform( p, 0 ) ); + ret.push( gl.getAttachedShaders( p ) ); + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TexImage2DTest +// +//------------------------------------------------------------------ +var TexImage2DTest = OpenGLTestLayer.extend({ + + ctor:function() { + this._super(); + + if( 'opengl' in cc.sys.capabilities ) { + var glnode = new cc.GLNode(); + this.addChild(glnode,10); + this.glnode = glnode; + glnode.x = winSize.width/2; + glnode.y = winSize.height/2; + glnode.width = 128; + glnode.height = 128; + glnode.anchorX = 0.5; + glnode.anchorY = 0.5; + + this.shader = cc.shaderCache.getProgram("ShaderPositionTexture"); + this.initGL(); + + glnode.draw = function() { + this.shader.use(); + this.shader.setUniformsForBuiltins(); + + gl.bindTexture(gl.TEXTURE_2D, this.my_texture); + cc.glEnableVertexAttribs( cc.VERTEX_ATTRIB_FLAG_TEX_COORDS | cc.VERTEX_ATTRIB_FLAG_POSITION); + + // Draw fullscreen Square + gl.bindBuffer(gl.ARRAY_BUFFER, this.squareVertexPositionBuffer); + gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0); + + gl.bindBuffer(gl.ARRAY_BUFFER, this.squareVertexTextureBuffer); + gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 0, 0); + + gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); + + gl.bindTexture(gl.TEXTURE_2D, null); + gl.bindBuffer(gl.ARRAY_BUFFER, null); + + }.bind(this); + + } + }, + + initGL:function() { + var texture = this.my_texture = gl.createTexture(); + gl.bindTexture( gl.TEXTURE_2D, texture ); + + var pixels = new Uint8Array(4096); + for( var i=0; i 0 ) + cc.log( gl.getExtension( array[0] ) ); + } + } + }, + + title:function () { + return "GetSupportedExtensionsTest"; + }, + subtitle:function () { + return "See console for the supported GL extensions"; + }, + + // + // Automation + // + getExpectedResult:function() { + var ret = ["[object Array]",null]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + // Extensions varies from machine to machine. Just check for typeof Array + var ext = gl.getSupportedExtensions(); + var type = Object.prototype.toString.call( ext ); + var n = gl.getExtension('do_no_exist'); + return JSON.stringify([type,n]); + } +}); + +//------------------------------------------------------------------ +// +// GLTexParamterTest +// +//------------------------------------------------------------------ +var GLTexParamterTest = OpenGLTestLayer.extend({ + + ctor:function() { + this._super(); + + if( 'opengl' in cc.sys.capabilities ) { + if( ! autoTestEnabled ) { + cc.log( this.getTexValues() ); + } + } + }, + + title:function () { + return "GLTexParamterTest"; + }, + subtitle:function () { + return "tests texParameter()"; + }, + getTexValues:function() { + if(!cc.sys.isNative){ + var texture2d = cc.textureCache.getTextureForKey(s_pathGrossini); + gl.bindTexture(gl.TEXTURE_2D, texture2d.getName()); + } else { + gl.bindTexture(gl.TEXTURE_2D, null); + } + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); + gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); + + var mag = gl.getTexParameter(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER); + var min = gl.getTexParameter(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER); + var w_s = gl.getTexParameter(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S); + var w_t = gl.getTexParameter(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S); + + var a = [mag, min, w_s, w_t]; + return a; + }, + + // + // Automation + // + getExpectedResult:function() { + var ret = [9728,9728,33071,33071]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = this.getTexValues(); + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// GLGetUniformTest +// +//------------------------------------------------------------------ +var GLGetUniformTest = OpenGLTestLayer.extend({ + + ctor:function() { + this._super(); + + if( 'opengl' in cc.sys.capabilities ) { + + if( ! autoTestEnabled ) { + cc.log( JSON.stringify( this.runTest() )); + } + + } + }, + + title:function () { + return "GLGetUniformTest"; + }, + subtitle:function () { + return "tests texParameter()"; + }, + runTest:function() { + + var shader = cc.shaderCache.getProgram("ShaderPositionTextureColor"); + var program = shader.getProgram(); + shader.use(); + + var loc = cc.sys.isNative ? gl.getUniformLocation(program, "CC_MVPMatrix") : gl.getUniformLocation(program, "CC_MVMatrix"); + + var pMatrix = [1,2,3,4, 4,3,2,1, 1,2,4,8, 1.1,1.2,1.3,1.4]; + this.pMatrix = new Float32Array(pMatrix); + + gl.uniformMatrix4fv(loc, false, this.pMatrix); + + return gl.getUniform( program, loc ); + }, + + // + // Automation + // + getExpectedResult:function() { + var ret = {"0":1,"1":2,"2":3,"3":4,"4":4,"5":3,"6":2,"7":1,"8":1,"9":2,"10":4,"11":8,"12":1.100000023841858,"13":1.2000000476837158,"14":1.2999999523162842,"15":1.399999976158142}; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = this.runTest(); + return JSON.stringify(ret); + } +}); + +//- +// +// Flow control +// +var arrayOfOpenGLTest = [ + ShaderOutlineEffect, + ShaderRetroEffect, + ShaderMonjoriTest, + ShaderMandelbrotTest, + ShaderHeartTest, + ShaderPlasmaTest, + ShaderFlowerTest, + ShaderJuliaTest, + GLGetActiveTest, + TexImage2DTest, + GetSupportedExtensionsTest, + GLReadPixelsTest, + GLClearTest, + GLNodeWebGLAPITest, + GLNodeCCAPITest, + GLTexParamterTest, + GLGetUniformTest +]; + +var nextOpenGLTest = function () { + OpenGLTestIdx++; + OpenGLTestIdx = OpenGLTestIdx % arrayOfOpenGLTest.length; + + return new arrayOfOpenGLTest[OpenGLTestIdx](); +}; +var previousOpenGLTest = function () { + OpenGLTestIdx--; + if (OpenGLTestIdx < 0) + OpenGLTestIdx += arrayOfOpenGLTest.length; + + return new arrayOfOpenGLTest[OpenGLTestIdx](); +}; +var restartOpenGLTest = function () { + return new arrayOfOpenGLTest[OpenGLTestIdx](); +}; \ No newline at end of file diff --git a/tests/js-tests/src/ParallaxTest/ParallaxTest.js b/tests/js-tests/src/ParallaxTest/ParallaxTest.js new file mode 100644 index 0000000000..1646851caf --- /dev/null +++ b/tests/js-tests/src/ParallaxTest/ParallaxTest.js @@ -0,0 +1,265 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var TAG_NODE = 9960; + +var parallaxTestSceneIdx = -1; + +ParallaxDemo = BaseTestLayer.extend({ + _atlas:null, + ctor:function() { + this._super(cc.color(0,0,0,255), cc.color(160,32,32,255)); + }, + + title:function () { + return "No title"; + }, + + onBackCallback:function (sender) { + var s = new ParallaxTestScene(); + s.addChild(previousParallaxTest()); + director.runScene(s); + }, + + onRestartCallback:function (sender) { + var s = new ParallaxTestScene(); + s.addChild(restartParallaxTest()); + director.runScene(s); + }, + + onNextCallback:function (sender) { + var s = new ParallaxTestScene(); + s.addChild(nextParallaxTest()); + director.runScene(s); + }, + // automation + numberOfPendingTests:function() { + return ( (arrayOfParallaxTest.length-1) - parallaxTestSceneIdx ); + }, + + getTestNumber:function() { + return parallaxTestSceneIdx; + } + +}); + +var Parallax1 = ParallaxDemo.extend({ + _parentNode:null, + _background:null, + _tilemap:null, + _cocosimage:null, + + ctor:function () { + this._super(); + + // Top Layer, a simple image + this._cocosimage = new cc.Sprite(s_power); + // scale the image (optional) + this._cocosimage.scale = 1.5; + // change the transform anchor point to 0,0 (optional) + this._cocosimage.anchorX = 0; + this._cocosimage.anchorY = 0; + + // Middle layer: a Tile map atlas + //var tilemap = cc.TileMapAtlas.create(s_tilesPng, s_levelMapTga, 16, 16); + this._tilemap = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test2.tmx"); + + // change the transform anchor to 0,0 (optional) + this._tilemap.anchorX = 0; + this._tilemap.anchorY = 0; + + // Anti Aliased images + //tilemap.texture.setAntiAliasTexParameters(); + + // background layer: another image + this._background = new cc.Sprite(s_back); + // scale the image (optional) + //background.scale = 1.5; + // change the transform anchor point (optional) + this._background.anchorX = 0; + this._background.anchorY = 0; + + // create a void node, a parent node + this._parentNode = new cc.ParallaxNode(); + + // NOW add the 3 layers to the 'void' node + + // background image is moved at a ratio of 0.4x, 0.5y + this._parentNode.addChild(this._background, -1, cc.p(0.4, 0.5), cc.p(0,0)); + + // tiles are moved at a ratio of 2.2x, 1.0y + this._parentNode.addChild(this._tilemap, 1, cc.p(2.2, 1.0), cc.p(0, 0)); + + // top image is moved at a ratio of 3.0x, 2.5y + this._parentNode.addChild(this._cocosimage, 2, cc.p(3.0, 2.5), cc.p(0, 0)); + + // now create some actions that will move the '_parent' node + // and the children of the '_parent' node will move at different + // speed, thus, simulation the 3D environment + var goUp = cc.moveBy(2, cc.p(0, 100)); + var goRight = cc.moveBy(2, cc.p(200, 0)); + var delay = cc.delayTime(2.0); + var goDown = goUp.reverse(); + var goLeft = goRight.reverse(); + var seq = cc.sequence(goUp, goRight, delay, goDown, goLeft); + this._parentNode.runAction(seq.repeatForever()); + + this.addChild(this._parentNode); + }, + + title:function () { + return "Parallax: parent and 3 children"; + }, + + // default values for automation + testDuration:5, + getExpectedResult:function() { + var ret = {}; + ret.pos_parent = cc.p(200,100); + ret.pos_child1 = cc.p(-120, -50); + ret.pos_child2 = cc.p(240, 0); + ret.pos_child3 = cc.p(400, 150); + + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = {}; + ret.pos_parent = cc.p(Math.round(this._parentNode.x), Math.round(this._parentNode.y)); + ret.pos_child1 = cc.p(Math.round(this._background.x), Math.round(this._background.y)); + ret.pos_child2 = cc.p(Math.round(this._tilemap.x), Math.round(this._tilemap.y)); + ret.pos_child3 = cc.p(Math.round(this._cocosimage.x), Math.round(this._cocosimage.y)); + + return JSON.stringify(ret); + } +}); + +var Parallax2 = ParallaxDemo.extend({ + _root:null, + _target:null, + _streak:null, + ctor:function () { + this._super(); + + if( 'touches' in cc.sys.capabilities ){ + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesMoved:function (touches, event) { + var touch = touches[0]; + var node = event.getCurrentTarget().getChildByTag(TAG_NODE); + node.x += touch.getDelta().x; + node.y += touch.getDelta().y; + } + }, this); + } else if ('mouse' in cc.sys.capabilities ){ + cc.eventManager.addListener({ + event: cc.EventListener.MOUSE, + onMouseMove: function(event){ + if(event.getButton() == cc.EventMouse.BUTTON_LEFT){ + var node = event.getCurrentTarget().getChildByTag(TAG_NODE); + node.x += event.getDeltaX(); + node.y += event.getDeltaY(); + } + } + }, this); + } + + + // Top Layer, a simple image + var cocosImage = new cc.Sprite(s_power); + // scale the image (optional) + cocosImage.scale = 1.5; + // change the transform anchor point to 0,0 (optional) + cocosImage.anchorX = 0; + cocosImage.anchorY = 0; + + // Middle layer: a Tile map atlas + //var tilemap = cc.TileMapAtlas.create(s_tilesPng, s_levelMapTga, 16, 16); + var tilemap = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test2.tmx"); + + // change the transform anchor to 0,0 (optional) + tilemap.anchorX = 0; + tilemap.anchorY = 0; + + // Anti Aliased images + //tilemap.texture.setAntiAliasTexParameters(); + + // background layer: another image + var background = new cc.Sprite(s_back); + // scale the image (optional) + //background.scale = 1.5; + // change the transform anchor point (optional) + background.anchorX = 0; + background.anchorY = 0; + + // create a void node, a parent node + var voidNode = new cc.ParallaxNode(); + // NOW add the 3 layers to the 'void' node + + // background image is moved at a ratio of 0.4x, 0.5y + voidNode.addChild(background, -1, cc.p(0.4, 0.5), cc.p(0,0)); + + // tiles are moved at a ratio of 1.0, 1.0y + voidNode.addChild(tilemap, 1, cc.p(1.0, 1.0), cc.p(0, 0)); + + // top image is moved at a ratio of 3.0x, 2.5y + voidNode.addChild(cocosImage, 2, cc.p(3.0, 2.5), cc.p(0, 0)); + this.addChild(voidNode, 0, TAG_NODE); + }, + + title:function () { + return "Parallax: drag screen"; + } +}); + +ParallaxTestScene = TestScene.extend({ + runThisTest:function (num) { + parallaxTestSceneIdx = (num || num == 0) ? (num - 1) : -1; + this.addChild(nextParallaxTest()); + director.runScene(this); + } +}); + +var arrayOfParallaxTest = [ + Parallax1, + Parallax2 +]; + +var nextParallaxTest = function () { + parallaxTestSceneIdx++; + parallaxTestSceneIdx = parallaxTestSceneIdx % arrayOfParallaxTest.length; + + return new arrayOfParallaxTest[parallaxTestSceneIdx](); +}; +var previousParallaxTest = function () { + parallaxTestSceneIdx--; + if (parallaxTestSceneIdx < 0) + parallaxTestSceneIdx += arrayOfParallaxTest.length; + + return new arrayOfParallaxTest[parallaxTestSceneIdx](); +}; +var restartParallaxTest = function () { + return new arrayOfParallaxTest[parallaxTestSceneIdx](); +}; diff --git a/tests/js-tests/src/ParticleTest/ParticleTest.js b/tests/js-tests/src/ParticleTest/ParticleTest.js new file mode 100644 index 0000000000..78fa53d8eb --- /dev/null +++ b/tests/js-tests/src/ParticleTest/ParticleTest.js @@ -0,0 +1,1232 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var TAG_LABEL_ATLAS = 1; + +var particleSceneIdx = -1; + +var ParticleTestScene = TestScene.extend({ + runThisTest:function (num) { + particleSceneIdx = (num || num == 0) ? (num - 1) : -1; + + this.addChild(nextParticleAction()); + director.runScene(this); + } +}); + +var particleSceneArr = [ + function () { + return new DemoFlower(); + }, + function () { + return new DemoGalaxy(); + }, + function () { + return new DemoFirework(); + }, + function () { + return new DemoSpiral(); + }, + function () { + return new DemoSun(); + }, + function () { + return new DemoMeteor(); + }, + function () { + return new DemoFire(); + }, + function () { + return new DemoSmoke(); + }, + function () { + return new DemoExplosion(); + }, + function () { + return new DemoSnow(); + }, + function () { + return new DemoRain(); + }, + function () { + return new DemoBigFlower(); + }, + function () { + return new DemoRotFlower(); + }, + function () { + return new DemoModernArt(); + }, + function () { + return new DemoRing(); + }, + function () { + return new DemoParticleFromFile("BoilingFoam"); + }, + function () { + return new DemoParticleFromFile("BurstPipe"); + }, + function () { + return new DemoParticleFromFile("Comet"); + }, + function () { + return new DemoParticleFromFile("debian"); + }, + function () { + return new DemoParticleFromFile("ExplodingRing"); + }, + function () { + return new DemoParticleFromFile("LavaFlow"); + }, + function(){ + return new DemoParticleFromFile("SpinningPeas"); + }, + function () { + return new DemoParticleFromFile("SpookyPeas"); + }, + function () { + return new DemoParticleFromFile("Upsidedown"); + }, + function () { + return new DemoParticleFromFile("Flower"); + }, + function () { + return new DemoParticleFromFile("Spiral"); + }, + function () { + return new DemoParticleFromFile("Galaxy"); + }, + function () { + return new RadiusMode1(); + }, + function () { + return new RadiusMode2(); + }, + function () { + return new Issue704(); + }, + function () { + return new Issue870(); + }, + function () { + return new DemoParticleFromFile("Phoenix"); + }, + function() { + return new ParticleResizeTest(); + } +]; + +if( 'opengl' in cc.sys.capabilities ){ + particleSceneArr.push( function () { + return new ParallaxParticle(); + }); + particleSceneArr.push(function () { + return new ParticleBatchTest(); + }); +} + + +var nextParticleAction = function () { + particleSceneIdx++; + particleSceneIdx = particleSceneIdx % particleSceneArr.length; + return particleSceneArr[particleSceneIdx](); +}; + +var backParticleAction = function () { + particleSceneIdx--; + if (particleSceneIdx < 0) + particleSceneIdx += particleSceneArr.length; + + return particleSceneArr[particleSceneIdx](); +}; + +var restartParticleAction = function () { + return particleSceneArr[particleSceneIdx](); +}; + +var ParticleDemo = BaseTestLayer.extend({ + _emitter:null, + _background:null, + _shapeModeButton:null, + _textureModeButton:null, + _isPressed:false, + + setColor:function () { + }, + + ctor:function () { + this._super(cc.color(0,0,0,255), cc.color(98,99,117,255)); + this._emitter = null; + + if ('touches' in cc.sys.capabilities){ + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesBegan:function (touches, event) { + event.getCurrentTarget()._moveToTouchPoint(touches[0].getLocation()); + }, + onTouchesMoved:function (touches, event) { + event.getCurrentTarget()._moveToTouchPoint(touches[0].getLocation()); + } + }, this); + } else if ('mouse' in cc.sys.capabilities) + cc.eventManager.addListener({ + event: cc.EventListener.MOUSE, + onMouseDown: function(event){ + event.getCurrentTarget()._moveToTouchPoint(event.getLocation()); + }, + onMouseMove: function(event){ + if(event.getButton() == cc.EventMouse.BUTTON_LEFT) + event.getCurrentTarget()._moveToTouchPoint(event.getLocation()); + } + }, this); + + var s = director.getWinSize(); + + var freeBtnNormal = new cc.Sprite(s_MovementMenuItem, cc.rect(0, 23 * 2, 123, 23)); + var freeBtnSelected = new cc.Sprite(s_MovementMenuItem, cc.rect(0, 23, 123, 23)); + var freeBtnDisabled = new cc.Sprite(s_MovementMenuItem, cc.rect(0, 0, 123, 23)); + + var relativeBtnNormal = new cc.Sprite(s_MovementMenuItem, cc.rect(123, 23 * 2, 138, 23)); + var relativeBtnSelected = new cc.Sprite(s_MovementMenuItem, cc.rect(123, 23, 138, 23)); + var relativeBtnDisabled = new cc.Sprite(s_MovementMenuItem, cc.rect(123, 0, 138, 23)); + + var groupBtnNormal = new cc.Sprite(s_MovementMenuItem, cc.rect(261, 23 * 2, 136, 23)); + var groupBtnSelected = new cc.Sprite(s_MovementMenuItem, cc.rect(261, 23, 136, 23)); + var groupBtnDisabled = new cc.Sprite(s_MovementMenuItem, cc.rect(261, 0, 136, 23)); + + var selfPoint = this; + this._freeMovementButton = new cc.MenuItemSprite(freeBtnNormal, freeBtnSelected, freeBtnDisabled, + function () { + selfPoint._emitter.setPositionType(cc.ParticleSystem.TYPE_RELATIVE); + selfPoint._relativeMovementButton.setVisible(true); + selfPoint._freeMovementButton.setVisible(false); + selfPoint._groupMovementButton.setVisible(false); + }); + this._freeMovementButton.x = 10; + this._freeMovementButton.y = 150; + this._freeMovementButton.setAnchorPoint(0, 0); + + this._relativeMovementButton = new cc.MenuItemSprite(relativeBtnNormal, relativeBtnSelected, relativeBtnDisabled, + function () { + selfPoint._emitter.setPositionType(cc.ParticleSystem.TYPE_GROUPED); + selfPoint._relativeMovementButton.setVisible(false); + selfPoint._freeMovementButton.setVisible(false); + selfPoint._groupMovementButton.setVisible(true); + }); + this._relativeMovementButton.setVisible(false); + this._relativeMovementButton.x = 10; + this._relativeMovementButton.y = 150; + this._relativeMovementButton.setAnchorPoint(0, 0); + + this._groupMovementButton = new cc.MenuItemSprite(groupBtnNormal, groupBtnSelected, groupBtnDisabled, + function () { + selfPoint._emitter.setPositionType(cc.ParticleSystem.TYPE_FREE); + selfPoint._relativeMovementButton.setVisible(false); + selfPoint._freeMovementButton.setVisible(true); + selfPoint._groupMovementButton.setVisible(false); + }); + this._groupMovementButton.setVisible(false); + this._groupMovementButton.x = 10; + this._groupMovementButton.y = 150; + this._groupMovementButton.setAnchorPoint(0, 0); + + var spriteNormal = new cc.Sprite(s_shapeModeMenuItem, cc.rect(0, 23 * 2, 115, 23)); + var spriteSelected = new cc.Sprite(s_shapeModeMenuItem, cc.rect(0, 23, 115, 23)); + var spriteDisabled = new cc.Sprite(s_shapeModeMenuItem, cc.rect(0, 0, 115, 23)); + + this._shapeModeButton = new cc.MenuItemSprite(spriteNormal, spriteSelected, spriteDisabled, + function () { + if (selfPoint._emitter.setDrawMode) + selfPoint._emitter.setDrawMode(cc.ParticleSystem.TEXTURE_MODE); + selfPoint._textureModeButton.setVisible(true); + selfPoint._shapeModeButton.setVisible(false); + }); + this._shapeModeButton.setVisible(false); + this._shapeModeButton.x = 10; + this._shapeModeButton.y = 100; + this._shapeModeButton.setAnchorPoint(0, 0); + + var spriteNormal_t = new cc.Sprite(s_textureModeMenuItem, cc.rect(0, 23 * 2, 115, 23)); + var spriteSelected_t = new cc.Sprite(s_textureModeMenuItem, cc.rect(0, 23, 115, 23)); + var spriteDisabled_t = new cc.Sprite(s_textureModeMenuItem, cc.rect(0, 0, 115, 23)); + + this._textureModeButton = new cc.MenuItemSprite(spriteNormal_t, spriteSelected_t, spriteDisabled_t, + function () { + if (selfPoint._emitter.setDrawMode) + selfPoint._emitter.setDrawMode(cc.ParticleSystem.SHAPE_MODE); + selfPoint._textureModeButton.setVisible(false); + selfPoint._shapeModeButton.setVisible(true); + }); + this._textureModeButton.x = 10; + this._textureModeButton.y = 100; + this._textureModeButton.setAnchorPoint(0, 0); + + if ('opengl' in cc.sys.capabilities ) { + // Shape type is not compatible with JSB + this._textureModeButton.enabled = false; + } + + var menu = new cc.Menu( this._shapeModeButton, this._textureModeButton, + this._freeMovementButton, this._relativeMovementButton, this._groupMovementButton); + menu.x = 0; + menu.y = 0; + + this.addChild(menu, 100); + //TODO + var labelAtlas = new cc.LabelAtlas("0123456789", s_fpsImages, 16, 24, '.'); + this.addChild(labelAtlas, 100, TAG_LABEL_ATLAS); + labelAtlas.x = s.width - 66; + labelAtlas.y = 50; + + // moving background + this._background = new cc.Sprite(s_back3); + this.addChild(this._background, 5); + this._background.x = s.width / 2; + this._background.y = s.height - 180; + + var move = cc.moveBy(4, cc.p(300, 0)); + var move_back = move.reverse(); + + var seq = cc.sequence(move, move_back); + this._background.runAction(seq.repeatForever()); + this.scheduleUpdate(); + }, + + onEnter:function () { + this._super(); + + var pLabel = this.getChildByTag(BASE_TEST_TITLE_TAG); + pLabel.setString(this.title()); + }, + title:function () { + return "No title"; + }, + + subtitle:function () { + return "(Tap the Screen)"; + }, + + onRestartCallback:function (sender) { + this._emitter.resetSystem(); + }, + onNextCallback:function (sender) { + var s = new ParticleTestScene(); + s.addChild(nextParticleAction()); + director.runScene(s); + }, + onBackCallback:function (sender) { + var s = new ParticleTestScene(); + s.addChild(backParticleAction()); + director.runScene(s); + }, + toggleCallback:function (sender) { + if (this._emitter.getPositionType() == cc.ParticleSystem.TYPE_GROUPED) + this._emitter.setPositionType(cc.ParticleSystem.TYPE_FREE); + else if (this._emitter.getPositionType() == cc.ParticleSystem.TYPE_FREE) + this._emitter.setPositionType(cc.ParticleSystem.TYPE_RELATIVE); + else if (this._emitter.getPositionType() == cc.ParticleSystem.TYPE_RELATIVE) + this._emitter.setPositionType(cc.ParticleSystem.TYPE_GROUPED); + }, + + _moveToTouchPoint: function (location) { + var pos = cc.p(0, 0); + if (this._background) { + pos = this._background.convertToWorldSpace(cc.p(0, 0)); + } + this._emitter.x = location.x - pos.x; + this._emitter.y = location.y - pos.y; + }, + + update:function (dt) { + if (this._emitter) { + var atlas = this.getChildByTag(TAG_LABEL_ATLAS); + atlas.setString(this._emitter.getParticleCount().toFixed(0)); + } + }, + setEmitterPosition:function () { + var sourcePos = this._emitter.getSourcePosition(); + if (sourcePos.x === 0 && sourcePos.y === 0) + this._emitter.x = 200; + this._emitter.y = 70; + }, + // automation + numberOfPendingTests:function() { + return ( (particleSceneArr.length-1) - particleSceneIdx ); + }, + + getTestNumber:function() { + return particleSceneIdx; + } +}); + +var DemoFirework = ParticleDemo.extend({ + onEnter:function () { + this._super(); + + this._emitter = new cc.ParticleFireworks(); + this._background.addChild(this._emitter, 10); + this._emitter.texture = cc.textureCache.addImage(s_stars1); + if (this._emitter.setShapeType) + this._emitter.setShapeType(cc.ParticleSystem.STAR_SHAPE); + this.setEmitterPosition(); + }, + title:function () { + return "ParticleFireworks"; + } +}); + +var DemoFire = ParticleDemo.extend({ + onEnter:function () { + this._super(); + + this._emitter = new cc.ParticleFire(); + this._background.addChild(this._emitter, 10); + + this._emitter.texture = cc.textureCache.addImage(s_fire);//.pvr"]; + if (this._emitter.setShapeType) + this._emitter.setShapeType(cc.ParticleSystem.BALL_SHAPE); + + this.setEmitterPosition(); + }, + title:function () { + return "ParticleFire"; + } +}); + +var DemoSun = ParticleDemo.extend({ + onEnter:function () { + this._super(); + + this._emitter = new cc.ParticleSun(); + this._background.addChild(this._emitter, 10); + this._emitter.texture = cc.textureCache.addImage(s_fire); + if (this._emitter.setShapeType) + this._emitter.setShapeType(cc.ParticleSystem.BALL_SHAPE); + + this.setEmitterPosition(); + }, + title:function () { + return "ParticleSun"; + } +}); + +var DemoGalaxy = ParticleDemo.extend({ + onEnter:function () { + this._super(); + + this._emitter = new cc.ParticleGalaxy(); + this._background.addChild(this._emitter, 10); + this._emitter.texture = cc.textureCache.addImage(s_fire); + if (this._emitter.setShapeType) + this._emitter.setShapeType(cc.ParticleSystem.BALL_SHAPE); + + this.setEmitterPosition(); + }, + title:function () { + return "ParticleGalaxy"; + } +}); + +var DemoFlower = ParticleDemo.extend({ + _title:"ParticleFlower", + + onEnter:function () { + this._super(); + + this._emitter = new cc.ParticleFlower(); + this._background.addChild(this._emitter, 10); + this._emitter.texture = cc.textureCache.addImage(s_stars1); + + if (this._emitter.setShapeType) + this._emitter.setShapeType(cc.ParticleSystem.STAR_SHAPE); + + this.setEmitterPosition(); + }, + title:function () { + return this._title; + } +}); + +var DemoBigFlower = ParticleDemo.extend({ + onEnter:function () { + this._super(); + + this._emitter = new cc.ParticleSystem(50); + + this._background.addChild(this._emitter, 10); + this._emitter.texture = cc.textureCache.addImage(s_stars1); + this._emitter.shapeType = cc.ParticleSystem.STAR_SHAPE; + + this._emitter.duration = -1; + + // gravity + this._emitter.gravity = cc.p(0, 0); + + // angle + this._emitter.angle = 90; + this._emitter.angleVar = 360; + + // speed of particles + this._emitter.speed = 160; + this._emitter.speedVar = 20; + + // radial + this._emitter.radialAccel = -120; + this._emitter.radialAccelVar = 0; + + // tagential + this._emitter.tangentialAccel = 30; + this._emitter.tangentialAccelVar = 0; + + // emitter position + this._emitter.x = 160; + this._emitter.y = 240; + this._emitter.posVar = cc.p(0, 0); + + // life of particles + this._emitter.life = 4; + this._emitter.lifeVar = 1; + + // spin of particles + this._emitter.startSpin = 0; + this._emitter.startSizeVar = 0; + this._emitter.endSpin = 0; + this._emitter.endSpinVar = 0; + + // color of particles + this._emitter.startColor = cc.color(128, 128, 128, 255); + this._emitter.startColorVar = cc.color(128, 128, 128, 255); + this._emitter.endColor = cc.color(26, 26, 26, 50); + this._emitter.endColorVar = cc.color(26, 26, 26, 50); + + // size, in pixels + this._emitter.startSize = 80.0; + this._emitter.startSizeVar = 40.0; + this._emitter.endSize = cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE; + + // emits per second + this._emitter.emissionRate = this._emitter.totalParticles / this._emitter.life; + + // additive + this._emitter.setBlendAdditive(true); + + this.setEmitterPosition(); + }, + title:function () { + return "ParticleBigFlower"; + } +}); + +var DemoRotFlower = ParticleDemo.extend({ + onEnter:function () { + this._super(); + + this._emitter = new cc.ParticleSystem(("opengl" in cc.sys.capabilities) ? 300 : 150); + + this._background.addChild(this._emitter, 10); + this._emitter.texture = cc.textureCache.addImage(s_stars2); + if (this._emitter.setShapeType) + this._emitter.setShapeType(cc.ParticleSystem.STAR_SHAPE); + + // duration + this._emitter.duration = -1; + + // gravity + this._emitter.gravity = cc.p(0, 0); + + // angle + this._emitter.angle = 90; + this._emitter.angleVar = 360; + + // speed of particles + this._emitter.speed = 160; + this._emitter.speedVar = 20; + + // radial + this._emitter.radialAccel = -120; + this._emitter.radialAccelVar = 0; + + // tangential + this._emitter.tangentialAccel = 30; + this._emitter.tangentialAccelVar = 0; + + // emitter position + this._emitter.x = 160; + this._emitter.y = 240; + this._emitter.posVar = cc.p(0, 0); + + // life of particles + this._emitter.life = 3; + this._emitter.lifeVar = 1; + + // spin of particles + this._emitter.startSpin = 0; + this._emitter.startSpinVar = 0; + this._emitter.endSpin = 0; + this._emitter.endSpinVar = 2000; + + this._emitter.startColor = cc.color(128, 128, 128, 255); + this._emitter.startColorVar = cc.color(128, 128, 128, 255); + this._emitter.endColor = cc.color(26, 26, 26, 50); + this._emitter.endColorVar = cc.color(26, 26, 26, 50); + + // size, in pixels + this._emitter.startSize = 30.0; + this._emitter.startSizeVar = 0; + this._emitter.endSize = cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE; + + // emits per second + this._emitter.emissionRate = this._emitter.totalParticles / this._emitter.life; + + // additive + this._emitter.setBlendAdditive(false); + + this.setEmitterPosition(); + }, + title:function () { + return "ParticleRotFlower"; + } +}); + +var DemoMeteor = ParticleDemo.extend({ + onEnter:function () { + this._super(); + + this._emitter = new cc.ParticleMeteor(); + this._background.addChild(this._emitter, 10); + + this._emitter.texture = cc.textureCache.addImage(s_fire); + this._emitter.shapeType = cc.ParticleSystem.BALL_SHAPE; + + this.setEmitterPosition(); + }, + title:function () { + return "ParticleMeteor"; + } +}); + +var DemoSpiral = ParticleDemo.extend({ + onEnter:function () { + this._super(); + + this._emitter = new cc.ParticleSpiral(); + this._background.addChild(this._emitter, 10); + + this._emitter.texture = cc.textureCache.addImage(s_fire); + this._emitter.shapeType = cc.ParticleSystem.BALL_SHAPE; + + this.setEmitterPosition(); + }, + title:function () { + return "ParticleSpiral"; + } +}); + +var DemoExplosion = ParticleDemo.extend({ + onEnter:function () { + this._super(); + + this._emitter = new cc.ParticleExplosion(); + this._background.addChild(this._emitter, 10); + + this._emitter.texture = cc.textureCache.addImage(s_stars1); + this._emitter.shapeType = cc.ParticleSystem.STAR_SHAPE; + + this._emitter.setAutoRemoveOnFinish(true); + + this.setEmitterPosition(); + }, + onExit: function() { + this._super(); + }, + title:function () { + return "ParticleExplosion"; + } +}); + +var DemoSmoke = ParticleDemo.extend({ + onEnter:function () { + this._super(); + + this._emitter = new cc.ParticleSmoke(); + this._background.addChild(this._emitter, 10); + this._emitter.texture = cc.textureCache.addImage(s_fire); + + this.setEmitterPosition(); + }, + title:function () { + return "ParticleSmoke"; + } +}); + +var DemoSnow = ParticleDemo.extend({ + onEnter:function () { + this._super(); + + this._emitter = new cc.ParticleSnow(); + this._background.addChild(this._emitter, 10); + + this._emitter.life = 3; + this._emitter.lifeVar = 1; + + // gravity + this._emitter.gravity = cc.p(0, -10); + + // speed of particles + this._emitter.speed = 130; + this._emitter.speedVar = 30; + + + var startColor = this._emitter.startColor; + startColor.r = 230; + startColor.g = 230; + startColor.b = 230; + this._emitter.startColor = startColor; + + var startColorVar = this._emitter.startColorVar; + startColorVar.b = 26; + this._emitter.startColorVar = startColorVar; + + this._emitter.emissionRate = this._emitter.totalParticles / this._emitter.life; + + this._emitter.texture = cc.textureCache.addImage(s_snow); + this._emitter.shapeType = cc.ParticleSystem.STAR_SHAPE; + + this.setEmitterPosition(); + }, + title:function () { + return "ParticleSnow"; + } +}); + +var DemoRain = ParticleDemo.extend({ + onEnter:function () { + this._super(); + + this._emitter = new cc.ParticleRain(); + this._background.addChild(this._emitter, 10); + + this._emitter.life = 4; + + this._emitter.texture = cc.textureCache.addImage(s_fire); + this._emitter.shapeType = cc.ParticleSystem.BALL_SHAPE; + + this.setEmitterPosition(); + }, + title:function () { + return "ParticleRain"; + } +}); + +var DemoModernArt = ParticleDemo.extend({ + onEnter:function () { + this._super(); + + this._emitter = new cc.ParticleSystem(("opengl" in cc.sys.capabilities) ? 1000 : 200); + + this._background.addChild(this._emitter, 10); + + var winSize = director.getWinSize(); + + // duration + this._emitter.duration = -1; + + // gravity + this._emitter.gravity = cc.p(0, 0); + + // angle + this._emitter.angle = 0; + this._emitter.angleVar = 360; + + // radial + this._emitter.radialAccel = 70; + this._emitter.radialAccelVar = 10; + + // tangential + this._emitter.tangentialAccel = 80; + this._emitter.tangentialAccelVar = 0; + + // speed of particles + this._emitter.speed = 50; + this._emitter.speedVar = 10; + + // life of particles + this._emitter.life = 2.0; + this._emitter.lifeVar = 0.3; + + // emits per frame + this._emitter.emissionRate = this._emitter.totalParticles / this._emitter.life; + + // color of particles + this._emitter.startColor = cc.color(128, 128, 128, 255); + this._emitter.startColorVar = cc.color(128, 128, 128, 255); + this._emitter.endColor = cc.color(26, 26, 26, 50); + this._emitter.endColorVar = cc.color(26, 26, 26, 50); + + // size, in pixels + this._emitter.startSize = 1.0; + this._emitter.startSizeVar = 1.0; + this._emitter.endSize = 32.0; + this._emitter.endSizeVar = 8.0; + + // texture + this._emitter.texture = cc.textureCache.addImage(s_fire); + this._emitter.shapeType = cc.ParticleSystem.BALL_SHAPE; + + // additive + this._emitter.setBlendAdditive(false); + + this.setEmitterPosition(); + }, + title:function () { + return "Varying size"; + } +}); + +var DemoRing = ParticleDemo.extend({ + onEnter:function () { + this._super(); + + this._emitter = new cc.ParticleFlower(); + + this._background.addChild(this._emitter, 10); + + this._emitter.texture = cc.textureCache.addImage(s_stars1); + this._emitter.shapeType = cc.ParticleSystem.STAR_SHAPE; + + this._emitter.lifeVar = 0; + this._emitter.life = 10; + this._emitter.speed = 100; + this._emitter.speedVar = 0; + this._emitter.emissionRate = 10000; + + this.setEmitterPosition(); + }, + title:function () { + return "Ring Demo"; + } +}); + +var ParallaxParticle = ParticleDemo.extend({ + onEnter:function () { + this._super(); + + this._background.getParent().removeChild(this._background, true); + this._background = null; + + //TODO + var p = new cc.ParallaxNode(); + this.addChild(p, 5); + + var p1 = new cc.Sprite(s_back3); + var p2 = new cc.Sprite(s_back3); + + p.addChild(p1, 1, cc.p(0.5, 1), cc.p(0, 250)); + p.addChild(p2, 2, cc.p(1.5, 1), cc.p(0, 50)); + + this._emitter = new cc.ParticleFlower(); + this._emitter.texture = cc.textureCache.addImage(s_fire); + + p1.addChild(this._emitter, 10); + this._emitter.x = 250; + this._emitter.y = 200; + + var par = new cc.ParticleSun(); + p2.addChild(par, 10); + par.texture = cc.textureCache.addImage(s_fire); + + var move = cc.moveBy(4, cc.p(300, 0)); + var move_back = move.reverse(); + var seq = cc.sequence(move, move_back); + p.runAction(seq.repeatForever()); + }, + title:function () { + return "Parallax + Particles"; + } +}); + +var DemoParticleFromFile = ParticleDemo.extend({ + _title:"", + ctor:function (filename) { + this._super(); + this._title = filename; + }, + onEnter:function () { + this._super(); + this.setColor(cc.color(0, 0, 0)); + this.removeChild(this._background, true); + this._background = null; + + this._emitter = new cc.ParticleSystem(s_resprefix + "Particles/" + this._title + ".plist"); + // test create from a object + // var plistData = jsb.fileUtils.getValueMapFromFile(s_resprefix + "Particles/" + this._title + ".plist"); + // this._emitter = new cc.ParticleSystem(plistData); + + this.addChild(this._emitter, 10); + + if (this._title == "Flower") { + this._emitter.shapeType = cc.ParticleSystem.STAR_SHAPE; + }//else if( this._title == "Upsidedown"){ + // this._emitter.setDrawMode(cc.ParticleSystem.TEXTURE_MODE); + //} + + this.setEmitterPosition(); + }, + + setEmitterPosition:function () { + var sourcePos = this._emitter.getSourcePosition(); + if (sourcePos.x === 0 && sourcePos.y === 0) + this._emitter.x = director.getWinSize().width / 2; + this._emitter.y = director.getWinSize().height / 2 - 50; + }, + + title:function () { + return this._title; + } +}); + +var RadiusMode1 = ParticleDemo.extend({ + onEnter:function () { + this._super(); + + this.setColor(cc.color(0, 0, 0)); + this.removeChild(this._background, true); + this._background = null; + + this._emitter = new cc.ParticleSystem(100); + this.addChild(this._emitter, 10); + this._emitter.texture = cc.textureCache.addImage(s_starsGrayscale); + + // duration + this._emitter.duration = cc.ParticleSystem.DURATION_INFINITY; + + // radius mode + this._emitter.emitterMode = cc.ParticleSystem.MODE_RADIUS; + + // radius mode: start and end radius in pixels + this._emitter.startRadius = 0; + this._emitter.startRadiusVar = 0; + this._emitter.endRadius = 160; + this._emitter.endRadiusVar = 0; + + // radius mode: degrees per second + this._emitter.rotatePerS = 180; + this._emitter.rotatePerSVar = 0; + + + // angle + this._emitter.angle = 90; + this._emitter.angleVar = 0; + + // emitter position + var size = director.getWinSize(); + this._emitter.x = size.width / 2; + this._emitter.y = size.height / 2; + this._emitter.posVar = cc.p(0, 0); + + // life of particles + this._emitter.life = 5; + this._emitter.lifeVar = 0; + + // spin of particles + this._emitter.startSpin = 0; + this._emitter.startSpinVar = 0; + this._emitter.endSpin = 0; + this._emitter.endSpinVar = 0; + + // color of particles + this._emitter.startColor = cc.color(128, 128, 128, 255); + this._emitter.startColorVar = cc.color(128, 128, 128, 255); + this._emitter.endColor = cc.color(26, 26, 26, 50); + this._emitter.endColorVar = cc.color(26, 26, 26, 50); + + // size, in pixels + this._emitter.startSize = 32; + this._emitter.startSizeVar = 0; + this._emitter.endSize = cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE; + + // emits per second + this._emitter.emissionRate = this._emitter.totalParticles / this._emitter.life; + + // additive + this._emitter.setBlendAdditive(false); + }, + title:function () { + return "Radius Mode: Spiral"; + } +}); + +var RadiusMode2 = ParticleDemo.extend({ + onEnter:function () { + this._super(); + + this.color = cc.color(0, 0, 0); + this.removeChild(this._background, true); + this._background = null; + + this._emitter = new cc.ParticleSystem(100); + this.addChild(this._emitter, 10); + this._emitter.texture = cc.textureCache.addImage(s_starsGrayscale); + + // duration + this._emitter.duration = cc.ParticleSystem.DURATION_INFINITY; + + // radius mode + this._emitter.emitterMode = cc.ParticleSystem.MODE_RADIUS; + + // radius mode: start and end radius in pixels + this._emitter.startRadius = 100; + this._emitter.startRadiusVar = 0; + this._emitter.endRadius = cc.ParticleSystem.START_RADIUS_EQUAL_TO_END_RADIUS; + this._emitter.endRadiusVar = 0; + + // radius mode: degrees per second + this._emitter.rotatePerS = 45; + this._emitter.rotatePerSVar = 0; + + // angle + this._emitter.angle = 90; + this._emitter.angleVar = 0; + + // emitter position + var size = director.getWinSize(); + this._emitter.x = size.width / 2; + this._emitter.y = size.height / 2; + this._emitter.posVar = cc.p(0, 0); + + // life of particles + this._emitter.life = 4; + this._emitter.lifeVar = 0; + + // spin of particles + this._emitter.startSpin = 0; + this._emitter.startSpinVar = 0; + this._emitter.endSpin = 0; + this._emitter.endSpinVar = 0; + + // color of particles + this._emitter.startColor = cc.color(128, 128, 128, 255); + this._emitter.startColorVar = cc.color(128, 128, 128, 255); + this._emitter.endColor = cc.color(26, 26, 26, 50); + this._emitter.endColorVar = cc.color(26, 26, 26, 50); + + // size, in pixels + this._emitter.startSize = 32; + this._emitter.startSizeVar = 0; + this._emitter.endSize = cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE; + + // emits per second + this._emitter.emissionRate = this._emitter.totalParticles / this._emitter.life; + + // additive + this._emitter.setBlendAdditive(false); + }, + title:function () { + return "Radius Mode: Semi Circle"; + } +}); + +var Issue704 = ParticleDemo.extend({ + onEnter:function () { + this._super(); + + this.color = cc.color(0, 0, 0); + this.removeChild(this._background, true); + this._background = null; + + this._emitter = new cc.ParticleSystem(100); + this.addChild(this._emitter, 10); + this._emitter.texture = cc.textureCache.addImage(s_fire); + this._emitter.shapeType = cc.ParticleSystem.BALL_SHAPE; + + // duration + this._emitter.duration = cc.ParticleSystem.DURATION_INFINITY; + + // radius mode + this._emitter.emitterMode = cc.ParticleSystem.MODE_RADIUS; + + // radius mode: start and end radius in pixels + this._emitter.startRadius = 50; + this._emitter.startRadiusVar = 0; + this._emitter.endRadius = cc.ParticleSystem.START_RADIUS_EQUAL_TO_END_RADIUS; + this._emitter.endRadiusVar = 0; + + // radius mode: degrees per second + this._emitter.rotatePerS = 0; + this._emitter.rotatePerSVar = 0; + + // angle + this._emitter.angle = 90; + this._emitter.angleVar = 0; + + // emitter position + var size = director.getWinSize(); + this._emitter.x = size.width / 2; + this._emitter.y = size.height / 2; + this._emitter.posVar = cc.p(0, 0); + + // life of particles + this._emitter.life = 5; + this._emitter.lifeVar = 0; + + // spin of particles + this._emitter.startSpin = 0; + this._emitter.startSpinVar = 0; + this._emitter.endSpin = 0; + this._emitter.endSpinVar = 0; + + // color of particles + this._emitter.startColor = cc.color(128, 128, 128, 255); + this._emitter.startColorVar = cc.color(128, 128, 128, 255); + this._emitter.endColor = cc.color(26, 26, 26, 50); + this._emitter.endColorVar = cc.color(26, 26, 26, 50); + + // size, in pixels + this._emitter.startSize = 16; + this._emitter.startSizeVar = 0; + this._emitter.endSize = cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE; + + // emits per second + this._emitter.emissionRate = this._emitter.totalParticles / this._emitter.life; + + // additive + this._emitter.setBlendAdditive(false); + + var rot = cc.rotateBy(16, 360); + this._emitter.runAction(rot.repeatForever()); + }, + title:function () { + return "Issue 704. Free + Rot"; + }, + subtitle:function () { + return "Emitted particles should not rotate"; + } +}); + +var Issue870 = ParticleDemo.extend({ + _index:0, + onEnter:function () { + this._super(); + + this.setColor(cc.color(0, 0, 0)); + this.removeChild(this._background, true); + this._background = null; + + var system = new cc.ParticleSystem(s_resprefix + "Particles/SpinningPeas.plist"); + system.setTextureWithRect(cc.textureCache.addImage(s_particles), cc.rect(0, 0, 32, 32)); + this.addChild(system, 10); + this._emitter = system; + this._emitter.drawMode = cc.ParticleSystem.TEXTURE_MODE; + this._emitter.x = director.getWinSize().width / 2; + this._emitter.y = director.getWinSize().height / 2 - 50; + this._index = 0; + this.schedule(this.updateQuads, 2.0); + }, + title:function () { + return "Issue 870. SubRect"; + }, + subtitle:function () { + return "Every 2 seconds the particle should change"; + }, + updateQuads:function (dt) { + this._index = (this._index + 1) % 4; + var rect = cc.rect(this._index * 32, 0, 32, 32); + this._emitter.setTextureWithRect(this._emitter.texture, rect); + } +}); + +var ParticleBatchTest = ParticleDemo.extend({ + _index:0, + onEnter:function () { + this._super(); + + var emitter1 = new cc.ParticleSystem(s_resprefix + 'Particles/LavaFlow.plist'); + emitter1.startColor = cc.color(255, 0, 0, 255); + var emitter2 = new cc.ParticleSystem(s_resprefix + 'Particles/LavaFlow.plist'); + emitter2.startColor = cc.color(0, 255, 0, 255); + var emitter3 = new cc.ParticleSystem(s_resprefix + 'Particles/LavaFlow.plist'); + emitter3.startColor = cc.color(0, 0, 255, 255); + + emitter1.x = winSize.width / 1.25; + + emitter1.y = winSize.height / 1.25; + emitter2.x = winSize.width / 2; + emitter2.y = winSize.height / 2; + emitter3.x = winSize.width / 4; + emitter3.y = winSize.height / 4; + + var batch = new cc.ParticleBatchNode(emitter1.texture); + + batch.addChild(emitter1); + batch.addChild(emitter2); + batch.addChild(emitter3); + + this.addChild(batch, 10); + + // to be able to use "reset" button + this.removeChild(this._background, true); + this._background = null; + this._emitter = emitter1; + }, + title:function () { + return "Particle Batch Test"; + }, + subtitle:function () { + return "You should 3 particles. They are batched"; + } +}); + +var ParticleResizeTest = ParticleDemo.extend({ + _index:0, + onEnter:function () { + this._super(); + + var emitter1 = new cc.ParticleSystem( s_resprefix + 'Particles/LavaFlow.plist'); + emitter1.x = winSize.width/2; + emitter1.y = winSize.height/2; + this.addChild(emitter1); + + this.schedule( this.onResizeParticle50, 2 ); + + // to be able to use "reset" button + this.removeChild(this._background, true); + this._background = null; + this._emitter = emitter1; + }, + onResizeParticle50:function(dt) { + this._emitter.totalParticles = 50; + this.scheduleOnce( this.onResizeParticle400, 1); + }, + onResizeParticle400:function(dt) { + this._emitter.totalParticles = 400; + }, + + title:function () { + return "Particle Resize Test"; + }, + subtitle:function () { + return "In 2 seconds, the emitter should have only 15 particles. Shall not crash."; + } +}); \ No newline at end of file diff --git a/tests/js-tests/src/PathTest/PathTest.js b/tests/js-tests/src/PathTest/PathTest.js new file mode 100644 index 0000000000..06d799d86f --- /dev/null +++ b/tests/js-tests/src/PathTest/PathTest.js @@ -0,0 +1,132 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +//------------------------------------------------------------------ +// +// PathTestLayer +// +//------------------------------------------------------------------ +var PathTestLayer = BaseTestLayer.extend({ + _title:"cc.path", + _subtitle:"See the console please!", + + ctor:function() { + this._super(cc.color(0,0,0,255), cc.color(98,99,117,255)); + + this._join([ + ["a", "b.png"], + ["a", "b", "c.png"], + ["a", "b"], + ["a", "b", "/"], + ["a", "b/", "/"] + ]); + + this._extname(["a/b.png", "a/b.png?a=1&b=2", "a/b", "a/b?a=1&b=2", ".a/b.png", ".a/b.png?a=1&b=2", ".a/b", ".a/b?a=1&b=2"]); + + this._basename([ + ["a/b.png"], + ["a/b.png?a=1&b=2"], + ["a/b.png", ".png"], + ["a/b.png?a=1&b=2", ".png"], + ["a/b.png", ".txt"] + ]); + + this._dirname(["a/b/c.png", "a/b/c.png?a=1&b=2"]); + + this._changeExtname([ + ["a/b.png", ".plist"], + ["a/b.png?a=1&b=2", ".plist"] + ]); + + this._changeBasename([ + ["a/b/c.plist", "b.plist"], + ["a/b/c.plist?a=1&b=2", "b.plist"], + ["a/b/c.plist", ".png"], + ["a/b/c.plist", "b"], + ["a/b/c.plist", "b", true] + ]); + }, + + _join : function(args){ + cc.log("-----------cc.path.join begin----------") + for(var i = 0, li = args.length; i < li; i++){ + var obj = args[i]; + cc.log("cc.path.join('" + obj.join("','") + "') ---> " + cc.path.join.apply(cc.path, obj)); + } + cc.log("-----------cc.path.join end------------") + }, + + _extname : function(args){ + cc.log("-----------cc.path.extname begin----------") + for(var i = 0, li = args.length; i < li; i++){ + var obj = args[i]; + cc.log("cc.path.extname('" + obj + "') ---> " + cc.path.extname(obj)); + } + cc.log("-----------cc.path.extname end------------") + }, + + _basename : function(args){ + cc.log("-----------cc.path.basename begin----------") + for(var i = 0, li = args.length; i < li; i++){ + var obj = args[i]; + cc.log("cc.path.basename('" + obj.join("','") + "') ---> " + cc.path.basename.apply(cc.path, obj)); + } + cc.log("-----------cc.path.basename end------------") + }, + + _dirname : function(args){ + cc.log("-----------cc.path.dirname begin----------") + for(var i = 0, li = args.length; i < li; i++){ + var obj = args[i]; + cc.log("cc.path.dirname('" + obj + "') ---> " + cc.path.dirname(obj)); + } + cc.log("-----------cc.path.dirname end------------") + }, + + _changeExtname : function(args){ + cc.log("-----------cc.path.changeExtname begin----------") + for(var i = 0, li = args.length; i < li; i++){ + var obj = args[i]; + cc.log("cc.path.changeExtname('" + obj.join("','") + "') ---> " + cc.path.changeExtname.apply(cc.path, obj)); + } + cc.log("-----------cc.path.changeExtname end------------") + }, + + _changeBasename : function(args){ + cc.log("-----------cc.path.changeBasename begin----------") + for(var i = 0, li = args.length; i < li; i++){ + var obj = args[i]; + var str = obj.length == 3 ? "'" + obj[0] + "','" + obj[1] + "'," + obj[2] : "" + obj.join("','") + "'" + cc.log("cc.path.changeBasename(" + str + ") ---> " + cc.path.changeBasename.apply(cc.path, obj)); + } + cc.log("-----------cc.path.changeBasename end------------") + } +}); + +var PathTestScene = TestScene.extend({ + runThisTest:function () { + this.addChild(new PathTestLayer()); + director.runScene(this); + } +}); diff --git a/tests/js-tests/src/PerformanceTest/PerformanceAnimationTest.js b/tests/js-tests/src/PerformanceTest/PerformanceAnimationTest.js new file mode 100644 index 0000000000..068e454517 --- /dev/null +++ b/tests/js-tests/src/PerformanceTest/PerformanceAnimationTest.js @@ -0,0 +1,240 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var s_nAnimationCurCase = 0; +//////////////////////////////////////////////////////// +// +// AnimationLayer +// +//////////////////////////////////////////////////////// +var AnimationMenuLayer = PerformBasicLayer.extend({ + showCurrentTest:function () { + var scene = null; + switch (this._curCase) { + case 0: + scene = AnimationTest.scene(); + break; + } + s_nAnimationCurCase = this._curCase; + + if (scene) { + cc.director.runScene(scene); + } + }, + + onEnter:function () { + this._super(); + + var s = cc.director.getWinSize(); + + // Title + var label = new cc.LabelTTF(this.title(), "Arial", 40); + this.addChild(label, 1); + label.x = s.width / 2; + label.y = s.height - 32; + label.color = cc.color(255, 255, 40); + + // Subtitle + var strSubTitle = this.subtitle(); + if (strSubTitle.length) { + var l = new cc.LabelTTF(strSubTitle, "Thonburi", 16); + this.addChild(l, 1); + l.x = s.width / 2; + l.y = s.height - 80; + } + + }, + title:function () { + return "no title"; + }, + subtitle:function () { + return "no subtitle"; + }, + performTests:function () { + + } +}); + +//////////////////////////////////////////////////////// +// +// AnimationTest +// +//////////////////////////////////////////////////////// +var AnimationTest = AnimationMenuLayer.extend({ + numNodes:null, + lastRenderedCount:null, + moveLayerList:null, + init:function () { + this._super(); + + var size = cc.director.getWinSize(); + + cc.MenuItemFont.setFontSize(65); + var decrease = new cc.MenuItemFont(" - ", this.onDecrease, this); + decrease.color = cc.color(0, 200, 20); + var increase = new cc.MenuItemFont(" + ", this.onIncrease, this); + increase.color = cc.color(0, 200, 20); + + var menu = new cc.Menu(decrease, increase); + menu.alignItemsHorizontally(); + menu.x = size.width / 2; + menu.y = size.height / 2 + 100; + this.addChild(menu, 1); + + var infoLabel = new cc.LabelTTF("0 nodes", "Marker Felt", 24); + infoLabel.color = cc.color(0, 200, 20); + infoLabel.x = size.width / 2; + infoLabel.y = size.height - 90; + this.addChild(infoLabel, 1, TAG_INFO_LAYER); + this.numNodes = 0; + this.moveLayerList = []; + this.createMovieClip(); + //this.scheduleUpdate(); + }, + performTests:function () { + this.init(); + }, + title:function () { + return "Animation Performance Test"; + }, + subtitle:function () { + return ""; + }, + createMovieClip:function () { + var moveLayer = new cc.Node(); + this.addChild(moveLayer); + this.moveLayerList.push(moveLayer); + var size = cc.director.getWinSize(); + for(var i=0; i<10; i++) { + var character = new CharacterView(); + character.init(); + character.x = size.width /2 - i*15 - 200; + character.y = size.height /2 - i*15; + this.numNodes++; + cc.log("create"+this.numNodes); + moveLayer.addChild(character, 0, this.numNodes); + } + var action = cc.moveBy(1, cc.p(20,0)); + moveLayer.runAction(action.repeatForever()); + this.updateNodes(); + }, + onIncrease:function () { + this.createMovieClip(); + }, + onDecrease:function () { + if(this.numNodes > 0) { + var moveLayer = this.moveLayerList[this.moveLayerList.length-1]; + for(var i=0;i<10;i++) { + cc.log("remove"+this.numNodes); + moveLayer.removeChildByTag(this.numNodes, true); + this.numNodes--; + } + moveLayer.removeFromParent(true); + this.moveLayerList.pop(); + } + this.updateNodes(); + }, + updateNodes:function () { + if (this.numNodes != this.lastRenderedCount) { + var infoLabel = this.getChildByTag(TAG_INFO_LAYER); + var str = this.numNodes + " nodes"; + infoLabel.setString(str); + + this.lastRenderedCount = this.numNodes; + } + } +}); + +var CharacterView = cc.Node.extend({ + leftData:null, + leftItem:null, + rightData:null, + rightItem:null, + leftX:null, + + init: function() { + this._super(); + cc.spriteFrameCache.addSpriteFrames("res/animations/crystals.plist"); + var i = 0; + rightData = new Array(10); + for (i = 0; i < 10; i++) { + var right = new cc.Sprite("#crystals/4.png"); + right.x = 50; + right.y = i * 10 - 40; + right.rotation = -90; + right.scale = 1; + this.addChild(right); + + rightData[i] = right; + if (i == 0) { + rightItem = right; + } + } + + for(i=0; i<10; i++){ + var head = new cc.Sprite("#crystals/1.png"); + head.x = i * 5; + head.y = 50; + this.addChild(head); + head.scale = 1.5; + head.rotation = 350; + var rotateToA = cc.rotateBy(0.01, 5); + head.runAction(rotateToA.repeatForever()); + } + + leftData = new Array(10); + for(i=0; i<10; i++){ + var left = new cc.Sprite("#crystals/2.png"); + left.x = 10; + left.y = i * 5 - 20; + left.rotation = 90; + this.addChild(left); + //var moveStep = cc.moveBy(0.01, cc.p(-5,0)); + // left.runAction(moveStep); + leftData[i] = left; + if(i==0){ + leftItem = left; + } + } + + }, + + setDistance: function(){ + leftX = leftItem.x; + } +}); + +AnimationTest.scene = function () { + var scene = new cc.Scene(); + var layer = new AnimationTest(false, 1, s_nAnimationCurCase); + scene.addChild(layer); + return scene; +}; +function runAnimationTest() { + s_nAnimationCurCase = 0; + var scene = AnimationTest.scene(); + cc.director.runScene(scene); +} diff --git a/tests/js-tests/src/PerformanceTest/PerformanceNodeChildrenTest.js b/tests/js-tests/src/PerformanceTest/PerformanceNodeChildrenTest.js new file mode 100644 index 0000000000..3033f2300b --- /dev/null +++ b/tests/js-tests/src/PerformanceTest/PerformanceNodeChildrenTest.js @@ -0,0 +1,524 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var TAG_BASE = 2000; +var MAX_NODES = 1500; +var NODES_INCREASE = 50; +var s_nCurCase = 0; + +//////////////////////////////////////////////////////// +// +// NodeChildrenMenuLayer +// +//////////////////////////////////////////////////////// +var NodeChildrenMenuLayer = PerformBasicLayer.extend({ + _maxCases:4, + showCurrentTest:function () { + var nodes = (this.parent).getQuantityOfNodes(); + var scene = null; + switch (this._curCase) { + case 0: + scene = new IterateSpriteSheetCArray(); + break; + case 1: + scene = new AddSpriteSheet(); + break; + case 2: + scene = new RemoveSpriteSheet(); + break; + case 3: + scene = new ReorderSpriteSheet(); + break; + } + s_nCurCase = this._curCase; + + if (scene) { + scene.initWithQuantityOfNodes(nodes); + cc.director.runScene(scene); + } + } +}); + +//////////////////////////////////////////////////////// +// +// NodeChildrenMainScene +// +//////////////////////////////////////////////////////// +var NodeChildrenMainScene = cc.Scene.extend({ + _lastRenderedCount:null, + _quantityOfNodes:null, + _currentQuantityOfNodes:null, + + ctor:function() { + this._super(); + this.init(); + }, + + initWithQuantityOfNodes:function (nodes) { + //srand(time()); + var s = cc.director.getWinSize(); + + // Title + var label = new cc.LabelTTF(this.title(), "Arial", 40); + this.addChild(label, 1); + label.x = s.width / 2; + label.y = s.height - 32; + label.color = cc.color(255, 255, 40); + + // Subtitle + var strSubTitle = this.subtitle(); + if (strSubTitle.length) { + var l = new cc.LabelTTF(strSubTitle, "Thonburi", 16); + this.addChild(l, 1); + l.x = s.width / 2; + l.y = s.height - 80; + } + + this._lastRenderedCount = 0; + this._currentQuantityOfNodes = 0; + this._quantityOfNodes = nodes; + + cc.MenuItemFont.setFontSize(65); + var that = this; + var decrease = new cc.MenuItemFont(" - ", this.onDecrease, this); + decrease.color = cc.color(0, 200, 20); + var increase = new cc.MenuItemFont(" + ", this.onIncrease, this); + increase.color = cc.color(0, 200, 20); + + var menu = new cc.Menu(decrease, increase); + menu.alignItemsHorizontally(); + menu.x = s.width / 2; + menu.y = s.height / 2 + 15; + this.addChild(menu, 1); + + var infoLabel = new cc.LabelTTF("0 nodes", "Marker Felt", 30); + infoLabel.color = cc.color(0, 200, 20); + infoLabel.x = s.width / 2; + infoLabel.y = s.height / 2 - 15; + this.addChild(infoLabel, 1, TAG_INFO_LAYER); + + var menu = new NodeChildrenMenuLayer(true, 4, s_nCurCase); + this.addChild(menu); + + this.updateQuantityLabel(); + this.updateQuantityOfNodes(); + }, + title:function () { + return "No title"; + }, + subtitle:function () { + return ""; + }, + updateQuantityOfNodes:function () { + + }, + onDecrease:function (sender) { + this._quantityOfNodes -= NODES_INCREASE; + if (this._quantityOfNodes < 0) { + this._quantityOfNodes = 0; + } + + this.updateQuantityLabel(); + this.updateQuantityOfNodes(); + }, + onIncrease:function (sender) { + this._quantityOfNodes += NODES_INCREASE; + if (this._quantityOfNodes > MAX_NODES) { + this._quantityOfNodes = MAX_NODES + } + + this.updateQuantityLabel(); + this.updateQuantityOfNodes(); + }, + updateQuantityLabel:function () { + if (this._quantityOfNodes != this._lastRenderedCount) { + var infoLabel = this.getChildByTag(TAG_INFO_LAYER); + var str = this._quantityOfNodes + " nodes"; + infoLabel.setString(str); + + this._lastRenderedCount = this._quantityOfNodes; + } + }, + getQuantityOfNodes:function () { + return this._quantityOfNodes; + } +}); + +//////////////////////////////////////////////////////// +// +// IterateSpriteSheet +// +//////////////////////////////////////////////////////// +var IterateSpriteSheet = NodeChildrenMainScene.extend({ + _batchNode:null, + _profilingTimer:null, + ctor:function () { + this._super(); + if (cc.ENABLE_PROFILERS) { + this._profilingTimer = new cc.ProfilingTimer(); + } + }, + updateQuantityOfNodes:function () { + var s = cc.director.getWinSize(); + + // increase nodes + if (this._currentQuantityOfNodes < this._quantityOfNodes) { + for (var i = 0; i < (this._quantityOfNodes - this._currentQuantityOfNodes); i++) { + var sprite = new cc.Sprite(this._batchNode.texture, cc.rect(0, 0, 32, 32)); + this._batchNode.addChild(sprite); + sprite.x = Math.random() * s.width; + sprite.y = Math.random() * s.height; + } + } + + // decrease nodes + else if (this._currentQuantityOfNodes > this._quantityOfNodes) { + for (var i = 0; i < (this._currentQuantityOfNodes - this._quantityOfNodes); i++) { + var index = this._currentQuantityOfNodes - i - 1; + this._batchNode.removeChildAtIndex(index, true); + } + } + + this._currentQuantityOfNodes = this._quantityOfNodes; + }, + initWithQuantityOfNodes:function (nodes) { + this._batchNode = new cc.SpriteBatchNode("res/Images/spritesheet1.png"); + this.addChild(this._batchNode); + + this._super(nodes); + + if (cc.ENABLE_PROFILERS) { + this._profilingTimer = cc.Profiler.timerWithName(this.profilerName(), this); + } + this.scheduleUpdate(); + }, + update:function (dt) { + }, + profilerName:function () { + return "none"; + } +}); + +//////////////////////////////////////////////////////// +// +// IterateSpriteSheetFastEnum +// +//////////////////////////////////////////////////////// +var IterateSpriteSheetFastEnum = IterateSpriteSheet.extend({ + update:function (dt) { + // iterate using fast enumeration protocol + var children = this._batchNode.children; + + if (cc.ENABLE_PROFILERS) { + cc.ProfilingBeginTimingBlock(this._profilingTimer); + } + + for (var i = 0; i < children.length; i++) { + var sprite = children[i]; + sprite.visible = false; + } + + if (cc.ENABLE_PROFILERS) { + cc.ProfilingEndTimingBlock(this._profilingTimer); + } + }, + + title:function () { + return "A - Iterate SpriteSheet"; + }, + subtitle:function () { + return "Iterate children using Fast Enum API. See console"; + }, + profilerName:function () { + return "iter fast enum"; + } +}); + +//////////////////////////////////////////////////////// +// +// IterateSpriteSheetCArray +// +//////////////////////////////////////////////////////// +var IterateSpriteSheetCArray = IterateSpriteSheet.extend({ + update:function (dt) { + // iterate using fast enumeration protocol + var children = this._batchNode.children; + + if (cc.ENABLE_PROFILERS) { + cc.ProfilingBeginTimingBlock(this._profilingTimer); + } + for (var i = 0; i < children.length; i++) { + var sprite = children[i]; + sprite.visible = false; + } + + if (cc.ENABLE_PROFILERS) { + cc.ProfilingEndTimingBlock(this._profilingTimer); + } + }, + + title:function () { + return "B - Iterate SpriteSheet"; + }, + subtitle:function () { + return "Iterate children using Array API. See console"; + }, + profilerName:function () { + return "iter c-array"; + } +}); + +//////////////////////////////////////////////////////// +// +// AddRemoveSpriteSheet +// +//////////////////////////////////////////////////////// +var AddRemoveSpriteSheet = NodeChildrenMainScene.extend({ + _batchNode:null, + ctor:function () { + this._super(); + if (cc.ENABLE_PROFILERS) { + this._profilingTimer = new cc.ProfilingTimer(); + } + }, + updateQuantityOfNodes:function () { + var s = cc.director.getWinSize(); + + // increase nodes + if (this._currentQuantityOfNodes < this._quantityOfNodes) { + for (var i = 0; i < (this._quantityOfNodes - this._currentQuantityOfNodes); i++) { + var sprite = new cc.Sprite(this._batchNode.texture, cc.rect(0, 0, 32, 32)); + this._batchNode.addChild(sprite); + sprite.x = Math.random() * s.width; + sprite.y = Math.random() * s.height; + sprite.visible = false; + } + } + // decrease nodes + else if (this._currentQuantityOfNodes > this._quantityOfNodes) { + for (var i = 0; i < (this._currentQuantityOfNodes - this._quantityOfNodes); i++) { + var index = this._currentQuantityOfNodes - i - 1; + this._batchNode.removeChildAtIndex(index, true); + } + } + + this._currentQuantityOfNodes = this._quantityOfNodes; + }, + initWithQuantityOfNodes:function (nodes) { + this._batchNode = new cc.SpriteBatchNode("res/Images/spritesheet1.png"); + this.addChild(this._batchNode); + + this._super(nodes); + + if (cc.ENABLE_PROFILERS) { + this._profilingTimer = cc.Profiler.timerWithName(this.profilerName(), this); + } + + this.scheduleUpdate(); + }, + update:function (dt) { + }, + profilerName:function () { + return "none"; + } +}); + +//////////////////////////////////////////////////////// +// +// AddSpriteSheet +// +//////////////////////////////////////////////////////// +var AddSpriteSheet = AddRemoveSpriteSheet.extend({ + update:function (dt) { + // reset seed + //srandom(0); + + // 15 percent + var totalToAdd = this._currentQuantityOfNodes * 0.15; + + if (totalToAdd > 0) { + var sprites = []; + var zs = []; + + // Don't include the sprite creation time and random as part of the profiling + for (var i = 0; i < totalToAdd; i++) { + var sprite = new cc.Sprite(this._batchNode.texture, cc.rect(0, 0, 32, 32)); + sprites.push(sprite); + zs[i] = (Math.random()*2-1) * 50; + } + + // add them with random Z (very important!) + if (cc.ENABLE_PROFILERS) + cc.ProfilingBeginTimingBlock(this._profilingTimer); + } + + for (var i = 0; i < totalToAdd; i++) { + this._batchNode.addChild(sprites[i], zs[i], TAG_BASE + i); + } + + if (cc.ENABLE_PROFILERS) { + cc.ProfilingEndTimingBlock(this._profilingTimer); + } + + // remove them + for (var i = 0; i < totalToAdd; i++) { + this._batchNode.removeChildByTag(TAG_BASE + i, true); + } + + delete zs; + + }, + title:function () { + return "C - Add to spritesheet"; + }, + subtitle:function () { + return "Adds %10 of total sprites with random z. See console"; + }, + profilerName:function () { + return "add sprites"; + } + }) + ; + +//////////////////////////////////////////////////////// +// +// RemoveSpriteSheet +// +//////////////////////////////////////////////////////// +var RemoveSpriteSheet = AddRemoveSpriteSheet.extend({ + update:function (dt) { + //srandom(0); + + // 15 percent + var totalToAdd = this._currentQuantityOfNodes * 0.15; + + if (totalToAdd > 0) { + var sprites = []; + + // Don't include the sprite creation time as part of the profiling + for (var i = 0; i < totalToAdd; i++) { + var sprite = new cc.Sprite(this._batchNode.texture, cc.rect(0, 0, 32, 32)); + sprites.push(sprite); + } + + // add them with random Z (very important!) + for (var i = 0; i < totalToAdd; i++) { + this._batchNode.addChild(sprites[i], (Math.random()*2-1) * 50, TAG_BASE + i); + } + + // remove them + if (cc.ENABLE_PROFILERS) { + cc.ProfilingBeginTimingBlock(this._profilingTimer); + } + + for (var i = 0; i < totalToAdd; i++) { + this._batchNode.removeChildByTag(TAG_BASE + i, true); + } + + if (cc.ENABLE_PROFILERS) { + cc.ProfilingEndTimingBlock(this._profilingTimer); + } + } + }, + title:function () { + return "D - Del from spritesheet"; + }, + subtitle:function () { + return "Remove %10 of total sprites placed randomly. See console"; + }, + profilerName:function () { + return "remove sprites"; + } +}); + +//////////////////////////////////////////////////////// +// +// ReorderSpriteSheet +// +//////////////////////////////////////////////////////// +var ReorderSpriteSheet = AddRemoveSpriteSheet.extend({ + + update:function (dt) { + //srandom(0); + + // 15 percent + var totalToAdd = this._currentQuantityOfNodes * 0.15; + + if (totalToAdd > 0) { + var sprites = []; + + // Don't include the sprite creation time as part of the profiling + for (var i = 0; i < totalToAdd; i++) { + var sprite = new cc.Sprite(this._batchNode.texture, cc.rect(0, 0, 32, 32)); + sprites.push(sprite); + } + + // add them with random Z (very important!) + for (var i = 0; i < totalToAdd; i++) { + this._batchNode.addChild(sprites[i], (Math.random()*2-1) * 50, TAG_BASE + i); + } + + // [this._batchNode sortAllChildren]; + + // reorder them + if (cc.ENABLE_PROFILERS) { + cc.ProfilingBeginTimingBlock(this._profilingTimer); + } + + for (var i = 0; i < totalToAdd; i++) { + var node = this._batchNode.children[i]; + ; + this._batchNode.reorderChild(node, (Math.random()*2-1) * 50); + } + if (cc.ENABLE_PROFILERS) { + cc.ProfilingEndTimingBlock(this._profilingTimer); + } + } + + + // remove them + for (var i = 0; i < totalToAdd; i++) { + this._batchNode.removeChildByTag(TAG_BASE + i, true); + } + + }, + + title:function () { + return "E - Reorder from spritesheet"; + }, + subtitle:function () { + return "Reorder %10 of total sprites placed randomly. See console"; + }, + profilerName:function () { + return "reorder sprites"; + } +}); + +function runNodeChildrenTest() { + var scene = new IterateSpriteSheetCArray(); + scene.initWithQuantityOfNodes(NODES_INCREASE); + cc.director.runScene(scene); +} diff --git a/tests/js-tests/src/PerformanceTest/PerformanceParticleTest.js b/tests/js-tests/src/PerformanceTest/PerformanceParticleTest.js new file mode 100644 index 0000000000..197c6e1f09 --- /dev/null +++ b/tests/js-tests/src/PerformanceTest/PerformanceParticleTest.js @@ -0,0 +1,526 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var TAG_PARTICLE_SYSTEM = 3; +var TAG_LABEL_ATLAS = 4; +var MAX_PARTICLES = 3000; +var PARTICLE_NODES_INCREASE = 200; +var s_nParCurIdx = 0; +var TAG_PARTICLE_MENU_LAYER = 1000; + +//////////////////////////////////////////////////////// +// +// ParticleMenuLayer +// +//////////////////////////////////////////////////////// +var ParticleMenuLayer = PerformBasicLayer.extend({ + _maxCases:4, + showCurrentTest:function () { + var scene = this.parent; + var subTest = scene.getSubTestNum(); + var parNum = scene.getParticlesNum(); + + var newScene = null; + + switch (this._curCase) { + case 0: + newScene = new ParticlePerformTest1; + break; + case 1: + newScene = new ParticlePerformTest2; + break; + case 2: + newScene = new ParticlePerformTest3; + break; + case 3: + newScene = new ParticlePerformTest4; + break; + } + + s_nParCurIdx = this._curCase; + if (newScene) { + newScene.initWithSubTest(subTest, parNum); + cc.director.runScene(newScene); + } + } +}); + +//////////////////////////////////////////////////////// +// +// ParticleMainScene +// +//////////////////////////////////////////////////////// +var ParticleMainScene = cc.Scene.extend({ + _lastRenderedCount:null, + _quantityParticles:null, + _subtestNumber:null, + ctor:function () { + this._super(); + this.init(); + }, + initWithSubTest:function (asubtest, particles) { + //srandom(0); + + this._subtestNumber = asubtest; + var s = cc.director.getWinSize(); + + this._lastRenderedCount = 0; + this._quantityParticles = particles; + + cc.MenuItemFont.setFontSize(65); + var decrease = new cc.MenuItemFont(" - ", this.onDecrease, this); + decrease.color = cc.color(0, 200, 20); + var increase = new cc.MenuItemFont(" + ", this.onIncrease, this); + increase.color = cc.color(0, 200, 20); + + var menu = new cc.Menu(decrease, increase); + menu.alignItemsHorizontally(); + menu.x = s.width / 2; + menu.y = s.height / 2 + 15; + this.addChild(menu, 1); + + var infoLabel = new cc.LabelTTF("0 nodes", "Marker Felt", 30); + infoLabel.color = cc.color(0, 200, 20); + infoLabel.x = s.width / 2; + infoLabel.y = s.height - 90; + this.addChild(infoLabel, 1, TAG_INFO_LAYER); + + // particles on stage + var labelAtlas = new cc.LabelAtlas("0000", "res/Images/fps_images.png", 16, 24, '.'); + // var labelAtlas = cc.LabelTTF.create("0000", "Marker Felt", 30); + this.addChild(labelAtlas, 0, TAG_LABEL_ATLAS); + labelAtlas.x = s.width - 66; + labelAtlas.y = 50; + + // Next Prev Test + var menu = new ParticleMenuLayer(true, 4, s_nParCurIdx); + this.addChild(menu, 1, TAG_PARTICLE_MENU_LAYER); + + // Sub Tests + cc.MenuItemFont.setFontSize(40); + var subMenu = new cc.Menu(); + for (var i = 1; i <= 3; ++i) { + var str = i.toString(); + var itemFont = new cc.MenuItemFont(str, this.testNCallback, this); + itemFont.tag = i; + subMenu.addChild(itemFont, 10); + + if (i <= 1) { + itemFont.color = cc.color(200, 20, 20); + } + else { + itemFont.color = cc.color(0, 200, 20); + } + } + subMenu.alignItemsHorizontally(); + subMenu.x = s.width / 2; + subMenu.y = 80; + this.addChild(subMenu, 2); + + var label = new cc.LabelTTF(this.title(), "Arial", 40); + this.addChild(label, 1); + label.x = s.width / 2; + label.y = s.height - 32; + label.color = cc.color(255, 255, 40); + + this.updateQuantityLabel(); + this.createParticleSystem(); + + this.schedule(this.step); + }, + title:function () { + return "No title"; + }, + + step:function (dt) { + var atlas = this.getChildByTag(TAG_LABEL_ATLAS); + var emitter = this.getChildByTag(TAG_PARTICLE_SYSTEM); + + var str = emitter.getParticleCount().toString(); + atlas.setString(str); + }, + createParticleSystem:function () { + /* + * Tests: + * 1 Quad Particle System using 32-bit textures (PNG) + * 2: Quad Particle System using 16-bit textures (PNG) + * 3: Quad Particle System using 8-bit textures (PNG) + * 4: Quad Particle System using 4-bit textures (PVRTC) + */ + + this.removeChildByTag(TAG_PARTICLE_SYSTEM, true); + + // remove the "fire.png" from the TextureCache cache. + //var texture = cc.textureCache.addImage("res/Images/fire.png"); + //cc.textureCache.removeTexture(texture); + + var particleSystem = new cc.ParticleSystem(this._quantityParticles); + + switch (this._subtestNumber) { + case 1: + if ("opengl" in cc.sys.capabilities) + cc.Texture2D.defaultPixelFormat = cc.Texture2D.PIXEL_FORMAT_RGBA8888; + particleSystem.texture = cc.textureCache.addImage("res/Images/fire.png"); + break; + case 2: + if ("opengl" in cc.sys.capabilities) + cc.Texture2D.defaultPixelFormat = cc.Texture2D.PIXEL_FORMAT_RGBA4444; + particleSystem.texture = cc.textureCache.addImage("res/Images/fire.png"); + break; + case 3: + if ("opengl" in cc.sys.capabilities) + cc.Texture2D.defaultPixelFormat = cc.Texture2D.PIXEL_FORMAT_A8; + particleSystem.texture = cc.textureCache.addImage("res/Images/fire.png"); + break; + default: + particleSystem = null; + cc.log("Shall not happen!"); + break; + } + this.addChild(particleSystem, 0, TAG_PARTICLE_SYSTEM); + + this.doTest(); + + // restore the default pixel format + if ("opengl" in cc.sys.capabilities) + cc.Texture2D.defaultPixelFormat = cc.Texture2D.PIXEL_FORMAT_RGBA8888; + }, + onDecrease:function (sender) { + this._quantityParticles -= PARTICLE_NODES_INCREASE; + if (this._quantityParticles < 0) + this._quantityParticles = 0; + + this.updateQuantityLabel(); + this.createParticleSystem(); + }, + onIncrease:function (sender) { + this._quantityParticles += PARTICLE_NODES_INCREASE; + if (this._quantityParticles > MAX_PARTICLES) { + this._quantityParticles = MAX_PARTICLES; + } + this.updateQuantityLabel(); + this.createParticleSystem(); + }, + testNCallback:function (sender) { + this._subtestNumber = sender.tag; + var menu = this.getChildByTag(TAG_PARTICLE_MENU_LAYER); + menu.restartCallback(sender); + }, + updateQuantityLabel:function () { + if (this._quantityParticles != this._lastRenderedCount) { + var infoLabel = this.getChildByTag(TAG_INFO_LAYER); + var str = this._quantityParticles + " particles"; + infoLabel.setString(str); + + this._lastRenderedCount = this._quantityParticles; + } + }, + getSubTestNum:function () { + return this._subtestNumber; + }, + getParticlesNum:function () { + return this._quantityParticles; + }, + doTest:function () { + } +}); + +//////////////////////////////////////////////////////// +// +// ParticlePerformTest1 +// +//////////////////////////////////////////////////////// +var ParticlePerformTest1 = ParticleMainScene.extend({ + + title:function () { + return "A " + this._subtestNumber + " size=4"; + }, + doTest:function () { + var s = cc.director.getWinSize(); + var particleSystem = this.getChildByTag(TAG_PARTICLE_SYSTEM); + + // duration + particleSystem.setDuration(-1); + + // gravity + particleSystem.setGravity(cc.p(0, -90)); + + // angle + particleSystem.setAngle(90); + particleSystem.setAngleVar(0); + + // radial + particleSystem.setRadialAccel(0); + particleSystem.setRadialAccelVar(0); + + // speed of particles + particleSystem.setSpeed(180); + particleSystem.setSpeedVar(50); + + // emitter position + particleSystem.x = s.width / 2; + particleSystem.y = 100; + particleSystem.setPosVar(cc.p(s.width / 2, 0)); + + // life of particles + particleSystem.setLife(2.0); + particleSystem.setLifeVar(1); + + // emits per frame + particleSystem.setEmissionRate(particleSystem.getTotalParticles() / particleSystem.getLife()); + + // color of particles + var startColor = cc.color(128, 128, 128, 255); + particleSystem.setStartColor(startColor); + + var startColorVar = cc.color(128, 128, 128, 255); + particleSystem.setStartColorVar(startColorVar); + + var endColor = cc.color(26, 26, 26, 51); + particleSystem.setEndColor(endColor); + + var endColorVar = cc.color(26, 26, 26, 51); + particleSystem.setEndColorVar(endColorVar); + + // size, in pixels + particleSystem.setEndSize(4.0); + particleSystem.setStartSize(4.0); + particleSystem.setEndSizeVar(0); + particleSystem.setStartSizeVar(0); + + // additive + particleSystem.setBlendAdditive(false); + } +}); + +//////////////////////////////////////////////////////// +// +// ParticlePerformTest2 +// +//////////////////////////////////////////////////////// +var ParticlePerformTest2 = ParticleMainScene.extend({ + + title:function () { + return "B " + this._subtestNumber + " size=8"; + }, + doTest:function () { + var s = cc.director.getWinSize(); + var particleSystem = this.getChildByTag(TAG_PARTICLE_SYSTEM); + + // duration + particleSystem.setDuration(-1); + + // gravity + particleSystem.setGravity(cc.p(0, -90)); + + // angle + particleSystem.setAngle(90); + particleSystem.setAngleVar(0); + + // radial + particleSystem.setRadialAccel(0); + particleSystem.setRadialAccelVar(0); + + // speed of particles + particleSystem.setSpeed(180); + particleSystem.setSpeedVar(50); + + // emitter position + particleSystem.x = s.width / 2; + particleSystem.y = 100; + particleSystem.setPosVar(cc.p(s.width / 2, 0)); + + // life of particles + particleSystem.setLife(2.0); + particleSystem.setLifeVar(1); + + // emits per frame + particleSystem.setEmissionRate(particleSystem.getTotalParticles() / particleSystem.getLife()); + + // color of particles + var startColor = cc.color(128, 128, 128, 255); + particleSystem.setStartColor(startColor); + + var startColorVar = cc.color(128, 128, 128, 255); + particleSystem.setStartColorVar(startColorVar); + + var endColor = cc.color(26, 26, 26, 51); + particleSystem.setEndColor(endColor); + + var endColorVar = cc.color(26, 26, 26, 51); + particleSystem.setEndColorVar(endColorVar); + + // size, in pixels + particleSystem.setEndSize(8.0); + particleSystem.setStartSize(8.0); + particleSystem.setEndSizeVar(0); + particleSystem.setStartSizeVar(0); + + // additive + particleSystem.setBlendAdditive(false); + } +}); + +//////////////////////////////////////////////////////// +// +// ParticlePerformTest3 +// +//////////////////////////////////////////////////////// +var ParticlePerformTest3 = ParticleMainScene.extend({ + + title:function () { + return "C " + this._subtestNumber + " size=32"; + }, + doTest:function () { + var s = cc.director.getWinSize(); + var particleSystem = this.getChildByTag(TAG_PARTICLE_SYSTEM); + + // duration + particleSystem.setDuration(-1); + + // gravity + particleSystem.setGravity(cc.p(0, -90)); + + // angle + particleSystem.setAngle(90); + particleSystem.setAngleVar(0); + + // radial + particleSystem.setRadialAccel(0); + particleSystem.setRadialAccelVar(0); + + // speed of particles + particleSystem.setSpeed(180); + particleSystem.setSpeedVar(50); + + // emitter position + particleSystem.x = s.width / 2; + particleSystem.y = 100; + particleSystem.setPosVar(cc.p(s.width / 2, 0)); + + // life of particles + particleSystem.setLife(2.0); + particleSystem.setLifeVar(1); + + // emits per frame + particleSystem.setEmissionRate(particleSystem.getTotalParticles() / particleSystem.getLife()); + + // color of particles + var startColor = cc.color(128, 128, 128, 255); + particleSystem.setStartColor(startColor); + + var startColorVar = cc.color(128, 128, 128, 255); + particleSystem.setStartColorVar(startColorVar); + + var endColor = cc.color(26, 26, 26, 51); + particleSystem.setEndColor(endColor); + + var endColorVar = cc.color(26, 26, 26, 51); + particleSystem.setEndColorVar(endColorVar); + + // size, in pixels + particleSystem.setEndSize(32.0); + particleSystem.setStartSize(32.0); + particleSystem.setEndSizeVar(0); + particleSystem.setStartSizeVar(0); + + // additive + particleSystem.setBlendAdditive(false); + } +}); + +//////////////////////////////////////////////////////// +// +// ParticlePerformTest4 +// +//////////////////////////////////////////////////////// +var ParticlePerformTest4 = ParticleMainScene.extend({ + + title:function () { + return "D " + this._subtestNumber + " size=64"; + }, + doTest:function () { + var s = cc.director.getWinSize(); + var particleSystem = this.getChildByTag(TAG_PARTICLE_SYSTEM); + + // duration + particleSystem.setDuration(-1); + + // gravity + particleSystem.setGravity(cc.p(0, -90)); + + // angle + particleSystem.setAngle(90); + particleSystem.setAngleVar(0); + + // radial + particleSystem.setRadialAccel(0); + particleSystem.setRadialAccelVar(0); + + // speed of particles + particleSystem.setSpeed(180); + particleSystem.setSpeedVar(50); + + // emitter position + particleSystem.x = s.width / 2; + particleSystem.y = 100; + particleSystem.setPosVar(cc.p(s.width / 2, 0)); + + // life of particles + particleSystem.setLife(2.0); + particleSystem.setLifeVar(1); + + // emits per frame + particleSystem.setEmissionRate(particleSystem.getTotalParticles() / particleSystem.getLife()); + + // color of particles + var startColor = cc.color(128, 128, 128, 255); + particleSystem.setStartColor(startColor); + + var startColorVar = cc.color(128, 128, 128, 255); + particleSystem.setStartColorVar(startColorVar); + + var endColor = cc.color(26, 26, 26, 51); + particleSystem.setEndColor(endColor); + + var endColorVar = cc.color(26, 26, 26, 51); + particleSystem.setEndColorVar(endColorVar); + + // size, in pixels + particleSystem.setEndSize(64.0); + particleSystem.setStartSize(64.0); + particleSystem.setEndSizeVar(0); + particleSystem.setStartSizeVar(0); + + // additive + particleSystem.setBlendAdditive(false); + } +}); + +function runParticleTest() { + var scene = new ParticlePerformTest1; + scene.initWithSubTest(1, PARTICLE_NODES_INCREASE); + cc.director.runScene(scene); +} diff --git a/tests/js-tests/src/PerformanceTest/PerformanceSpriteTest.js b/tests/js-tests/src/PerformanceTest/PerformanceSpriteTest.js new file mode 100644 index 0000000000..7b6b0b0f2c --- /dev/null +++ b/tests/js-tests/src/PerformanceTest/PerformanceSpriteTest.js @@ -0,0 +1,606 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var MAX_SPRITES = 10000; +var SPRITES_INCREASE = 500; + +if ( !cc.sys.isNative) { + if(cc.sys.isMobile){ + MAX_SPRITES = 3000; + SPRITES_INCREASE = 50; + } +} + +var TAG_INFO_LAYER = 1; +var TAG_MAIN_LAYER = 2; +var TAG_SPRITE_MENU_LAYER = (MAX_SPRITES + 1000); + +var s_nSpriteCurCase = 0; + +//////////////////////////////////////////////////////// +// +// SubTest +// +//////////////////////////////////////////////////////// +var SubTest = cc.Class.extend({ + _subtestNumber:null, + _batchNode:null, + _parent:null, + removeByTag:function (tag) { + switch (this._subtestNumber) { + case 1: + case 4: + case 7: + this._parent.removeChildByTag(tag + 100, true); + break; + case 2: + case 3: + case 5: + case 6: + case 8: + case 9: + this._batchNode.removeChildAtIndex(tag, true); + break; + default: + break; + } + }, + createSpriteWithTag:function (tag) { +// create + if( "opengl" in cc.sys.capabilities ) + cc.Texture2D.defaultPixelFormat = cc.Texture2D.PIXEL_FORMAT_RGBA8888; + + var sprite = null; + switch (this._subtestNumber) { + case 1: + { + sprite = new cc.Sprite("res/Images/grossinis_sister1.png"); + this._parent.addChild(sprite, 0, tag + 100); + break; + } + case 2: + case 3: + { + sprite = new cc.Sprite(this._batchNode.texture, cc.rect(0, 0, 52, 139)); + this._batchNode.addChild(sprite, 0, tag + 100); + break; + } + case 4: + { + var idx = parseInt(Math.random() * 14) + 1; + idx = idx < 10 ? "0" + idx : idx.toString(); + var str = "res/Images/grossini_dance_" + idx + ".png"; + sprite = new cc.Sprite(str); + this._parent.addChild(sprite, 0, tag + 100); + break; + } + case 5: + case 6: + { + var idx = 0 | (Math.random() * 14); + var x = (idx % 5) * 85; + var y = (0 | (idx / 5)) * 121; + sprite = new cc.Sprite(this._batchNode.texture, cc.rect(x, y, 85, 121)); + this._batchNode.addChild(sprite, 0, tag + 100); + break; + } + + case 7: + { + var y, x; + var r = 0 | (Math.random() * 64); + + y = parseInt(r / 8); + x = parseInt(r % 8); + + var str = "res/Images/sprites_test/sprite-" + x + "-" + y + ".png"; + sprite = new cc.Sprite(str); + this._parent.addChild(sprite, 0, tag + 100); + break; + } + + case 8: + case 9: + { + var y, x; + var r = 0 | (Math.random() * 64); + + y = (0 | (r / 8)) * 32; + x = (r % 8) * 32; + sprite = new cc.Sprite(this._batchNode.texture, cc.rect(x, y, 32, 32)); + this._batchNode.addChild(sprite, 0, tag + 100); + break; + } + + default: + break; + } + + if( "opengl" in cc.sys.capabilities ) + cc.Texture2D.defaultPixelFormat = cc.Texture2D.PIXEL_FORMAT_DEFAULT; + + return sprite; + }, + initWithSubTest:function (subTest, p) { + this._subtestNumber = subTest; + this._parent = p; + this._batchNode = null; + /* + * Tests: + * 1: 1 (32-bit) PNG sprite of 52 x 139 + * 2: 1 (32-bit) PNG Batch Node using 1 sprite of 52 x 139 + * 3: 1 (16-bit) PNG Batch Node using 1 sprite of 52 x 139 + * 4: 1 (4-bit) PVRTC Batch Node using 1 sprite of 52 x 139 + + * 5: 14 (32-bit) PNG sprites of 85 x 121 each + * 6: 14 (32-bit) PNG Batch Node of 85 x 121 each + * 7: 14 (16-bit) PNG Batch Node of 85 x 121 each + * 8: 14 (4-bit) PVRTC Batch Node of 85 x 121 each + + * 9: 64 (32-bit) sprites of 32 x 32 each + *10: 64 (32-bit) PNG Batch Node of 32 x 32 each + *11: 64 (16-bit) PNG Batch Node of 32 x 32 each + *12: 64 (4-bit) PVRTC Batch Node of 32 x 32 each + */ + + // purge textures + // + // [mgr removeAllTextures]; + if ( cc.sys.isNative) { + var mgr = cc.textureCache; + mgr.removeTexture(mgr.addImage("res/Images/grossinis_sister1.png")); + mgr.removeTexture(mgr.addImage("res/Images/grossini_dance_atlas.png")); + mgr.removeTexture(mgr.addImage("res/Images/spritesheet1.png")); + } + + switch (this._subtestNumber) { + case 1: + case 4: + case 7: + break; + /// + case 2: + if( "opengl" in cc.sys.capabilities ) + cc.Texture2D.defaultPixelFormat = cc.Texture2D.PIXEL_FORMAT_RGBA8888; + this._batchNode = new cc.SpriteBatchNode("res/Images/grossinis_sister1.png", 500); + p.addChild(this._batchNode, 0); + break; + case 3: + if( "opengl" in cc.sys.capabilities ) + cc.Texture2D.defaultPixelFormat = cc.Texture2D.PIXEL_FORMAT_RGBA4444; + this._batchNode = new cc.SpriteBatchNode("res/Images/grossinis_sister1.png", 500); + p.addChild(this._batchNode, 0); + break; + + /// + case 5: + if( "opengl" in cc.sys.capabilities ) + cc.Texture2D.defaultPixelFormat = cc.Texture2D.PIXEL_FORMAT_RGBA8888; + this._batchNode = new cc.SpriteBatchNode("res/Images/grossini_dance_atlas.png", 500); + p.addChild(this._batchNode, 0); + break; + case 6: + if( "opengl" in cc.sys.capabilities ) + cc.Texture2D.defaultPixelFormat = cc.Texture2D.PIXEL_FORMAT_RGBA4444; + this._batchNode = new cc.SpriteBatchNode("res/Images/grossini_dance_atlas.png", 500); + p.addChild(this._batchNode, 0); + break; + + /// + case 8: + if( "opengl" in cc.sys.capabilities ) + cc.Texture2D.defaultPixelFormat = cc.Texture2D.PIXEL_FORMAT_RGBA8888; + this._batchNode = new cc.SpriteBatchNode("res/Images/spritesheet1.png", 500); + p.addChild(this._batchNode, 0); + break; + case 9: + if( "opengl" in cc.sys.capabilities ) + cc.Texture2D.defaultPixelFormat = cc.Texture2D.PIXEL_FORMAT_RGBA4444; + this._batchNode = new cc.SpriteBatchNode("res/Images/spritesheet1.png", 500); + p.addChild(this._batchNode, 0); + break; + + default: + break; + } + + if( "opengl" in cc.sys.capabilities ) + cc.Texture2D.defaultPixelFormat = cc.Texture2D.PIXEL_FORMAT_DEFAULT; + } +}); + +//////////////////////////////////////////////////////// +// +// SpriteMenuLayer +// +//////////////////////////////////////////////////////// +var SpriteMenuLayer = PerformBasicLayer.extend({ + _maxCases:7, + showCurrentTest:function () { + var scene = null; + var preScene = this.parent; + var subTest = preScene.getSubTestNum(); + var nodes = preScene.getNodesNum(); + + Math.seedrandom('perftest'); + + switch (this._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; + } + s_nSpriteCurCase = this._curCase; + + if (scene) { + scene.initWithSubTest(subTest, nodes); + cc.director.runScene(scene); + } + } +}); + +//////////////////////////////////////////////////////// +// +// SpriteMainScene +// +//////////////////////////////////////////////////////// +var SpriteMainScene = cc.Scene.extend({ + _lastRenderedCount:null, + _quantityNodes:null, + _subTest:null, + _subtestNumber:1, + ctor:function() { + this._super(); + this.init(); + }, + + title:function () { + return "No title"; + }, + initWithSubTest:function (asubtest, nodes) { + this._subtestNumber = asubtest; + this._subTest = new SubTest(); + this._subTest.initWithSubTest(asubtest, this); + + var s = cc.director.getWinSize(); + + this._lastRenderedCount = 0; + this._quantityNodes = 0; + + // add title label + var label = new cc.LabelTTF(this.title(), "Arial", 40); + this.addChild(label, 1); + label.x = s.width / 2; + label.y = s.height - 32; + label.color = cc.color(255, 255, 40); + + cc.MenuItemFont.setFontSize(65); + var decrease = new cc.MenuItemFont(" - ", this.onDecrease, this); + decrease.color = cc.color(0, 200, 20); + var increase = new cc.MenuItemFont(" + ", this.onIncrease, this); + increase.color = cc.color(0, 200, 20); + + var menu = new cc.Menu(decrease, increase); + menu.alignItemsHorizontally(); + + menu.x = s.width / 2; + + menu.y = s.height - 65; + this.addChild(menu, 1); + + var infoLabel = new cc.LabelTTF("0 nodes", "Marker Felt", 30); + infoLabel.color = cc.color(0, 200, 20); + infoLabel.x = s.width / 2; + infoLabel.y = s.height - 90; + this.addChild(infoLabel, 1, TAG_INFO_LAYER); + + // add menu + var menu = new SpriteMenuLayer(true, 7, s_nSpriteCurCase); + this.addChild(menu, 1, TAG_SPRITE_MENU_LAYER); + + // Sub Tests + cc.MenuItemFont.setFontSize(32); + var subMenu = new cc.Menu(); + for (var i = 1; i <= 9; ++i) { + var text = i.toString(); + var itemFont = new cc.MenuItemFont(text, this.testNCallback, this); + itemFont.tag = i; + subMenu.addChild(itemFont, 10); + + if (i <= 3) + itemFont.color = cc.color(200, 20, 20); + else if (i <= 6) + itemFont.color = cc.color(0, 200, 20); + else + itemFont.color = cc.color(0, 20, 200); + } + + subMenu.alignItemsHorizontally(); + subMenu.x = s.width / 2; + subMenu.y = 80; + this.addChild(subMenu, 2); + + while (this._quantityNodes < nodes) { + this.onIncrease(this); + } + }, + updateNodes:function () { + if (this._quantityNodes != this._lastRenderedCount) { + var infoLabel = this.getChildByTag(TAG_INFO_LAYER); + var str = this._quantityNodes + " nodes"; + infoLabel.setString(str); + + this._lastRenderedCount = this._quantityNodes; + } + }, + testNCallback:function (sender) { + this._subtestNumber = sender.tag; + var menu = this.getChildByTag(TAG_SPRITE_MENU_LAYER); + menu.restartCallback(sender); + }, + onIncrease:function (sender) { + if (this._quantityNodes >= MAX_SPRITES) + return; + + for (var i = 0; i < SPRITES_INCREASE; i++) { + var sprite = this._subTest.createSpriteWithTag(this._quantityNodes); + this.doTest(sprite); + this._quantityNodes++; + } + + this.updateNodes(); + }, + onDecrease:function (sender) { + if (this._quantityNodes <= 0) + return; + + for (var i = 0; i < SPRITES_INCREASE; i++) { + this._quantityNodes--; + this._subTest.removeByTag(this._quantityNodes); + } + + this.updateNodes(); + }, + + doTest:function (sprite) { + + }, + + getSubTestNum:function () { + return this._subtestNumber + }, + getNodesNum:function () { + return this._quantityNodes + } +}); + + +//////////////////////////////////////////////////////// +// +// For test functions +// +//////////////////////////////////////////////////////// +function performanceActions(sprite) { + var size = cc.director.getWinSize(); + sprite.x = parseInt(Math.random() * size.width); + sprite.y = parseInt(Math.random() * size.height); + + var period = 0.5 + (Math.random() * 1000) / 500.0; + var rot = cc.rotateBy(period, 360.0 * Math.random()); + var rot_back = rot.reverse(); + var permanentRotation = cc.sequence(rot, rot_back).repeatForever(); + sprite.runAction(permanentRotation); + + var growDuration = 0.5 + (Math.random() * 1000) / 500.0; + var grow = cc.scaleBy(growDuration, 0.5, 0.5); + var permanentScaleLoop = cc.sequence(grow, grow.reverse()).repeatForever(); + sprite.runAction(permanentScaleLoop); +} + +function performanceActions20(sprite) { + var size = cc.director.getWinSize(); + if (Math.random() < 0.2) { + sprite.x = parseInt(Math.random() * size.width); + sprite.y = parseInt(Math.random() * size.height); + } + else { + sprite.x = -1000; + sprite.y = -1000; + } + + var period = 0.5 + (Math.random() * 1000) / 500.0; + var rot = cc.rotateBy(period, 360.0 * Math.random()); + var rot_back = rot.reverse(); + var permanentRotation = cc.sequence(rot, rot_back).repeatForever(); + sprite.runAction(permanentRotation); + + var growDuration = 0.5 + (Math.random() * 1000) / 500.0; + var grow = cc.scaleBy(growDuration, 0.5, 0.5); + var permanentScaleLoop = cc.sequence(grow, grow.reverse()).repeatForever(); + sprite.runAction(permanentScaleLoop); +} + +function performanceRotationScale(sprite) { + var size = cc.director.getWinSize(); + sprite.x = parseInt(Math.random() * size.width); + sprite.y = parseInt(Math.random() * size.height); + sprite.rotation = Math.random() * 360; + sprite.scale = Math.random() * 2; +} + +function performancePosition(sprite) { + var size = cc.director.getWinSize(); + sprite.x = parseInt(Math.random() * size.width); + sprite.y = parseInt(Math.random() * size.height); +} + +function performanceout20(sprite) { + var size = cc.director.getWinSize(); + + if (Math.random() < 0.2) { + sprite.x = parseInt(Math.random() * size.width); + sprite.y = parseInt(Math.random() * size.height); + } + else { + sprite.x = -1000; + sprite.y = -1000; + } +} + +function performanceOut100(sprite) { + sprite.x = -1000; + sprite.y = -1000; +} + +function performanceScale(sprite) { + var size = cc.director.getWinSize(); + sprite.x = parseInt(Math.random() * size.width); + sprite.y = parseInt(Math.random() * size.height); + sprite.scale = Math.random() * 100 / 50; +} + + +//////////////////////////////////////////////////////// +// +// SpritePerformTest1 +// +//////////////////////////////////////////////////////// +var SpritePerformTest1 = SpriteMainScene.extend({ + doTest:function (sprite) { + performancePosition(sprite); + }, + title:function () { + return "A (" + this._subtestNumber + ") position"; + } +}); + +//////////////////////////////////////////////////////// +// +// SpritePerformTest2 +// +//////////////////////////////////////////////////////// +var SpritePerformTest2 = SpriteMainScene.extend({ + doTest:function (sprite) { + performanceScale(sprite); + }, + title:function () { + return "B (" + this._subtestNumber + ") scale"; + } +}); + +//////////////////////////////////////////////////////// +// +// SpritePerformTest3 +// +//////////////////////////////////////////////////////// +var SpritePerformTest3 = SpriteMainScene.extend({ + doTest:function (sprite) { + performanceRotationScale(sprite); + }, + title:function () { + return "C (" + this._subtestNumber + ") scale + rot"; + } +}); + +//////////////////////////////////////////////////////// +// +// SpritePerformTest4 +// +//////////////////////////////////////////////////////// +var SpritePerformTest4 = SpriteMainScene.extend({ + doTest:function (sprite) { + performanceOut100(sprite); + }, + title:function () { + return "D (" + this._subtestNumber + ") 100% out"; + } +}); + +//////////////////////////////////////////////////////// +// +// SpritePerformTest5 +// +//////////////////////////////////////////////////////// +var SpritePerformTest5 = SpriteMainScene.extend({ + doTest:function (sprite) { + performanceout20(sprite); + }, + title:function () { + return "E (" + this._subtestNumber + ") 80% out"; + } +}); + +//////////////////////////////////////////////////////// +// +// SpritePerformTest6 +// +//////////////////////////////////////////////////////// +var SpritePerformTest6 = SpriteMainScene.extend({ + doTest:function (sprite) { + performanceActions(sprite); + }, + title:function () { + return "F (" + this._subtestNumber + ") actions"; + } +}); + +//////////////////////////////////////////////////////// +// +// SpritePerformTest7 +// +//////////////////////////////////////////////////////// +var SpritePerformTest7 = SpriteMainScene.extend({ + doTest:function (sprite) { + performanceActions20(sprite); + }, + title:function () { + return "G (" + this._subtestNumber + ") actions 80% out"; + } +}); + +function runSpriteTest() { + Math.seedrandom('perftest'); + + var scene = new SpritePerformTest1; + scene.initWithSubTest(1, 50); + cc.director.runScene(scene); +} diff --git a/tests/js-tests/src/PerformanceTest/PerformanceSpriteTest2.js b/tests/js-tests/src/PerformanceTest/PerformanceSpriteTest2.js new file mode 100644 index 0000000000..ec58fb9551 --- /dev/null +++ b/tests/js-tests/src/PerformanceTest/PerformanceSpriteTest2.js @@ -0,0 +1,305 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var SECONDS_PER_TEST = 5; +//------------------------------------------------------------------ +// +// Profiler +// +//------------------------------------------------------------------ + +function Profiling(name) { + this.name = name; + this.numberOfCalls = 0; + this.totalTime = 0; + this.minTime = 10000; + this.maxTime = 0; + this.lastUpdate = 0; + + this.beginBlock = function() { + this.lastUpdate = Date.now(); + }; + + this.endBlock = function() { + var now = Date.now(); + var diff = now-this.lastUpdate; + this.totalTime += diff; + this.numberOfCalls++; + this.minTime = Math.min(this.minTime, diff); + this.maxTime = Math.max(this.maxTime, diff); + }; + + this.beginEndBlock = function(diff) { + this.totalTime += diff; + this.numberOfCalls++; + this.minTime = Math.min(this.minTime, diff); + this.maxTime = Math.max(this.maxTime, diff); + }; + + this.reset = function() { + this.totalTime = 0; + this.minTime = 100000; + this.maxTime = 0; + this.lastUpdate = 0; + this.numberOfCalls = 0; + }; + + this.dump = function() { + cc.log('Profiling info for: ' + this.name + '\n' + + 'Number of calls: ' + this.numberOfCalls + '\n' + + 'Average Time: ' + (this.totalTime/this.numberOfCalls)/1000 + '\n' + + 'Min Time: ' + this.minTime/1000 + '\n' + + 'Max Time: ' + this.maxTime/1000 + '\n' + + 'Total Time: ' + this.totalTime/1000 + '\n' + ); + }; +} + + + +var performanceSpriteTestSceneIdx = -1; +//------------------------------------------------------------------ +// +// PerformanceSpriteTestDemo +// +//------------------------------------------------------------------ +var PerformanceTestBase = cc.Layer.extend({ + _title:"", + _subtitle:"", + + ctor:function() { + this._super(); + this.init(); + }, + onEnter:function () { + this._super(); + + var label = new cc.LabelTTF(this._title, "Arial", 28); + this.addChild(label, 1); + label.x = winSize.width / 2; + label.y = winSize.height - 50; + + if (this._subtitle !== "") { + var l = new cc.LabelTTF(this._subtitle, "Thonburi", 16); + this.addChild(l, 1); + l.x = winSize.width / 2; + l.y = winSize.height - 80; + } + + var item1 = new cc.MenuItemImage(s_pathB1, s_pathB2, this.onBackCallback, this); + var item2 = new cc.MenuItemImage(s_pathR1, s_pathR2, this.onRestartCallback, this); + var item3 = new cc.MenuItemImage(s_pathF1, s_pathF2, this.onNextCallback, this); + + var menu = new cc.Menu(item1, item2, item3); + + menu.x = 0; + + menu.y = 0; + var csw = item2.width, csh = item2.height; + item1.x = winSize.width/2 - csw*2; + item1.y = csh/2; + item2.x = winSize.width/2; + item2.y = csh/2; + item3.x = winSize.width/2 + csw*2; + item3.y = csh/2; + + this.addChild(menu, 1); + }, + + onRestartCallback:function (sender) { + var s = new PerformanceSpriteTestScene(); + s.addChild(restartPerformanceSpriteTest()); + director.runScene(s); + }, + onNextCallback:function (sender) { + var s = new PerformanceSpriteTestScene(); + s.addChild(nextPerformanceSpriteTest()); + director.runScene(s); + }, + onBackCallback:function (sender) { + var s = new PerformanceSpriteTestScene(); + s.addChild(previousPerformanceSpriteTest()); + director.runScene(s); + } +}); + +//------------------------------------------------------------------ +// +// PerformanceSpriteTest1 +// +//------------------------------------------------------------------ +var PerformanceSpriteTest1 = PerformanceTestBase.extend({ + _title:"Performance Test 1", + _subtitle:"Let it run until you see the 'done' message. See console for results.", + + ctor:function () { + this._super(); + + this.testFunctions = [this.testA, this.testB]; + this.endFunctions = [this.endA, this.endB]; + this.testSpriteTotals = [100,500,1000,2000,5000,10000]; + this.functionsIdx = 0; + this.spritesTotalsIdx = -1; + + this.runNextTest(); + + this.scheduleUpdate(); + this.schedule( this.endProfiling, SECONDS_PER_TEST); + this.firstTick = true; + }, + + runNextTest:function() { + + // cleanup current function + if( this.spritesTotalsIdx != -1) { + var cleanup = this.endFunctions[ this.functionsIdx ]; + cleanup.bind(this)(); + } + + this.spritesTotalsIdx++; + + // get next function + if( this.spritesTotalsIdx >= this.testSpriteTotals.length ) { + this.spritesTotalsIdx = 0; + this.functionsIdx++; + if( this.functionsIdx >= this.testFunctions.length ) { + cc.log("No more tests"); + return false; + } + } + var func = this.testFunctions[ this.functionsIdx ]; + var t = this.testSpriteTotals[ this.spritesTotalsIdx ]; + func.bind(this)(t); + return true; + }, + + testA:function(num) { + // Draws all sprites on the screen + // Non-batched drawing + + this.profiling = new Profiling("Test A - Total Sprites: " + num); + + // use the same seed for the tests + Math.seedrandom('perftest'); + var parent = new cc.Node(); + this.addChild(parent,0,10); + + for( var i=0; i 1.0) { + var frameRateB = (this._numberOfTouchesB / this._elapsedTime).toFixed(1); + var frameRateM = (this._numberOfTouchesM / this._elapsedTime).toFixed(1); + var frameRateE = (this._numberOfTouchesE / this._elapsedTime).toFixed(1); + var frameRateC = (this._numberOfTouchesC / this._elapsedTime).toFixed(1); + this._elapsedTime = 0; + this._numberOfTouchesB = this._numberOfTouchesM = this._numberOfTouchesE = this._numberOfTouchesC = 0; + + var str = frameRateB + " " + frameRateM + " " + frameRateE + " " + frameRateC; + this._plabel.setString(str); + } + } +}); + +//////////////////////////////////////////////////////// +// +// TouchesPerformTest1 +// +//////////////////////////////////////////////////////// +var TouchesPerformTest1 = TouchesMainScene.extend({ + onEnter:function () { + this._super(); + + var _this = this; + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches: true, + onTouchBegan:function (touch, event) { + _this._numberOfTouchesB++; + return true; + }, + onTouchMoved:function (touch, event) { + _this._numberOfTouchesM++; + }, + onTouchEnded:function (touch, event) { + _this._numberOfTouchesE++; + }, + onTouchCancelled:function (touch, event) { + _this._numberOfTouchesC++; + } + }, this); + }, + title:function () { + return "Targeted touches"; + } +}); + +//////////////////////////////////////////////////////// +// +// TouchesPerformTest2 +// +//////////////////////////////////////////////////////// +var TouchesPerformTest2 = TouchesMainScene.extend({ + onEnter:function () { + this._super(); + var _this = this; + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesBegan:function (touches, event) { + _this._numberOfTouchesB += touches.length; + }, + onTouchesMoved:function (touches, event) { + _this._numberOfTouchesM += touches.length; + }, + onTouchesEnded:function (touches, event) { + _this._numberOfTouchesE += touches.length; + }, + onTouchesCancelled:function (touches, event) { + _this._numberOfTouchesC += touches.length; + } + }, this); + }, + title:function () { + return "Standard touches"; + } +}); + +function runTouchesTest() { + s_nTouchCurCase = 0; + var scene = new cc.Scene(); + var layer = new TouchesPerformTest1(true, 2, s_nTouchCurCase); + scene.addChild(layer); + cc.director.runScene(scene); +} diff --git a/tests/js-tests/src/PerformanceTest/PerformanceVirtualMachineTest.js b/tests/js-tests/src/PerformanceTest/PerformanceVirtualMachineTest.js new file mode 100644 index 0000000000..1385f6f00e --- /dev/null +++ b/tests/js-tests/src/PerformanceTest/PerformanceVirtualMachineTest.js @@ -0,0 +1,550 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var VM_TAG_BASE = 2000; +var VM_MAX_NODES = 1500; +var VM_NODES_INCREASE = 100; +var s_nVMCurCase = 0; + +//////////////////////////////////////////////////////// +// +// VirtualMachineTestMenuLayer +// +// These are some demo test cases about low level JS engine behavior, so in +// some sense this is simliar to PerformanceNodeChildrenTest. This file is +// derived from PerformanceNodeChildrenTest.js actually. +// +// See https://github.com/oupengsoftware/v8/wiki for some of the details (V8) +// under the hood. +// Keyword: hidden class, inline cache, dictionary mode. +// +//////////////////////////////////////////////////////// +var VirtualMachineTestMenuLayer = PerformBasicLayer.extend({ + _maxCases:6, + ctor:function(){ + this._super(); + this._maxCases = (cc._renderType === cc._RENDER_TYPE_CANVAS) ? 6 : 4; + }, + showCurrentTest:function () { + var nodes = (this.parent).getQuantityOfNodes(); + var scene = null; + switch (this._curCase) { + case 0: + scene = new SpritesWithManyPropertiesTestScene1(); + break; + case 1: + scene = new SpritesWithManyPropertiesTestScene2(); + break; + case 2: + scene = new SpritesUndergoneDifferentOperationsTestScene1(); + break; + case 3: + scene = new SpritesUndergoneDifferentOperationsTestScene2(); + break; + case 4: + scene = new ClonedSpritesTestScene1(); + break; + case 5: + scene = new ClonedSpritesTestScene2(); + break; + } + s_nVMCurCase = this._curCase; + + if (scene) { + scene.initWithQuantityOfNodes(nodes); + cc.director.runScene(scene); + } + } +}); + +//////////////////////////////////////////////////////// +// +// VirtualMachineTestMainScene +// +//////////////////////////////////////////////////////// +var VirtualMachineTestMainScene = cc.Scene.extend({ + _lastRenderedCount:null, + _quantityOfNodes:null, + _currentQuantityOfNodes:null, + _batchNode:null, + + ctor:function() { + this._super(); + this.init(); + }, + + initWithQuantityOfNodes:function (nodes) { + this._batchNode = new cc.SpriteBatchNode("res/Images/grossinis_sister1.png"); + this.addChild(this._batchNode); + + //srand(time()); + var s = cc.director.getWinSize(); + + // Title + var label = new cc.LabelTTF(this.title(), "Arial", 40); + this.addChild(label, 1); + label.x = s.width / 2; + label.y = s.height - 32; + label.color = cc.color(255, 255, 40); + + // Subtitle + var strSubTitle = this.subtitle(); + if (strSubTitle.length) { + var l = new cc.LabelTTF(strSubTitle, "Thonburi", 16); + this.addChild(l, 1); + l.x = s.width / 2; + l.y = s.height - 80; + } + + this._lastRenderedCount = 0; + this._currentQuantityOfNodes = 0; + this._quantityOfNodes = nodes; + + cc.MenuItemFont.setFontSize(65); + var that = this; + var decrease = new cc.MenuItemFont(" - ", this.onDecrease, this); + decrease.color = cc.color(0, 200, 20); + var increase = new cc.MenuItemFont(" + ", this.onIncrease, this); + increase.color = cc.color(0, 200, 20); + + var menu = new cc.Menu(decrease, increase); + menu.alignItemsHorizontally(); + menu.x = s.width / 2; + menu.y = s.height / 2 + 15; + this.addChild(menu, 1); + + var infoLabel = new cc.LabelTTF("0 nodes", "Marker Felt", 30); + infoLabel.color = cc.color(0, 200, 20); + infoLabel.x = s.width / 2; + infoLabel.y = s.height / 2 - 15; + this.addChild(infoLabel, 1, TAG_INFO_LAYER); + + var menu = new VirtualMachineTestMenuLayer(true, 3, s_nVMCurCase); + this.addChild(menu); + + this.updateQuantityLabel(); + this.updateQuantityOfNodes(); + this.scheduleUpdate(); + }, + title:function () { + cc.Assert(0); + // override me + }, + subtitle:function () { + cc.Assert(0); + // override me + }, + updateQuantityOfNodes:function () { + cc.Assert(0); + // override me + }, + onDecrease:function (sender) { + this._quantityOfNodes -= VM_NODES_INCREASE; + if (this._quantityOfNodes < 0) { + this._quantityOfNodes = 0; + } + + this.updateQuantityLabel(); + this.updateQuantityOfNodes(); + }, + onIncrease:function (sender) { + this._quantityOfNodes += VM_NODES_INCREASE; + if (this._quantityOfNodes > VM_MAX_NODES) { + this._quantityOfNodes = VM_MAX_NODES + } + + this.updateQuantityLabel(); + this.updateQuantityOfNodes(); + }, + updateQuantityLabel:function () { + if (this._quantityOfNodes != this._lastRenderedCount) { + var infoLabel = this.getChildByTag(TAG_INFO_LAYER); + var str = this._quantityOfNodes + " nodes"; + infoLabel.setString(str); + + this._lastRenderedCount = this._quantityOfNodes; + } + }, + getQuantityOfNodes:function () { + return this._quantityOfNodes; + }, + arrayToUpdate:null, + update:function (dt) { + if (!this.arrayToUpdate) return; + for (var i = 0, imax = this.arrayToUpdate.length; i < imax; ++i) { + var child = this.arrayToUpdate[i]; + if (!(child instanceof SimpleNewtonianSprite) && + child instanceof cc.Class) continue; // old cc.clone-ed + // sprite is not a cc.Class + for (var j = 0; j < 1000; ++j ) { + child._velocityX = child._velocityX + dt * child._accelerationX; + child._velocityY = child._velocityY + dt * child._accelerationY; + child._positionX = child._positionX + dt * child._velocityX; + child._positionY = child._positionY + dt * child._velocityY; + } + } + } +}); + +// Simple sprite extension used for testing the performance of property access. +var SimpleNewtonianSprite = cc.Sprite.extend({ + ctor:function(texture, rect) { + cc.Sprite.prototype.ctor.call(this); + // Since jsb doesn't have ._position, in order not to make these + // showcase more complicated by introducing fuction calls (because + // different JS engines have different inlining strategy), we simply + // introduce ._postionX ._positionY here. These (and update()) really + // just represent *heavy property access operation* anyway (they're + // otherwise dummy). + this._positionX = 0.0; + this._positionY = 0.0; + this._velocityX = 0.0; + this._velocityY = 0.0; + this._accelerationX = 0.0; + this._accelerationY = 0.0; + + if(texture && rect) + this.initWithTexture(texture, rect); + } +}); + +//////////////////////////////////////////////////////// +// +// SpritesWithManyPropertiesTestScene +// +// Some JS engines (notably, V8) assume that objects with many properties are +// dictionary (c.f CCClass.js) and that makes bad performance. Here we +// simulate a character class with many properties of a character, but +// otherwise these properties are dummy (and probably doesn't make much +// sense) in the test of course. +// (TODO: Find a open source real world example, which shouldn't be that hard. +// :) ) +// +//////////////////////////////////////////////////////// +var SpriteWithManyProperties = SimpleNewtonianSprite.extend({ + ctor:function(texture, rect) { + SimpleNewtonianSprite.prototype.ctor.call(this, texture, rect); + this._name = ""; + this._species = ""; + this._id = -1; + this._hp = 100; + this._mp = 100; + this._exp = 100; + this._lv = 1; + this._str = 100; + this._dex = 100; + this._int = 100; + this._luk = 100; + this._gold = 10000000; // I'm rich. + this._weight = 100.0; + this._height = 100.0; + this._items = []; + this._spells = []; + this._dressing = null; + this._weapon = null; + this._mission = null; + this._friends = []; + this._groups = []; + + this._idleTime = 0.0; + this._loginTime = 0.0; + this._isAutoMove = false; + this._autoMoveTarget = false; + this._attackMode = 0; + this._active = true; + this._canBeAttack = true; + this._isLocalPlayer = false; + this._moveType = null; + this._I_AM_TIRED_OF_COMING_UP_WITH_NEW_PROPERTIES = true; + } +}); + +var SpritesWithManyPropertiesTestScene1 = VirtualMachineTestMainScene.extend({ + updateQuantityOfNodes:function () { + var s = cc.director.getWinSize(); + + // increase nodes + if (this._currentQuantityOfNodes < this._quantityOfNodes) { + for (var i = 0; + i < (this._quantityOfNodes - this._currentQuantityOfNodes); + i++) { + var sprite = + new SpriteWithManyProperties(this._batchNode.texture, + cc.rect(0, 0, 52, 139)); + this._batchNode.addChild(sprite); + sprite.x = Math.random() * s.width; + sprite.y = Math.random() * s.height; + } + } + + // decrease nodes + else if (this._currentQuantityOfNodes > this._quantityOfNodes) { + for (var i = 0; + i < (this._currentQuantityOfNodes - this._quantityOfNodes); + i++) { + var index = this._currentQuantityOfNodes - i - 1; + this._batchNode.removeChildAtIndex(index, true); + } + } + + this._currentQuantityOfNodes = this._quantityOfNodes; + }, + title:function () { + return "A1 - Sprites Have Many Properties"; + }, + subtitle:function () { + return "See fps (and source code of this test)."; + } +}); + +var SpritesWithManyPropertiesTestScene2 = + SpritesWithManyPropertiesTestScene1.extend({ + updateQuantityOfNodes:function () { + this._super(); + var arrayToUpdate = this._batchNode.children; + for (var i = 0, imax = arrayToUpdate.length; i < imax; ++i) + arrayToUpdate[i].visible = false; + this.arrayToUpdate = arrayToUpdate; + }, + title:function () { + return "A2 - Sprites Have Many Properties"; + }, + subtitle:function () { + return "No draw(). update() does heavy calculations."; + } +}); + +//////////////////////////////////////////////////////// +// +// SpritesUndergoneDifferentOperationsTestScene +// +// If properties in use are not initilized on each instance, a combinarial +// explosion of hidden classes have to be created for each possible +// permutation of operations. This increases inline cache size and +// constitutes significant performance penalty. +// +//////////////////////////////////////////////////////// + +var SpritesUndergoneDifferentOperationsTestScene1 = VirtualMachineTestMainScene.extend({ + // Adpated from http://codereview.stackexchange.com/a/7025 + possibleOperationSeries:(function permutations(array){ + var fn = function(active, rest, a) { + if (!active.length && !rest.length) { + a.push([]); + return; + } + if (!rest.length) { + if (active.length === 1) { + a.push(active); + return; + } + + var fac = 1; + for (var i = active.length; i > 0; --i) fac = fac * i; + for (var i = 0; i < fac; ++i) { + var choice_num = i; + var choice = []; + for (var j = 1; j < active.length + 1; ++j) { + choice.unshift(choice_num % j); + choice_num = (choice_num - choice_num % j) / j; + } + + var to_choose_from = active.slice(0); + var new_permutation = []; + for (var k = 0; k < active.length; ++k) + new_permutation.push(to_choose_from. + splice(choice[k], 1)[0]); + a.push(new_permutation); + } + } else { + fn(active.concat([rest[0]]), rest.slice(1), a); + fn(active, rest.slice(1), a); + } + return a; + }; + return fn([], array, []); + })([ + function() { this.children; }, // appends ._children + function() { this.tag = cc.NODE_TAG_INVALID; }, // appends .tag + function() { this.setParent(null); }, // appends ._parent + function() { this.zIndex = 0; }, // appends ._zOrder + function() { this.rotation = 0; }, // appends ._rotationX/Y + function() { this.visible = true; }, // appends ._visible + function() { this.onEnter(); } // appends ._running + ]), + updateQuantityOfNodes:function () { + var s = cc.director.getWinSize(); + + // increase nodes + if (this._currentQuantityOfNodes < this._quantityOfNodes) { + for (var i = 0; + i < (this._quantityOfNodes - this._currentQuantityOfNodes); + i++) { + var sprite = + new SimpleNewtonianSprite(this._batchNode.texture, + cc.rect(0, 0, 52, 139)); + var series = this.possibleOperationSeries[i]; + for (var op = 0, opmax = series.length; op < opmax; ++op) + series[op].call(sprite); + + this._batchNode.addChild(sprite); + sprite.x = Math.random() * s.width; + sprite.y = Math.random() * s.height; + } + } + + // decrease nodes + else if (this._currentQuantityOfNodes > this._quantityOfNodes) { + for (var i = 0; + i < (this._currentQuantityOfNodes - this._quantityOfNodes); + i++) { + var index = this._currentQuantityOfNodes - i - 1; + this._batchNode.removeChildAtIndex(index, true); + } + } + + this._currentQuantityOfNodes = this._quantityOfNodes; + }, + title:function () { + return "B1 - Sprites Undergone Different Op. Order"; + }, + subtitle:function () { + return "See fps (and source code of this test)."; + } +}); + +var SpritesUndergoneDifferentOperationsTestScene2 = + SpritesUndergoneDifferentOperationsTestScene1.extend({ + // This looks exactly like the one on ManyPropertiesTestScene2, but + // we can't just do + // 'updateQuantityOfNodes: SpritesWithManyPropertiesTestScene2.prototype.updateQuantityOfNodes' + // here becasue this._super() is different! + updateQuantityOfNodes:function () { + this._super(); + var arrayToUpdate = this._batchNode.children; + for (var i = 0, imax = arrayToUpdate.length; i < imax; ++i) + arrayToUpdate[i].visible = false; + this.arrayToUpdate = arrayToUpdate; + }, + title:function () { + return "B2 - Sprites Undergone Different Op. Order"; + }, + subtitle:function () { + return "No draw(). update() does heavy calculations."; + } +}); + +//////////////////////////////////////////////////////// +// +// ClonedSpritesTestScene +// +// cc.clone has to be written carefully or cloned objects all go to dictionary +// mode. +// +//////////////////////////////////////////////////////// +var ClonedSpritesTestScene1 = VirtualMachineTestMainScene.extend({ + template:null, + updateQuantityOfNodes:function () { + if (!this.template) + this.template = + new SimpleNewtonianSprite(this._batchNode.texture, + cc.rect(0, 0, 52, 139)); + var s = cc.director.getWinSize(); + + // increase nodes + if (this._currentQuantityOfNodes < this._quantityOfNodes) { + for (var i = 0; + i < (this._quantityOfNodes - this._currentQuantityOfNodes); + i++) { + var sprite = cc.clone(this.template); + sprite.setParent(null); // old cc.clone copies null as {}... + + // cc.SpriteBatchNode doesn't support adding non-cc.Sprite child + // and hence incompatible with old cc.clone. We add the sprite + // to the scene directly. + this.addChild(sprite, -1); // zOrder has to be less than 0 or it + // overlaps the menu. + sprite.x = Math.random() * s.width; + sprite.y = Math.random() * s.height; + } + } + + // decrease nodes + else if (this._currentQuantityOfNodes > this._quantityOfNodes) { + var children = this.children; + var lastChildToRemove = children.length; + for (var i = children.length - 1; i >= 0; --i) { + var child = children[i]; + if (child instanceof SimpleNewtonianSprite || + !(child instanceof cc.Class)) { // old cc.clone-ed + // sprite is not a cc.Class + lastChildToRemove = i; + break; + } + } + + for (var i = 0; + i < (this._currentQuantityOfNodes - this._quantityOfNodes); + i++) { + var index = lastChildToRemove - i; + this.removeChild(children[index], true); + } + } + + this._currentQuantityOfNodes = this._quantityOfNodes; + }, + title:function () { + return "C1 - Cloned Sprites"; + }, + subtitle:function () { + return "See fps (and source code of this test)."; + } +}); + +var ClonedSpritesTestScene2 = ClonedSpritesTestScene1.extend({ + updateQuantityOfNodes:function () { + if (!this.template) { + this.template = + new SimpleNewtonianSprite(this._batchNode.texture, + cc.rect(0, 0, 52, 139)); + this.template.visible = false; + } + this._super(); + this.arrayToUpdate = this.children; + }, + title:function () { + return "C2 - Cloned Sprites"; + }, + subtitle:function () { + return "No draw(). update() does heavy calculations."; + } +}); + +function runVirtualMachineTest() { + var scene = new SpritesWithManyPropertiesTestScene1(); + scene.initWithQuantityOfNodes(VM_NODES_INCREASE); + cc.director.runScene(scene); +} diff --git a/tests/js-tests/src/PerformanceTest/seedrandom.js b/tests/js-tests/src/PerformanceTest/seedrandom.js new file mode 100644 index 0000000000..58b4a96158 --- /dev/null +++ b/tests/js-tests/src/PerformanceTest/seedrandom.js @@ -0,0 +1,272 @@ +// seedrandom.js version 2.0. +// Author: David Bau 4/2/2011 +// +// Defines a method Math.seedrandom() that, when called, substitutes +// an explicitly seeded RC4-based algorithm for Math.random(). Also +// supports automatic seeding from local or network sources of entropy. +// +// Usage: +// +// +// +// Math.seedrandom('yipee'); Sets Math.random to a function that is +// initialized using the given explicit seed. +// +// Math.seedrandom(); Sets Math.random to a function that is +// seeded using the current time, dom state, +// and other accumulated local entropy. +// The generated seed string is returned. +// +// Math.seedrandom('yowza', true); +// Seeds using the given explicit seed mixed +// together with accumulated entropy. +// +// +// Seeds using physical random bits downloaded +// from random.org. +// +// Seeds using urandom bits from call.jsonlib.com, +// which is faster than random.org. +// +// Examples: +// +// Math.seedrandom("hello"); // Use "hello" as the seed. +// document.write(Math.random()); // Always 0.5463663768140734 +// document.write(Math.random()); // Always 0.43973793770592234 +// var rng1 = Math.random; // Remember the current prng. +// +// var autoseed = Math.seedrandom(); // New prng with an automatic seed. +// document.write(Math.random()); // Pretty much unpredictable. +// +// Math.random = rng1; // Continue "hello" prng sequence. +// document.write(Math.random()); // Always 0.554769432473455 +// +// Math.seedrandom(autoseed); // Restart at the previous seed. +// document.write(Math.random()); // Repeat the 'unpredictable' value. +// +// Notes: +// +// Each time seedrandom('arg') is called, entropy from the passed seed +// is accumulated in a pool to help generate future seeds for the +// zero-argument form of Math.seedrandom, so entropy can be injected over +// time by calling seedrandom with explicit data repeatedly. +// +// On speed - This javascript implementation of Math.random() is about +// 3-10x slower than the built-in Math.random() because it is not native +// code, but this is typically fast enough anyway. Seeding is more expensive, +// especially if you use auto-seeding. Some details (timings on Chrome 4): +// +// Our Math.random() - avg less than 0.002 milliseconds per call +// seedrandom('explicit') - avg less than 0.5 milliseconds per call +// seedrandom('explicit', true) - avg less than 2 milliseconds per call +// seedrandom() - avg about 38 milliseconds per call +// +// LICENSE (BSD): +// +// Copyright 2010 David Bau, all rights reserved. +// +// 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. Neither the name of this module nor the names of its contributors may +// be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS 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. +// +/** + * All code is in an anonymous closure to keep the global namespace clean. + * + * @param {number=} overflow + * @param {number=} startdenom + */ +(function (pool, math, width, chunks, significance, overflow, startdenom) { + + +// +// seedrandom() +// This is the seedrandom function described above. +// +math.seedrandom = function seedrandom(seed, use_entropy) { + var key = []; + var arc4; + + // Flatten the seed string or build one from local entropy if needed. + seed = mixkey(flatten( + use_entropy ? [seed, pool] : + arguments.length ? seed : + [Date.now(), pool, window], 3), key); + + // Use the seed to initialize an ARC4 generator. + arc4 = new ARC4(key); + + // Mix the randomness into accumulated entropy. + mixkey(arc4.S, pool); + + // Override Math.random + + // This function returns a random double in [0, 1) that contains + // randomness in every bit of the mantissa of the IEEE 754 value. + + math.random = function random() { // Closure to return a random double: + var n = arc4.g(chunks); // Start with a numerator n < 2 ^ 48 + var d = startdenom; // and denominator d = 2 ^ 48. + var x = 0; // and no 'extra last byte'. + while (n < significance) { // Fill up all significant digits by + n = (n + x) * width; // shifting numerator and + d *= width; // denominator and generating a + x = arc4.g(1); // new least-significant-byte. + } + while (n >= overflow) { // To avoid rounding up, before adding + n /= 2; // last byte, shift everything + d /= 2; // right using integer math until + x >>>= 1; // we have exactly the desired bits. + } + return (n + x) / d; // Form the number within [0, 1). + }; + + // Return the seed that was used + return seed; +}; + +// +// ARC4 +// +// An ARC4 implementation. The constructor takes a key in the form of +// an array of at most (width) integers that should be 0 <= x < (width). +// +// The g(count) method returns a pseudorandom integer that concatenates +// the next (count) outputs from ARC4. Its return value is a number x +// that is in the range 0 <= x < (width ^ count). +// +/** @constructor */ +function ARC4(key) { + var t, u, me = this, keylen = key.length; + var i = 0, j = me.i = me.j = me.m = 0; + me.S = []; + me.c = []; + + // The empty key [] is treated as [0]. + if (!keylen) { key = [keylen++]; } + + // Set up S using the standard key scheduling algorithm. + while (i < width) { me.S[i] = i++; } + for (i = 0; i < width; i++) { + t = me.S[i]; + j = lowbits(j + t + key[i % keylen]); + u = me.S[j]; + me.S[i] = u; + me.S[j] = t; + } + + // The "g" method returns the next (count) outputs as one number. + me.g = function getnext(count) { + var s = me.S; + var i = lowbits(me.i + 1); var t = s[i]; + var j = lowbits(me.j + t); var u = s[j]; + s[i] = u; + s[j] = t; + var r = s[lowbits(t + u)]; + while (--count) { + i = lowbits(i + 1); t = s[i]; + j = lowbits(j + t); u = s[j]; + s[i] = u; + s[j] = t; + r = r * width + s[lowbits(t + u)]; + } + me.i = i; + me.j = j; + return r; + }; + // For robust unpredictability discard an initial batch of values. + // See http://www.rsa.com/rsalabs/node.asp?id=2009 + me.g(width); +} + +// +// flatten() +// Converts an object tree to nested arrays of strings. +// +/** @param {Object=} result + * @param {string=} prop + * @param {string=} typ */ +function flatten(obj, depth, result, prop, typ) { + result = []; + typ = typeof(obj); + if (depth && typ == 'object') { + for (prop in obj) { + if (prop.indexOf('S') < 5) { // Avoid FF3 bug (local/sessionStorage) + try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {} + } + } + } + return (result.length ? result : obj + (typ != 'string' ? '\0' : '')); +} + +// +// mixkey() +// Mixes a string seed into a key that is an array of integers, and +// returns a shortened string seed that is equivalent to the result key. +// +/** @param {number=} smear + * @param {number=} j */ +function mixkey(seed, key, smear, j) { + seed += ''; // Ensure the seed is a string + smear = 0; + for (j = 0; j < seed.length; j++) { + key[lowbits(j)] = + lowbits((smear ^= key[lowbits(j)] * 19) + seed.charCodeAt(j)); + } + seed = ''; + for (j in key) { seed += String.fromCharCode(key[j]); } + return seed; +} + +// +// lowbits() +// A quick "n mod width" for width a power of 2. +// +function lowbits(n) { return n & (width - 1); } + +// +// The following constants are related to IEEE 754 limits. +// +startdenom = math.pow(width, chunks); +significance = math.pow(2, significance); +overflow = significance * 2; + +// +// When seedrandom.js is loaded, we immediately mix a few bits +// from the built-in RNG into the entropy pool. Because we do +// not want to intefere with determinstic PRNG state later, +// seedrandom will not call math.random on its own again after +// initialization. +// +mixkey(math.random(), pool); + +// End anonymous scope, and pass initial values. +})( + [], // pool: entropy pool starts empty + Math, // math: package containing random, pow, and seedrandom + 256, // width: each RC4 output is 0 <= x < 256 + 6, // chunks: at least six RC4 outputs for each double + 52 // significance: there are 52 significant digits in a double +); diff --git a/tests/js-tests/src/Presentation/Presentation.js b/tests/js-tests/src/Presentation/Presentation.js new file mode 100644 index 0000000000..8d82ee231f --- /dev/null +++ b/tests/js-tests/src/Presentation/Presentation.js @@ -0,0 +1,768 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + + +var presentationSceneIdx = -1; +var centerPos = cc.p(0,0); // will be updated later +var images_path = 'res/Presentation/'; + +//------------------------------------------------------------------ +// +// PresentationBaseLayer +// +//------------------------------------------------------------------ +var PresentationBaseLayer = function() { + + // + // VERY IMPORTANT + // + // Only subclasses of a native classes MUST call __associateObjectWithNative + // Failure to do so, it will crash. + // + var parent = BaseTestLayer.call(this, cc.color(0,0,0,255), cc.color(98,99,117,255)); + + this._title = "No title"; + this._subtitle = "No Subtitle"; + this.isMainTitle = false; + +}; +cc.inherits(PresentationBaseLayer, BaseTestLayer ); + +// +// Instance 'base' methods +// XXX: Should be defined after "cc.inherits" +// +PresentationBaseLayer.prototype.onEnter = function() { + + BaseTestLayer.prototype.onEnter.call(this); + + var fontSize = 36; + var tl = this._title.length; + fontSize = (winSize.width / tl) * 1.60; + if( fontSize/winSize.width > 0.09 ) { + fontSize = winSize.width * 0.09; + } + + this.label = new cc.LabelTTF(this._title, "Gill Sans", fontSize); + this.addChild(this.label, 100); + + var isMain = this.isMainTitle; + + if( isMain === true ) { + this.label.x = centerPos.x; + this.label.y = centerPos.y; + } + else { + this.label.x = winSize.width / 2; + this.label.y = winSize.height*11/12 ; + } + + var subStr = this._subtitle; + if (subStr !== "") { + tl = this._subtitle.length; + var subfontSize = (winSize.width / tl) * 1.3; + if( subfontSize > fontSize *0.4 ) { + subfontSize = fontSize *0.4; + } + + this.sublabel = new cc.LabelTTF(subStr, "Thonburi", subfontSize); + this.addChild(this.sublabel, 90); + if( isMain ) { + this.sublabel.x = winSize.width / 2; + this.sublabel.y = winSize.height*3/8; + } + else { + this.sublabel.x = winSize.width / 2; + this.sublabel.y = winSize.height*4/5; + } + } else + this.sublabel = null; + + // Opacity in Menu + var menu = this.getChildByTag(BASE_TEST_MENU_TAG); + var item1 = menu.getChildByTag(BASE_TEST_MENUITEM_PREV_TAG); + var item2 = menu.getChildByTag(BASE_TEST_MENUITEM_RESET_TAG); + var item3 = menu.getChildByTag(BASE_TEST_MENUITEM_NEXT_TAG); + + [item1, item2, item3 ].forEach( function(item) { + item.getNormalImage().opacity = 45; + item.getSelectedImage().opacity = 45; + } ); + + // remove "super" titles + this.removeChildByTag(BASE_TEST_TITLE_TAG); + this.removeChildByTag(BASE_TEST_SUBTITLE_TAG); +}; + +PresentationBaseLayer.prototype.prevTransition = function () { + return cc.TransitionSlideInL; +}; + +PresentationBaseLayer.prototype.nextTransition = function () { + return cc.TransitionSlideInR; +}; + +PresentationBaseLayer.prototype.createBulletList = function () { + var str = ""; + for(var i=0; i 1) { + var locLastLocation = this._lastLocation; + this._target.begin(); + this._brushs = []; + for(var i = 0; i < distance; ++i) { + var diffX = locLastLocation.x - location.x; + var diffY = locLastLocation.y - location.y; + var delta = i / distance; + var sprite = new cc.Sprite(s_fire); + sprite.attr({ + x: location.x + diffX * delta, + y: location.y + diffY * delta, + rotation: Math.random() * 360, + color: cc.color(Math.random() * 255, 255, 255), + scale: Math.random() + 0.25, + opacity: 20 + }); + sprite.retain(); + this._brushs.push(sprite); + } + for (var i = 0; i < distance; i++) { + this._brushs[i].visit(); + } + this._target.end(); + } + this._lastLocation = location; + }, + + subtitle:function () { + return "Testing 'save'"; + } +}); + +var RenderTextureIssue937 = RenderTextureBaseLayer.extend({ + ctor:function () { + this._super(); + var winSize = cc.director.getWinSize(); + /* + * 1 2 + * A: A1 A2 + * + * B: B1 B2 + * + * A1: premulti sprite + * A2: premulti render + * + * B1: non-premulti sprite + * B2: non-premulti render + */ + var background = new cc.LayerColor(cc.color(200, 200, 200, 255)); + this.addChild(background); + + var spr_premulti = new cc.Sprite(s_fire); + spr_premulti.x = 16; + spr_premulti.y = 48; + + var spr_nonpremulti = new cc.Sprite(s_fire); + spr_nonpremulti.x = 16; + spr_nonpremulti.y = 16; + + /* A2 & B2 setup */ + var rend = new cc.RenderTexture(32, 64, cc.Texture2D.PIXEL_FORMAT_RGBA8888); + if (!rend) + return; + // It's possible to modify the RenderTexture blending function by + // [[rend sprite] setBlendFunc:(ccBlendFunc) {GL_ONE, GL_ONE_MINUS_SRC_ALPHA}]; + //rend.getSprite().setBlendFunc(cc._renderContext.ONE, cc._renderContext.ONE_MINUS_SRC_ALPHA); + rend.begin(); + spr_premulti.visit(); + spr_nonpremulti.visit(); + rend.end(); + + /* A1: setup */ + spr_premulti.x = winSize.width / 2 - 16; + spr_premulti.y = winSize.height / 2 + 16; + /* B1: setup */ + spr_nonpremulti.x = winSize.width / 2 - 16; + spr_nonpremulti.y = winSize.height / 2 - 16; + + rend.x = winSize.width / 2 + 16; + rend.y = winSize.height / 2; + //background.visible = false; + this.addChild(spr_nonpremulti); + this.addChild(spr_premulti); + this.addChild(rend); + }, + + title:function () { + return "Testing issue #937"; + }, + + subtitle:function () { + return "All images should be equal.."; + } +}); + +var RenderTextureZbuffer = RenderTextureBaseLayer.extend({ + mgr:null, + sp1:null, + sp2:null, + sp3:null, + sp4:null, + sp5:null, + sp6:null, + sp7:null, + sp8:null, + sp9:null, + + ctor:function () { + this._super(); + + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesBegan: this.onTouchesBegan.bind(this), + onTouchesEnded: this.onTouchesEnded.bind(this), + onTouchesMoved: this.onTouchesMoved.bind(this) + }, this); + + var size = cc.director.getWinSize(); + var label = new cc.LabelTTF("vertexZ = 50", "Marker Felt", 64); + label.x = size.width / 2; + label.y = size.height * 0.25; + this.addChild(label); + + var label2 = new cc.LabelTTF("vertexZ = 0", "Marker Felt", 64); + label2.x = size.width / 2; + label2.y = size.height * 0.5; + this.addChild(label2); + + var label3 = new cc.LabelTTF("vertexZ = -50", "Marker Felt", 64); + label3.x = size.width / 2; + label3.y = size.height * 0.75; + this.addChild(label3); + + label.vertexZ = 50; + label2.vertexZ = 0; + label3.vertexZ = -50; + + cc.spriteFrameCache.addSpriteFrames(s_circle_plist); + this.mgr = new cc.SpriteBatchNode(s_circle_png, 9); + this.addChild(this.mgr); + this.sp1 = new cc.Sprite("#circle.png"); + this.sp2 = new cc.Sprite("#circle.png"); + this.sp3 = new cc.Sprite("#circle.png"); + this.sp4 = new cc.Sprite("#circle.png"); + this.sp5 = new cc.Sprite("#circle.png"); + this.sp6 = new cc.Sprite("#circle.png"); + this.sp7 = new cc.Sprite("#circle.png"); + this.sp8 = new cc.Sprite("#circle.png"); + this.sp9 = new cc.Sprite("#circle.png"); + + this.mgr.addChild(this.sp1, 9); + this.mgr.addChild(this.sp2, 8); + this.mgr.addChild(this.sp3, 7); + this.mgr.addChild(this.sp4, 6); + this.mgr.addChild(this.sp5, 5); + this.mgr.addChild(this.sp6, 4); + this.mgr.addChild(this.sp7, 3); + this.mgr.addChild(this.sp8, 2); + this.mgr.addChild(this.sp9, 1); + + this.sp1.vertexZ = 400; + this.sp2.vertexZ = 300; + this.sp3.vertexZ = 200; + this.sp4.vertexZ = 100; + this.sp5.vertexZ = 0; + this.sp6.vertexZ = -100; + this.sp7.vertexZ = -200; + this.sp8.vertexZ = -300; + this.sp9.vertexZ = -400; + + this.sp9.scale = 2; + this.sp9.color = cc.color.YELLOW; + }, + + onTouchesBegan:function (touches, event) { + if (!touches || touches.length === 0) + return; + + for (var i = 0; i < touches.length; i++) { + var location = touches[i].getLocation(); + + this.sp1.x = location.x; + this.sp1.y = location.y; + this.sp2.x = location.x; + this.sp2.y = location.y; + this.sp3.x = location.x; + this.sp3.y = location.y; + this.sp4.x = location.x; + this.sp4.y = location.y; + this.sp5.x = location.x; + this.sp5.y = location.y; + this.sp6.x = location.x; + this.sp6.y = location.y; + this.sp7.x = location.x; + this.sp7.y = location.y; + this.sp8.x = location.x; + this.sp8.y = location.y; + this.sp9.x = location.x; + this.sp9.y = location.y; + } + }, + + onTouchesMoved:function (touches, event) { + if (!touches || touches.length === 0) + return; + + for (var i = 0; i < touches.length; i++) { + var location = touches[i].getLocation(); + + this.sp1.x = location.x; + this.sp1.y = location.y; + this.sp2.x = location.x; + this.sp2.y = location.y; + this.sp3.x = location.x; + this.sp3.y = location.y; + this.sp4.x = location.x; + this.sp4.y = location.y; + this.sp5.x = location.x; + this.sp5.y = location.y; + this.sp6.x = location.x; + this.sp6.y = location.y; + this.sp7.x = location.x; + this.sp7.y = location.y; + this.sp8.x = location.x; + this.sp8.y = location.y; + this.sp9.x = location.x; + this.sp9.y = location.y; + } + }, + + onTouchesEnded:function (touches, event) { + this.renderScreenShot(); + }, + + title:function () { + return "Testing Z Buffer in Render Texture"; + }, + + subtitle:function () { + return "Touch screen. It should be green"; + }, + + renderScreenShot:function () { + var winSize = cc.director.getWinSize(); + var texture = new cc.RenderTexture(winSize.width, winSize.width); + if (!texture) + return; + + texture.anchorX = 0; + texture.anchorY = 0; + texture.begin(); + this.visit(); + texture.end(); + + var sprite = new cc.Sprite(texture.getSprite().texture); + + sprite.x = winSize.width/2; + sprite.y = winSize.width/2; + sprite.opacity = 182; + sprite.flippedY = 1; + this.addChild(sprite, 999999); + sprite.color = cc.color.GREEN; + + sprite.runAction(cc.sequence(cc.fadeTo(2, 0), cc.hide())); + } +}); + +var RenderTextureTestDepthStencil = RenderTextureBaseLayer.extend({ + ctor:function () { + //Need to re-write test case for new renderer + this._super(); + var gl = cc._renderContext; + + var winSize = cc.director.getWinSize(); + + var sprite = new cc.Sprite(s_fire); + sprite.x = winSize.width * 0.25; + sprite.y = 0; + sprite.scale = 10; + //TODO GL_DEPTH24_STENCIL8 + //var rend = new cc.RenderTexture(winSize.width, winSize.height, cc.TEXTURE_2D_PIXEL_FORMAT_RGBA4444); + var rend = new cc.RenderTexture(winSize.width, winSize.height); + + gl.stencilMask(0xFF); + rend.beginWithClear(0, 0, 0, 0, 0, 0); + + //! mark sprite quad into stencil buffer + gl.enable(gl.STENCIL_TEST); + gl.stencilFunc(gl.ALWAYS, 1, 0xFF); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE); + gl.colorMask(0, 0, 0, 1); + sprite.visit(); + + //! move sprite half width and height, and draw only where not marked + sprite.x += sprite.width * sprite.scale / 2; + sprite.y += sprite.height * sprite.scale / 2; + gl.stencilFunc(gl.NOTEQUAL, 1, 0xFF); + gl.colorMask(1, 1, 1, 1); + sprite.visit(); + + rend.end(); + + gl.disable(gl.STENCIL_TEST); + + rend.x = winSize.width * 0.5; + rend.y = winSize.height * 0.5; + + this.addChild(rend); + }, + + title:function () { + return "Testing depthStencil attachment"; + }, + + subtitle:function () { + return "Circle should be missing 1/4 of its region"; + } +}); + +var RenderTextureTargetNode = RenderTextureBaseLayer.extend({ + _sprite1:null, + _sprite2:null, + _time:0, + _winSize:null, + + _renderTexture:null, + + ctor:function () { + this._super(); + /* + * 1 2 + * A: A1 A2 + * + * B: B1 B2 + * + * A1: premulti sprite + * A2: premulti render + * + * B1: non-premulti sprite + * B2: non-premulti render + */ + var background = new cc.LayerColor(cc.color(40, 40, 40, 255)); + this.addChild(background); + + var winSize = cc.director.getWinSize(); + this._winSize = winSize; + + // sprite 1 + var sprite1 = new cc.Sprite(s_fire); + sprite1.x = winSize.width; + sprite1.y = winSize.height; + this._sprite1 = sprite1; + + // sprite 2 + //todo Images/fire_rgba8888.pvr + var sprite2 = new cc.Sprite(s_fire); + sprite2.x = winSize.width; + sprite2.y = winSize.height; + this._sprite2 = sprite2; + + /* Create the render texture */ + //var renderTexture = new cc.RenderTexture(winSize.width, winSize.height, cc.TEXTURE_2D_PIXEL_FORMAT_RGBA4444); + var renderTexture = new cc.RenderTexture(winSize.width, winSize.height); + this._renderTexture = renderTexture; + + renderTexture.x = winSize.width / 2; + renderTexture.y = winSize.height / 2; + // [renderTexture setPosition:cc.p(s.width, s.height)]; + // renderTexture.scale = 2; + + /* add the sprites to the render texture */ + renderTexture.addChild(this._sprite1); + renderTexture.addChild(this._sprite2); + renderTexture.clearColorVal = cc.color(0, 0, 0, 0); + renderTexture.clearFlags = cc._renderContext.COLOR_BUFFER_BIT; + + /* add the render texture to the scene */ + this.addChild(renderTexture); + + renderTexture.setAutoDraw(true); + + this.scheduleUpdate(); + + // Toggle clear on / off + var item = new cc.MenuItemFont("Clear On/Off", this.touched, this); + var menu = new cc.Menu(item); + this.addChild(menu); + + menu.x = winSize.width / 2; + menu.y = winSize.height / 2; + }, + + update:function (dt) { + var r = 80; + var locWinSize = this._winSize; + var locTime = this._time; + this._sprite1.x = Math.cos(locTime * 2) * r + locWinSize.width /2; + this._sprite1.y = Math.sin(locTime * 2) * r + locWinSize.height /2; + this._sprite2.x = Math.sin(locTime * 2) * r + locWinSize.width /2; + this._sprite2.y = Math.cos(locTime * 2) * r + locWinSize.height /2; + + this._time += dt; + }, + + title:function () { + return "Testing Render Target Node"; + }, + + subtitle:function () { + return "Sprites should be equal and move with each frame"; + }, + + touched:function (sender) { + if (this._renderTexture.clearFlags == 0) + this._renderTexture.clearFlags = cc._renderContext.COLOR_BUFFER_BIT; + else { + this._renderTexture.clearFlags = 0; + this._renderTexture.clearColorVal = cc.color(Math.random()*255, Math.random()*255, Math.random()*255, 255); + } + } +}); + +//------------------------------------------------------------------ +// +// Issue1464 +// +//------------------------------------------------------------------ +var Issue1464 = RenderTextureBaseLayer.extend({ + _brush : null, + _target : null, + _lastLocation : null, + _counter :0, + + ctor:function() { + this._super(); + + var sprite = new cc.Sprite(s_grossini); + + // create a render texture + var rend = new cc.RenderTexture( winSize.width/2, winSize.height/2 ); + rend.x = winSize.width/2; + rend.y = winSize.height/2 ; + this.addChild( rend, 1 ); + + sprite.x = winSize.width/4; + + sprite.y = winSize.height/4; + rend.begin(); + sprite.visit(); + rend.end(); + + var fadeout = cc.fadeOut(2); + var fadein = fadeout.reverse(); + var delay = cc.delayTime(0.25); + var seq = cc.sequence(fadeout, delay, fadein, delay.clone()); + var fe = seq.repeatForever(); + rend.getSprite().runAction(fe); + + if (!cc.sys.isNative && !("opengl" in cc.sys.capabilities)) { + var label = new cc.LabelTTF("Not support Actions on HTML5-canvas", "Times New Roman", 30); + label.x = winSize.width / 2; + label.y = winSize.height / 2 + 50; + this.addChild(label, 100); + } + }, + + title:function () { + return "Issue 1464"; + }, + + subtitle:function () { + return "Sprites should fade in / out correctly"; + }, + + // + // Automation + // + testDuration:2.1, + + getExpectedResult:function() { + // blue, red, blue + var ret = {"0":0,"1":0,"2":0,"3":255,"4":0,"5":0,"6":0,"7":255,"8":0,"9":0,"10":0,"11":255,"12":0,"13":0,"14":0,"15":255,"16":0,"17":0,"18":0,"19":255,"20":0,"21":0,"22":0,"23":255,"24":0,"25":0,"26":0,"27":255,"28":0,"29":0,"30":0,"31":255,"32":0,"33":0,"34":0,"35":255,"36":0,"37":0,"38":0,"39":255,"40":0,"41":0,"42":0,"43":255,"44":0,"45":0,"46":0,"47":255,"48":0,"49":0,"50":0,"51":255,"52":0,"53":0,"54":0,"55":255,"56":0,"57":0,"58":0,"59":255,"60":0,"61":0,"62":0,"63":255}; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = this.readPixels(winSize.width/2-2, winSize.height/2-2, 4, 4); + return JSON.stringify(ret); + } +}); + + +var RenderTextureTestScene = TestScene.extend({ + runThisTest:function (num) { + sceneRenderTextureIdx = (num || num == 0) ? (num - 1) : -1; + var layer = nextRenderTextureTest(); + this.addChild(layer); + + director.runScene(this); + } +}); + +// +// Flow control +// +var arrayOfRenderTextureTest = [ + RenderTextureSave, + Issue1464 +]; + +if(('opengl' in cc.sys.capabilities) && (!cc.sys.isNative) ){ + arrayOfRenderTextureTest.push(RenderTextureIssue937); + arrayOfRenderTextureTest.push(RenderTextureZbuffer); + arrayOfRenderTextureTest.push(RenderTextureTestDepthStencil); + arrayOfRenderTextureTest.push(RenderTextureTargetNode); +} + +var nextRenderTextureTest = function () { + sceneRenderTextureIdx++; + sceneRenderTextureIdx = sceneRenderTextureIdx % arrayOfRenderTextureTest.length; + + return new arrayOfRenderTextureTest[sceneRenderTextureIdx](); +}; +var previousRenderTextureTest = function () { + sceneRenderTextureIdx--; + if (sceneRenderTextureIdx < 0) + sceneRenderTextureIdx += arrayOfRenderTextureTest.length; + + return new arrayOfRenderTextureTest[sceneRenderTextureIdx](); +}; +var restartRenderTextureTest = function () { + return new arrayOfRenderTextureTest[sceneRenderTextureIdx](); +}; diff --git a/tests/js-tests/src/RotateWorldTest/RotateWorldTest.js b/tests/js-tests/src/RotateWorldTest/RotateWorldTest.js new file mode 100644 index 0000000000..bca0c01fc0 --- /dev/null +++ b/tests/js-tests/src/RotateWorldTest/RotateWorldTest.js @@ -0,0 +1,164 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var RotateWorldTestScene = TestScene.extend({ + runThisTest:function () { + var layer = new RotateWorldMainLayer(); + this.addChild(layer); + this.runAction(cc.rotateBy(4, -360)); + director.runScene(this); + } +}); + +var SpriteLayer = cc.Layer.extend({ + ctor:function () { + this._super(); + this.init(); + }, + + onEnter:function () { + this._super(); + + var x, y; + + var size = director.getWinSize(); + x = size.width; + y = size.height; + + var sprite = new cc.Sprite(s_pathGrossini); + var spriteSister1 = new cc.Sprite(s_pathSister1); + var spriteSister2 = new cc.Sprite(s_pathSister2); + + sprite.scale = 1.5; + spriteSister1.scale = 1.5; + spriteSister2.scale = 1.5; + + sprite.x = x / 2; + sprite.y = y / 2; + spriteSister1.x = 40; + spriteSister1.y = y / 2; + spriteSister2.x = x - 40; + spriteSister2.y = y / 2; + + var rot = cc.rotateBy(16, -3600); + + this.addChild(sprite); + this.addChild(spriteSister1); + this.addChild(spriteSister2); + + sprite.runAction(rot); + + var jump1 = cc.jumpBy(4, cc.p(-400, 0), 100, 4); + var jump2 = jump1.reverse(); + + var rot1 = cc.rotateBy(4, 360 * 2); + var rot2 = rot1.reverse(); + + spriteSister1.runAction(cc.sequence(jump2, jump1).repeat(5)); + spriteSister2.runAction(cc.sequence(jump1.clone(), jump2.clone()).repeat(5)); + + spriteSister1.runAction(cc.sequence(rot1, rot2).repeat(5)); + spriteSister2.runAction(cc.sequence(rot2.clone(), rot1.clone()).repeat(5)); + } +}); + +var TestLayer = cc.Layer.extend({ + ctor:function () { + this._super(); + this.init(); + }, + + onEnter:function () { + this._super(); + + var x, y; + + var size = director.getWinSize(); + x = size.width; + y = size.height; + + //cc.MutableArray *array = [UIFont familyNames]; + //for( cc.String *s in array ) + // NSLog( s ); + var label = new cc.LabelTTF("cocos2d", "Tahoma", 64); + + label.x = x / 2; + label.y = y / 2; + + this.addChild(label); + } +}); + +var RotateWorldMainLayer = cc.Layer.extend({ + ctor:function () { + this._super(); + this.init(); + }, + + onEnter:function () { + this._super(); + var x, y; + + var size = director.getWinSize(); + x = size.width; + y = size.height; + + var blue = new cc.LayerColor(cc.color(0, 0, 255, 255)); + var red = new cc.LayerColor(cc.color(255, 0, 0, 255)); + var green = new cc.LayerColor(cc.color(0, 255, 0, 255)); + var white = new cc.LayerColor(cc.color(255, 255, 255, 255)); + + blue.scale = 0.5; + blue.x = -x / 4; + blue.y = -y / 4; + blue.addChild(new SpriteLayer()); + + red.scale = 0.5; + red.x = x / 4; + red.y = -y / 4; + + green.scale = 0.5; + green.x = -x / 4; + green.y = y / 4; + green.addChild(new TestLayer()); + + white.scale = 0.5; + white.x = x / 4; + white.y = y / 4; + + this.addChild(blue, -1); + this.addChild(white); + this.addChild(green); + this.addChild(red); + + var rot = cc.rotateBy(8, 720); + + blue.runAction(rot); + red.runAction(rot.clone()); + green.runAction(rot.clone()); + white.runAction(rot.clone()); + } +}); diff --git a/tests/js-tests/src/SceneTest/SceneTest.js b/tests/js-tests/src/SceneTest/SceneTest.js new file mode 100644 index 0000000000..50df170891 --- /dev/null +++ b/tests/js-tests/src/SceneTest/SceneTest.js @@ -0,0 +1,221 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var MID_PUSHSCENE = 100; +var MID_PUSHSCENETRAN = 101; +var MID_QUIT = 102; +var MID_runScene = 103; +var MID_runSceneTRAN = 104; +var MID_GOBACK = 105; + +var SceneTestLayer1 = cc.Layer.extend({ + ctor:function () { + //----start0----Scene1-ctor + this._super(); + this.init(); + + var s = director.getWinSize(); + var item1 = new cc.MenuItemFont("Test pushScene", this.onPushScene, this); + var item2 = new cc.MenuItemFont("Test pushScene w/transition", this.onPushSceneTran, this); + var item3 = new cc.MenuItemFont("Quit", function () { + cc.log("quit!") + }, this); + + var menu = new cc.Menu(item1, item2, item3); + menu.alignItemsVertically(); + this.addChild(menu); + + var sprite = new cc.Sprite(s_pathGrossini); + this.addChild(sprite); + sprite.x = s.width - 40; + sprite.y = s.height / 2; + var rotate = cc.rotateBy(2, 360); + var repeat = rotate.repeatForever(); + sprite.runAction(repeat); + //----end0---- + + //cc.schedule(this.testDealloc); + }, + + + onEnter:function () { + cc.log("SceneTestLayer1#onEnter"); + this._super(); + }, + + onEnterTransitionDidFinish:function () { + cc.log("SceneTestLayer1#onEnterTransitionDidFinish"); + this._super(); + }, + + testDealloc:function (dt) { + //cc.log("SceneTestLayer1:testDealloc"); + }, + + onPushScene:function (sender) { + var scene = new SceneTestScene(); + var layer = new SceneTestLayer2(); + scene.addChild(layer, 0); + director.pushScene(scene); + }, + + onPushSceneTran:function (sender) { + var scene = new SceneTestScene(); + var layer = new SceneTestLayer2(); + scene.addChild(layer, 0); + + director.pushScene(new cc.TransitionSlideInT(1, scene)); + }, + onQuit:function (sender) { + } + + //CREATE_NODE(SceneTestLayer1); +}); + +var SceneTestLayer2 = cc.Layer.extend({ + + timeCounter:0, + + ctor:function () { + //----start0----Scene2-ctor + this._super(); + this.init(); + + this.timeCounter = 0; + + var s = director.getWinSize(); + + var item1 = new cc.MenuItemFont("runScene", this.runScene, this); + var item2 = new cc.MenuItemFont("runScene w/transition", this.runSceneTran, this); + var item3 = new cc.MenuItemFont("Go Back", this.onGoBack, this); + + var menu = new cc.Menu(item1, item2, item3); + menu.alignItemsVertically(); + this.addChild(menu); + + var sprite = new cc.Sprite(s_pathGrossini); + this.addChild(sprite); + + sprite.x = s.width - 40; + sprite.y = s.height / 2; + var rotate = cc.rotateBy(2, 360); + var repeat = rotate.repeatForever(); + sprite.runAction(repeat); + //----end0---- + + //cc.schedule(this.testDealloc); + }, + + testDealloc:function (dt) { + + }, + + onGoBack:function (sender) { + director.popScene(); + }, + + runScene:function (sender) { + var scene = new SceneTestScene(); + var layer = new SceneTestLayer3(); + scene.addChild(layer, 0); + director.runScene(scene); + + }, + + runSceneTran:function (sender) { + var scene = new SceneTestScene(); + var layer = new SceneTestLayer3(); + scene.addChild(layer, 0); + director.runScene(new cc.TransitionSlideInT(2, scene)); + } + + //CREATE_NODE(SceneTestLayer2); +}); + +var SceneTestLayer3 = cc.LayerColor.extend({ + + ctor:function () { + + //----start0----Scene3-ctor + this._super(); + this.init( cc.color(0,128,255,255) ); + + var label = new cc.LabelTTF("Touch to popScene", "Arial", 28); + this.addChild(label); + var s = director.getWinSize(); + label.x = s.width / 2; + label.y = s.height / 2; + + var sprite = new cc.Sprite(s_pathGrossini); + this.addChild(sprite); + + sprite.x = s.width - 40; + + sprite.y = s.height / 2; + var rotate = cc.rotateBy(2, 360); + var repeat = rotate.repeatForever(); + sprite.runAction(repeat); + //----end0---- + }, + + onEnterTransitionDidFinish: function () { + if ('touches' in cc.sys.capabilities){ + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded: function(touches, event){ + director.popScene(); + } + }, this); + } else if ('mouse' in cc.sys.capabilities) + cc.eventManager.addListener({ + event: cc.EventListener.MOUSE, + onMouseUp: function(event){ + director.popScene(); + } + }, this); + }, + + testDealloc:function (dt) { + + } + + //CREATE_NODE(SceneTestLayer3); +}); + +SceneTestScene = TestScene.extend({ + + runThisTest:function () { + var layer = new SceneTestLayer1(); + this.addChild(layer); + + director.runScene(this); + + } +}); + +var arrayOfSceneTest = [ + SceneTestLayer1 +]; diff --git a/tests/js-tests/src/SchedulerTest/SchedulerTest.js b/tests/js-tests/src/SchedulerTest/SchedulerTest.js new file mode 100644 index 0000000000..ac0c3c96f5 --- /dev/null +++ b/tests/js-tests/src/SchedulerTest/SchedulerTest.js @@ -0,0 +1,749 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var TAG_ANIMATION_DANCE = 1; +var schedulerTestSceneIdx = -1; + +/* + Base Layer +*/ +var SchedulerTestLayer = BaseTestLayer.extend({ + + title:function () { + return "No title"; + }, + subtitle:function () { + return ""; + }, + + onBackCallback:function (sender) { + var scene = new SchedulerTestScene(); + var layer = previousSchedulerTest(); + + scene.addChild(layer); + director.runScene(scene); + }, + onNextCallback:function (sender) { + var scene = new SchedulerTestScene(); + var layer = nextSchedulerTest(); + + scene.addChild(layer); + director.runScene(scene); + }, + onRestartCallback:function (sender) { + var scene = new SchedulerTestScene(); + var layer = restartSchedulerTest(); + + scene.addChild(layer); + director.runScene(scene); + }, + // automation + numberOfPendingTests:function() { + return ( (arrayOfSchedulerTest.length-1) - schedulerTestSceneIdx ); + }, + + getTestNumber:function() { + return schedulerTestSceneIdx; + } + +}); + +/* + SchedulerAutoremove +*/ +var SchedulerAutoremove = SchedulerTestLayer.extend({ + _accum:0, + + onEnter:function () { + //----start0----onEnter + this._super(); + + this.schedule(this.onAutoremove, 0.5); + this.schedule(this.onTick, 0.5); + this._accum = 0; + //----end0---- + }, + title:function () { + return "Self-remove an scheduler"; + }, + subtitle:function () { + return "1 scheduler will be autoremoved in 3 seconds. See console"; + }, + + onAutoremove:function (dt) { + //----start0----onAutoremove + this._accum += dt; + cc.log("Time: " + this._accum); + + if (this._accum > 3) { + this.unschedule(this.onAutoremove); + cc.log("scheduler removed"); + } + //----end0---- + }, + onTick:function (dt) { + cc.log("This scheduler should not be removed"); + } +}); + +/* + SchedulerPauseResume +*/ +var SchedulerPauseResume = SchedulerTestLayer.extend({ + onEnter:function () { + //----start1----onEnter + this._super(); + + this.schedule(this.onTick1, 0.5); + this.schedule(this.onTick2, 0.5); + this.schedule(this.onPause, 3); + //----end1---- + }, + title:function () { + return "Pause / Resume"; + }, + subtitle:function () { + return "Scheduler should be paused after 3 seconds. See console"; + }, + + onTick1:function (dt) { + //----start1----onTick1 + cc.log("tick1"); + //----end1---- + }, + onTick2:function (dt) { + //----start1----onTick2 + cc.log("tick2"); + //----end1---- + }, + onPause:function (dt) { + //----start1----onPause + director.getScheduler().pauseTarget(this); + //----end1---- + } +}); + +/* + SchedulerUnscheduleAll +*/ +var SchedulerUnscheduleAll = SchedulerTestLayer.extend({ + onEnter:function () { + //----start2----onEnter + this._super(); + + this.schedule(this.onTick1, 0.5); + this.schedule(this.onTick2, 1.0); + this.schedule(this.onTick3, 1.5); + this.schedule(this.onTick4, 1.5); + this.schedule(this.onUnscheduleAll, 4); + //----end2---- + }, + title:function () { + return "Unschedule All callbacks"; + }, + subtitle:function () { + return "All scheduled callbacks will be unscheduled in 4 seconds. See console"; + }, + + onTick1:function (dt) { + //----start2----onTick1 + cc.log("tick1"); + //----end2---- + }, + onTick2:function (dt) { + //----start2----onTick2 + cc.log("tick2"); + //----end2---- + }, + onTick3:function (dt) { + //----start2----onTick3 + cc.log("tick3"); + //----end2---- + }, + onTick4:function (dt) { + //----start2----onTick4 + cc.log("tick4"); + //----end2---- + }, + onUnscheduleAll:function (dt) { + //----start2----onUnscheduleAll + this.unscheduleAllCallbacks(); + //----end2---- + } +}); + +/* + SchedulerUnscheduleAllHard +*/ +var SchedulerUnscheduleAllHard = SchedulerTestLayer.extend({ + onEnter:function () { + //----start3----onEnter + this._super(); + + this.schedule(this.onTick1, 0.5); + this.schedule(this.onTick2, 1.0); + this.schedule(this.onTick3, 1.5); + this.schedule(this.onTick4, 1.5); + this.schedule(this.onUnscheduleAll, 4); + //----end3---- + }, + title:function () { + return "Unschedule All callbacks #2"; + }, + subtitle:function () { + return "Unschedules all callbacks after 4s. Uses CCScheduler. See console"; + }, + + onTick1:function (dt) { + //----start3----onTick1 + cc.log("tick1"); + //----end3---- + }, + onTick2:function (dt) { + //----start3----onTick2 + cc.log("tick2"); + //----end3---- + }, + onTick3:function (dt) { + //----start3----onTick3 + cc.log("tick3"); + //----end3---- + }, + onTick4:function (dt) { + //----start3----onTick4 + cc.log("tick4"); + //----end3---- + }, + onUnscheduleAll:function (dt) { + //----start3----onUnscheduleAll + director.getScheduler().unscheduleAllCallbacks(); + //----end3---- + } +}); + +/* + SchedulerSchedulesAndRemove +*/ +var SchedulerSchedulesAndRemove = SchedulerTestLayer.extend({ + onEnter:function () { + //----start4----onEnter + this._super(); + + this.schedule(this.onTick1, 0.5); + this.schedule(this.onTick2, 1.0); + this.schedule(this.onScheduleAndUnschedule, 4.0); + //----end4---- + }, + title:function () { + return "Schedule from Schedule"; + }, + subtitle:function () { + return "Will unschedule and schedule callbacks in 4s. See console"; + }, + + onTick1:function (dt) { + //----start4----onTick1 + cc.log("tick1"); + //----end4---- + }, + onTick2:function (dt) { + //----start4----onTick2 + cc.log("tick2"); + //----end4---- + }, + onTick3:function (dt) { + //----start4----onTick3 + cc.log("tick3"); + //----end4---- + }, + onTick4:function (dt) { + //----start4----onTick4 + cc.log("tick4"); + //----end4---- + }, + onScheduleAndUnschedule:function (dt) { + //----start4----onScheduleAndUnschedule + this.unschedule(this.onTick1); + this.unschedule(this.onTick2); + this.unschedule(this.onScheduleAndUnschedule); + + this.schedule(this.onTick3, 1.0); + this.schedule(this.onTick4, 1.0) + //----end4---- + } +}); + +/* + SchedulerUpdate +*/ +var TestNode = cc.Node.extend({ + _pString:"", + + ctor:function (str, priority) { + this._super(); + this.init(); + this._pString = str; + this.scheduleUpdateWithPriority(priority); + }, + update:function(dt) { + cc.log( this._pString ); + } +}); + +var SchedulerUpdate = SchedulerTestLayer.extend({ + onEnter:function () { + //----start5----onEnter + this._super(); + + var str = "---"; + var d = new TestNode(str,50); + this.addChild(d); + + str = "3rd"; + var b = new TestNode(str,0); + this.addChild(b); + + str = "1st"; + var a = new TestNode(str, -10); + this.addChild(a); + + str = "4th"; + var c = new TestNode(str,10); + this.addChild(c); + + str = "5th"; + var e = new TestNode(str,20); + this.addChild(e); + + str = "2nd"; + var f = new TestNode(str,-5); + this.addChild(f); + + this.schedule(this.onRemoveUpdates, 4.0); + //----end5---- + }, + title:function () { + return "Schedule update with priority"; + }, + subtitle:function () { + return "3 scheduled updates. Priority should work. Stops in 4s. See console"; + }, + + onRemoveUpdates:function (dt) { + //----start5----onRemoveUpdates + var children = this.children; + + for (var i = 0; i < children.length; i++) { + var node = children[i]; + if (node) { + node.unscheduleAllCallbacks(); + } + } + //----end5---- + } +}); + +/* + SchedulerUpdateAndCustom +*/ +var SchedulerUpdateAndCustom = SchedulerTestLayer.extend({ + onEnter:function () { + //----start6----onEnter + this._super(); + + this.scheduleUpdate(); + this.schedule(this.onTick); + this.schedule(this.onStopCallbacks, 4); + //----end6---- + }, + title:function () { + return "Schedule Update + custom callback"; + }, + subtitle:function () { + return "Update + custom callback at the same time. Stops in 4s. See console"; + }, + + update:function (dt) { + //----start6----update + cc.log("update called:" + dt); + //----end6---- + }, + onTick:function (dt) { + //----start6----onTick + cc.log("custom callback called:" + dt); + //----end6---- + }, + onStopCallbacks:function (dt) { + //----start6----onStopCallbacks + this.unscheduleAllCallbacks(); + //----end6---- + } +}); + +/* + SchedulerUpdateFromCustom +*/ +var SchedulerUpdateFromCustom = SchedulerTestLayer.extend({ + onEnter:function () { + //----start7----onEnter + this._super(); + + this.schedule(this.onSchedUpdate, 2.0); + //----end7---- + }, + title:function () { + return "Schedule Update in 2 sec"; + }, + subtitle:function () { + return "Update schedules in 2 secs. Stops 2 sec later. See console"; + }, + + update:function (dt) { + //----start7----update + cc.log("update called:" + dt); + //----end7---- + }, + onSchedUpdate:function (dt) { + //----start7----onSchedUpdate + this.unschedule(this.onSchedUpdate); + this.scheduleUpdate(); + this.schedule(this.onStopUpdate, 2.0); + //----end7---- + }, + onStopUpdate:function (dt) { + //----start7----onStopUpdate + this.unscheduleUpdate(); + this.unschedule(this.onStopUpdate); + //----end7---- + } +}); + + +/* + RescheduleCallback +*/ +var RescheduleCallback = SchedulerTestLayer.extend({ + _interval:1.0, + _ticks:0, + + onEnter:function () { + //----start8----onEnter + this._super(); + + this._interval = 1.0; + this._ticks = 0; + this.schedule(this.onSchedUpdate, this._interval); + //----end8---- + }, + title:function () { + return "Reschedule Callback"; + }, + subtitle:function () { + return "Interval is 1 second, then 2, then 3..."; + }, + + onSchedUpdate:function (dt) { + //----start8----onSchedUpdate + this._ticks++; + + cc.log("schedUpdate: " + dt.toFixed(2)); + if (this._ticks > 3) { + this._interval += 1.0; + this.schedule(this.onSchedUpdate, this._interval); + this._ticks = 0; + } + //----end8---- + } +}); + +/* + ScheduleUsingSchedulerTest +*/ +var ScheduleUsingSchedulerTest = SchedulerTestLayer.extend({ + _accum:0, + + onEnter:function () { + //----start9----onEnter + this._super(); + + this._accum = 0; + var scheduler = director.getScheduler(); + + var priority = 0; // priority 0. default. + var paused = false; // not paused, queue it now. + scheduler.scheduleUpdateForTarget(this, priority, paused); + + var interval = 0.25; // every 1/4 of second + var repeat = cc.REPEAT_FOREVER; // how many repeats. cc.REPEAT_FOREVER means forever + var delay = 2; // start after 2 seconds; + paused = false; // not paused. queue it now. + scheduler.scheduleCallbackForTarget(this, this.onSchedUpdate, interval, repeat, delay, paused); + //----end9---- + }, + title:function () { + return "Schedule / Unschedule using Scheduler"; + }, + subtitle:function () { + return "After 5 seconds all callbacks should be removed"; + }, + + // callbacks + update:function(dt) { + //----start9----update + cc.log("update: " + dt); + //----end9---- + }, + onSchedUpdate:function (dt) { + //----start9----onSchedUpdate + cc.log("onSchedUpdate delta: " + dt); + + this._accum += dt; + if( this._accum > 3 ) { + var scheduler = director.getScheduler(); + scheduler.unscheduleAllCallbacksForTarget(this); + } + cc.log("onSchedUpdate accum: " + this._accum); + //----end9---- + } +}); + +// SchedulerTimeScale + +var SchedulerTimeScale = SchedulerTestLayer.extend({ + _newScheduler: null, + _newActionManager: null, + + onEnter: function() { + this._super(); + + this._newScheduler = new cc.Scheduler(); + this._newActionManager = new cc.ActionManager(); + + var s = cc.winSize; + + // rotate and jump + var jump1 = new cc.JumpBy(4, cc.p(-s.width+80,0), 100, 4); + var jump2 = jump1.reverse(); + var rot1 = new cc.RotateBy(4, 360*2); + var rot2 = rot1.reverse(); + + var seq3_1 = new cc.Sequence(jump2, jump1); + var seq3_2 = new cc.Sequence(rot1, rot2); + var spawn = new cc.Spawn(seq3_1, seq3_2); + var action = new cc.Repeat(spawn, 50); + + var action2 = action.clone(); + var action3 = action.clone(); + + var grossini = new cc.Sprite("res/Images/grossini.png"); + var tamara = new cc.Sprite("res/Images/grossinis_sister1.png"); + var kathia = new cc.Sprite("res/Images/grossinis_sister2.png"); + + grossini.setActionManager(this._newActionManager); + grossini.setScheduler(this._newScheduler); + + grossini.setPosition(cc.p(40,80)); + tamara.setPosition(cc.p(40,80)); + kathia.setPosition(cc.p(40,80)); + + this.addChild(grossini); + this.addChild(tamara); + this.addChild(kathia); + + grossini.runAction(new cc.Speed(action, 0.5)); + tamara.runAction(new cc.Speed(action2, 1.5)); + kathia.runAction(new cc.Speed(action3, 1.0)); + + cc.director.getScheduler().scheduleUpdateForTarget(this._newScheduler, 0, false); + + this._newScheduler.scheduleUpdateForTarget(this._newActionManager, 0, false); + + var emitter = new cc.ParticleFireworks(); + emitter.setTexture( cc.textureCache.addImage(s_stars1) ); + this.addChild(emitter); + + var slider = null; + var l = null; + + slider = new ccui.Slider(); + slider.setTouchEnabled(true); + slider.loadBarTexture("res/cocosui/sliderTrack.png"); + slider.loadSlidBallTextures("res/cocosui/sliderThumb.png", "res/cocosui/sliderThumb.png", ""); + slider.loadProgressBarTexture("res/cocosui/sliderProgress.png"); + slider.x = cc.winSize.width / 2.0; + slider.y = cc.winSize.height / 3.0 * 2; + slider.addEventListener(this.sliderEventForGrossini, this); + this.addChild(slider); + slider.setPercent(20); + + l = new cc.LabelTTF("Control time scale only for Grossini", "Thonburi", 16); + this.addChild(l); + l.x = slider.x; + l.y = slider.y + 30; + + slider = new ccui.Slider(); + slider.setTouchEnabled(true); + slider.loadBarTexture("res/cocosui/sliderTrack.png"); + slider.loadSlidBallTextures("res/cocosui/sliderThumb.png", "res/cocosui/sliderThumb.png", ""); + slider.loadProgressBarTexture("res/cocosui/sliderProgress.png"); + slider.x = cc.winSize.width / 2.0; + slider.y = cc.winSize.height / 3.0; + slider.addEventListener(this.sliderEventForGlobal, this); + this.addChild(slider); + slider.setPercent(20); + l = new cc.LabelTTF("Control time scale for all", "Thonburi", 16); + this.addChild(l); + l.x = slider.x; + l.y = slider.y + 30; + }, + + sliderEventForGrossini: function (sender, type) { + switch (type) { + case ccui.Slider.EVENT_PERCENT_CHANGED: + var slider = sender; + var percent = slider.getPercent() / 100.0 * 5; + this._newScheduler.setTimeScale(percent); + break; + default: + break; + } + }, + + sliderEventForGlobal: function (sender, type) { + switch (type) { + case ccui.Slider.EVENT_PERCENT_CHANGED: + var slider = sender; + var percent = slider.getPercent() / 100.0 * 5; + cc.director.getScheduler().setTimeScale(percent); + break; + default: + break; + } + }, + + onExit: function() { + // restore scale + cc.director.getScheduler().unscheduleUpdateForTarget(this._newScheduler); + this._super(); + }, + + title:function () { + return "Scheduler timeScale Test"; + }, + + subtitle:function () { + return "Fast-forward and rewind using scheduler.timeScale"; + } +}); + +var unScheduleAndRepeatTest = SchedulerTestLayer.extend({ + + onEnter: function(){ + this._super(); + cc.log("start schedule 'repeat': run once and repeat 4 times"); + this.schedule(this.repeat, 0.5, 4); + cc.log("start schedule 'forever': repeat forever (stop in 8s)"); + this.schedule(this.forever, 0.5); + this.schedule(function(){ + cc.log("stop the 'forever'"); + this.unschedule(this.forever); + }, 8); + }, + + _times: 5, + + repeat: function(){ + cc.log("Repeat - the remaining number: " + this._times--); + }, + + forever: function(){ + cc.log("Repeat Forever..."); + }, + + title: function(){ + return "Repeat And unschedule Test"; + }, + + subtitle: function(){ + return "Repeat will print 5 times\nForever will stop in 8 seconds."; + } +}); + +/* + main entry +*/ +var SchedulerTestScene = TestScene.extend({ + runThisTest:function (num) { + schedulerTestSceneIdx = (num || num == 0) ? (num - 1) : -1; + var layer = nextSchedulerTest(); + this.addChild(layer); + + director.runScene(this); + } +}); + +// +// Flow control +// + +var arrayOfSchedulerTest = [ + SchedulerTimeScale, + SchedulerAutoremove, + SchedulerPauseResume, + SchedulerUnscheduleAll, + SchedulerUnscheduleAllHard, + SchedulerSchedulesAndRemove, + SchedulerUpdate, + SchedulerUpdateAndCustom, + SchedulerUpdateFromCustom, + RescheduleCallback, + ScheduleUsingSchedulerTest, + unScheduleAndRepeatTest +]; + +var nextSchedulerTest = function () { + schedulerTestSceneIdx++; + schedulerTestSceneIdx = schedulerTestSceneIdx % arrayOfSchedulerTest.length; + + if(window.sideIndexBar){ + schedulerTestSceneIdx = window.sideIndexBar.changeTest(schedulerTestSceneIdx, 34); + } + + return new arrayOfSchedulerTest[schedulerTestSceneIdx](); +}; +var previousSchedulerTest = function () { + schedulerTestSceneIdx--; + if (schedulerTestSceneIdx < 0) + schedulerTestSceneIdx += arrayOfSchedulerTest.length; + + if(window.sideIndexBar){ + schedulerTestSceneIdx = window.sideIndexBar.changeTest(schedulerTestSceneIdx, 34); + } + + return new arrayOfSchedulerTest[schedulerTestSceneIdx](); +}; +var restartSchedulerTest = function () { + return new arrayOfSchedulerTest[schedulerTestSceneIdx](); +}; diff --git a/tests/js-tests/src/SpineTest/SpineTest.js b/tests/js-tests/src/SpineTest/SpineTest.js new file mode 100644 index 0000000000..f88cd68949 --- /dev/null +++ b/tests/js-tests/src/SpineTest/SpineTest.js @@ -0,0 +1,280 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var sp = sp || {}; + +var spineSceneIdx = -1; +var SpineTestScene = TestScene.extend({ + runThisTest:function () { + var layer = SpineTestScene.nextSpineTestLayer(); + this.addChild(layer); + director.runScene(this); + } +}); + +SpineTestScene.nextSpineTestLayer = function() { + spineSceneIdx++; + var layers = SpineTestScene.testLayers; + spineSceneIdx = spineSceneIdx % layers.length; + return new layers[spineSceneIdx](); +}; + +SpineTestScene.backSpineTestLayer = function() { + spineSceneIdx--; + var layers = SpineTestScene.testLayers; + if(spineSceneIdx < 0) + spineSceneIdx = layers.length; + return new layers[spineSceneIdx](); +}; + +SpineTestScene.restartSpineTestLayer = function(){ + return new SpineTestScene.testLayers[spineSceneIdx](); +}; + +var SpineTestLayer = BaseTestLayer.extend({ + onRestartCallback: function(sender){ + var s = new SpineTestScene(); + s.addChild(SpineTestScene.restartSpineTestLayer()); + cc.director.runScene(s); + }, + + onNextCallback: function(sender){ + var s = new SpineTestScene(); + s.addChild(SpineTestScene.nextSpineTestLayer()); + cc.director.runScene(s); + }, + + onBackCallback: function(sender){ + var s = new SpineTestScene(); + s.addChild(SpineTestScene.backSpineTestLayer()); + cc.director.runScene(s); + } +}); + +var SpineTestLayerNormal = SpineTestLayer.extend({ + _spineboy:null, + _debugMode: 0, + _flipped: false, + ctor:function () { + this._super(cc.color(0,0,0,255), cc.color(98,99,117,255)); + + var size = director.getWinSize(); + + ///////////////////////////// + // Make Spine's Animated skeleton Node + // You need 'json + atlas + image' resource files to make it. + // No JS binding for spine-c in this version. So, only file loading is supported. + var spineBoy = new sp.SkeletonAnimation('res/skeletons/spineboy.json', 'res/skeletons/spineboy.atlas'); + spineBoy.setPosition(cc.p(size.width / 2, size.height / 2 - 150)); + spineBoy.setMix('walk', 'jump', 0.2); + spineBoy.setMix('jump', 'run', 0.2); + spineBoy.setAnimation(0, 'walk', true); + //spineBoy.setAnimationListener(this, this.animationStateEvent); + spineBoy.setScale(0.5); + this.addChild(spineBoy, 4); + this._spineboy = spineBoy; + spineBoy.setStartListener(function(trackIndex){ + var entry = spineBoy.getState().getCurrent(trackIndex); + if(entry){ + var animationName = entry.animation ? entry.animation.name : ""; + cc.log("%d start: %s", trackIndex, animationName); + } + }); + spineBoy.setEndListener(function(traceIndex){ + cc.log("%d end.", traceIndex); + }); + spineBoy.setCompleteListener(function(traceIndex, loopCount){ + cc.log("%d complete: %d", traceIndex, loopCount); + }); + spineBoy.setEventListener(function(traceIndex, event){ + cc.log( traceIndex + " event: %s, %d, %f, %s",event.data.name, event.intValue, event.floatValue, event.stringValue); + }); + + var jumpEntry = spineBoy.addAnimation(0, "jump", false, 3); + spineBoy.addAnimation(0, "run", true); + // spineBoy.setTrackStartListener(jumpEntry, function(traceIndex){ + // cc.log("jumped!"); + // }); + + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesBegan: function(touches, event){ + if(spineBoy.getTimeScale() === 1.0) + spineBoy.setTimeScale(0.3); + else + spineBoy.setTimeScale(1); + } + }, this); + + cc.MenuItemFont.setFontSize(20); + var bonesToggle = new cc.MenuItemToggle( + new cc.MenuItemFont("Debug Bones: Off"), + new cc.MenuItemFont("Debug Bones: On")); + bonesToggle.setCallback(this.onDebugBones, this); + bonesToggle.setPosition(160 - size.width / 2, 120 - size.height / 2); + var slotsToggle = new cc.MenuItemToggle( + new cc.MenuItemFont("Debug Slots: Off"), + new cc.MenuItemFont("Debug Slots: On")); + slotsToggle.setCallback(this.onDebugSlots, this); + slotsToggle.setPosition(160 - size.width / 2, 160 - size.height / 2); + var menu = new cc.Menu(); + menu.ignoreAnchorPointForPosition(true); + menu.addChild(bonesToggle); + menu.addChild(slotsToggle); + this.addChild(menu, 5); + }, + + onDebugBones: function(sender){ + this._spineboy.setDebugBonesEnabled(!this._spineboy.getDebugBonesEnabled()); + }, + + onDebugSlots: function(sender){ + this._spineboy.setDebugSlotsEnabled(!this._spineboy.getDebugSlotsEnabled()); + }, + + subtitle:function () { + return "Spine test"; + }, + title:function () { + return "Spine test"; + }, + + animationStateEvent: function(obj, trackIndex, type, event, loopCount) { + var entry = this._spineboy.getCurrent(); + var animationName = (entry && entry.animation) ? entry.animation.name : 0; + switch(type) { + case sp.ANIMATION_EVENT_TYPE.START: + cc.log(trackIndex + " start: " + animationName); + break; + case sp.ANIMATION_EVENT_TYPE.END: + cc.log(trackIndex + " end:" + animationName); + break; + case sp.ANIMATION_EVENT_TYPE.EVENT: + cc.log(trackIndex + " event: " + animationName); + break; + case sp.ANIMATION_EVENT_TYPE.COMPLETE: + cc.log(trackIndex + " complete: " + animationName + "," + loopCount); + if(this._flipped){ + this._flipped = false; + this._spineboy.setScaleX(0.5); + }else{ + this._flipped = true; + this._spineboy.setScaleX(-0.5); + } + break; + default : + break; + } + }, + + // automation + numberOfPendingTests:function() { + return 1; + }, + getTestNumber:function() { + return 0; + } +}); + +var SpineTestLayerFFD = SpineTestLayer.extend({ + ctor: function(){ + this._super(cc.color(0,0,0,255), cc.color(98,99,117,255)); + + var skeletonNode = new sp.SkeletonAnimation("res/skeletons/goblins-ffd.json", "res/skeletons/goblins-ffd.atlas", 1.5); + skeletonNode.setAnimation(0, "walk", true); + skeletonNode.setSkin("goblin"); + + skeletonNode.setScale(0.5); + var winSize = cc.director.getWinSize(); + skeletonNode.setPosition(winSize.width /2, 20); + this.addChild(skeletonNode); + + var listener = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + onTouchBegan : function(touch, event){ + if(!skeletonNode.getDebugBonesEnabled()) + skeletonNode.setDebugBonesEnabled(true); + else if(skeletonNode.getTimeScale() === 1.0) + skeletonNode.setTimeScale(0.3); + else{ + skeletonNode.setTimeScale(1); + skeletonNode.setDebugBonesEnabled(false); + } + return true; + } + }); + cc.eventManager.addListener(listener, this); + }, + + title: function(){ + return "Spine Test"; + }, + + subtitle: function(){ + return "FFD Spine"; + } +}); + +var SpineTestPerformanceLayer = SpineTestLayer.extend({ + ctor: function(){ + this._super(cc.color(0,0,0,255), cc.color(98,99,117,255)); + + var self = this; + var listener = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + onTouchBegan: function(touch, event){ + var pos = self.convertToNodeSpace(touch.getLocation()); + var skeletonNode = new sp.SkeletonAnimation("res/skeletons/goblins-ffd.json", "res/skeletons/goblins-ffd.atlas", 1.5); + skeletonNode.setAnimation(0, "walk", true); + skeletonNode.setSkin("goblin"); + + skeletonNode.setScale(0.2); + skeletonNode.setPosition(pos); + self.addChild(skeletonNode); + return true; + } + }); + cc.eventManager.addListener(listener, this); + }, + title: function(){ + return "Spine Test"; + }, + subtitle: function() { + return "Performance Test for Spine"; + } +}); + +SpineTestScene.testLayers = [ + SpineTestLayerNormal + //SpineTestLayerFFD, //it doesn't support mesh on Web. + //SpineTestPerformanceLayer +]; + +if(cc.sys.isNative){ + SpineTestScene.testLayers.push(SpineTestLayerFFD); + SpineTestScene.testLayers.push(SpineTestPerformanceLayer); +} + diff --git a/tests/js-tests/src/Sprite3DTest/Sprite3DTest.js b/tests/js-tests/src/Sprite3DTest/Sprite3DTest.js new file mode 100644 index 0000000000..f4f2973c8c --- /dev/null +++ b/tests/js-tests/src/Sprite3DTest/Sprite3DTest.js @@ -0,0 +1,1589 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var Sprite3DTestIdx = -1; + +var Sprite3DTestDemo = cc.Layer.extend({ + _title:"", + _subtitle:"", + + ctor:function () { + this._super(); + }, + + // + // Menu + // + onEnter:function () { + this._super(); + + var label = new cc.LabelTTF(this._title, "Arial", 28); + this.addChild(label, 100, BASE_TEST_TITLE_TAG); + label.x = winSize.width / 2; + label.y = winSize.height - 50; + + var label2 = new cc.LabelTTF(this._subtitle, "Thonburi", 16); + this.addChild(label2, 101, BASE_TEST_SUBTITLE_TAG); + label2.x = winSize.width / 2; + label2.y = winSize.height - 80; + + var item1 = new cc.MenuItemImage(s_pathB1, s_pathB2, this.onBackCallback, this); + var item2 = new cc.MenuItemImage(s_pathR1, s_pathR2, this.onRestartCallback, this); + var item3 = new cc.MenuItemImage(s_pathF1, s_pathF2, this.onNextCallback, this); + + item1.tag = BASE_TEST_MENUITEM_PREV_TAG; + item2.tag = BASE_TEST_MENUITEM_RESET_TAG; + item3.tag = BASE_TEST_MENUITEM_NEXT_TAG; + + var menu = new cc.Menu(item1, item2, item3); + + menu.x = 0; + menu.y = 0; + var width = item2.width, height = item2.height; + item1.x = winSize.width/2 - width*2; + item1.y = height/2 ; + item2.x = winSize.width/2; + item2.y = height/2 ; + item3.x = winSize.width/2 + width*2; + item3.y = height/2 ; + + this.addChild(menu, 102, BASE_TEST_MENU_TAG); + }, + + onRestartCallback:function (sender) { + var s = new Sprite3DTestScene(); + s.addChild(restartSprite3DTest()); + director.runScene(s); + }, + + onNextCallback:function (sender) { + var s = new Sprite3DTestScene(); + s.addChild(nextSprite3DTest()); + director.runScene(s); + }, + + onBackCallback:function (sender) { + var s = new Sprite3DTestScene(); + s.addChild(previousSprite3DTest()); + director.runScene(s); + }, +}); + +var Sprite3DTestScene = cc.Scene.extend({ + ctor:function () { + this._super(); + + var label = new cc.LabelTTF("Main Menu", "Arial", 20); + var menuItem = new cc.MenuItemLabel(label, this.onMainMenuCallback, this); + + var menu = new cc.Menu(menuItem); + menu.x = 0; + menu.y = 0; + menuItem.x = winSize.width - 50; + menuItem.y = 25; + this.addChild(menu); + }, + onMainMenuCallback:function () { + var scene = new cc.Scene(); + var layer = new TestController(); + scene.addChild(layer); + director.runScene(scene); + }, + runThisTest:function (num) { + Sprite3DTestIdx = (num || num == 0) ? (num - 1) : -1; + var layer = nextSprite3DTest(); + this.addChild(layer); + + director.runScene(this); + } +}); + + +var Sprite3DBasicTest = Sprite3DTestDemo.extend({ + _title: "Testing Sprite3D", + _subtitle: "Tap screen to add more sprites", + + ctor:function(){ + this._super(); + + var winSize = cc.winSize; + this.addNewSpriteWithCoords(cc.p(winSize.width/2, winSize.height/2)); + + var that = this; + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded: function(touches, event){ + for(var i in touches){ + that.addNewSpriteWithCoords(touches[i].getLocation()); + } + } + }, this); + }, + + addNewSpriteWithCoords:function(position){ + var sprite = new jsb.Sprite3D("Sprite3DTest/boss1.obj"); + sprite.setScale(3.0); + sprite.setTexture("Sprite3DTest/boss.png"); + sprite.x = position.x; + sprite.y = position.y; + + this.addChild(sprite); + + var action; + var random = Math.random(); + if(random < 0.2) + action = cc.scaleBy(3, 2); + else if(random < 0.4) + action = cc.rotateBy(3, 360); + else if(random < 0.6) + action = cc.blink(1, 3); + else if(random < 0.8) + action = cc.tintBy(2, 0, -255, -255); + else + action = cc.fadeOut(2); + + var action_back = action.reverse(); + var seq = cc.sequence(action, action_back); + + sprite.runAction(seq.repeatForever()); + } +}); + +var Sprite3DHitTest = Sprite3DTestDemo.extend({ + _title:"Testing Sprite3D Touch in 2D", + _subtitle:"Tap Sprite3D and Drag", + + ctor:function(){ + this._super(); + + var s = cc.winSize; + + var sprite1 = new jsb.Sprite3D("Sprite3DTest/boss1.obj"); + sprite1.setScale(4.0); + sprite1.setTexture("Sprite3DTest/boss.png"); + sprite1.setPosition(cc.p(s.width/2, s.height/2)); + + this.addChild(sprite1); + sprite1.runAction(cc.rotateBy(3, 360).repeatForever()); + + var sprite2 = new jsb.Sprite3D("Sprite3DTest/boss1.obj") + sprite2.setScale(4.0); + sprite2.setTexture("Sprite3DTest/boss.png"); + sprite2.setPosition(cc.p(s.width/2, s.height/2)); + sprite2.setAnchorPoint(cc.p(0.5, 0.5)); + + this.addChild(sprite2); + sprite2.runAction(cc.rotateBy(3, -360).repeatForever()); + + // Make sprite1 touchable + var listener1 = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches: true, + onTouchBegan: function (touch, event) { + var target = event.getCurrentTarget(); + var rect = target.getBoundingBox(); + if(cc.rectContainsPoint(rect, touch.getLocation())){ + cc.log("sprite3d began... x = " + touch.getLocation().x + ", y = " + touch.getLocation().y); + target.setOpacity(100); + return true; + } + return false; + }, + onTouchMoved: function (touch, event) { + var target = event.getCurrentTarget(); + var oldPos = target.getPosition(); + var delta = touch.getDelta(); + target.setPosition(cc.p(oldPos.x + delta.x, oldPos.y + delta.y)); + }, + onTouchEnded: function (touch, event) { + var target = event.getCurrentTarget(); + cc.log("sprite3d onTouchEnded..."); + target.setOpacity(255); + } + }); + cc.eventManager.addListener(listener1, sprite1); + cc.eventManager.addListener(listener1.clone(), sprite2); + } +}); + +var AsyncLoadSprite3DTest = Sprite3DTestDemo.extend({ + _title:"Testing Sprite3D::createAsync", + _subtitle:"", + _path:["Sprite3DTest/boss.obj", "Sprite3DTest/girl.c3b", "Sprite3DTest/orc.c3b", "Sprite3DTest/ReskinGirl.c3b", "Sprite3DTest/axe.c3b"], + + ctor:function(){ + this._super(); + + var label = new cc.LabelTTF("AsyncLoad Sprite3D", "Arial", 15); + var item = new cc.MenuItemLabel(label, this. menuCallback_asyncLoadSprite, this); + + var s = cc.winSize; + item.setPosition(s.width / 2, s.height / 2); + + var menu = new cc.Menu(item); + menu.setPosition(cc.p(0, 0)); + this.addChild(menu, 10); + + var node = new cc.Node(); + node.setTag(101); + this.addChild(node); + + this.menuCallback_asyncLoadSprite(); + }, + + menuCallback_asyncLoadSprite:function(sender){ + //Note that you must stop the tasks before leaving the scene. + cc.AsyncTaskPool.getInstance().stopTasks(cc.AsyncTaskPool.TaskType.TASK_IO); + + var node = this.getChildByTag(101); + node.removeAllChildren(); // remove all loaded sprites + + //remove cache data + jsb.sprite3DCache.removeAllSprite3DData(); + + for(var i = 0; i < this._path.length; ++i){ + jsb.Sprite3D.createAsync(this._path[i], this.asyncLoad_Callback, this, i); + } + + }, + + asyncLoad_Callback:function(sprite, data){ + var node = this.getChildByTag(101); + var s = cc.winSize; + var width = s.width / this._path.length; + sprite.setPosition(width * (0.5 + data), s.height / 2); + node.addChild(sprite); + } +}); + +var Sprite3DWithSkinTest = Sprite3DTestDemo.extend({ + _title:"Testing Sprite3D", + _subtitle:"Tap screen to add more sprite3D", + + ctor:function(){ + this._super(); + + var size = cc.winSize; + this.addNewSpriteWithCoords(cc.p(size.width/2, size.height/2)); + + var that = this; + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded: function(touches, event){ + for(var i in touches){ + that.addNewSpriteWithCoords(touches[i].getLocation()); + } + } + }, this); + }, + + addNewSpriteWithCoords:function(position){ + var sprite = new jsb.Sprite3D("Sprite3DTest/orc.c3b"); + sprite.setScale(3); + sprite.setRotation3D({x : 0, y : 180, z: 0}); + this.addChild(sprite); + sprite.setPosition(position); + + var animation = jsb.Animation3D.create("Sprite3DTest/orc.c3b"); + if(animation){ + var animate = jsb.Animate3D.create(animation); + var inverse = Math.random() < 0.33 ? true : false; + + var rand2 = Math.random(); + var speed = 1.0; + if(rand2 < 0.33) + speed = animate.getSpeed() + Math.random(); + else if(rand2 < 0.66) + spped = animate.getSpeed() - 0.5 * Math.random(); + + animate.setSpeed(inverse ? -speed : speed); + sprite.runAction(new cc.RepeatForever(animate)); + } + } +}); + +var Animate3DTest = (function(){ + + var State = { + SWIMMING : 0, + SWIMMING_TO_HURT : 1, + HURT : 2, + HURT_TO_SWIMMING : 3 + }; + + return Sprite3DTestDemo.extend({ + _title:"Testing Animate3D", + _subtitle:"Touch to beat the tortoise", + _sprite:null, + _swim:null, + _hurt:null, + _moveAction:null, + _state:0, + _elapseTransTime:0, + + ctor:function(){ + this._super(); + + this.addSprite3D(); + + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded: this.onTouchesEnded.bind(this) + }, this); + + this.scheduleUpdate(); + }, + + onExit:function(){ + this._super(); + this._moveAction.release(); + this._hurt.release(); + this._swim.release(); + }, + + addSprite3D:function(){ + var sprite = new jsb.Sprite3D("Sprite3DTest/tortoise.c3b"); + sprite.setScale(0.1); + var s = cc.winSize; + sprite.setPosition(cc.p(s.width * 4 / 5, s.height / 2)); + this.addChild(sprite); + this._sprite = sprite; + + var animation = jsb.Animation3D.create("Sprite3DTest/tortoise.c3b"); + if(animation){ + var animate = jsb.Animate3D.create(animation, 0, 1.933); + this._swim = new cc.RepeatForever(animate); + sprite.runAction(this._swim); + + this._swim.retain(); + this._hurt = jsb.Animate3D.create(animation, 1.933, 2.8); + this._hurt.retain(); + + this._state = State.SWIMMING; + } + + this._moveAction = cc.moveBy(4.0, cc.p(-s.width / 5 * 3, 0)); + this._moveAction.retain(); + var seq = cc.sequence(this._moveAction, cc.callFunc(this.reachEndCallBack, this)); + seq.setTag(100); + sprite.runAction(seq); + }, + + reachEndCallBack:function(sender){ + var sprite = this._sprite; + sprite.stopActionByTag(100); + var inverse = this._moveAction.reverse(); + inverse.retain(); + this._moveAction.release(); + this._moveAction = inverse; + var rot = cc.rotateBy(1, {x : 0, y : 180, z : 0}); + var seq = cc.sequence(rot, this._moveAction, cc.callFunc(this.reachEndCallBack, this)); + seq.setTag(100); + sprite.runAction(seq); + }, + + renewCallBack:function(){ + this._sprite.runAction(this._swim); + this._state = State.HURT_TO_SWIMMING; + this._elapseTransTime = 0.0; + }, + + onTouchesEnded:function(touches, event){ + for(var i in touches){ + var location = touches[i].getLocation(); + + if(this._sprite){ + var len = cc.pDistance(this._sprite.getPosition(), location); + + if(len < 40){ + //hurt the tortoise + if(this._state == State.SWIMMING){ + this._elapseTransTime = 0; + this._state = State.SWIMMING_TO_HURT; + this._sprite.stopAction(this._hurt); + this._sprite.runAction(this._hurt); + var delay = cc.delayTime(this._hurt.getDuration() - jsb.Animate3D.getTransitionTime()); + var seq = cc.sequence(delay, cc.callFunc(this.renewCallBack, this)); + seq.setTag(101); + this._sprite.runAction(seq); + } + } + } + } + }, + + update:function(dt){ + if(this._state == State.HURT_TO_SWIMMING){ + this._elapseTransTime += dt; + + if(this._elapseTransTime >= jsb.Animate3D.getTransitionTime()){ + this._sprite.stopAction(this._hurt); + this._state = State.SWIMMING; + } + }else if(this._state == State.SWIMMING_TO_HURT){ + this._elapseTransTime += dt; + + if(this._elapseTransTime >= jsb.Animate3D.getTransitionTime()){ + this._sprite.stopAction(this._swim); + this._state = State.HURT; + } + } + } + }); +})(); + + +var AttachmentTest = Sprite3DTestDemo.extend({ + _title:"Testing Sprite3D Attachment", + _subtitle:"touch to switch weapon", + _hasWeapon:false, + _sprite:null, + + ctor:function(){ + this._super(); + + var s = cc.winSize; + this.addNewSpriteWithCoords(cc.p(s.width/2, s.height/2)); + + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded: this.onTouchesEnded.bind(this) + }, this); + }, + + addNewSpriteWithCoords:function(position){ + var sprite = new jsb.Sprite3D("Sprite3DTest/orc.c3b"); + sprite.setScale(5); + sprite.setRotation3D(cc.math.vec3(0, 180, 0)); + this.addChild(sprite); + sprite.setPosition(position); + + //test attach + var sp = new jsb.Sprite3D("Sprite3DTest/axe.c3b"); + sprite.getAttachNode("Bip001 R Hand").addChild(sp); + + var animation = jsb.Animation3D.create("Sprite3DTest/orc.c3b"); + if(animation){ + var animate = jsb.Animate3D.create(animation); + sprite.runAction(cc.repeatForever(animate)); + } + + this._sprite = sprite; + this._hasWeapon = true; + }, + + onTouchesEnded:function(touches, event){ + if(this._hasWeapon){ + this._sprite.removeAllAttachNode(); + }else{ + var sp = new jsb.Sprite3D("Sprite3DTest/axe.c3b"); + this._sprite.getAttachNode("Bip001 R Hand").addChild(sp); + } + this._hasWeapon = !this._hasWeapon; + } +}); + +var Sprite3DReskinTest = (function(){ + var SkinType = { + UPPER_BODY : 0, + PANTS : 1, + SHOES : 2, + HAIR : 3, + FACE : 4, + HAND : 5, + GLASSES : 6, + MAX_TYPE : 7 + }; + + return Sprite3DTestDemo.extend({ + _title:"Testing Sprite3D Reskin", + _subtitle:"", + _sprite:null, + _skins:[["Girl_UpperBody01", "Girl_UpperBody02"], ["Girl_LowerBody01", "Girl_LowerBody02"], ["Girl_Shoes01", "Girl_Shoes02"], ["Girl_Hair01", "Girl_Hair02"], ["Girl_Face01", "Girl_Face02"], ["Girl_Hand01", "Girl_Hand02"], ["", "Girl_Glasses01"]], + _curSkin:["Girl_UpperBody01", "Girl_LowerBody01", "Girl_Shoes01", "Girl_Hair01", "Girl_Face01", "Girl_Hand01", ""], + + ctor:function(){ + this._super(); + + var s = cc.winSize; + this.addNewSpriteWithCoords(cc.p(s.width/2, s.height/2)); + + var label1 = new cc.LabelTTF("Hair", "Arial", 20); + var item1 = new cc.MenuItemLabel(label1, this.menuCallback_reSkin, this ); + item1.setPosition(cc.p(50, item1.getContentSize().height * 4)); + item1.setUserData(SkinType.HAIR); + + var label2 = new cc.LabelTTF("Glasses", "Arial", 20); + var item2 = new cc.MenuItemLabel(label2, this.menuCallback_reSkin, this); + item2.setPosition(cc.p(50, item2.getContentSize().height * 5)); + item2.setUserData(SkinType.GLASSES); + + var label3 = new cc.LabelTTF("Coat", "Arial", 20); + var item3 = new cc.MenuItemLabel(label3, this.menuCallback_reSkin, this); + item3.setPosition(cc.p(50, item3.getContentSize().height * 6)); + item3.setUserData(SkinType.UPPER_BODY); + + var label4 = new cc.LabelTTF("Pants", "Arial", 20); + var item4 = new cc.MenuItemLabel(label4, this.menuCallback_reSkin, this); + item4.setPosition(cc.p(50, item4.getContentSize().height * 7)); + item4.setUserData(SkinType.PANTS); + + var label5 = new cc.LabelTTF("Shoes", "Arial", 20); + var item5 = new cc.MenuItemLabel(label5, this.menuCallback_reSkin, this); + item5.setPosition(cc.p(50, item5.getContentSize().height * 8)); + item5.setUserData(SkinType.SHOES); + + var menu = new cc.Menu(item1, item2, item3, item4, item5); + this.addChild(menu); + menu.setPosition(cc.p(0, 0)); + }, + + addNewSpriteWithCoords:function(position){ + var sprite = new jsb.Sprite3D("Sprite3DTest/ReskinGirl.c3b"); + sprite.setScale(4); + sprite.setRotation3D(cc.math.vec3(0, 0, 0)); + this.addChild(sprite); + sprite.setPosition(cc.p(position.x, position.y - 60)); + var animation = jsb.Animation3D.create("Sprite3DTest/ReskinGirl.c3b"); + if(animation){ + var animate = jsb.Animate3D.create(animation); + sprite.runAction(cc.repeatForever(animate)); + } + this._sprite = sprite; + + this.applyCurSkin(); + }, + + applyCurSkin:function(){ + for(var i = 0; i < this._sprite.getMeshCount(); i++){ + var mesh = this._sprite.getMeshByIndex(i); + var isVisible = false; + for(var j = 0; j < SkinType.MAX_TYPE; j++){ + if(mesh.getName() == this._curSkin[j]){ + isVisible = true; + break; + } + } + mesh.setVisible(isVisible); + } + }, + + menuCallback_reSkin:function(sender){ + var index = sender.getUserData(); + if(index < SkinType.MAX_TYPE){ + var curr = (this._skins[index].indexOf(this._curSkin[index]) + 1) % this._skins[index].length; + this._curSkin[index] = this._skins[index][curr]; + } + this.applyCurSkin(); + } + }); +})(); + +var Sprite3DWithOBBPerformanceTest = Sprite3DTestDemo.extend({ + _title:"OBB Collison Performance Test", + _subtitle:"", + _drawOBB:null, + _drawDebug:null, + _sprite:null, + _moveAction:null, + _obbt:null, + _obb:[], + _labelCubeCount:null, + _targetObbIndex:-1, + + ctor:function(){ + this._super(); + + cc.eventManager.addListener({ + event:cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesBegan:this.onTouchesBegan.bind(this), + onTouchesMoved:this.onTouchesMoved.bind(this) + }, this); + + this.initDrawBox(); + this.addSprite(); + + var s = cc.winSize; + cc.MenuItemFont.setFontName("Arial"); + cc.MenuItemFont.setFontSize(65); + var decrease = new cc.MenuItemFont(" - ", this.delOBBCallback, this); + decrease.setColor(cc.color(0, 200, 20)); + var increase = new cc.MenuItemFont(" + ", this.addOBBCallback, this); + increase.setColor(cc.color(0, 200, 20)); + + var menu = new cc.Menu(decrease, increase); + menu.alignItemsHorizontally(); + menu.setPosition(s.width / 2, s.height - 65); + this.addChild(menu, 1); + + this._labelCubeCount = new cc.LabelTTF("0 cubes", "Arial", 30); + this._labelCubeCount.setColor(cc.color(0, 200, 20)); + this._labelCubeCount.setPosition(cc.p(s.width / 2, s.height - 90)); + this.addChild(this._labelCubeCount); + + this.addOBBCallback(); + this.scheduleUpdate(); + }, + + onExit:function(){ + this._super(); + this._moveAction.release(); + }, + + update:function(){ + if(this._drawDebug !== undefined){ + this._drawDebug.clear(); + + var mat = this._sprite.getNodeToWorldTransform3D(); + this._obbt.xAxis.x = mat[0]; + this._obbt.xAxis.y = mat[1]; + this._obbt.xAxis.z = mat[2]; + this._obbt.xAxis.normalize(); + + this._obbt.yAxis.x = mat[4]; + this._obbt.yAxis.y = mat[5]; + this._obbt.yAxis.z = mat[6]; + this._obbt.yAxis.normalize(); + + this._obbt.zAxis.x = -mat[8]; + this._obbt.zAxis.y = -mat[9]; + this._obbt.zAxis.z = -mat[10]; + this._obbt.zAxis.normalize(); + + this._obbt.center = this._sprite.getPosition3D(); + + var corners = cc.math.obbGetCorners(this._obbt); + this._drawDebug.drawCube(corners, cc.color(0, 0, 255)); + } + + if(this._obb.length > 0){ + this._drawOBB.clear(); + for(var i = 0; i < this._obb.length; ++i){ + corners = cc.math.obbGetCorners(this._obb[i]); + this._drawOBB.drawCube(corners, cc.math.obbIntersectsObb(this._obbt, this._obb[i]) ? cc.color(255, 0, 0) : cc.color(0, 255, 0)); + } + } + }, + + initDrawBox:function(){ + this._drawOBB = new cc.DrawNode3D(); + this.addChild(this._drawOBB); + }, + + addSprite:function(){ + var sprite = new jsb.Sprite3D("Sprite3DTest/tortoise.c3b"); + sprite.setScale(0.1); + var s = cc.winSize; + sprite.setPosition(cc.p(s.width * 4 / 5, s.height / 2)); + this.addChild(sprite); + + this._sprite = sprite; + var animation = jsb.Animation3D.create("Sprite3DTest/tortoise.c3b"); + if(animation){ + var animate = jsb.Animate3D.create(animation); + sprite.runAction(cc.repeatForever(animate)); + } + + this._moveAction = cc.moveBy(4, cc.p(-s.width * 3 / 5, 0)); + this._moveAction.retain(); + var seq = cc.sequence(this._moveAction, cc.callFunc(this.reachEndCallBack, this)); + seq.setTag(100); + sprite.runAction(seq); + + var aabb = sprite.getAABB(); + this._obbt = cc.math.obb(aabb); + + this._drawDebug = new cc.DrawNode3D(); + this.addChild(this._drawDebug); + }, + + reachEndCallBack:function(){ + var sprite = this._sprite; + sprite.stopActionByTag(100); + var inverse = this._moveAction.reverse(); + inverse.retain(); + this._moveAction.release(); + this._moveAction = inverse; + var rot = cc.rotateBy(1, {x : 0, y : 180, z : 0}); + var seq = cc.sequence(rot, this._moveAction, cc.callFunc(this.reachEndCallBack, this)); + seq.setTag(100); + sprite.runAction(seq); + }, + + addOBBCallback:function(sender){ + var s = cc.winSize; + for(var i = 0; i < 10; ++i){ + var randompos = cc.p(Math.random() * s.width, Math.random() * s.height); + var aabb = cc.math.aabb(cc.math.vec3(-10, -10, -10), cc.math.vec3(10, 10, 10)); + var obb = cc.math.obb(aabb); + obb.center = cc.math.vec3(randompos.x, randompos.y, 0); + this._obb.push(obb); + } + this._labelCubeCount.setString(this._obb.length + " cubes"); + }, + + delOBBCallback:function(sender){ + if(this._obb.length >= 10){ + this._obb.splice(0, 10); + this._drawOBB.clear(); + } + this._labelCubeCount.setString(this._obb.length + " cubes"); + }, + + onTouchesBegan:function(touches, event){ + var location = touches[0].getLocationInView(); + var ray = this.calculateRayByLocationInView(location); + for(var j = 0; j < this._obb.length; ++j){ + if(cc.math.rayIntersectsObb(ray, this._obb[j])){ + this._targetObbIndex = j; + return; + } + } + this._targetObbIndex = -1; + }, + + onTouchesMoved:function(touches, event){ + if(this._targetObbIndex >= 0){ + var location = touches[0].getLocation(); + this._obb[this._targetObbIndex].center = cc.math.vec3(location.x, location.y, 0); + } + }, + + calculateRayByLocationInView:function(location){ + var camera = cc.Camera.getDefaultCamera(); + + var src = cc.math.vec3(location.x, location.y, -1); + var nearPoint = camera.unproject(src); + + src = cc.math.vec3(location.x, location.y, 1); + var farPoint = camera.unproject(src); + + var direction = cc.math.vec3(farPoint.x - nearPoint.x, farPoint.y - nearPoint.y, farPoint.z - nearPoint.z); + direction.normalize(); + + return cc.math.ray(nearPoint, direction); + } +}); + +var Sprite3DMirrorTest = Sprite3DTestDemo.extend({ + _title:"Sprite3D Mirror Test", + _subtitle:"", + + ctor:function(){ + this._super(); + + var s = cc.winSize; + this.addNewSpriteWithCoords(cc.p(s.width / 2, s.height / 2)); + }, + + addNewSpriteWithCoords:function(position){ + var fileName = "Sprite3DTest/orc.c3b"; + var sprite = new jsb.Sprite3D("Sprite3DTest/orc.c3b"); + sprite.setScale(5); + sprite.setRotation3D(cc.math.vec3(0, 180, 0)); + this.addChild(sprite); + sprite.setPosition(cc.p(position.x - 80, position.y)); + + //test attach + var sp = new jsb.Sprite3D("Sprite3DTest/axe.c3b"); + sprite.getAttachNode("Bip001 R Hand").addChild(sp); + + var animation = jsb.Animation3D.create(fileName); + if(animation){ + var animate = jsb.Animate3D.create(animation); + sprite.runAction(cc.repeatForever(animate)); + } + + //create mirror Sprite3D + sprite = new jsb.Sprite3D(fileName); + sprite.setScale(5); + sprite.setScaleX(-5); + sprite.setCullFace(gl.FRONT); + sprite.setRotation3D(cc.math.vec3(0, 180, 0)); + this.addChild(sprite); + sprite.setPosition(cc.p(position.x + 80, position.y)); + + //test attach + sp = new jsb.Sprite3D("Sprite3DTest/axe.c3b"); + sprite.getAttachNode("Bip001 R Hand").addChild(sp); + + var animation = jsb.Animation3D.create(fileName); + if(animation){ + var animate = jsb.Animate3D.create(animation); + sprite.runAction(cc.repeatForever(animate)); + } + } + +}); + +var QuaternionTest = Sprite3DTestDemo.extend({ + _title:"Test Rotation With Quaternion", + _subtitle:"", + _sprite:null, + _radius:100, + _accAngle:0, + + ctor:function(){ + this._super(); + + var sprite = new jsb.Sprite3D("Sprite3DTest/tortoise.c3b"); + sprite.setScale(0.1); + var s = cc.winSize; + sprite.setPosition(cc.p(s.width/2 + this._radius * Math.cos(this._accAngle), s.height / 2 + this._radius * Math.sin(this._accAngle))); + this.addChild(sprite); + this._sprite = sprite; + var animation = jsb.Animation3D.create("Sprite3DTest/tortoise.c3b"); + if(animation){ + var animate = jsb.Animate3D.create(animation, 0, 1.933); + sprite.runAction(cc.repeatForever(animate)); + } + + this.scheduleUpdate(); + }, + + update:function(dt){ + this._accAngle += dt * cc.degreesToRadians(90); + if(this._accAngle >= 2 * Math.PI) + this._accAngle -= 2 * Math.PI; + + var s = cc.winSize; + this._sprite.setPosition(cc.p(s.width / 2 + this._radius * Math.cos(this._accAngle), s.height / 2 + this._radius * Math.sin(this._accAngle))); + + var quat = cc.math.quaternion(cc.math.vec3(0, 0, 1), this._accAngle - Math.PI * 0.5); + this._sprite.setRotationQuat(quat); + } +}); + +var Sprite3DEmptyTest = Sprite3DTestDemo.extend({ + _title:"Testing Sprite3D Container", + _subtitle:"Sprite3D can act as containers for 2D objects", + + ctor:function(){ + this._super(); + + var s = new jsb.Sprite3D(); + s.setNormalizedPosition(cc.p(0.5, 0.5)); + var l = new cc.LabelTTF("Test"); + s.addChild(l); + this.addChild(s); + } +}); + +var Sprite3DForceDepthTest = Sprite3DTestDemo.extend({ + _title:"Force Depth Write Error Test", + _subtitle:"Ship should always appear behind orc", + + ctor:function(){ + this._super(); + + var orc = new jsb.Sprite3D("Sprite3DTest/orc.c3b"); + orc.setScale(5); + orc.setNormalizedPosition(cc.p(0.5, 0.3)); + // orc.setPositionZ(40); + orc.setVertexZ(40); + orc.setRotation3D(cc.math.vec3(0, 180, 0)); + orc.setGlobalZOrder(-1); + + this.addChild(orc); + + var ship = new jsb.Sprite3D("Sprite3DTest/boss1.obj"); + ship.setScale(5); + ship.setTexture("Sprite3DTest/boss.png"); + ship.setNormalizedPosition(cc.p(0.5, 0.5)); + ship.setRotation3D(cc.math.vec3(90, 0, 0)); + ship.setForceDepthWrite(true); + + this.addChild(ship); + } +}); + +var UseCaseSprite3D1 = Sprite3DTestDemo.extend({ + _title:"Use Case For 2D + 3D", + _subtitle:"3d transparent sprite + 2d sprite", + _accAngle:0, + + ctor:function(){ + this._super(); + + var s = cc.winSize; + //setup camera + var camera = cc.Camera.createPerspective(40, s.width/s.height, 0.01, 1000); + camera.setCameraFlag(cc.CameraFlag.USER1); + camera.setPosition3D(cc.math.vec3(0, 30, 100)); + camera.lookAt(cc.math.vec3(0, 0, 0)); + this.addChild(camera); + + var sprite = new jsb.Sprite3D("Sprite3DTest/girl.c3b"); + sprite.setScale(0.15); + var animation = jsb.Animation3D.create("Sprite3DTest/girl.c3b"); + if(animation){ + var animate = jsb.Animate3D.create(animation); + sprite.runAction(cc.repeatForever(animate)); + } + + var circleBack = new jsb.Sprite3D(); + var circle = new cc.Sprite("Sprite3DTest/circle.png"); + circleBack.setScale(0.5); + circleBack.addChild(circle); + circle.runAction(cc.rotateBy(3, cc.math.vec3(0, 0, 360)).repeatForever()); + + circleBack.setRotation3D(cc.math.vec3(90, 0, 0)); + + var pos = sprite.getPosition3D(); + circleBack.setPosition3D(cc.math.vec3(pos.x, pos.y, pos.z-1)); + + sprite.setOpacity(250); + sprite.setCameraMask(2); + circleBack.setCameraMask(2); + sprite.setTag(3); + circleBack.setTag(2); + + this.addChild(sprite); + this.addChild(circleBack); + + this.scheduleUpdate(); + this.update(0.1); + }, + + update:function(dt){ + this._accAngle += dt * cc.degreesToRadians(60); + + var radius = 30; + var x = Math.cos(this._accAngle) * radius; + var z = Math.sin(this._accAngle) * radius; + + var sprite = this.getChildByTag(3); + var circle = this.getChildByTag(2); + + sprite.setPositionX(x); + sprite.setVertexZ(z); + circle.setPositionX(x); + circle.setVertexZ(z); + } +}); + +var UseCaseSprite3D2 = Sprite3DTestDemo.extend({ + _title:"Use Case For 2D + 3D", + _subtitle:"ui - 3d - ui, last ui should on the top", + ctor:function(){ + this._super(); + + var s = cc.winSize; + //setup camera + var camera = cc.Camera.createPerspective(40, s.width/s.height, 0.01, 1000); + camera.setCameraFlag(cc.CameraFlag.USER1); + camera.setPosition3D(cc.math.vec3(0, 30, 100)); + camera.lookAt(cc.math.vec3(0, 0, 0)); + this.addChild(camera); + + var layer = new cc.LayerColor(cc.color(0, 0, 100, 255), s.width/2, s.height/2); + layer.setPosition(s.width/4, s.height/4); + layer.setGlobalZOrder(-1); + layer.setTag(101); + this.addChild(layer); + + var sprite = new jsb.Sprite3D("Sprite3DTest/girl.c3b"); + sprite.setScale(0.5); + var animation = jsb.Animation3D.create("Sprite3DTest/girl.c3b"); + if(animation){ + var animate = jsb.Animate3D.create(animation); + sprite.runAction(cc.repeatForever(animate)); + } + sprite.setPosition(s.width/4, s.height/4); + layer.addChild(sprite); + + var label1 = new cc.LabelTTF("Message", "Arial", 15); + var item1 = new cc.MenuItemLabel(label1, this.menuCallback_Message, this); + var label2 = new cc.LabelTTF("Message", "Arial", 15); + var item2 = new cc.MenuItemLabel(label2, this.menuCallback_Message, this); + + item1.setPosition(cc.p(s.width/2 - item1.getContentSize().width/2, s.height/2 - item1.getContentSize().height)); + item2.setPosition(cc.p(s.width/2 - item1.getContentSize().width/2, s.height/2 - item1.getContentSize().height * 2)); + + var menu = new cc.Menu(item1, item2); + menu.setPosition(cc.p(0, 0)); + layer.addChild(menu); + + }, + + menuCallback_Message:function(sender){ + var layer = this.getChildByTag(101); + var message = layer.getChildByTag(102); + if(message) + layer.removeChild(message); + else{ + // create a new message layer on the top + var s = layer.getContentSize(); + var messagelayer = new cc.LayerColor(cc.color(100, 100, 0, 255)); + messagelayer.setContentSize(cc.size(s.width/2, s.height/2)); + messagelayer.setPosition(cc.p(s.width/4, s.height/4)); + var label = new cc.LabelTTF("This Message Layer \n Should Be On Top"); + label.setPosition(cc.p(s.width/4, s.height/4)); + messagelayer.addChild(label); + messagelayer.setTag(102); + layer.addChild(messagelayer); + } + + } +}); + +var Sprite3DEffectTest = Sprite3DTestDemo.extend({ + _title:"Testing Sprite3D", + _subtitle:"Sprite3d with effects", + + ctor:function(){ + this._super(); + + cc.eventManager.addListener({ + event:cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesBegan:this.onTouchesBegan.bind(this) + }, this); + + this.addNewSpriteWithCoords(cc.p(cc.winSize.width/2, cc.winSize.height/2)); + }, + + addNewSpriteWithCoords:function(position){ + var sprite = new cc.EffectSprite3D("Sprite3DTest/boss1.obj", "Sprite3DTest/boss.png"); + var effect = new cc.Effect3DOutline(); + effect.setOutlineColor(cc.math.vec3(1, 0, 0)); + effect.setOutlineWidth(0.01); + sprite.addEffect(effect, -1); + + var effect2 = new cc.Effect3DOutline(); + effect2.setOutlineColor(cc.math.vec3(1, 1, 0)); + effect2.setOutlineWidth(0.02); + sprite.addEffect(effect2, -2); + + sprite.setScale(6); + this.addChild(sprite); + sprite.setPosition(position); + + var action; + var random = Math.random(); + if(random < 0.2) + action = cc.scaleBy(3, 2); + else if(random < 0.4) + action = cc.rotateBy(3, 360); + else if(random < 0.6) + action = cc.blink(1, 3); + else if(random < 0.8) + action = cc.tintBy(2, 0, -255, -255); + else + action = cc.fadeOut(2); + + var action_back = action.reverse(); + var seq = cc.sequence(action, action_back); + + sprite.runAction(seq.repeatForever()); + }, + + onTouchesBegan:function(touches, event){ + for(var i = 0; i < touches.length; ++i){ + var location = touches[i].getLocation(); + this.addNewSpriteWithCoords(location); + } + } +}); + +var Sprite3DWithSkinOutlineTest = Sprite3DTestDemo.extend({ + _title:"Testing Sprite3D for skinned outline", + _subtitle:"Tap screen to add more sprite3D", + + ctor:function(){ + this._super(); + + cc.eventManager.addListener({ + event:cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesBegan:this.onTouchesBegan.bind(this) + }, this); + + this.addNewSpriteWithCoords(cc.p(cc.winSize.width/2, cc.winSize.height/2)); + }, + + addNewSpriteWithCoords:function(p){ + var sprite = new cc.EffectSprite3D("Sprite3DTest/orc.c3b"); + sprite.setScale(3); + sprite.setRotation3D(cc.math.vec3(0, 180, 0)); + this.addChild(sprite); + sprite.setPosition(p); + + var effect = new cc.Effect3DOutline(); + effect.setOutlineColor(cc.math.vec3(1, 0, 0)); + effect.setOutlineWidth(0.01); + sprite.addEffect(effect, -1); + + var effect2 = new cc.Effect3DOutline(); + effect2.setOutlineColor(cc.math.vec3(1, 1, 0)); + effect2.setOutlineWidth(0.02); + sprite.addEffect(effect2, -2); + + var animation = jsb.Animation3D.create("Sprite3DTest/orc.c3b"); + if(animation){ + var animate = jsb.Animate3D.create(animation); + var inverse = Math.random() < 0.33 ? true : false; + + var rand2 = Math.random(); + var speed = 1.0; + if(rand2 < 0.33) + speed = animate.getSpeed() + Math.random(); + else if(rand2 < 0.66) + spped = animate.getSpeed() - 0.5 * Math.random(); + + animate.setSpeed(inverse ? -speed : speed); + sprite.runAction(new cc.RepeatForever(animate)); + } + }, + + onTouchesBegan:function(touches, event){ + for(var i = 0; i < touches.length; ++i){ + var location = touches[i].getLocation(); + this.addNewSpriteWithCoords(location); + } + } +}); + +var Sprite3DLightMapTest = Sprite3DTestDemo.extend({ + _title:"light map test", + _subtitle:"drag the screen to move around", + _camera:null, + + ctor:function(){ + this._super(); + + //the assets are from the OpenVR demo + //get the visible size. + var visibleSize = cc.director.getVisibleSize(); + this._camera = cc.Camera.createPerspective(60, visibleSize.width/visibleSize.height, 0.1, 200); + this._camera.setCameraFlag(cc.CameraFlag.USER1); + this._camera.setPosition3D(cc.math.vec3(0, 25, 15)); + this._camera.setRotation3D(cc.math.vec3(-35, 0, 0)); + + var LightMapScene = new jsb.Sprite3D("Sprite3DTest/LightMapScene.c3b"); + LightMapScene.setScale(0.1); + this.addChild(LightMapScene); + this.addChild(this._camera); + this.setCameraMask(2); + + //add a point light + var light = jsb.PointLight.create(cc.math.vec3(35, 75, -20.5), cc.color(255, 255, 255), 150); + this.addChild(light); + //set the ambient light + var ambient = jsb.AmbientLight.create(cc.color(55, 55, 55)); + this.addChild(ambient); + + //create a listener + cc.eventManager.addListener({ + event:cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesMoved:this.onTouchesMoved.bind(this) + }, this); + }, + + onTouchesMoved:function(touches, event){ + if(touches.length === 1){ + var dt = cc.director.getDeltaTime(); + var touch = touches[0]; + var location = touch.getLocation(); + var previousLocation = touch.getPreviousLocation(); + var newPos = cc.p(previousLocation.x - location.x, previousLocation.y - location.y); + + var m = this._camera.getNodeToWorldTransform3D(); + var cameraDir = cc.math.vec3(-m[8], -m[9], -m[10]); + cameraDir.normalize(); + cameraDir.y = 0; + + var cameraRightDir = cc.math.vec3(m[0], m[1], m[2]); + cameraRightDir.normalize(); + cameraRightDir.y = 0; + + var cameraPos = this._camera.getPosition3D(); + cameraPos.x += cameraDir.x * newPos.y * dt + cameraRightDir.x * newPos.x * dt; + cameraPos.y += cameraDir.y * newPos.y * dt + cameraRightDir.y * newPos.x * dt; + cameraPos.z += cameraDir.z * newPos.y * dt + cameraRightDir.z * newPos.x * dt; + this._camera.setPosition3D(cameraPos); + } + } +}); + +var Sprite3DUVAnimationTest = Sprite3DTestDemo.extend({ + _title:"Testing UV Animation", + _subtitle:"", + _cylinder_texture_offset:0, + _shining_duraion:0, + _state:null, + fade_in:true, + + ctor:function(){ + this._super(); + + var visibleSize = cc.director.getVisibleSize(); + //use custom camera + var camera = cc.Camera.createPerspective(60, visibleSize.width/visibleSize.height, 0.1, 200); + camera.setCameraFlag(cc.CameraFlag.USER1); + this.addChild(camera); + this.setCameraMask(2); + + //create cylinder + var cylinder = new jsb.Sprite3D("Sprite3DTest/cylinder.c3b"); + this.addChild(cylinder); + cylinder.setScale(3); + cylinder.setPosition(visibleSize.width/2, visibleSize.height/2); + cylinder.setRotation3D(cc.math.vec3(-90, 0, 0)); + + //create and set our custom shader + var shader = new cc.GLProgram("Sprite3DTest/cylinder.vert","Sprite3DTest/cylinder.frag"); + this._state = cc.GLProgramState.create(shader); + cylinder.setGLProgramState(this._state); + + this._state.setUniformFloat("offset", this._cylinder_texture_offset); + this._state.setUniformFloat("duration", this._shining_duraion); + + //pass mesh's attribute to shader + var offset = 0; + var attributeCount = cylinder.getMesh().getMeshVertexAttribCount(); + for(var i = 0; i < attributeCount; ++i){ + var meshattribute = cylinder.getMesh().getMeshVertexAttribute(i); + this._state.setVertexAttribPointer(cc.attributeNames[meshattribute.vertexAttrib], + meshattribute.size, + meshattribute.type, + gl.FALSE, + cylinder.getMesh().getVertexSizeInBytes(), + offset); + offset += meshattribute.attribSizeBytes; + } + + //create the second texture for cylinder + var shining_texture = cc.textureCache.addImage("Sprite3DTest/caustics.png"); + shining_texture.setTexParameters(gl.NEAREST, gl.NEAREST, gl.REPEAT, gl.REPEAT); + //pass the texture sampler to our custom shader + this._state.setUniformTexture("caustics", shining_texture); + + this.scheduleUpdate(); + }, + + update:function(dt){ + //callback function to update cylinder's texcoord + this._cylinder_texture_offset += 0.3 * dt; + this._cylinder_texture_offset = this._cylinder_texture_offset > 1 ? 0 : this._cylinder_texture_offset; + + if(this.fade_in){ + this._shining_duraion += 0.5 * dt; + if(this._shining_duraion > 1) + this.fade_in = false; + }else{ + this._shining_duraion -= 0.5 * dt; + if(this._shining_duraion < 0) + this.fade_in = true; + } + + //pass the result to shader + this._state.setUniformFloat("offset", this._cylinder_texture_offset); + this._state.setUniformFloat("duration", this._shining_duraion); + } +}); + +var State = { + State_None : 0, + State_Idle : 0x01, + State_Move : 0x02, + State_Rotate : 0x04, + State_Speak : 0x08, + State_MeleeAttack : 0x10, + State_RemoteAttack : 0x20, + State_Attack : 0x40 +}; + +var Sprite3DFakeShadowTest = Sprite3DTestDemo.extend({ + _title:"fake shadow effect", + _subtitle:"touch the screen to move around", + _camera:null, + _plane:null, + _orc:null, + _targetPos:null, + _curState:0, + + ctor:function(){ + this._super(); + + cc.eventManager.addListener({ + event:cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded:this.onTouchesEnded.bind(this) + }, this); + + var visibleSize = cc.director.getVisibleSize(); + var s = cc.winSize; + + this._orc = new jsb.Sprite3D("Sprite3DTest/orc.c3b"); + this._orc.setScale(0.2); + this._orc.setRotation3D(cc.math.vec3(0, 180, 0)); + this._orc.setPosition3D(cc.math.vec3(0, 0, 0)); + + this._targetPos = this._orc.getPosition3D(); + this.addChild(this._orc); + + //create a plane + this._plane = new jsb.Sprite3D("Sprite3DTest/plane.c3t"); + this._plane.setRotation3D(cc.math.vec3(90, 0, 0)); + this.addChild(this._plane); + + //use a custom shader + var shader = new cc.GLProgram("Sprite3DTest/simple_shadow.vert", "Sprite3DTest/simple_shadow.frag"); + var state = cc.GLProgramState.create(shader); + this._plane.setGLProgramState(state); + + //pass mesh's attribute to shader + var offset = 0; + var attributeCount = this._plane.getMesh().getMeshVertexAttribCount(); + for(var i = 0; i < attributeCount; ++i){ + var meshattribute = this._plane.getMesh().getMeshVertexAttribute(i); + state.setVertexAttribPointer(cc.attributeNames[meshattribute.vertexAttrib], + meshattribute.size, + meshattribute.type, + gl.FALSE, + this._plane.getMesh().getVertexSizeInBytes(), + offset); + offset += meshattribute.attribSizeBytes; + } + state.setUniformMat4("u_model_matrix", this._plane.getNodeToWorldTransform3D()); + + //create shadow texture + var shadowTexture = cc.textureCache.addImage("Sprite3DTest/shadowCircle.png"); + shadowTexture.setTexParameters(gl.LINEAR, gl.LINEAR, gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE); + state.setUniformTexture("u_shadowTexture", shadowTexture); + state.setUniformVec3("u_target_pos", this._targetPos); + + this._camera = cc.Camera.createPerspective(60, s.width/s.height, 1, 1000); + this._camera.setCameraFlag(cc.CameraFlag.USER1); + this._camera.setPosition3D(cc.math.vec3(0, 20, 25)); + this._camera.lookAt(cc.math.vec3(0, 0, 0)); + this.addChild(this._camera); + this.setCameraMask(2); + + this.scheduleUpdate(); + }, + + update:function(dt){ + this.updateState(dt) + + if(this.isState(State.State_Move)){ + this.move3D(dt); + if(this.isState(State.State_Rotate)){ + var curPos = this._orc.getPosition3D(); + var newFaceDir = cc.math.vec3(this._targetPos.x - curPos.x, this._targetPos.y - curPos.y, this._targetPos.z - curPos.z); + newFaceDir.y = 0; + newFaceDir.normalize(); + + var m = this._orc.getNodeToWorldTransform3D(); + var up = cc.math.vec3(m[4], m[5], m[6]); + up.normalize(); + + var right = cc.math.vec3Cross(cc.math.vec3(-newFaceDir.x, -newFaceDir.y, -newFaceDir.z), up); + right.normalize(); + + var mat = [right.x, right.y, right.z, 0, + up.x, up.y, up.z, 0, + newFaceDir.x, newFaceDir.y, newFaceDir.z, 0, + 0, 0, 0, 1]; + + this._orc.setAdditionalTransform(mat); + } + } + }, + + updateState:function(dt){ + if(!this._targetPos) + return; + var curPos = this._orc.getPosition3D(); + var m = this._orc.getNodeToWorldTransform3D(); + var curFaceDir = cc.math.vec3(m[8], m[9], m[10]); + curFaceDir.normalize(); + var newFaceDir = cc.math.vec3(this._targetPos.x - curPos.x, this._targetPos.y - curPos.y, this._targetPos.z - curPos.z); + newFaceDir.y = 0; + newFaceDir.normalize(); + var cosAngle = Math.abs(cc.math.vec3Dot(curFaceDir, newFaceDir) - 1); + + var dx = curPos.x - this._targetPos.x, + dy = curPos.y - this._targetPos.y, + dz = curPos.z - this._targetPos.z; + var dist = dx * dx + dy * dy + dz * dz; + + if(dist <= 4){ + if(cosAngle <= 0.01) + this._curState = State.State_Idle; + else + this._curState = State.State_Rotate; + }else{ + if(cosAngle > 0.01) + this._curState = State.State_Rotate | State.State_Move; + else + this._curState = State.State_Move; + } + }, + + isState:function(bit){ + return (this._curState & bit) == bit; + }, + + move3D:function(dt){ + if(!this._targetPos) + return; + var curPos = this._orc.getPosition3D(); + var newFaceDir = cc.math.vec3(this._targetPos.x - curPos.x, this._targetPos.y - curPos.y, this._targetPos.z - curPos.z); + newFaceDir.y = 0; + newFaceDir.normalize(); + var offset = cc.math.vec3(newFaceDir.x * 25 * dt, newFaceDir.y * 25 * dt, newFaceDir.z * 25 * dt); + curPos.x += offset.x; + curPos.y += offset.y; + curPos.z += offset.z; + this._orc.setPosition3D(curPos); + //pass the newest orc position + this._plane.getGLProgramState().setUniformVec3("u_target_pos",curPos); + }, + + onTouchesEnded:function(touches, event){ + var touch = touches[0]; + var location = touch.getLocationInView(); + if(this._camera !== null){ + var nearP = cc.math.vec3(location.x, location.y, -1); + var farP = cc.math.vec3(location.x, location.y, 1); + + nearP = this._camera.unproject(nearP); + farP = this._camera.unproject(farP); + + var dir = cc.math.vec3(farP.x-nearP.x, farP.y-nearP.y, farP.z-nearP.z); + var ndd = dir.y; // (0, 1, 0) * dir + var ndo = nearP.y; // (0, 1, 0) * nearP + var dist = - ndo / ndd; + var p = cc.math.vec3(nearP.x+dist*dir.x, nearP.y+dist*dir.y, nearP.z+dist*dir.z); + + if(p.x > 100) + p.x = 100; + if(p.x < -100) + p.x = -100; + if(p.z > 100) + p.z = 100 + if(p.z < -100) + p.z = -100; + + this._targetPos = p; + } + } +}); + +var Sprite3DBasicToonShaderTest = Sprite3DTestDemo.extend({ + _title:"basic toon shader test", + _subtitle:"", + + ctor:function(){ + this._super(); + + var camera = cc.Camera.createPerspective(60, cc.winSize.width/cc.winSize.height, 1, 1000); + camera.setCameraFlag(cc.CameraFlag.USER1); + this.addChild(camera); + this.setCameraMask(2); + + //create a teapot + var teapot = new jsb.Sprite3D("Sprite3DTest/teapot.c3b"); + //create and set out custom shader + var shader = new cc.GLProgram("Sprite3DTest/toon.vert", "Sprite3DTest/toon.frag"); + var state = cc.GLProgramState.create(shader); + teapot.setGLProgramState(state); + teapot.setPosition3D(cc.math.vec3(cc.winSize.width/2, cc.winSize.height/2, -20)); + teapot.setRotation3D(cc.math.vec3(-90, 180, 0)); + teapot.setScale(10); + teapot.runAction(cc.rotateBy(1.5, cc.math.vec3(0, 30, 0)).repeatForever()); + this.addChild(teapot); + + //pass mesh's attribute to shader + var offset = 0; + var attributeCount = teapot.getMesh().getMeshVertexAttribCount(); + for(var i = 0; i < attributeCount; ++i){ + var meshattribute = teapot.getMesh().getMeshVertexAttribute(i); + state.setVertexAttribPointer(cc.attributeNames[meshattribute.vertexAttrib], + meshattribute.size, + meshattribute.type, + gl.FALSE, + teapot.getMesh().getVertexSizeInBytes(), + offset); + offset += meshattribute.attribSizeBytes; + } + } +}); + +// +// Flow control +// +var arrayOfSprite3DTest = [ + Sprite3DBasicTest, + Sprite3DHitTest, + AsyncLoadSprite3DTest, + Sprite3DWithSkinTest, + Animate3DTest, + AttachmentTest, + Sprite3DReskinTest, + Sprite3DWithOBBPerformanceTest, + Sprite3DMirrorTest, + QuaternionTest, + Sprite3DEmptyTest, + Sprite3DForceDepthTest, + UseCaseSprite3D1, + UseCaseSprite3D2 +]; + +// 3DEffect use custom shader which is not supported on WP8/WinRT yet. +if (cc.sys.os !== cc.sys.OS_WP8 || cc.sys.os !== cc.sys.OS_WINRT) { + arrayOfSprite3DTest = arrayOfSprite3DTest.concat([ + Sprite3DEffectTest, + Sprite3DWithSkinOutlineTest, + Sprite3DLightMapTest, + Sprite3DUVAnimationTest, + Sprite3DFakeShadowTest, + Sprite3DBasicToonShaderTest, + ]); +} + +var nextSprite3DTest = function () { + Sprite3DTestIdx++; + Sprite3DTestIdx = Sprite3DTestIdx % arrayOfSprite3DTest.length; + + if(window.sideIndexBar){ + Sprite3DTestIdx = window.sideIndexBar.changeTest(Sprite3DTestIdx, 36); + } + + return new arrayOfSprite3DTest[Sprite3DTestIdx ](); +}; +var previousSprite3DTest = function () { + Sprite3DTestIdx--; + if (Sprite3DTestIdx < 0) + Sprite3DTestIdx += arrayOfSprite3DTest.length; + + if(window.sideIndexBar){ + Sprite3DTestIdx = window.sideIndexBar.changeTest(Sprite3DTestIdx, 36); + } + + return new arrayOfSprite3DTest[Sprite3DTestIdx ](); +}; +var restartSprite3DTest = function () { + return new arrayOfSprite3DTest[Sprite3DTestIdx ](); +}; diff --git a/tests/js-tests/src/SpriteTest/SpriteTest.js b/tests/js-tests/src/SpriteTest/SpriteTest.js new file mode 100644 index 0000000000..3909bd49bc --- /dev/null +++ b/tests/js-tests/src/SpriteTest/SpriteTest.js @@ -0,0 +1,5499 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var TAG_TILE_MAP = 1; +var TAG_SPRITE_BATCH_NODE = 1; +var TAG_NODE = 2; +var TAG_ANIMATION1 = 1; +var TAG_SPRITE_LEFT = 2; +var TAG_SPRITE_RIGHT = 3; + +var TAG_SPRITE1 = 0; +var TAG_SPRITE2 = 1; +var TAG_SPRITE3 = 2; +var TAG_SPRITE4 = 3; +var TAG_SPRITE5 = 4; +var TAG_SPRITE6 = 5; +var TAG_SPRITE7 = 6; +var TAG_SPRITE8 = 7; + +var IDC_NEXT = 100; +var IDC_BACK = 101; +var IDC_RESTART = 102; + +var spriteTestIdx = -1; + +var spriteFrameCache = cc.spriteFrameCache; + +//------------------------------------------------------------------ +// +// SpriteTestDemo +// +//------------------------------------------------------------------ +var SpriteTestDemo = BaseTestLayer.extend({ + _title:"", + _subtitle:"", + + ctor:function () { + if (arguments.length === 0) { + this._super(cc.color(0, 0, 0, 255), cc.color(98, 99, 117, 255)); + } else { + this._super.apply(this, arguments); + } + }, + + onRestartCallback:function (sender) { + var s = new SpriteTestScene(); + s.addChild(restartSpriteTest()); + director.runScene(s); + }, + + onNextCallback:function (sender) { + var s = new SpriteTestScene(); + s.addChild(nextSpriteTest()); + director.runScene(s); + }, + + onBackCallback:function (sender) { + var s = new SpriteTestScene(); + s.addChild(previousSpriteTest()); + director.runScene(s); + }, + + // automation + numberOfPendingTests:function () { + return ( (arrayOfSpriteTest.length - 1) - spriteTestIdx ); + }, + + getTestNumber:function () { + return spriteTestIdx; + } +}); + +//------------------------------------------------------------------ +// +// Sprite1 +// +//------------------------------------------------------------------ +var Sprite1 = SpriteTestDemo.extend({ + _title:"Non Batched Sprite ", + _subtitle:"Tap screen to add more sprites", + + ctor:function () { + //----start0----ctor + this._super(); + + this.addNewSpriteWithCoords(cc.p(winSize.width / 2, winSize.height / 2)); + + if ('touches' in cc.sys.capabilities) { + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded: function(touches, event){ + for (var it = 0; it < touches.length; it++) { + var touch = touches[it]; + if (!touch) + break; + + var location = touch.getLocation(); + event.getCurrentTarget().addNewSpriteWithCoords(location); + } + } + }, this); + } else if ('mouse' in cc.sys.capabilities) + cc.eventManager.addListener({ + event: cc.EventListener.MOUSE, + onMouseUp: function(event){ + event.getCurrentTarget().addNewSpriteWithCoords(event.getLocation()); + } + }, this); + //----end0---- + }, + + addNewSpriteWithCoords:function (p) { + //----start0----addNewSpriteWithCoords + var idx = 0 | (Math.random() * 14); + var x = (idx % 5) * 85; + var y = (0 | (idx / 5)) * 121; + var sprite = new cc.Sprite(s_grossini_dance_atlas, cc.rect(x, y, 85, 121)); + this.addChild(sprite); + sprite.x = p.x; + sprite.y = p.y; + + var action; + var random = Math.random(); + if (random < 0.20) { + action = cc.scaleBy(3, 2); + } else if (random < 0.40) { + action = cc.rotateBy(3, 360); + } else if (random < 0.60) { + action = cc.blink(1, 3); + } else if (random < 0.8) { + action = cc.tintBy(2, 0, -255, -255); + } else { + action = cc.fadeOut(2); + } + + var action_back = action.reverse(); + var seq = cc.sequence(action, action_back); + + sprite.runAction(seq.repeatForever()); + this.testSprite = sprite; + //----end0---- + }, + // + // Automation + // + testDuration:1, + pixel:{"0":51, "1":0, "2":51, "3":255}, + testSprite:null, + setupAutomation:function () { + var fun = function () { + var sprite = new cc.Sprite(s_grossini_dance_atlas, cc.rect(0, 0, 85, 121)); + this.addChild(sprite, 999); + sprite.x = winSize.width / 2; + sprite.y = winSize.height / 2; + }; + this.scheduleOnce(fun, 0.5); + }, + getExpectedResult:function () { + var ret = {"useBatch":false, "pixel":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 2, winSize.height / 2, 5, 5); + var ret = {"useBatch":this.testSprite.getBatchNode() != null, "pixel":this.containsPixel(ret1, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteBatchNode1 +// +//------------------------------------------------------------------ +var SpriteBatchNode1 = SpriteTestDemo.extend({ + + _title:"Batched Sprite ", + _subtitle:"Tap screen to add more sprites", + + ctor:function () { + //----start1----ctor + this._super(); + if ('touches' in cc.sys.capabilities) { + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded: function (touches, event) { + for (var it = 0; it < touches.length; it++) { + var touch = touches[it]; + if (!touch) + break; + + var location = touch.getLocation(); + event.getCurrentTarget().addNewSpriteWithCoords(location); + } + } + }, this); + } else if ('mouse' in cc.sys.capabilities) + cc.eventManager.addListener({ + event: cc.EventListener.MOUSE, + onMouseUp: function(event){ + event.getCurrentTarget().addNewSpriteWithCoords(event.getLocation()); + } + }, this); + + var batchNode = new cc.SpriteBatchNode(s_grossini_dance_atlas, 50); + this.addChild(batchNode, 0, TAG_SPRITE_BATCH_NODE); + this.addNewSpriteWithCoords(cc.p(winSize.width / 2, winSize.height / 2)); + //----end1---- + }, + + addNewSpriteWithCoords:function (p) { + //----start1----addNewSpriteWithCoords + var batchNode = this.getChildByTag(TAG_SPRITE_BATCH_NODE); + + var idx = 0 | (Math.random() * 14); + var x = (idx % 5) * 85; + var y = (0 | (idx / 5)) * 121; + + var sprite = new cc.Sprite(batchNode.texture, cc.rect(x, y, 85, 121)); + batchNode.addChild(sprite); + + sprite.x = p.x; + + sprite.y = p.y; + + var action; + var random = Math.random(); + + if (random < 0.20) + action = cc.scaleBy(3, 2); + else if (random < 0.40) + action = cc.rotateBy(3, 360); + else if (random < 0.60) + action = cc.blink(1, 3); + else if (random < 0.8) + action = cc.tintBy(2, 0, -255, -255); + else + action = cc.fadeOut(2); + + var action_back = action.reverse(); + var seq = cc.sequence(action, action_back); + + sprite.runAction(seq.repeatForever()); + this.testSprite = sprite; + //----end1---- + }, + + // + // Automation + // + testDuration:1, + pixel:{"0":51, "1":0, "2":51, "3":255}, + testSprite:null, + setupAutomation:function () { + var fun = function () { + var sprite = new cc.Sprite(s_grossini_dance_atlas, cc.rect(0, 0, 85, 121)); + this.addChild(sprite, 999); + sprite.x = winSize.width / 2; + sprite.y = winSize.height / 2; + } + this.scheduleOnce(fun, 0.5); + }, + getExpectedResult:function () { + var ret = {"useBatch":true, "pixel":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 2, winSize.height / 2, 5, 5); + var ret = {"useBatch":this.testSprite.getBatchNode() != null, "pixel":this.containsPixel(ret1, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteColorOpacity +// +//------------------------------------------------------------------ +var SpriteColorOpacity = SpriteTestDemo.extend({ + + _title:"Sprite: Color & Opacity", + + ctor:function () { + //----start11----ctor + this._super(); + var sprite1 = new cc.Sprite(s_grossini_dance_atlas, cc.rect(0, 121, 85, 121)); + var sprite2 = new cc.Sprite(s_grossini_dance_atlas, cc.rect(85, 121, 85, 121)); + var sprite3 = new cc.Sprite(s_grossini_dance_atlas, cc.rect(85 * 2, 121, 85, 121)); + var sprite4 = new cc.Sprite(s_grossini_dance_atlas, cc.rect(85 * 3, 121, 85, 121)); + + var sprite5 = new cc.Sprite(s_grossini_dance_atlas, cc.rect(0, 121, 85, 121)); + var sprite6 = new cc.Sprite(s_grossini_dance_atlas, cc.rect(85, 121, 85, 121)); + var sprite7 = new cc.Sprite(s_grossini_dance_atlas, cc.rect(85 * 2, 121, 85, 121)); + var sprite8 = new cc.Sprite(s_grossini_dance_atlas, cc.rect(85 * 3, 121, 85, 121)); + + sprite1.x = (winSize.width / 5); + + sprite1.y = (winSize.height / 3); + sprite2.x = (winSize.width / 5) * 2; + sprite2.y = (winSize.height / 3); + sprite3.x = (winSize.width / 5) * 3; + sprite3.y = (winSize.height / 3); + sprite4.x = (winSize.width / 5) * 4; + sprite4.y = (winSize.height / 3); + sprite5.x = (winSize.width / 5); + sprite5.y = (winSize.height / 3) * 2; + sprite6.x = (winSize.width / 5) * 2; + sprite6.y = (winSize.height / 3) * 2; + sprite7.x = (winSize.width / 5) * 3; + sprite7.y = (winSize.height / 3) * 2; + sprite8.x = (winSize.width / 5) * 4; + sprite8.y = (winSize.height / 3) * 2; + + var delay = cc.delayTime(0.25); + var action = cc.fadeOut(2); + var action_back = action.reverse(); + var fade = cc.sequence(action, delay.clone(), action_back).repeatForever(); + + var tintRed = cc.tintBy(2, 0, -255, -255); + var tintRedBack = tintRed.reverse(); + var red = cc.sequence(tintRed, delay.clone(), tintRedBack).repeatForever(); + + var tintGreen = cc.tintBy(2, -255, 0, -255); + var tintGreenBack = tintGreen.reverse(); + var green = cc.sequence(tintGreen, delay.clone(), tintGreenBack).repeatForever(); + + var tintBlue = cc.tintBy(2, -255, -255, 0); + var tintBlueBack = tintBlue.reverse(); + var blue = cc.sequence(tintBlue, delay.clone(), tintBlueBack).repeatForever(); + + // late add: test dirtyColor and dirtyPosition + this.addChild(sprite1, 0, TAG_SPRITE1); + this.addChild(sprite2, 0, TAG_SPRITE2); + this.addChild(sprite3, 0, TAG_SPRITE3); + this.addChild(sprite4, 0, TAG_SPRITE4); + this.addChild(sprite5, 0, TAG_SPRITE5); + this.addChild(sprite6, 0, TAG_SPRITE6); + this.addChild(sprite7, 0, TAG_SPRITE7); + this.addChild(sprite8, 0, TAG_SPRITE8); + + sprite5.runAction(red); + sprite6.runAction(green); + sprite7.runAction(blue); + sprite8.runAction(fade); + + this.schedule(this.removeAndAddSprite, 2); + //----end11---- + }, + // this function test if remove and add works as expected: +// color array and vertex array should be reindexed + removeAndAddSprite:function (dt) { + //----start11----removeAndAddSprite + var sprite = this.getChildByTag(TAG_SPRITE5); + + this.removeChild(sprite, false); + this.addChild(sprite, 0, TAG_SPRITE5); + //----end11---- + }, + // + // Automation + // + testDuration:2.1, + pixel1:{"0":255, "1":0, "2":0, "3":255}, + pixel2:{"0":0, "1":204, "2":0, "3":255}, + pixel3:{"0":0, "1":0, "2":153, "3":255}, + pixel4:{"0":255, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes", "pixel4":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels((winSize.width / 5) * 1, (winSize.height / 3) * 2 + 40, 5, 5); + var ret2 = this.readPixels((winSize.width / 5) * 2, (winSize.height / 3) * 2 + 40, 5, 5); + var ret3 = this.readPixels((winSize.width / 5) * 3, (winSize.height / 3) * 2 + 40, 5, 5); + var ret4 = this.readPixels((winSize.width / 5) * 4, (winSize.height / 3) * 2 + 40, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2) ? "yes" : "no", + "pixel3":this.containsPixel(ret3, this.pixel3) ? "yes" : "no", + "pixel4":this.containsPixel(ret4, this.pixel4) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteBatchNodeColorOpacity +// +//------------------------------------------------------------------ +var SpriteBatchNodeColorOpacity = SpriteTestDemo.extend({ + + _title:"SpriteBatchNode: Color & Opacity", + + ctor:function () { + //----start12----ctor + this._super(); + // small capacity. Testing resizing. + // Don't use capacity=1 in your real game. It is expensive to resize the capacity + var batch = new cc.SpriteBatchNode(s_grossini_dance_atlas, 1); + this.addChild(batch, 0, TAG_SPRITE_BATCH_NODE); + + var sprite1 = new cc.Sprite(batch.texture, cc.rect(0, 121, 85, 121)); + var sprite2 = new cc.Sprite(batch.texture, cc.rect(85, 121, 85, 121)); + var sprite3 = new cc.Sprite(batch.texture, cc.rect(85 * 2, 121, 85, 121)); + var sprite4 = new cc.Sprite(batch.texture, cc.rect(85 * 3, 121, 85, 121)); + + var sprite5 = new cc.Sprite(batch.texture, cc.rect(0, 121, 85, 121)); + var sprite6 = new cc.Sprite(batch.texture, cc.rect(85, 121, 85, 121)); + var sprite7 = new cc.Sprite(batch.texture, cc.rect(85 * 2, 121, 85, 121)); + var sprite8 = new cc.Sprite(batch.texture, cc.rect(85 * 3, 121, 85, 121)); + + + sprite1.x = (winSize.width / 5) * 1; + sprite1.y = (winSize.height / 3) * 1; + sprite2.x = (winSize.width / 5) * 2; + sprite2.y = (winSize.height / 3) * 1; + sprite3.x = (winSize.width / 5) * 3; + sprite3.y = (winSize.height / 3) * 1; + sprite4.x = (winSize.width / 5) * 4; + sprite4.y = (winSize.height / 3) * 1; + sprite5.x = (winSize.width / 5) * 1; + sprite5.y = (winSize.height / 3) * 2; + sprite6.x = (winSize.width / 5) * 2; + sprite6.y = (winSize.height / 3) * 2; + sprite7.x = (winSize.width / 5) * 3; + sprite7.y = (winSize.height / 3) * 2; + sprite8.x = (winSize.width / 5) * 4; + sprite8.y = (winSize.height / 3) * 2; + + var delay = cc.delayTime(0.25); + var action = cc.fadeOut(2); + var action_back = action.reverse(); + var fade = cc.sequence(action, delay.clone(), action_back).repeatForever(); + + var tintRed = cc.tintBy(2, 0, -255, -255); + var red = cc.sequence(tintRed, delay.clone(), tintRed.reverse()).repeatForever(); + + var tintGreen = cc.tintBy(2, -255, 0, -255); + var tintGreenBack = tintGreen.reverse(); + var green = cc.sequence(tintGreen, delay.clone(), tintGreenBack).repeatForever(); + + var tintBlue = cc.tintBy(2, -255, -255, 0); + var tintBlueBack = tintBlue.reverse(); + var blue = cc.sequence(tintBlue, delay.clone(), tintBlueBack).repeatForever(); + + // late add: test dirtyColor and dirtyPosition + batch.addChild(sprite1, 0, TAG_SPRITE1); + batch.addChild(sprite2, 0, TAG_SPRITE2); + batch.addChild(sprite3, 0, TAG_SPRITE3); + batch.addChild(sprite4, 0, TAG_SPRITE4); + batch.addChild(sprite5, 0, TAG_SPRITE5); + batch.addChild(sprite6, 0, TAG_SPRITE6); + batch.addChild(sprite7, 0, TAG_SPRITE7); + batch.addChild(sprite8, 0, TAG_SPRITE8); + + sprite5.runAction(red); + sprite6.runAction(green); + sprite7.runAction(blue); + sprite8.runAction(fade); + + this.schedule(this.removeAndAddSprite, 2); + //----end12---- + }, + // this function test if remove and add works as expected: + // color array and vertex array should be reindexed + removeAndAddSprite:function (dt) { + //----start12----removeAndAddSprite + var batch = this.getChildByTag(TAG_SPRITE_BATCH_NODE); + var sprite = batch.getChildByTag(TAG_SPRITE5); + + batch.removeChild(sprite, false); + batch.addChild(sprite, 0, TAG_SPRITE5); + //----end12---- + }, + // + // Automation + // + testDuration:2.1, + pixel1:{"0":255, "1":0, "2":0, "3":255}, + pixel2:{"0":0, "1":204, "2":0, "3":255}, + pixel3:{"0":0, "1":0, "2":153, "3":255}, + pixel4:{"0":255, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes", "pixel4":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels((winSize.width / 5) * 1, (winSize.height / 3) * 2 + 40, 5, 5); + var ret2 = this.readPixels((winSize.width / 5) * 2, (winSize.height / 3) * 2 + 40, 5, 5); + var ret3 = this.readPixels((winSize.width / 5) * 3, (winSize.height / 3) * 2 + 40, 5, 5); + var ret4 = this.readPixels((winSize.width / 5) * 4, (winSize.height / 3) * 2 + 40, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2) ? "yes" : "no", + "pixel3":this.containsPixel(ret3, this.pixel3) ? "yes" : "no", + "pixel4":this.containsPixel(ret4, this.pixel4) ? "yes" : "no"}; + return JSON.stringify(ret); + } + +}); + +//------------------------------------------------------------------ +// +// SpriteZOrder +// +//------------------------------------------------------------------ +var SpriteZOrder = SpriteTestDemo.extend({ + _dir:0, + _title:"Sprite: Z order", + ctor:function () { + //----start13----ctor + this._super(); + this._dir = 1; + + var sprite; + var step = winSize.width / 11; + for (var i = 0; i < 5; i++) { + sprite = new cc.Sprite(s_grossini_dance_atlas, cc.rect(85 * 0, 121 * 1, 85, 121)); + sprite.x = (i + 1) * step; + sprite.y = winSize.height / 2; + this.addChild(sprite, i); + } + + for (i = 5; i < 10; i++) { + sprite = new cc.Sprite(s_grossini_dance_atlas, cc.rect(85 * 1, 121 * 0, 85, 121)); + sprite.x = (i + 1) * step; + sprite.y = winSize.height / 2; + this.addChild(sprite, 14 - i); + } + + sprite = new cc.Sprite(s_grossini_dance_atlas, cc.rect(85 * 3, 121 * 0, 85, 121)); + this.addChild(sprite, -1, TAG_SPRITE1); + sprite.x = winSize.width / 2; + sprite.y = winSize.height / 2 - 20; + sprite.scaleX = 10; + sprite.color = cc.color.RED; + + this.schedule(this.reorderSprite, 1); + //----end13---- + }, + reorderSprite:function (dt) { + //----start13----reorderSprite + var sprite = this.getChildByTag(TAG_SPRITE1); + var z = sprite.zIndex; + if (z < -1) + this._dir = 1; + if (z > 10) + this._dir = -1; + z += this._dir * 3; + this.reorderChild(sprite, z); + //----end13---- + }, + // + // Automation + // + testDuration:4.2, + pixel:{"0":255, "1":0, "2":0, "3":255}, + getExpectedResult:function () { + var ret = {"pixel":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var step = winSize.width / 11; + var ret1 = this.readPixels((6 + 1) * step, winSize.height / 2 + 10, 5, 5); + var ret = {"pixel":this.containsPixel(ret1, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteBatchNodeZOrder +// +//------------------------------------------------------------------ +var SpriteBatchNodeZOrder = SpriteTestDemo.extend({ + _dir:0, + _title:"SpriteBatch: Z order", + ctor:function () { + //----start14----ctor + this._super(); + this._dir = 1; + + // small capacity. Testing resizing. + // Don't use capacity=1 in your real game. It is expensive to resize the capacity + var batch = new cc.SpriteBatchNode(s_grossini_dance_atlas, 1); + this.addChild(batch, 0, TAG_SPRITE_BATCH_NODE); + + var sprite; + var step = winSize.width / 11; + for (var i = 0; i < 5; i++) { + sprite = new cc.Sprite(batch.texture, cc.rect(85 * 0, 121 * 1, 85, 121)); + sprite.x = (i + 1) * step; + sprite.y = winSize.height / 2; + batch.addChild(sprite, i); + } + + for (i = 5; i < 10; i++) { + sprite = new cc.Sprite(batch.texture, cc.rect(85 * 1, 121 * 0, 85, 121)); + sprite.x = (i + 1) * step; + sprite.y = winSize.height / 2; + batch.addChild(sprite, 14 - i); + } + + sprite = new cc.Sprite(batch.texture, cc.rect(85 * 3, 121 * 0, 85, 121)); + batch.addChild(sprite, -1, TAG_SPRITE1); + sprite.x = winSize.width / 2; + sprite.y = winSize.height / 2 - 20; + sprite.scaleX = 10; + sprite.color = cc.color.RED; + this.schedule(this.reorderSprite, 1); + //----end14---- + }, + reorderSprite:function (dt) { + //----start14----reorderSprite + var batch = this.getChildByTag(TAG_SPRITE_BATCH_NODE); + var sprite = batch.getChildByTag(TAG_SPRITE1); + var z = sprite.zIndex; + if (z < -1) + this._dir = 1; + if (z > 10) + this._dir = -1; + z += this._dir * 3; + batch.reorderChild(sprite, z); + //----end14---- + }, + // + // Automation + // + testDuration:4.2, + pixel:{"0":255, "1":0, "2":0, "3":255}, + getExpectedResult:function () { + var ret = {"pixel":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var step = winSize.width / 11; + var ret1 = this.readPixels((6 + 1) * step, winSize.height / 2 + 10, 5, 5); + var ret = {"pixel":this.containsPixel(ret1, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteBatchNodeReorder +// +//------------------------------------------------------------------ +var SpriteBatchNodeReorder = SpriteTestDemo.extend({ + + _title:"SpriteBatchNode: reorder #1", + _subtitle:"Should not crash", + + ctor:function () { + //----start15----ctor + this._super(); + var a = []; + var asmtest = new cc.SpriteBatchNode(s_ghosts); + + for (var i = 0; i < 10; i++) { + var s1 = new cc.Sprite(asmtest.texture, cc.rect(0, 0, 50, 50)); + a.push(s1); + asmtest.addChild(s1, 10); + } + + for (i = 0; i < 10; i++) { + if (i != 5) + asmtest.reorderChild(a[i], 9); + } + + var prev = -1, currentIndex; + var children = asmtest.children; + var child; + for (i = 0; i < children.length; i++) { + child = children[i]; + if (!child) + break; + + //TODO need fixed + currentIndex = child.atlasIndex; + //cc.Assert(prev == currentIndex - 1, "Child order failed"); + ////----UXLog("children %x - atlasIndex:%d", child, currentIndex); + prev = currentIndex; + } + + prev = -1; + var sChildren = asmtest.descendants; + for (i = 0; i < sChildren.length; i++) { + child = sChildren[i]; + if (!child) + break; + + currentIndex = child.atlasIndex; + //cc.Assert(prev == currentIndex - 1, "Child order failed"); + ////----UXLog("descendant %x - atlasIndex:%d", child, currentIndex); + prev = currentIndex; + } + //----end15---- + }, + // + // Automation + // + testDuration:1.2, + getExpectedResult:function () { + return JSON.stringify(true); + }, + getCurrentResult:function () { + return JSON.stringify(true); + } +}); + +//------------------------------------------------------------------ +// +// SpriteBatchNodeReorderIssue744 +// +//------------------------------------------------------------------ +var SpriteBatchNodeReorderIssue744 = SpriteTestDemo.extend({ + _title:"SpriteBatchNode: reorder issue #744", + _subtitle:"Should not crash", + + ctor:function () { + //----start16----ctor + this._super(); + + // Testing issue #744 + // http://code.google.com/p/cocos2d-iphone/issues/detail?id=744 + var batch = new cc.SpriteBatchNode(s_grossini_dance_atlas, 15); + this.addChild(batch, 0, TAG_SPRITE_BATCH_NODE); + + var sprite = new cc.Sprite(batch.texture, cc.rect(0, 0, 85, 121)); + sprite.x = winSize.width / 2; + sprite.y = winSize.height / 2; + batch.addChild(sprite, 3); + batch.reorderChild(sprite, 1); + //----end16---- + }, + // + // Automation + // + testDuration:1.2, + pixel:{"0":51, "1":0, "2":51, "3":255}, + getExpectedResult:function () { + var ret = {"pixel":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 2, winSize.height / 2, 5, 5); + var ret = {"pixel":this.containsPixel(ret1, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteBatchNodeReorderIssue766 +// +//------------------------------------------------------------------ +var SpriteBatchNodeReorderIssue766 = SpriteTestDemo.extend({ + _batchNode:null, + _sprite1:null, + _sprite2:null, + _sprite3:null, + + _title:"SpriteBatchNode: reorder issue #766", + _subtitle:"In 2 seconds 1 sprite will be reordered", + + ctor:function () { + //----start17----ctor + this._super(); + this._batchNode = new cc.SpriteBatchNode(s_piece, 15); + this.addChild(this._batchNode, 1, 0); + + this._sprite1 = this.makeSpriteZ(2); + this._sprite1.x = 200; + this._sprite1.y = 160; + + this._sprite2 = this.makeSpriteZ(3); + this._sprite2.x = 264; + this._sprite2.y = 160; + + this._sprite3 = this.makeSpriteZ(4); + this._sprite3.x = 328; + this._sprite3.y = 160; + + this.schedule(this.reorderSprite, 2); + //----end17---- + }, + reorderSprite:function (dt) { + //----start17----reorderSprite + this.unschedule(this.reorderSprite); + + this._batchNode.reorderChild(this._sprite1, 4); + //----end17---- + }, + makeSpriteZ:function (aZ) { + //----start17----makeSpriteZ + var sprite = new cc.Sprite(this._batchNode.texture, cc.rect(128, 0, 64, 64)); + this._batchNode.addChild(sprite, aZ + 1, 0); + + //children + var spriteShadow = new cc.Sprite(this._batchNode.texture, cc.rect(0, 0, 64, 64)); + spriteShadow.opacity = 128; + sprite.addChild(spriteShadow, aZ, 3); + + var spriteTop = new cc.Sprite(this._batchNode.texture, cc.rect(64, 0, 64, 64)); + sprite.addChild(spriteTop, aZ + 2, 3); + + return sprite; + //----end17---- + }, + // + // Automation + // + testDuration:2.2, + pixel1:{"0":0, "1":0, "2":0, "3":255}, + pixel2:{"0":255, "1":255, "2":255, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(213, 159, 5, 5); + var ret2 = this.readPixels(211, 108, 5, 5); + var ret = {"pixel1":!this.containsPixel(ret1, this.pixel1) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteBatchNodeReorderIssue767 +// +//------------------------------------------------------------------ +var SpriteBatchNodeReorderIssue767 = SpriteTestDemo.extend({ + _title:"SpriteBatchNode: reorder issue #767", + _subtitle:"Should not crash", + + ctor:function () { + //----start18----ctor + this._super(); + + spriteFrameCache.addSpriteFrames(s_ghostsPlist, s_ghosts); + // + // SpriteBatchNode: 3 levels of children + // + var aParent = new cc.SpriteBatchNode(s_ghosts); + this.addChild(aParent, 0, TAG_SPRITE1); + + // parent + var l1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("father.gif")); + l1.x = winSize.width / 2; + l1.y = winSize.height / 2; + aParent.addChild(l1, 0, TAG_SPRITE2); + var l1W = l1.width, l1H = l1.height; + + // child left + var l2a = new cc.Sprite(spriteFrameCache.getSpriteFrame("sister1.gif")); + l2a.x = -25 + l1W / 2; + l2a.y = 0 + l1H / 2; + l1.addChild(l2a, -1, TAG_SPRITE_LEFT); + var l2aW = l2a.width, l2aH = l2a.height; + + + // child right + var l2b = new cc.Sprite(spriteFrameCache.getSpriteFrame("sister2.gif")); + l2b.x = 25 + l1W / 2; + l2b.y = 0 + l1H / 2; + l1.addChild(l2b, 1, TAG_SPRITE_RIGHT); + var l2bW = l2b.width, l2bH = l2b.height; + + + // child left bottom + var l3a1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("child1.gif")); + l3a1.scale = 0.65; + l3a1.x = 0 + l2aW / 2; + l3a1.y = -50 + l2aH / 2; + l2a.addChild(l3a1, -1); + + // child left top + var l3a2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("child1.gif")); + l3a2.scale = 0.65; + l3a2.x = 0 + l2aW / 2; + l3a2.y = +50 + l2aH / 2; + l2a.addChild(l3a2, 1); + + // child right bottom + var l3b1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("child1.gif")); + l3b1.scale = 0.65; + l3b1.x = 0 + l2bW / 2; + l3b1.y = -50 + l2bH / 2; + l2b.addChild(l3b1, -1); + + // child right top + var l3b2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("child1.gif")); + l3b2.scale = 0.65; + l3b2.x = 0 + l2bW / 2; + l3b2.y = +50 + l2bH / 2; + l2b.addChild(l3b2, 1); + + this.schedule(this.reorderSprites, 1); + //----end18---- + }, + reorderSprites:function (dt) { + //----start18----reorderSprites + var spritebatch = this.getChildByTag(TAG_SPRITE1); + var father = spritebatch.getChildByTag(TAG_SPRITE2); + var left = father.getChildByTag(TAG_SPRITE_LEFT); + var right = father.getChildByTag(TAG_SPRITE_RIGHT); + + var newZLeft = 1; + + if (left.zIndex === 1) + newZLeft = -1; + + father.reorderChild(left, newZLeft); + father.reorderChild(right, -newZLeft); + //----end18---- + }, + // + // Automation + // + testDuration:1.5, + pixel1:{"0":255, "1":204, "2":153, "3":255}, + pixel2:{"0":255, "1":255, "2":255, "3":255}, + curPixel1:null, + curPixel2:null, + setupAutomation:function () { + var fun = function(){ + this.curPixel1 = this.readPixels(winSize.width / 2 + 11, winSize.height / 2 - 11, 2, 2); + } + this.scheduleOnce(fun, 0.5); + }, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + this.curPixel2 = this.readPixels(winSize.width / 2 + 11, winSize.height / 2 - 11, 2, 2); + var ret = {"pixel1":this.containsPixel(this.curPixel1, this.pixel1) ? "yes" : "no", + "pixel2":this.containsPixel(this.curPixel2, this.pixel2) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteZVertex +// +//------------------------------------------------------------------ +var SpriteZVertex = SpriteTestDemo.extend({ + _dir:0, + _time:0, + _title:"Sprite: openGL Z vertex", + _subtitle:"Scene should rotate", + + ctor:function () { + //----start19----ctor + this._super(cc.color(255, 0, 0, 80), cc.color(255, 98, 117, 20)); + + + if ("opengl" in cc.sys.capabilities) { + + gl.enable(gl.DEPTH_TEST); + // + // This test tests z-order + // If you are going to use it is better to use a 3D projection + // + // WARNING: + // The developer is resposible for ordering it's sprites according to it's Z if the sprite has + // transparent parts. + // + + // + // Configure shader to mimic glAlphaTest + // + var alphaTestShader = cc.shaderCache.getProgram("ShaderPositionTextureColorAlphaTest"); + var glprogram = alphaTestShader.getProgram(); + var alphaValueLocation = gl.getUniformLocation(glprogram, cc.UNIFORM_ALPHA_TEST_VALUE_S); + + // set alpha test value + // NOTE: alpha test shader is hard-coded to use the equivalent of a glAlphaFunc(GL_GREATER) comparison + gl.useProgram(glprogram); + alphaTestShader.setUniformLocationF32(alphaValueLocation, 0.5); + + this._dir = 1; + this._time = 0; + + var step = winSize.width / 12; + + var node = new cc.Node(); + // camera uses the center of the image as the pivoting point + node.width = winSize.width; + node.height = winSize.height; + node.anchorX = 0.5; + node.anchorY = 0.5; + node.x = winSize.width / 2; + node.y = winSize.height / 2; + + this.addChild(node, 0); + var sprite; + for (var i = 0; i < 5; i++) { + sprite = new cc.Sprite(s_grossini_dance_atlas, cc.rect(0, 121, 85, 121)); + sprite.x = (i + 1) * step; + sprite.y = winSize.height / 2; + sprite.vertexZ = 10 + i * 40; + sprite.shaderProgram = alphaTestShader; + node.addChild(sprite, 0); + } + + for (i = 5; i < 11; i++) { + sprite = new cc.Sprite(s_grossini_dance_atlas, cc.rect(85, 0, 85, 121)); + sprite.x = (i + 1) * step; + sprite.y = winSize.height / 2; + sprite.vertexZ = 10 + (10 - i) * 40; + sprite.shaderProgram = alphaTestShader; + node.addChild(sprite, 0); + } + + this.runAction(cc.orbitCamera(10, 1, 0, 0, 360, 0, 0)); + } else { + var label = new cc.LabelTTF("Not supported on HTML5-canvas", "Times New Roman", 30); + this.addChild(label); + label.x = winSize.width / 2; + label.y = winSize.height / 2; + } + //----end19---- + }, + onEnter:function () { + //----start19----onEnter + this._super(); + if ("opengl" in cc.sys.capabilities) { + director.setProjection(cc.Director.PROJECTION_3D); + gl.enable(gl.DEPTH_TEST); + + // Avoid Z-fighting with menu and title + var menu = this.getChildByTag(BASE_TEST_MENU_TAG); + menu.vertexZ = 1; + var title = this.getChildByTag(BASE_TEST_TITLE_TAG); + title.vertexZ = 1; + var subtitle = this.getChildByTag(BASE_TEST_SUBTITLE_TAG); + subtitle.vertexZ = 1; + } + //----end19---- + }, + onExit:function () { + //----start19----onExit + if ("opengl" in cc.sys.capabilities) { + director.setProjection(cc.Director.PROJECTION_2D); + gl.disable(gl.DEPTH_TEST); + } + this._super(); + //----end19---- + }, + // Automation + testDuration:2.2, + pixel1:{"0":51, "1":0, "2":51, "3":255}, + pixel2:{"0":0, "1":0, "2":0, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 2 - 171, winSize.height / 2, 5, 5); + var ret2 = this.readPixels(winSize.width / 2 - 189, winSize.height / 2, 5, 5); + var ret3 = this.readPixels(winSize.width / 2 - 146, winSize.height / 2, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1, false) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2, false) ? "yes" : "no", + "pixel3":this.containsPixel(ret3, this.pixel2, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteBatchNodeZVertex +// +//------------------------------------------------------------------ +var SpriteBatchNodeZVertex = SpriteTestDemo.extend({ + _dir:0, + _time:0, + _title:"SpriteBatchNode: openGL Z vertex", + _subtitle:"Scene should rotate", + + ctor:function () { + //----start20----ctor + this._super(cc.color(255, 0, 0, 80), cc.color(255, 98, 117, 20)); + + if ("opengl" in cc.sys.capabilities) { + + // + // This test tests z-order + // If you are going to use it is better to use a 3D projection + // + // WARNING: + // The developer is resposible for ordering it's sprites according to it's Z if the sprite has + // transparent parts. + // + + // + // Configure shader to mimic glAlphaTest + // + var alphaTestShader = cc.shaderCache.getProgram("ShaderPositionTextureColorAlphaTest"); + var glprogram = alphaTestShader.getProgram(); + var alphaValueLocation = gl.getUniformLocation(glprogram, cc.UNIFORM_ALPHA_TEST_VALUE_S); + + // set alpha test value + // NOTE: alpha test shader is hard-coded to use the equivalent of a glAlphaFunc(GL_GREATER) comparison + gl.useProgram(glprogram); + alphaTestShader.setUniformLocationF32(alphaValueLocation, 0.5); + + var step = winSize.width / 12; + + // small capacity. Testing resizing. + // Don't use capacity=1 in your real game. It is expensive to resize the capacity + var batch = new cc.SpriteBatchNode(s_grossini_dance_atlas, 1); + // camera uses the center of the image as the pivoting point + batch.width = winSize.width; + batch.height = winSize.height; + batch.anchorX = 0.5; + batch.anchorY = 0.5; + batch.x = winSize.width / 2; + batch.y = winSize.height / 2; + batch.shaderProgram = alphaTestShader; + + this.addChild(batch, 0, TAG_SPRITE_BATCH_NODE); + var sprite; + + for (var i = 0; i < 5; i++) { + sprite = new cc.Sprite(batch.texture, cc.rect(0, 121, 85, 121)); + sprite.x = (i + 1) * step; + sprite.y = winSize.height / 2; + sprite.vertexZ = 10 + i * 40; + batch.addChild(sprite, 0); + + } + + for (i = 5; i < 11; i++) { + sprite = new cc.Sprite(batch.texture, cc.rect(85, 0, 85, 121)); + sprite.x = (i + 1) * step; + sprite.y = winSize.height / 2; + sprite.vertexZ = 10 + (10 - i) * 40; + batch.addChild(sprite, 0); + } + + this.runAction(cc.orbitCamera(10, 1, 0, 0, 360, 0, 0)); + } else { + var label = new cc.LabelTTF("Not supported on HTML5-canvas", "Times New Roman", 30); + this.addChild(label); + label.x = winSize.width / 2; + label.y = winSize.height / 2; + } + //----end20---- + }, + onEnter:function () { + //----start20----onEnter + this._super(); + + if ("opengl" in cc.sys.capabilities) { + director.setProjection(cc.Director.PROJECTION_3D); + gl.enable(gl.DEPTH_TEST); + + // Avoid Z-fighting with menu and title + var menu = this.getChildByTag(BASE_TEST_MENU_TAG); + menu.vertexZ = 1; + var title = this.getChildByTag(BASE_TEST_TITLE_TAG); + title.vertexZ = 1; + var subtitle = this.getChildByTag(BASE_TEST_SUBTITLE_TAG); + subtitle.vertexZ = 1; + + } + //----end20---- + }, + onExit:function () { + //----start20----onExit + if ("opengl" in cc.sys.capabilities) { + director.setProjection(cc.Director.PROJECTION_2D); + gl.disable(gl.DEPTH_TEST); + } + this._super(); + //----end20---- + }, + // Automation + testDuration:2.2, + pixel1:{"0":51, "1":0, "2":51, "3":255}, + pixel2:{"0":0, "1":0, "2":0, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 2 - 171, winSize.height / 2, 5, 5); + var ret2 = this.readPixels(winSize.width / 2 - 189, winSize.height / 2, 5, 5); + var ret3 = this.readPixels(winSize.width / 2 - 146, winSize.height / 2, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1, false) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2, false) ? "yes" : "no", + "pixel3":this.containsPixel(ret3, this.pixel2, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteAnchorPoint +// +//------------------------------------------------------------------ +var SpriteAnchorPoint = SpriteTestDemo.extend({ + _title:"Sprite: anchor point", + + ctor:function () { + //----start4----ctor + this._super(); + + for (var i = 0; i < 3; i++) { + var rotate = cc.rotateBy(10, 360); + var action = rotate.repeatForever(); + var sprite = new cc.Sprite(s_grossini_dance_atlas, cc.rect(85 * i, 121, 85, 121)); + sprite.x = winSize.width / 4 * (i + 1); + sprite.y = winSize.height / 2; + + var point = new cc.Sprite(s_pathR1); + point.scale = 0.25; + point.x = sprite.x; + point.y = sprite.y; + this.addChild(point, 10); + + switch (i) { + case 0: + sprite.anchorX = 0; + sprite.anchorY = 0; + break; + case 1: + sprite.anchorX = 0.5; + sprite.anchorY = 0.5; + break; + case 2: + sprite.anchorX = 1; + sprite.anchorY = 1; + break; + } + + point.x = sprite.x; + + point.y = sprite.y; + + //var copy = action.clone(); + sprite.runAction(action); + this.addChild(sprite, i); + } + //----end4---- + }, + // + // Automation + // + testDuration:0.15, + pixel:{"0":255, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 4 + 45, winSize.height / 2 + 104, 5, 5); + var ret2 = this.readPixels(winSize.width / 4 * 2 - 3, winSize.height / 2 + 44, 5, 5); + var ret3 = this.readPixels(winSize.width / 4 * 3 - 44, winSize.height / 2 - 16, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel) ? "yes" : "no", "pixel2":this.containsPixel(ret2, this.pixel) ? "yes" : "no", "pixel3":this.containsPixel(ret3, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteBatchNodeAnchorPoint +// +//------------------------------------------------------------------ +var SpriteBatchNodeAnchorPoint = SpriteTestDemo.extend({ + _title:"SpriteBatchNode: anchor point", + + ctor:function () { + //----start5----ctor + this._super(); + // small capacity. Testing resizing. + // Don't use capacity=1 in your real game. It is expensive to resize the capacity + var batch = new cc.SpriteBatchNode(s_grossini_dance_atlas, 1); + this.addChild(batch, 0, TAG_SPRITE_BATCH_NODE); + + for (var i = 0; i < 3; i++) { + var rotate = cc.rotateBy(10, 360); + var action = rotate.repeatForever(); + var sprite = new cc.Sprite(batch.texture, cc.rect(85 * i, 121, 85, 121)); + sprite.x = winSize.width / 4 * (i + 1); + sprite.y = winSize.height / 2; + + var point = new cc.Sprite(s_pathR1); + point.scale = 0.25; + point.x = sprite.x; + point.y = sprite.y; + this.addChild(point, 1); + + switch (i) { + case 0: + sprite.anchorX = 0; + sprite.anchorY = 0; + break; + case 1: + sprite.anchorX = 0.5; + sprite.anchorY = 0.5; + break; + case 2: + sprite.anchorX = 1; + sprite.anchorY = 1; + break; + } + + point.x = sprite.x; + + point.y = sprite.y; + sprite.runAction(action); + batch.addChild(sprite, i); + } + //----end5---- + }, + // + // Automation + // + testDuration:0.15, + pixel:{"0":255, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 4 + 45, winSize.height / 2 + 104, 5, 5); + var ret2 = this.readPixels(winSize.width / 4 * 2 - 3, winSize.height / 2 + 44, 5, 5); + var ret3 = this.readPixels(winSize.width / 4 * 3 - 44, winSize.height / 2 - 16, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel) ? "yes" : "no", "pixel2":this.containsPixel(ret2, this.pixel) ? "yes" : "no", "pixel3":this.containsPixel(ret3, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// Sprite6 +// +//------------------------------------------------------------------ +var Sprite6 = SpriteTestDemo.extend({ + _title:"SpriteBatchNode transformation", + + ctor:function () { + //----start21----ctor + this._super(); + // small capacity. Testing resizing + // Don't use capacity=1 in your real game. It is expensive to resize the capacity + var batch = new cc.SpriteBatchNode(s_grossini_dance_atlas, 1); + this.addChild(batch, 0, TAG_SPRITE_BATCH_NODE); + batch.ignoreAnchorPointForPosition(true); + + batch.anchorX = 0.5; + + batch.anchorY = 0.5; + batch.width = winSize.width; + batch.height = winSize.height; + + // SpriteBatchNode actions + var rotate1 = cc.rotateBy(5, 360); + var rotate_back = rotate1.reverse(); + var rotate_seq = cc.sequence(rotate1, rotate_back); + var rotate_forever = rotate_seq.repeatForever(); + + var scale = cc.scaleBy(5, 1.5); + var scale_back = scale.reverse(); + var scale_seq = cc.sequence(scale, scale_back); + var scale_forever = scale_seq.repeatForever(); + + for (var i = 0; i < 3; i++) { + var sprite = new cc.Sprite(batch.texture, cc.rect(85 * i, 121, 85, 121)); + switch (i) { + case 0: + sprite.x = winSize.width / 2 - 100; + sprite.y = winSize.height / 2; + break; + case 1: + sprite.x = winSize.width / 2; + sprite.y = winSize.height / 2; + break; + case 2: + sprite.x = winSize.width / 2 + 100; + sprite.y = winSize.height / 2; + break; + } + var rotate = cc.rotateBy(5, 360); + var action = rotate.repeatForever(); + sprite.runAction(action.clone()); + batch.addChild(sprite, i); + } + + batch.runAction(scale_forever); + batch.runAction(rotate_forever); + //----end21---- + }, + // Automation + testDuration:2, + pixel:{"0":255, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 2 + 111, winSize.height / 2 + 82, 5, 5); + var ret2 = this.readPixels(winSize.width / 2 - 148, winSize.height / 2 - 58, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel, false) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteFlip +// +//------------------------------------------------------------------ +var SpriteFlip = SpriteTestDemo.extend({ + _title:"Sprite Flip X & Y", + + ctor:function () { + //----start22----ctor + this._super(); + var sprite1 = new cc.Sprite(s_grossini_dance_atlas, cc.rect(85, 121, 85, 121)); + sprite1.x = winSize.width / 2 - 100; + sprite1.y = winSize.height / 2; + this.addChild(sprite1, 0, TAG_SPRITE1); + + var sprite2 = new cc.Sprite(s_grossini_dance_atlas, cc.rect(85, 121, 85, 121)); + sprite2.x = winSize.width / 2 + 100; + sprite2.y = winSize.height / 2; + this.addChild(sprite2, 0, TAG_SPRITE2); + + this.schedule(this.onFlipSprites, 1); + //----end22---- + }, + onFlipSprites:function (dt) { + //----start22----onFlipSprites + var sprite1 = this.getChildByTag(TAG_SPRITE1); + var sprite2 = this.getChildByTag(TAG_SPRITE2); + + sprite1.flippedX = !sprite1.flippedX; + sprite2.flippedY = !sprite2.flippedY; + //----end22---- + }, + // + // Automation + // + testDuration:1.5, + pixel:{"0":255, "1":204, "2":153, "3":255}, + pixel1:null, + pixel2:null, + pixel3:null, + pixel4:null, + setupAutomation:function () { + this.scheduleOnce(this.getBeforePixel, 0.5); + }, + getBeforePixel:function () { + this.pixel1 = this.readPixels(winSize.width / 2 - 131, winSize.height / 2 - 11, 5, 5); + this.pixel2 = this.readPixels(winSize.width / 2 + 100, winSize.height / 2 + 44, 5, 5); + }, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes", "pixel4":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + this.pixel3 = this.readPixels(winSize.width / 2 - 69, winSize.height / 2 - 11, 5, 5); + this.pixel4 = this.readPixels(winSize.width / 2 + 100, winSize.height / 2 - 44, 5, 5); + var ret = {"pixel1":this.containsPixel(this.pixel1, this.pixel) ? "yes" : "no", + "pixel2":this.containsPixel(this.pixel2, this.pixel) ? "yes" : "no", + "pixel3":this.containsPixel(this.pixel3, this.pixel) ? "yes" : "no", + "pixel4":this.containsPixel(this.pixel4, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteBatchNodeFlip +// +//------------------------------------------------------------------ +var SpriteBatchNodeFlip = SpriteTestDemo.extend({ + _title:"SpriteBatchNode Flip X & Y", + + ctor:function () { + //----start23----ctor + this._super(); + var batch = new cc.SpriteBatchNode(s_grossini_dance_atlas, 10); + this.addChild(batch, 0, TAG_SPRITE_BATCH_NODE); + + var sprite1 = new cc.Sprite(batch.texture, cc.rect(85, 121, 85, 121)); + sprite1.x = winSize.width / 2 - 100; + sprite1.y = winSize.height / 2; + batch.addChild(sprite1, 0, TAG_SPRITE1); + + var sprite2 = new cc.Sprite(batch.texture, cc.rect(85, 121, 85, 121)); + sprite2.x = winSize.width / 2 + 100; + sprite2.y = winSize.height / 2; + batch.addChild(sprite2, 0, TAG_SPRITE2); + + this.schedule(this.onFlipSprites, 1); + //----end23---- + }, + onFlipSprites:function (dt) { + //----start23----onFlipSprites + var batch = this.getChildByTag(TAG_SPRITE_BATCH_NODE); + var sprite1 = batch.getChildByTag(TAG_SPRITE1); + var sprite2 = batch.getChildByTag(TAG_SPRITE2); + + sprite1.flippedX = !sprite1.flippedX; + sprite2.flippedY = !sprite2.flippedY; + //----end23---- + }, + // + // Automation + // + testDuration:1.5, + pixel:{"0":255, "1":204, "2":153, "3":255}, + pixel1:null, + pixel2:null, + pixel3:null, + pixel4:null, + setupAutomation:function () { + this.scheduleOnce(this.getBeforePixel, 0.5); + }, + getBeforePixel:function () { + this.pixel1 = this.readPixels(winSize.width / 2 - 131, winSize.height / 2 - 11, 5, 5); + this.pixel2 = this.readPixels(winSize.width / 2 + 100, winSize.height / 2 + 44, 5, 5); + }, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes", "pixel4":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + this.pixel3 = this.readPixels(winSize.width / 2 - 69, winSize.height / 2 - 11, 5, 5); + this.pixel4 = this.readPixels(winSize.width / 2 + 100, winSize.height / 2 - 44, 5, 5); + var ret = {"pixel1":this.containsPixel(this.pixel1, this.pixel) ? "yes" : "no", + "pixel2":this.containsPixel(this.pixel2, this.pixel) ? "yes" : "no", + "pixel3":this.containsPixel(this.pixel3, this.pixel) ? "yes" : "no", + "pixel4":this.containsPixel(this.pixel4, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteAliased +// +//------------------------------------------------------------------ +var SpriteAliased = SpriteTestDemo.extend({ + _title:"Sprite Aliased", + _subtitle:"You should see pixelated sprites", + + ctor:function () { + //----start24----ctor + this._super(); + var sprite1 = new cc.Sprite(s_grossini_dance_atlas, cc.rect(85, 121, 85, 121)); + sprite1.x = winSize.width / 2 - 100; + sprite1.y = winSize.height / 2; + this.addChild(sprite1, 0, TAG_SPRITE1); + + var sprite2 = new cc.Sprite(s_grossini_dance_atlas, cc.rect(85, 121, 85, 121)); + sprite2.x = winSize.width / 2 + 100; + sprite2.y = winSize.height / 2; + this.addChild(sprite2, 0, TAG_SPRITE2); + + var scale = cc.scaleBy(2, 5); + var scale_back = scale.reverse(); + var seq = cc.sequence(scale, scale_back); + var repeat = seq.repeatForever(); + + var scale2 = cc.scaleBy(2, 5); + var scale_back2 = scale2.reverse(); + var seq2 = cc.sequence(scale2, scale_back2); + var repeat2 = seq2.repeatForever(); + + sprite1.runAction(repeat); + sprite2.runAction(repeat2); + //----end24---- + }, + onEnter:function () { + //----start24----onEnter + this._super(); + // + // IMPORTANT: + // This change will affect every sprite that uses the same texture + // So sprite1 and sprite2 will be affected by this change + // + if (!cc.sys.isNative && !("opengl" in cc.sys.capabilities)) { + var label = new cc.LabelTTF("Not supported on HTML5-canvas", "Times New Roman", 30); + this.addChild(label); + label.x = winSize.width / 2; + label.y = winSize.height / 2; + } else { + var sprite = this.getChildByTag(TAG_SPRITE1); + sprite.texture.setAliasTexParameters(); + } + + //----end24---- + }, + onExit:function () { + //----start24----onExit + if (cc.sys.isNative || ("opengl" in cc.sys.capabilities)) { + var sprite = this.getChildByTag(TAG_SPRITE1); + sprite.texture.setAntiAliasTexParameters(); + } + this._super(); + //----end24---- + } +}); + +//------------------------------------------------------------------ +// +// SpriteBatchNodeAliased +// +//------------------------------------------------------------------ +var SpriteBatchNodeAliased = SpriteTestDemo.extend({ + _title:"SpriteBatchNode Aliased", + _subtitle:"You should see pixelated sprites", + + ctor:function () { + //----start25----ctor + this._super(); + var batch = new cc.SpriteBatchNode(s_grossini_dance_atlas, 10); + this.addChild(batch, 0, TAG_SPRITE_BATCH_NODE); + + var sprite1 = new cc.Sprite(batch.texture, cc.rect(85, 121, 85, 121)); + sprite1.x = winSize.width / 2 - 100; + sprite1.y = winSize.height / 2; + batch.addChild(sprite1, 0, TAG_SPRITE1); + + var sprite2 = new cc.Sprite(batch.texture, cc.rect(85, 121, 85, 121)); + sprite2.x = winSize.width / 2 + 100; + sprite2.y = winSize.height / 2; + batch.addChild(sprite2, 0, TAG_SPRITE2); + + var scale = cc.scaleBy(2, 5); + var scale_back = scale.reverse(); + var seq = cc.sequence(scale, scale_back); + var repeat = seq.repeatForever(); + + var scale2 = cc.scaleBy(2, 5); + var scale_back2 = scale2.reverse(); + var seq2 = cc.sequence(scale2, scale_back2); + var repeat2 = seq2.repeatForever(); + + sprite1.runAction(repeat); + sprite2.runAction(repeat2); + //----end25---- + }, + onEnter:function () { + //----start25----onEnter + this._super(); + // + // IMPORTANT: + // This change will affect every sprite that uses the same texture + // So sprite1 and sprite2 will be affected by this change + // + if (!cc.sys.isNative && !("opengl" in cc.sys.capabilities)) { + var label = new cc.LabelTTF("Not supported on HTML5-canvas", "Times New Roman", 30); + this.addChild(label); + label.x = winSize.width / 2; + label.y = winSize.height / 2; + } else { + var sprite = this.getChildByTag(TAG_SPRITE_BATCH_NODE); + sprite.texture.setAliasTexParameters(); + } + //----end25---- + + }, + onExit:function () { + //----start25----onExit + if (cc.sys.isNative || ("opengl" in cc.sys.capabilities)) { + var sprite = this.getChildByTag(TAG_SPRITE_BATCH_NODE); + sprite.texture.setAntiAliasTexParameters(); + } + this._super(); + //----end25---- + } +}); + +//------------------------------------------------------------------ +// +// SpriteNewTexture +// +//------------------------------------------------------------------ +var SpriteNewTexture = SpriteTestDemo.extend({ + _usingTexture1:false, + _texture1:null, + _texture2:null, + _title:"Sprite New texture (tap)", + + ctor:function () { + //----start26----ctor + this._super(); + + if ('touches' in cc.sys.capabilities){ + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded:function (touches, event) { + event.getCurrentTarget().onChangeTexture(); + } + }, this); + } else if ('mouse' in cc.sys.capabilities) + cc.eventManager.addListener({ + event: cc.EventListener.MOUSE, + onMouseUp: function(event){ + event.getCurrentTarget().onChangeTexture(); + } + }, this); + + var node = new cc.Node(); + this.addChild(node, 0, TAG_SPRITE_BATCH_NODE); + + this._texture1 = cc.textureCache.addImage(s_grossini_dance_atlas); + this._texture2 = cc.textureCache.addImage(s_grossini_dance_atlas_mono); + + this._usingTexture1 = true; + + for (var i = 0; i < 30; i++) { + this.addNewSprite(); + } + //----end26---- + }, + + addNewSprite:function () { + //----start26----addNewSprite + var p = cc.p(Math.random() * winSize.width, Math.random() * winSize.height); + + var idx = 0 | (Math.random() * 14); + var x = (idx % 5) * 85; + var y = (0 | (idx / 5)) * 121; + + + var node = this.getChildByTag(TAG_SPRITE_BATCH_NODE); + var sprite = new cc.Sprite(this._texture1, cc.rect(x, y, 85, 121)); + node.addChild(sprite); + + sprite.x = p.x; + + sprite.y = p.y; + + var action; + var random = Math.random(); + + if (random < 0.20) + action = cc.scaleBy(3, 2); + else if (random < 0.40) + action = cc.rotateBy(3, 360); + else if (random < 0.60) + action = cc.blink(1, 3); + // else if (random < 0.8) + // action = cc.tintBy(2, 0, -255, -255); + else + action = cc.fadeOut(2); + + var action_back = action.reverse(); + var seq = cc.sequence(action, action_back); + + sprite.runAction(seq.repeatForever()); + //----end26---- + }, + + onChangeTexture:function () { + //----start26----onChangeTexture + var node = this.getChildByTag(TAG_SPRITE_BATCH_NODE); + var children = node.children, sprite, i; + + if (this._usingTexture1) { //-. win32 : Let's it make just simple sentence + for (i = 0; i < children.length; i++) { + sprite = children[i]; + if (!sprite) + break; + sprite.texture = this._texture2; + } + this._usingTexture1 = false; + } else { + for (i = 0; i < children.length; i++) { + sprite = children[i]; + if (!sprite) + break; + sprite.texture = this._texture1; + } + this._usingTexture1 = true; + } + //----end26---- + }, + + // + // Automation + // + testDuration:1, + pixel:{"0":51, "1":0, "2":51, "3":255}, + setupAutomation:function () { + this.scheduleOnce(this.addTestSprite, 0.5); + }, + addTestSprite:function () { + var node = this.getChildByTag(TAG_SPRITE_BATCH_NODE); + var sprite = new cc.Sprite(this._texture1, cc.rect(0, 0, 85, 121)); + sprite.x = winSize.width / 2; + sprite.y = winSize.height / 2; + node.addChild(sprite); + }, + getExpectedResult:function () { + var ret = {"pixel":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 2, winSize.height / 2, 5, 5); + var ret = {"pixel":this.containsPixel(ret1, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteBatchNodeNewTexture +// +//------------------------------------------------------------------ +var SpriteBatchNodeNewTexture = SpriteTestDemo.extend({ + _texture1:null, + _texture2:null, + _title:"SpriteBatchNode new texture (tap)", + + ctor:function () { + //----start27----ctor + this._super(); + if ('touches' in cc.sys.capabilities){ + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded:function (touches, event) { + event.getCurrentTarget().onChangeTexture(); + } + }, this); + } else if ('mouse' in cc.sys.capabilities) + cc.eventManager.addListener({ + event: cc.EventListener.MOUSE, + onMouseUp: function(event){ + event.getCurrentTarget().onChangeTexture(); + } + }, this); + + var batch = new cc.SpriteBatchNode(s_grossini_dance_atlas, 50); + this.addChild(batch, 0, TAG_SPRITE_BATCH_NODE); + + this._texture1 = batch.texture; + this._texture2 = cc.textureCache.addImage(s_grossini_dance_atlas_mono); + + for (var i = 0; i < 30; i++) { + this.addNewSprite(); + } + //----end27---- + }, + addNewSprite:function () { + //----start27----addNewSprite + var s = winSize; + + var p = cc.p(Math.random() * winSize.width, Math.random() * winSize.height); + + var batch = this.getChildByTag(TAG_SPRITE_BATCH_NODE); + + var idx = 0 | (Math.random() * 14); + var x = (idx % 5) * 85; + var y = (0 | (idx / 5)) * 121; + + var sprite = new cc.Sprite(batch.texture, cc.rect(x, y, 85, 121)); + batch.addChild(sprite); + + sprite.x = p.x; + + sprite.y = p.y; + + var action; + var random = Math.random(); + + if (random < 0.20) + action = cc.scaleBy(3, 2); + else if (random < 0.40) + action = cc.rotateBy(3, 360); + else if (random < 0.60) + action = cc.blink(1, 3); + //else if (random < 0.8) + // action = cc.tintBy(2, 0, -255, -255); + else + action = cc.fadeOut(2); + var action_back = action.reverse(); + var seq = cc.sequence(action, action_back); + + sprite.runAction(seq.repeatForever()); + //----end27---- + }, + onChangeTexture:function () { + //----start27----onChangeTexture + var batch = this.getChildByTag(TAG_SPRITE_BATCH_NODE); + + if (batch.texture == this._texture1) + batch.texture = this._texture2; + else + batch.texture = this._texture1; + //----end27---- + }, + + // + // Automation + // + testDuration:1, + pixel:{"0":51, "1":0, "2":51, "3":255}, + setupAutomation:function () { + this.scheduleOnce(this.addTestSprite, 0.5); + }, + addTestSprite:function () { + var node = this.getChildByTag(TAG_SPRITE_BATCH_NODE); + var sprite = new cc.Sprite(this._texture1, cc.rect(0, 0, 85, 121)); + sprite.x = winSize.width / 2; + sprite.y = winSize.height / 2; + node.addChild(sprite); + }, + getExpectedResult:function () { + var ret = {"pixel":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 2, winSize.height / 2, 5, 5); + var ret = {"pixel":this.containsPixel(ret1, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteFrameTest +// +//------------------------------------------------------------------ +var SpriteFrameTest = SpriteTestDemo.extend({ + _sprite1:null, + _sprite2:null, + _counter:0, + _title:"Sprite vs. SpriteBatchNode animation", + _subtitle:"Testing issue #792", + + onEnter:function () { + //----start2----onEnter + this._super(); + // IMPORTANT: + // The sprite frames will be cached AND RETAINED, and they won't be released unless you call + // cc.spriteFrameCache.removeUnusedSpriteFrames); + spriteFrameCache.addSpriteFrames(s_grossiniPlist); + spriteFrameCache.addSpriteFrames(s_grossini_grayPlist, s_grossini_gray); + spriteFrameCache.addSpriteFrames(s_grossini_bluePlist, s_grossini_blue); + + // + // Animation using Sprite BatchNode + // + this._sprite1 = new cc.Sprite("#grossini_dance_01.png"); + this._sprite1.x = winSize.width / 2 - 80; + this._sprite1.y = winSize.height / 2; + + var spritebatch = new cc.SpriteBatchNode(s_grossini); + spritebatch.addChild(this._sprite1); + this.addChild(spritebatch); + + var animFrames = []; + var str = ""; + var frame; + for (var i = 1; i < 15; i++) { + str = "grossini_dance_" + (i < 10 ? ("0" + i) : i) + ".png"; + frame = spriteFrameCache.getSpriteFrame(str); + animFrames.push(frame); + } + + var animation = new cc.Animation(animFrames, 0.3); + this._sprite1.runAction(cc.animate(animation).repeatForever()); + + // to test issue #732, uncomment the following line + this._sprite1.flippedX = false; + this._sprite1.flippedY = false; + + // + // Animation using standard Sprite + // + this._sprite2 = new cc.Sprite("#grossini_dance_01.png"); + this._sprite2.x = winSize.width / 2 + 80; + this._sprite2.y = winSize.height / 2; + this.addChild(this._sprite2); + + var moreFrames = []; + for (i = 1; i < 15; i++) { + str = "grossini_dance_gray_" + (i < 10 ? ("0" + i) : i) + ".png"; + frame = spriteFrameCache.getSpriteFrame(str); + moreFrames.push(frame); + } + + for (i = 1; i < 5; i++) { + str = "grossini_blue_0" + i + ".png"; + frame = spriteFrameCache.getSpriteFrame(str); + moreFrames.push(frame); + } + + // append frames from another batch + moreFrames = moreFrames.concat(animFrames); + var animMixed = new cc.Animation(moreFrames, 0.3); + + this._sprite2.runAction(cc.animate(animMixed).repeatForever()); + + // to test issue #732, uncomment the following line + this._sprite2.flippedX = false; + this._sprite2.flippedY = false; + + this.schedule(this.onStartIn05Secs, 0.5); + this._counter = 0; + //----end2---- + }, + onExit:function () { + //----start2----onExit + this._super(); + spriteFrameCache.removeSpriteFramesFromFile(s_grossiniPlist); + spriteFrameCache.removeSpriteFramesFromFile(s_grossini_grayPlist); + spriteFrameCache.removeSpriteFramesFromFile(s_grossini_bluePlist); + //----end2---- + }, + onStartIn05Secs:function () { + //----start2----onStartIn05Secs + this.unschedule(this.onStartIn05Secs); + this.schedule(this.onFlipSprites, 1.0); + //----end2---- + }, + onFlipSprites:function (dt) { + //----start2----onFlipSprites + this._counter++; + + var fx = false; + var fy = false; + var i = this._counter % 4; + + switch (i) { + case 0: + fx = false; + fy = false; + break; + case 1: + fx = true; + fy = false; + break; + case 2: + fx = false; + fy = true; + break; + case 3: + fx = true; + fy = true; + break; + } + + this._sprite1.flippedX = fx; + this._sprite1.flippedY = fy; + this._sprite2.flippedX = fx; + this._sprite2.flippedY = fy; + //----end2---- + }, + // + // Automation + // + testDuration:3.1, + pixel1:{"0":255, "1":204, "2":153, "3":255}, + pixel2:{"0":255, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 2 - 50, winSize.height / 2 + 8, 5, 5); + var ret2 = this.readPixels(winSize.width / 2 - 80, winSize.height / 2 - 42, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteFrameAliasNameTest +// +//------------------------------------------------------------------ +var SpriteFrameAliasNameTest = SpriteTestDemo.extend({ + _title:"SpriteFrame Alias Name", + _subtitle:"SpriteFrames are obtained using the alias name", + onEnter:function (){ + //----start3----onEnter + this._super(); + // IMPORTANT: + // The sprite frames will be cached AND RETAINED, and they won't be released unless you call + // + // cc.SpriteFrameCache is a cache of cc.SpriteFrames + // cc.SpriteFrames each contain a texture id and a rect (frame). + spriteFrameCache.addSpriteFrames(s_grossini_aliasesPlist, s_grossini_aliases); + + // + // Animation using Sprite batch + // + // A cc.SpriteBatchNode can reference one and only one texture (one .png file) + // Sprites that are contained in that texture can be instantiatied as cc.Sprites and then added to the cc.SpriteBatchNode + // All cc.Sprites added to a cc.SpriteBatchNode are drawn in one OpenGL ES draw call + // If the cc.Sprites are not added to a cc.SpriteBatchNode then an OpenGL ES draw call will be needed for each one, which is less efficient + // + // When you animate a sprite, CCAnimation changes the frame of the sprite using setDisplayFrame: (this is why the animation must be in the same texture) + // When setDisplayFrame: is used in the CCAnimation it changes the frame to one specified by the cc.SpriteFrames that were added to the animation, + // but texture id is still the same and so the sprite is still a child of the cc.SpriteBatchNode, + // and therefore all the animation sprites are also drawn as part of the cc.SpriteBatchNode + // + var sprite = new cc.Sprite("#grossini_dance_01.png"); + sprite.x = winSize.width / 2; + sprite.y = winSize.height / 2; + + var spriteBatch = new cc.SpriteBatchNode(s_grossini_aliases); + spriteBatch.addChild(sprite); + this.addChild(spriteBatch); + + var animFrames = []; + var str = ""; + for (var i = 1; i < 15; i++) { + // Obtain frames by alias name + str = "dance_" + (i < 10 ? ("0" + i) : i); + var frame = spriteFrameCache.getSpriteFrame(str); + animFrames.push(frame); + } + + var animation = new cc.Animation(animFrames, 0.3); + // 14 frames * 1sec = 14 seconds + sprite.runAction(cc.animate(animation).repeatForever()); + this.testSprite = sprite; + //----end3---- + }, + onExit:function () { + this._super(); + spriteFrameCache.removeSpriteFramesFromFile(s_grossini_aliasesPlist); + }, + // + // Automation + // + testDuration:0.5, + pixel:{"0":255, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 2 - 32, winSize.height / 2 - 10, 5, 5); + var ret = {"pixel":this.containsPixel(ret1, this.pixel, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteOffsetAnchorRotation +// +//------------------------------------------------------------------ +var SpriteOffsetAnchorRotation = SpriteTestDemo.extend({ + + _title:"Sprite offset + anchor + rot", + ctor:function () { + //----start6----ctor + this._super(); + spriteFrameCache.addSpriteFrames(s_grossiniPlist); + spriteFrameCache.addSpriteFrames(s_grossini_grayPlist, s_grossini_gray); + + for (var i = 0; i < 3; i++) { + // + // Animation using Sprite BatchNode + // + var sprite = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_01.png")); + sprite.x = winSize.width / 4 * (i + 1); + sprite.y = winSize.height / 2; + + var point = new cc.Sprite(s_pathR1); + point.scale = 0.25; + point.x = sprite.x; + point.y = sprite.y; + this.addChild(point, 1); + + switch (i) { + case 0: + sprite.anchorX = 0; + sprite.anchorY = 0; + break; + case 1: + sprite.anchorX = 0.5; + sprite.anchorY = 0.5; + break; + case 2: + sprite.anchorX = 1; + sprite.anchorY = 1; + break; + } + + point.x = sprite.x; + + point.y = sprite.y; + + var animFrames = []; + var str = ""; + for (var j = 1; j < 15; j++) { + str = "grossini_dance_" + (j < 10 ? ("0" + j) : j) + ".png"; + var frame = spriteFrameCache.getSpriteFrame(str); + animFrames.push(frame); + } + + var animation = new cc.Animation(animFrames, 0.3); + sprite.runAction(cc.animate(animation).repeatForever()); + sprite.runAction(cc.rotateBy(10, 360).repeatForever()); + + this.addChild(sprite, 0); + } + //----end6---- + }, + onExit:function () { + //----start6----onExit + this._super(); + spriteFrameCache.removeSpriteFramesFromFile(s_grossiniPlist); + spriteFrameCache.removeSpriteFramesFromFile(s_grossini_grayPlist); + //----end6---- + }, + // + // Automation + // + testDuration:5, + pixel:{"0":255, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 4 - 13, winSize.height / 2 - 50, 5, 5); + var ret2 = this.readPixels(winSize.width / 4 * 2 + 29, winSize.height / 2 + 11, 5, 5); + var ret3 = this.readPixels(winSize.width / 4 * 3 + 71, winSize.height / 2 + 71, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel) ? "yes" : "no", "pixel2":this.containsPixel(ret2, this.pixel) ? "yes" : "no", "pixel3":this.containsPixel(ret3, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteBatchNodeOffsetAnchorRotation +// +//------------------------------------------------------------------ +var SpriteBatchNodeOffsetAnchorRotation = SpriteTestDemo.extend({ + _title:"SpriteBatchNode offset + anchor + rot", + + ctor:function () { + //----start7----ctor + this._super(); + + spriteFrameCache.addSpriteFrames(s_grossiniPlist); + spriteFrameCache.addSpriteFrames(s_grossini_grayPlist, s_grossini_gray); + + var spritebatch = new cc.SpriteBatchNode(s_grossini); + this.addChild(spritebatch); + + for (var i = 0; i < 3; i++) { + // + // Animation using Sprite BatchNode + // + var sprite = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_01.png")); + sprite.x = winSize.width / 4 * (i + 1); + sprite.y = winSize.height / 2; + + var point = new cc.Sprite(s_pathR1); + point.scale = 0.25; + point.x = sprite.x; + point.y = sprite.y; + this.addChild(point, 200); + + switch (i) { + case 0: + sprite.anchorX = 0; + sprite.anchorY = 0; + break; + case 1: + sprite.anchorX = 0.5; + sprite.anchorY = 0.5; + break; + case 2: + sprite.anchorX = 1; + sprite.anchorY = 1; + break; + } + point.x = sprite.x; + point.y = sprite.y; + + var animFrames = []; + var str = ""; + for (var k = 1; k < 15; k++) { + str = "grossini_dance_" + (k < 10 ? ("0" + k) : k) + ".png"; + var frame = spriteFrameCache.getSpriteFrame(str); + animFrames.push(frame); + } + + var animation = new cc.Animation(animFrames, 0.3); + sprite.runAction(cc.animate(animation).repeatForever()); + sprite.runAction(cc.rotateBy(10, 360).repeatForever()); + + spritebatch.addChild(sprite, i); + } + //----end7---- + }, + onExit:function () { + this._super(); + spriteFrameCache.removeSpriteFramesFromFile(s_grossiniPlist); + spriteFrameCache.removeSpriteFramesFromFile(s_grossini_grayPlist); + }, + // + // Automation + // + testDuration:5, + pixel:{"0":255, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 4 - 13, winSize.height / 2 - 50, 5, 5); + var ret2 = this.readPixels(winSize.width / 4 * 2 + 29, winSize.height / 2 + 11, 5, 5); + var ret3 = this.readPixels(winSize.width / 4 * 3 + 71, winSize.height / 2 + 71, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel) ? "yes" : "no", "pixel2":this.containsPixel(ret2, this.pixel) ? "yes" : "no", "pixel3":this.containsPixel(ret3, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteOffsetAnchorScale +// +//------------------------------------------------------------------ +var SpriteOffsetAnchorScale = SpriteTestDemo.extend({ + + _title:"Sprite offset + anchor + scale", + + ctor:function () { + //----start8----ctor + this._super(); + spriteFrameCache.addSpriteFrames(s_grossiniPlist); + spriteFrameCache.addSpriteFrames(s_grossini_grayPlist, s_grossini_gray); + + for (var i = 0; i < 3; i++) { + // + // Animation using Sprite BatchNode + // + var sprite = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_01.png")); + sprite.x = winSize.width / 4 * (i + 1); + sprite.y = winSize.height / 2; + + var point = new cc.Sprite(s_pathR1); + point.scale = 0.25; + point.x = sprite.x; + point.y = sprite.y; + this.addChild(point, 1); + + switch (i) { + case 0: + sprite.anchorX = 0; + sprite.anchorY = 0; + break; + case 1: + sprite.anchorX = 0.5; + sprite.anchorY = 0.5; + break; + case 2: + sprite.anchorX = 1; + sprite.anchorY = 1; + break; + } + + point.x = sprite.x; + + point.y = sprite.y; + + var animFrames = []; + var str = ""; + for (var k = 1; k <= 14; k++) { + str = "grossini_dance_" + (k < 10 ? ("0" + k) : k) + ".png"; + var frame = spriteFrameCache.getSpriteFrame(str); + animFrames.push(frame); + } + + var animation = new cc.Animation(animFrames, 0.3); + sprite.runAction(cc.animate(animation).repeatForever()); + + var scale = cc.scaleBy(2, 2); + var scale_back = scale.reverse(); + var delay = cc.delayTime(0.25); + var seq_scale = cc.sequence(scale, delay, scale_back); + sprite.runAction(seq_scale.repeatForever()); + + this.addChild(sprite, 0); + } + //----end8---- + }, + onExit:function () { + //----start8----onExit + this._super(); + spriteFrameCache.removeSpriteFramesFromFile(s_grossiniPlist); + spriteFrameCache.removeSpriteFramesFromFile(s_grossini_grayPlist); + //----end8---- + }, + // + // Automation + // + testDuration:2.1, + pixel:{"0":153, "1":0, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 4 * 3 - 85, winSize.height / 2 - 106, 5, 5); + var ret2 = this.readPixels(winSize.width / 4 * 2, winSize.height / 2 + 13, 5, 5); + var ret3 = this.readPixels(winSize.width / 4 + 82, winSize.height / 2 + 133, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel) ? "yes" : "no", "pixel2":this.containsPixel(ret2, this.pixel) ? "yes" : "no", "pixel3":this.containsPixel(ret3, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + + +//------------------------------------------------------------------ +// +// SpriteBatchNodeOffsetAnchorScale +// +//------------------------------------------------------------------ +var SpriteBatchNodeOffsetAnchorScale = SpriteTestDemo.extend({ + + _title:"SpriteBatchNode offset + anchor + scale", + + ctor:function () { + this._super(); + //----start9----ctor + var batch = new cc.SpriteBatchNode(s_grossini); + this.addChild(batch); + + spriteFrameCache.addSpriteFrames(s_grossiniPlist); + spriteFrameCache.addSpriteFrames(s_grossini_grayPlist, s_grossini_gray); + + for (var i = 0; i < 3; i++) { + // + // Animation using Sprite BatchNode + // + var sprite = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_01.png")); + sprite.x = winSize.width / 4 * (i + 1); + sprite.y = winSize.height / 2; + + var point = new cc.Sprite(s_pathR1); + point.scale = 0.25; + point.x = sprite.x; + point.y = sprite.y; + this.addChild(point, 200); + + switch (i) { + case 0: + sprite.anchorX = 0; + sprite.anchorY = 0; + break; + case 1: + sprite.anchorX = 0.5; + sprite.anchorY = 0.5; + break; + case 2: + sprite.anchorX = 1; + sprite.anchorY = 1; + break; + } + + point.x = sprite.x; + point.y = sprite.y; + + var animFrames = []; + var str = ""; + for (var k = 1; k <= 14; k++) { + str = "grossini_dance_" + (k < 10 ? ("0" + k) : k) + ".png"; + var frame = spriteFrameCache.getSpriteFrame(str); + animFrames.push(frame); + } + + var animation = new cc.Animation(animFrames, 0.3); + sprite.runAction(cc.animate(animation).repeatForever()); + + var scale = cc.scaleBy(2, 2); + var scale_back = scale.reverse(); + var seq_scale = cc.sequence(scale, scale_back); + sprite.runAction(seq_scale.repeatForever()); + + batch.addChild(sprite, i); + } + //----end9---- + }, + onExit:function () { + //----start9----onExit + this._super(); + spriteFrameCache.removeSpriteFramesFromFile(s_grossiniPlist); + spriteFrameCache.removeSpriteFramesFromFile(s_grossini_grayPlist); + //----end9---- + }, + // + // Automation + // + testDuration:2.1, + pixel:{"0":153, "1":0, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 4 * 3 - 85, winSize.height / 2 - 106, 5, 5); + var ret2 = this.readPixels(winSize.width / 4 * 2, winSize.height / 2 + 13, 5, 5); + var ret3 = this.readPixels(winSize.width / 4 + 82, winSize.height / 2 + 133, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel) ? "yes" : "no", "pixel2":this.containsPixel(ret2, this.pixel) ? "yes" : "no", "pixel3":this.containsPixel(ret3, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +// +// SpriteOffsetAnchorSkew +// +var SpriteOffsetAnchorSkew = SpriteTestDemo.extend({ + + _title:"Sprite offset + anchor + skew", + + ctor:function () { + //----start41----ctor + this._super(); + spriteFrameCache.addSpriteFrames(s_grossiniPlist); + spriteFrameCache.addSpriteFrames(s_grossini_grayPlist, s_grossini_gray); + + for (var i = 0; i < 3; i++) { + // + // Animation using Sprite batch + // + var sprite = new cc.Sprite("#grossini_dance_01.png"); + sprite.x = winSize.width / 4 * (i + 1); + sprite.y = winSize.height / 2; + + var point = new cc.Sprite(s_pathR1); + point.scale = 0.25; + point.x = sprite.x; + point.y = sprite.y; + this.addChild(point, 1); + + switch (i) { + case 0: + sprite.anchorX = 0; + sprite.anchorY = 0; + break; + case 1: + sprite.anchorX = 0.5; + sprite.anchorY = 0.5; + break; + case 2: + sprite.anchorX = 1; + sprite.anchorY = 1; + break; + } + + point.x = sprite.x; + point.y = sprite.y; + + var animFrames = []; + var tmp = ""; + for (var j = 1; j <= 14; j++) { + tmp = "grossini_dance_" + (j < 10 ? ("0" + j) : j) + ".png"; + var frame = spriteFrameCache.getSpriteFrame(tmp); + animFrames.push(frame); + } + + var animation = new cc.Animation(animFrames, 0.3); + sprite.runAction(cc.animate(animation).repeatForever()); + + var skewX = cc.skewBy(2, 45, 0); + var skewX_back = skewX.reverse(); + var skewY = cc.skewBy(2, 0, 45); + var skewY_back = skewY.reverse(); + + var seq_skew = cc.sequence(skewX, skewX_back, skewY, skewY_back); + sprite.runAction(seq_skew.repeatForever()); + + this.addChild(sprite, 0); + } + //----end41---- + }, + // + // Automation + // + testDuration:2, + pixel:{"0":255, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 4 + 142, winSize.height / 2 + 98, 5, 5); + var ret2 = this.readPixels(winSize.width / 4 * 2 + 50, winSize.height / 2 + 43, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +// +// SpriteBatchNodeOffsetAnchorSkew +// +var SpriteBatchNodeOffsetAnchorSkew = SpriteTestDemo.extend({ + + _title:"SpriteBatchNode offset + anchor + skew", + + ctor:function () { + //----start42----ctor + this._super(); + spriteFrameCache.addSpriteFrames(s_grossiniPlist); + spriteFrameCache.addSpriteFrames(s_grossini_grayPlist, s_grossini_gray); + + var spritebatch = new cc.SpriteBatchNode(s_grossini); + this.addChild(spritebatch); + + for (var i = 0; i < 3; i++) { + // + // Animation using Sprite batch + // + var sprite = new cc.Sprite("#grossini_dance_01.png"); + sprite.x = winSize.width / 4 * (i + 1); + sprite.y = winSize.height / 2; + + var point = new cc.Sprite(s_pathR1); + point.scale = 0.25; + point.x = sprite.x; + point.y = sprite.y; + this.addChild(point, 200); + + switch (i) { + case 0: + sprite.anchorX = 0; + sprite.anchorY = 0; + break; + case 1: + sprite.anchorX = 0.5; + sprite.anchorY = 0.5; + break; + case 2: + sprite.anchorX = 1; + sprite.anchorY = 1; + break; + } + + point.x = sprite.x; + point.y = sprite.y; + + var animFrames = []; + var tmp = ""; + for (var j = 1; j <= 14; j++) { + tmp = "grossini_dance_" + (j < 10 ? ("0" + j) : j) + ".png"; + var frame = spriteFrameCache.getSpriteFrame(tmp); + animFrames.push(frame); + } + + var animation = new cc.Animation(animFrames, 0.3); + sprite.runAction(cc.animate(animation).repeatForever()); + + animFrames = null; + + var skewX = cc.skewBy(2, 45, 0); + var skewX_back = skewX.reverse(); + var skewY = cc.skewBy(2, 0, 45); + var skewY_back = skewY.reverse(); + + var seq_skew = cc.sequence(skewX, skewX_back, skewY, skewY_back); + sprite.runAction(seq_skew.repeatForever()); + + spritebatch.addChild(sprite, i); + } + //----end42---- + }, + // + // Automation + // + testDuration:2, + pixel:{"0":255, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 4 + 142, winSize.height / 2 + 98, 5, 5); + var ret2 = this.readPixels(winSize.width / 4 * 2 + 50, winSize.height / 2 + 43, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +// +// SpriteOffsetAnchorSkewScale +// +var SpriteOffsetAnchorSkewScale = SpriteTestDemo.extend({ + + _title:"Sprite anchor + skew + scale", + ctor:function () { + //----start43----ctor + this._super(); + spriteFrameCache.addSpriteFrames(s_grossiniPlist); + spriteFrameCache.addSpriteFrames(s_grossini_grayPlist, s_grossini_gray); + + for (var i = 0; i < 3; i++) { + // + // Animation using Sprite batch + // + var sprite = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_01.png")); + sprite.x = winSize.width / 4 * (i + 1); + sprite.y = winSize.height / 2; + + var point = new cc.Sprite(s_pathR1); + point.scale = 0.25; + point.x = sprite.x; + point.y = sprite.y; + this.addChild(point, 1); + + switch (i) { + case 0: + sprite.anchorX = 0; + sprite.anchorY = 0; + break; + case 1: + sprite.anchorX = 0.5; + sprite.anchorY = 0.5; + break; + case 2: + sprite.anchorX = 1; + sprite.anchorY = 1; + break; + } + + point.x = sprite.x; + point.y = sprite.y; + + var animFrames = []; + var tmp = ""; + for (var j = 1; j <= 14; j++) { + tmp = "grossini_dance_" + (j < 10 ? ("0" + j) : j) + ".png"; + var frame = spriteFrameCache.getSpriteFrame(tmp); + animFrames.push(frame); + } + + var animation = new cc.Animation(animFrames, 0.3); + sprite.runAction(cc.animate(animation).repeatForever()); + + animFrames = null; + + // Skew + var skewX = cc.skewBy(2, 45, 0); + var skewX_back = skewX.reverse(); + var skewY = cc.skewBy(2, 0, 45); + var skewY_back = skewY.reverse(); + + var seq_skew = cc.sequence(skewX, skewX_back, skewY, skewY_back); + sprite.runAction(seq_skew.repeatForever()); + + // Scale + var scale = cc.scaleBy(2, 2); + var scale_back = scale.reverse(); + var seq_scale = cc.sequence(scale, scale_back); + sprite.runAction(seq_scale.repeatForever()); + + this.addChild(sprite, 0); + } + //----end43---- + }, + // + // Automation + // + testDuration:2, + pixel:{"0":255, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 4 + 121, winSize.height / 2 + 99, 5, 5); + var ret2 = this.readPixels(winSize.width / 4 * 2 - 83, winSize.height / 2 - 21, 5, 5); + var ret3 = this.readPixels(winSize.width / 4 * 3 - 286, winSize.height / 2 - 140, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel) ? "yes" : "no", + "pixel3":this.containsPixel(ret3, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +// +// SpriteBatchNodeOffsetAnchorSkewScale +// +var SpriteBatchNodeOffsetAnchorSkewScale = SpriteTestDemo.extend({ + + _title:"SpriteBatchNode anchor + skew + scale", + + ctor:function () { + //----start44----ctor + this._super(); + + spriteFrameCache.addSpriteFrames(s_grossiniPlist); + spriteFrameCache.addSpriteFrames(s_grossini_grayPlist, s_grossini_gray); + + var spritebatch = new cc.SpriteBatchNode(s_grossini); + this.addChild(spritebatch); + + for (var i = 0; i < 3; i++) { + // + // Animation using Sprite batch + // + var sprite = new cc.Sprite("#grossini_dance_01.png"); + sprite.x = winSize.width / 4 * (i + 1); + sprite.y = winSize.height / 2; + + var point = new cc.Sprite(s_pathR1); + point.scale = 0.25; + point.x = sprite.x; + point.y = sprite.y; + this.addChild(point, 200); + + switch (i) { + case 0: + sprite.anchorX = 0; + sprite.anchorY = 0; + break; + case 1: + sprite.anchorX = 0.5; + sprite.anchorY = 0.5; + break; + case 2: + sprite.anchorX = 1; + sprite.anchorY = 1; + break; + } + + point.x = sprite.x; + point.y = sprite.y; + + var animFrames = []; + var tmp = ""; + for (var j = 1; j <= 14; j++) { + tmp = "grossini_dance_" + (j < 10 ? ("0" + j) : j) + ".png"; + var frame = spriteFrameCache.getSpriteFrame(tmp); + animFrames.push(frame); + } + + var animation = new cc.Animation(animFrames, 0.3); + sprite.runAction(cc.animate(animation).repeatForever()); + + animFrames = null; + + // skew + var skewX = cc.skewBy(2, 45, 0); + var skewX_back = skewX.reverse(); + var skewY = cc.skewBy(2, 0, 45); + var skewY_back = skewY.reverse(); + + var seq_skew = cc.sequence(skewX, skewX_back, skewY, skewY_back); + sprite.runAction(seq_skew.repeatForever()); + + // scale + var scale = cc.scaleBy(2, 2); + var scale_back = scale.reverse(); + var seq_scale = cc.sequence(scale, scale_back); + sprite.runAction(seq_scale.repeatForever()); + + spritebatch.addChild(sprite, i); + } + //----end44---- + }, + // + // Automation + // + testDuration:2, + pixel:{"0":255, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 4 + 121, winSize.height / 2 + 99, 5, 5); + var ret2 = this.readPixels(winSize.width / 4 * 2 - 83, winSize.height / 2 - 21, 5, 5); + var ret3 = this.readPixels(winSize.width / 4 * 3 - 286, winSize.height / 2 - 140, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel) ? "yes" : "no", + "pixel3":this.containsPixel(ret3, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +// +// SpriteOffsetAnchorFlip +// +var SpriteOffsetAnchorFlip = SpriteTestDemo.extend({ + + _title:"Sprite offset + anchor + flip", + _subtitle:"issue #1078", + + ctor:function () { + //----start45----ctor + this._super(); + spriteFrameCache.addSpriteFrames(s_grossiniPlist); + spriteFrameCache.addSpriteFrames(s_grossini_grayPlist, s_grossini_gray); + + for (var i = 0; i < 3; i++) { + // + // Animation using Sprite batch + // + var sprite = new cc.Sprite("#grossini_dance_01.png"); + sprite.x = winSize.width / 4 * (i + 1); + sprite.y = winSize.height / 2; + + var point = new cc.Sprite(s_pathR1); + point.scale = 0.25; + point.x = sprite.x; + point.y = sprite.y; + this.addChild(point, 1); + + switch (i) { + case 0: + sprite.anchorX = 0; + sprite.anchorY = 0; + break; + case 1: + sprite.anchorX = 0.5; + sprite.anchorY = 0.5; + break; + case 2: + sprite.anchorX = 1; + sprite.anchorY = 1; + break; + } + + point.x = sprite.x; + point.y = sprite.y; + + var animFrames = []; + var tmp = ""; + for (var j = 1; j <= 14; j++) { + tmp = "grossini_dance_" + (j < 10 ? ("0" + j) : j) + ".png"; + var frame = spriteFrameCache.getSpriteFrame(tmp); + animFrames.push(frame); + } + + var animation = new cc.Animation(animFrames, 0.3); + sprite.runAction(cc.animate(animation).repeatForever()); + + animFrames = null; + + var flip = cc.flipY(true); + var flip_back = cc.flipY(false); + var delay = cc.delayTime(1); + var delay1 = cc.delayTime(1); + var seq = cc.sequence(delay, flip, delay1, flip_back); + sprite.runAction(seq.repeatForever()); + + this.addChild(sprite, 0); + } + //----end45---- + }, + // + // Automation + // + testDuration:1.5, + pixel:{"0":255, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 4 + 40, winSize.height / 2 + 18, 5, 5); + var ret2 = this.readPixels(winSize.width / 4 * 2, winSize.height / 2 - 44, 5, 5); + var ret3 = this.readPixels(winSize.width / 4 * 3 - 45, winSize.height / 2 - 105, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel) ? "yes" : "no", "pixel2":this.containsPixel(ret2, this.pixel) ? "yes" : "no", "pixel3":this.containsPixel(ret3, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +// +// SpriteBatchNodeOffsetAnchorFlip +// +var SpriteBatchNodeOffsetAnchorFlip = SpriteTestDemo.extend({ + + _title:"SpriteBatchNode offset + anchor + flip", + _subtitle:"issue #1078", + + ctor:function () { + //----start46----ctor + this._super(); + spriteFrameCache.addSpriteFrames(s_grossiniPlist); + spriteFrameCache.addSpriteFrames(s_grossini_grayPlist, s_grossini_gray); + + var spritebatch = new cc.SpriteBatchNode(s_grossini); + this.addChild(spritebatch); + + for (var i = 0; i < 3; i++) { + // + // Animation using Sprite batch + // + var sprite = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_01.png")); + sprite.x = winSize.width / 4 * (i + 1); + sprite.y = winSize.height / 2; + + var point = new cc.Sprite(s_pathR1); + point.scale = 0.25; + point.x = sprite.x; + point.y = sprite.y; + this.addChild(point, 200); + + switch (i) { + case 0: + sprite.anchorX = 0; + sprite.anchorY = 0; + break; + case 1: + sprite.anchorX = 0.5; + sprite.anchorY = 0.5; + break; + case 2: + sprite.anchorX = 1; + sprite.anchorY = 1; + break; + } + + point.x = sprite.x; + point.y = sprite.y; + + var animFrames = []; + var tmp = ""; + for (var j = 1; j <= 14; j++) { + tmp = "grossini_dance_" + (j < 10 ? ("0" + j) : j) + ".png"; + var frame = spriteFrameCache.getSpriteFrame(tmp); + animFrames.push(frame); + } + + var animation = new cc.Animation(animFrames, 0.3); + sprite.runAction(cc.animate(animation).repeatForever()); + + animFrames = null; + + var flip = cc.flipY(true); + var flip_back = cc.flipY(false); + var delay = cc.delayTime(1); + var seq = cc.sequence(delay, flip, delay.clone(), flip_back); + sprite.runAction(seq.repeatForever()); + + spritebatch.addChild(sprite, i); + } + //----end46---- + }, + // + // Automation + // + testDuration:1.5, + pixel:{"0":255, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 4 + 40, winSize.height / 2 + 18, 5, 5); + var ret2 = this.readPixels(winSize.width / 4 * 2, winSize.height / 2 - 44, 5, 5); + var ret3 = this.readPixels(winSize.width / 4 * 3 - 45, winSize.height / 2 - 105, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel) ? "yes" : "no", "pixel2":this.containsPixel(ret2, this.pixel) ? "yes" : "no", "pixel3":this.containsPixel(ret3, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteAnimationSplit +// +//------------------------------------------------------------------ +var SpriteAnimationSplit = SpriteTestDemo.extend({ + + _title:"Sprite: Animation + flip", + ctor:function () { + //----start10----ctor + this._super(); + var texture = cc.textureCache.addImage(s_dragon_animation); + + // manually add frames to the frame cache + var frame0 = new cc.SpriteFrame(texture, cc.rect(132 * 0, 132 * 0, 132, 132)); + var frame1 = new cc.SpriteFrame(texture, cc.rect(132 * 1, 132 * 0, 132, 132)); + var frame2 = new cc.SpriteFrame(texture, cc.rect(132 * 2, 132 * 0, 132, 132)); + var frame3 = new cc.SpriteFrame(texture, cc.rect(132 * 3, 132 * 0, 132, 132)); + var frame4 = new cc.SpriteFrame(texture, cc.rect(132 * 0, 132 * 1, 132, 132)); + var frame5 = new cc.SpriteFrame(texture, cc.rect(132 * 1, 132 * 1, 132, 132)); + + // + // Animation using Sprite BatchNode + // + var sprite = new cc.Sprite(frame0); + sprite.x = winSize.width / 2; + sprite.y = winSize.height / 2; + this.addChild(sprite); + + var animFrames = []; + animFrames.push(frame0); + animFrames.push(frame1); + animFrames.push(frame2); + animFrames.push(frame3); + animFrames.push(frame4); + animFrames.push(frame5); + + var animation = new cc.Animation(animFrames, 0.2); + var animate = cc.animate(animation); + var delay = cc.delayTime(0.5); + var seq = cc.sequence(animate, + cc.flipX(true), + animate.clone(), + delay, + cc.flipX(false)); + + sprite.runAction(seq.repeatForever()); + //----end10---- + }, + onExit:function () { + this._super(); + }, + // + // Automation + // + testDuration:2.8, + pixel1:{"0":208, "1":208, "2":208, "3":255}, + pixel2:{"0":0, "1":0, "2":0, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 2 + 52, winSize.height / 2 - 29, 5, 5); + var ret2 = this.readPixels(winSize.width / 2, winSize.height / 2 - 22, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1, true, 3) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteHybrid +// +//------------------------------------------------------------------ +var SpriteHybrid = SpriteTestDemo.extend({ + _usingSpriteBatchNode:false, + _title:"Hybrid.Sprite* sprite Test", + + ctor:function () { + //----start28----ctor + this._super(); + // parents + var parent1 = new cc.Node(); + var parent2 = new cc.SpriteBatchNode(s_grossini, 50); + + this.addChild(parent1, 0, TAG_NODE); + this.addChild(parent2, 0, TAG_SPRITE_BATCH_NODE); + + // IMPORTANT: + // The sprite frames will be cached AND RETAINED, and they won't be released unless you call + spriteFrameCache.addSpriteFrames(s_grossiniPlist); + + // create 250 sprites + // only show 80% of them + for (var i = 1; i <= 250; i++) { + var spriteIdx = Math.round(Math.random() * 14); + if (spriteIdx === 0) + spriteIdx = 1; + var str = "grossini_dance_" + (spriteIdx < 10 ? ("0" + spriteIdx) : spriteIdx) + ".png"; + + var frame = spriteFrameCache.getSpriteFrame(str); + var sprite = new cc.Sprite(frame); + parent1.addChild(sprite, i, i); + + var x = -1000; + var y = -1000; + if (Math.random() < 0.2) { + x = Math.random() * winSize.width; + y = Math.random() * winSize.height; + } + sprite.x = x; + sprite.y = y; + + var action = cc.rotateBy(4, 360); + sprite.runAction(action.repeatForever()); + } + + this._usingSpriteBatchNode = false; + + this.schedule(this.reparentSprite, 2); + //----end28---- + }, + onExit:function () { + //----start28----onExit + this._super(); + spriteFrameCache.removeSpriteFramesFromFile(s_grossiniPlist); + //----end28---- + }, + reparentSprite:function () { + //----start28----reparentSprite + var p1 = this.getChildByTag(TAG_NODE); + var p2 = this.getChildByTag(TAG_SPRITE_BATCH_NODE); + + var retArray = []; + var node; + + if (this._usingSpriteBatchNode) { + var tempNode = p2; + p2 = p1; + p1 = tempNode; + } + ////----UXLog("New parent is: %x", p2); + + var children = p1.children; + for (var i = 0; i < children.length; i++) { + node = children[i]; + if (!node) + break; + + retArray.push(node); + } + + p1.removeAllChildren(false); + for (i = 0; i < retArray.length; i++) { + node = retArray[i]; + if (!node) + break; + + p2.addChild(node, i, i); + } + + this._usingSpriteBatchNode = !this._usingSpriteBatchNode; + //----end28---- + }, + // + // Automation + // + testDuration:2.5, + pixel:{"0":51, "1":0, "2":51, "3":255}, + firstPixel1:false, + firstPixel2:false, + setupAutomation:function () { + this.scheduleOnce(this.addTestSprite, 1); + this.scheduleOnce(this.checkFirstPixel, 1.5); + }, + addTestSprite:function () { + var p = this.getChildByTag(TAG_NODE); + var frame = spriteFrameCache.getSpriteFrame("grossini_dance_01.png"); + var sprite1 = new cc.Sprite(frame); + sprite1.retain(); + p.addChild(sprite1, 1000); + sprite1.x = winSize.width / 4; + sprite1.y = winSize.height / 2; + var sprite2 = new cc.Sprite(frame); + sprite2.retain(); + p.addChild(sprite2, 1000); + sprite2.x = winSize.width / 2; + sprite2.y = winSize.height / 2; + }, + checkFirstPixel:function () { + var ret1 = this.readPixels(winSize.width / 4, winSize.height / 2, 5, 5); + var ret2 = this.readPixels(winSize.width / 2, winSize.height / 2, 5, 5); + this.firstPixel1 = this.containsPixel(ret1, this.pixel); + this.firstPixel2 = this.containsPixel(ret2, this.pixel); + }, + getExpectedResult:function () { + var ret = {"firstPixel1":true, "firstPixel2":true, "secondPixel1":true, "pixel2":true}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var pixel1 = this.readPixels(winSize.width / 4, winSize.height / 2, 5, 5); + var pixel2 = this.readPixels(winSize.width / 2, winSize.height / 2, 5, 5); + var secondPixel1 = this.containsPixel(pixel1, this.pixel); + var secondPixel2 = this.containsPixel(pixel2, this.pixel); + var ret = {"firstPixel1":this.firstPixel1, "firstPixel2":this.firstPixel2, "secondPixel1":secondPixel1, "pixel2":secondPixel2}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteBatchNodeChildren +// +//------------------------------------------------------------------ +var SpriteBatchNodeChildren = SpriteTestDemo.extend({ + _title:"SpriteBatchNode Grand Children", + + ctor:function () { + //----start29----ctor + this._super(); + // parents + var batch = new cc.SpriteBatchNode(s_grossini, 50); + this.addChild(batch, 0, TAG_SPRITE_BATCH_NODE); + + spriteFrameCache.addSpriteFrames(s_grossiniPlist); + + var sprite1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_01.png")); + sprite1.x = winSize.width / 3; + sprite1.y = winSize.height / 2; + + var sprite2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_02.png")); + sprite2.x = 50; + sprite2.y = 50; + + var sprite3 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_03.png")); + sprite3.x = -50; + sprite3.y = -50; + + batch.addChild(sprite1); + sprite1.addChild(sprite2); + sprite1.addChild(sprite3); + + // BEGIN NEW CODE + var animFrames = []; + var str = ""; + for (var i = 1; i < 15; i++) { + str = "grossini_dance_" + (i < 10 ? ("0" + i) : i) + ".png"; + var frame = spriteFrameCache.getSpriteFrame(str); + animFrames.push(frame); + } + + var animation = new cc.Animation(animFrames, 0.2); + sprite1.runAction(cc.animate(animation).repeatForever()); + // END NEW CODE + + var action = cc.moveBy(2, cc.p(200, 0)); + var action_back = action.reverse(); + var action_rot = cc.rotateBy(2, 360); + var action_s = cc.scaleBy(2, 2); + var action_s_back = action_s.reverse(); + + var seq2 = action_rot.reverse(); + sprite2.runAction(seq2.repeatForever()); + + sprite1.runAction(action_rot.repeatForever()); + sprite1.runAction(cc.sequence(action, action_back).repeatForever()); + sprite1.runAction(cc.sequence(action_s, action_s_back).repeatForever()); + //----end29---- + }, + // + // Automation + // + testDuration:0.5, + pixel:{"0":255, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 3 - 47, winSize.height / 2 + 107, 5, 5); + var ret2 = this.readPixels(winSize.width / 3 + 95, winSize.height / 2 - 5, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel) ? "yes" : "no", "pixel2":this.containsPixel(ret2, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteBatchNodeChildrenZ +// +//------------------------------------------------------------------ +var SpriteBatchNodeChildrenZ = SpriteTestDemo.extend({ + + _title:"SpriteBatchNode Children Z", + + ctor:function () { + //----start30----ctor + this._super(); + // parents + var batch; + var sprite1, sprite2, sprite3; + spriteFrameCache.addSpriteFrames(s_grossiniPlist); + + // test 1 + batch = new cc.SpriteBatchNode(s_grossini, 50); + this.addChild(batch, 0, TAG_SPRITE_BATCH_NODE); + + sprite1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_01.png")); + sprite1.x = winSize.width / 3; + sprite1.y = winSize.height / 2; + + sprite2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_02.png")); + sprite2.x = 20; + sprite2.y = 30; + + sprite3 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_03.png")); + sprite3.x = -20; + sprite3.y = 30; + + batch.addChild(sprite1); + sprite1.addChild(sprite2, 2); + sprite1.addChild(sprite3, -2); + + // test 2 + batch = new cc.SpriteBatchNode(s_grossini, 50); + this.addChild(batch, 0, TAG_SPRITE_BATCH_NODE); + + sprite1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_01.png")); + sprite1.x = 2 * winSize.width / 3; + sprite1.y = winSize.height / 2; + + sprite2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_02.png")); + sprite2.x = 20; + sprite2.y = 30; + + sprite3 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_03.png")); + sprite3.x = -20; + sprite3.y = 30; + + batch.addChild(sprite1); + sprite1.addChild(sprite2, -2); + sprite1.addChild(sprite3, 2); + + // test 3 + batch = new cc.SpriteBatchNode(s_grossini, 50); + this.addChild(batch, 0, TAG_SPRITE_BATCH_NODE); + + sprite1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_01.png")); + sprite1.x = winSize.width / 2 - 90; + sprite1.y = winSize.height / 4; + + sprite2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_02.png")); + sprite2.x = winSize.width / 2 - 60; + sprite2.y = winSize.height / 4; + + sprite3 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_03.png")); + sprite3.x = winSize.width / 2 - 30; + sprite3.y = winSize.height / 4; + + batch.addChild(sprite1, 10); + batch.addChild(sprite2, -10); + batch.addChild(sprite3, -5); + + // test 4 + batch = new cc.SpriteBatchNode(s_grossini, 50); + this.addChild(batch, 0, TAG_SPRITE_BATCH_NODE); + + sprite1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_01.png")); + sprite1.x = winSize.width / 2 + 30; + sprite1.y = winSize.height / 4; + + sprite2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_02.png")); + sprite2.x = winSize.width / 2 + 60; + sprite2.y = winSize.height / 4; + + sprite3 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_03.png")); + sprite3.x = winSize.width / 2 + 90; + sprite3.y = winSize.height / 4; + + batch.addChild(sprite1, -10); + batch.addChild(sprite2, -5); + batch.addChild(sprite3, -2); + //----end30---- + }, + // + // Automation + // + testDuration:1, + pixel1:{"0":51, "1":0, "2":51, "3":255}, + pixel2:{"0":51, "1":0, "2":51, "3":255}, + pixel3:{"0":255, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(2 * winSize.width / 3 - 20, winSize.height / 2, 5, 5); + var ret2 = this.readPixels(winSize.width / 3 - 20, winSize.height / 2 + 115, 5, 5); + var ret3 = this.readPixels(winSize.width / 2 + 30, winSize.height / 4 - 10, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1) ? "yes" : "no", + "pixel2":!this.containsPixel(ret2, this.pixel2) ? "yes" : "no", + "pixel3":this.containsPixel(ret3, this.pixel3) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteChildrenVisibility +// +//------------------------------------------------------------------ +var SpriteChildrenVisibility = SpriteTestDemo.extend({ + _title:"Sprite & SpriteBatchNode Visibility", + + ctor:function () { + //----start31----ctor + this._super(); + + spriteFrameCache.addSpriteFrames(s_grossiniPlist); + // + // SpriteBatchNode + // + // parents + var aParent = new cc.SpriteBatchNode(s_grossini, 50); + aParent.x = winSize.width / 3; + aParent.y = winSize.height / 2; + this.addChild(aParent, 0); + + var sprite1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_01.png")); + sprite1.x = 0; + sprite1.y = 0; + + var sprite2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_02.png")); + sprite2.x = 20; + sprite2.y = 30; + + var sprite3 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_03.png")); + sprite3.x = -20; + sprite3.y = 30; + + aParent.addChild(sprite1); + sprite1.addChild(sprite2, -2); + sprite1.addChild(sprite3, 2); + + sprite1.runAction(cc.blink(5, 10)); + + // + // Sprite + // + aParent = new cc.Node(); + aParent.x = 2 * winSize.width / 3; + aParent.y = winSize.height / 2; + this.addChild(aParent, 0); + + sprite1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_01.png")); + sprite1.x = 0; + sprite1.y = 0; + + sprite2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_02.png")); + sprite2.x = 20; + sprite2.y = 30; + + sprite3 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_03.png")); + sprite3.x = -20; + sprite3.y = 30; + + aParent.addChild(sprite1); + sprite1.addChild(sprite2, -2); + sprite1.addChild(sprite3, 2); + + sprite1.runAction(cc.blink(5, 10)); + //----end31---- + }, + // + // Automation + // + testDuration:1.7, + pixel1:{"0":0, "1":0, "2":0, "3":255}, + pixel2:{"0":255, "1":204, "2":153, "3":255}, + visible1:null, + visible2:null, + setupAutomation:function () { + this.scheduleOnce(this.getSpriteVisible, 1.2); + }, + getSpriteVisible:function () { + var ret1 = this.readPixels(winSize.width / 3, winSize.height / 2 + 38, 5, 5); + var ret2 = this.readPixels(2 * winSize.width / 3, winSize.height / 2 + 38, 5, 5); + this.visible1 = this.containsPixel(ret1, this.pixel1) ? "true" : "false"; + this.visible2 = this.containsPixel(ret2, this.pixel1) ? "true" : "false"; + }, + getExpectedResult:function () { + var ret = {"visible1":"true", "visible2":"true", "visible3":"false", "visible4":"false"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 3, winSize.height / 2 + 38, 5, 5); + var ret2 = this.readPixels(2 * winSize.width / 3, winSize.height / 2 + 38, 5, 5); + this.visible3 = this.containsPixel(ret1, this.pixel2) ? "true" : "false"; + this.visible4 = this.containsPixel(ret2, this.pixel2) ? "true" : "false"; + var ret = {"visible1":this.visible1, "visible2":this.visible2, "visible3":this.visible3, "visible4":this.visible4}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteChildrenVisibilityIssue665 +// +//------------------------------------------------------------------ +var SpriteChildrenVisibilityIssue665 = SpriteTestDemo.extend({ + + _title:"Sprite & SpriteBatchNode Visibility", + _subtitle:"No sprites should be visible", + + ctor:function () { + //----start32----ctor + this._super(); + spriteFrameCache.addSpriteFrames(s_grossiniPlist); + // + // SpriteBatchNode + // + // parents + var aParent = new cc.SpriteBatchNode(s_grossini, 50); + aParent.x = winSize.width / 3; + aParent.y = winSize.height / 2; + this.addChild(aParent, 0); + + var sprite1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_01.png")); + sprite1.x = 0; + sprite1.y = 0; + + var sprite2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_02.png")); + sprite2.x = 20; + sprite2.y = 30; + + var sprite3 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_03.png")); + sprite3.x = -20; + sprite3.y = 30; + + // test issue #665 + sprite1.visible = false; + + aParent.addChild(sprite1); + sprite1.addChild(sprite2, -2); + sprite1.addChild(sprite3, 2); + + // + // Sprite + // + aParent = new cc.Node(); + aParent.x = 2 * winSize.width / 3; + aParent.y = winSize.height / 2; + this.addChild(aParent, 0); + + sprite1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_01.png")); + sprite1.x = 0; + sprite1.y = 0; + + sprite2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_02.png")); + sprite2.x = 20; + sprite2.y = 30; + + sprite3 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_03.png")); + sprite3.x = -20; + sprite3.y = 30; + + // test issue #665 + sprite1.visible = false; + + aParent.addChild(sprite1); + sprite1.addChild(sprite2, -2); + sprite1.addChild(sprite3, 2); + //----end32---- + }, + // + // Automation + // + testDuration:1, + pixel:{"0":0, "1":0, "2":0, "3":255}, + getExpectedResult:function () { + var ret = {"visible1":"false", "visible2":"false"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 3, winSize.height / 2 + 38, 5, 5); + var ret2 = this.readPixels(2 * winSize.width / 3, winSize.height / 2 + 38, 5, 5); + var ret = {"visible1":this.containsPixel(ret1, this.pixel) ? "false" : "true", "visible2":this.containsPixel(ret2, this.pixel) ? "false" : "true"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteChildrenAnchorPoint +// +//------------------------------------------------------------------ +var SpriteChildrenAnchorPoint = SpriteTestDemo.extend({ + + _title:"Sprite: children + anchor", + + ctor:function () { + //----start33----ctor + this._super(); + spriteFrameCache.addSpriteFrames(s_grossiniPlist); + + var aParent = new cc.Node(); + this.addChild(aParent, 0); + + // anchor (0,0) + var sprite1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_08.png")); + sprite1.x = winSize.width / 4; + sprite1.y = winSize.height / 2; + sprite1.anchorX = 0; + sprite1.anchorY = 0; + + var sprite2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_02.png")); + sprite2.x = 20; + sprite2.y = 30; + + var sprite3 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_03.png")); + sprite3.x = -20; + sprite3.y = 30; + + var sprite4 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_04.png")); + sprite4.x = 0; + sprite4.y = 0; + sprite4.scale = 0.5; + + aParent.addChild(sprite1); + sprite1.addChild(sprite2, -2); + sprite1.addChild(sprite3, -2); + sprite1.addChild(sprite4, 3); + + var point = new cc.Sprite(s_pathR1); + point.scale = 0.25; + point.x = sprite1.x; + point.y = sprite1.y; + this.addChild(point, 10); + + // anchor (0.5, 0.5) + sprite1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_08.png")); + sprite1.x = winSize.width / 2; + sprite1.y = winSize.height / 2; + sprite1.anchorX = 0.5; + sprite1.anchorY = 0.5; + + sprite2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_02.png")); + sprite2.x = 20; + sprite2.y = 30; + + sprite3 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_03.png")); + sprite3.x = -20; + sprite3.y = 30; + + sprite4 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_04.png")); + sprite4.x = 0; + sprite4.y = 0; + sprite4.scale = 0.5; + + aParent.addChild(sprite1); + sprite1.addChild(sprite2, -2); + sprite1.addChild(sprite3, -2); + sprite1.addChild(sprite4, 3); + + point = new cc.Sprite(s_pathR1); + point.scale = 0.25; + point.x = sprite1.x; + point.y = sprite1.y; + this.addChild(point, 10); + + // anchor (1,1) + sprite1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_08.png")); + sprite1.x = winSize.width / 2 + winSize.width / 4; + sprite1.y = winSize.height / 2; + sprite1.anchorX = 1; + sprite1.anchorY = 1; + + sprite2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_02.png")); + sprite2.x = 20; + sprite2.y = 30; + + sprite3 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_03.png")); + sprite3.x = -20; + sprite3.y = 30; + + sprite4 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_04.png")); + sprite4.x = 0; + sprite4.y = 0; + sprite4.scale = 0.5; + + aParent.addChild(sprite1); + sprite1.addChild(sprite2, -2); + sprite1.addChild(sprite3, -2); + sprite1.addChild(sprite4, 3); + + point = new cc.Sprite(s_pathR1); + point.scale = 0.25; + point.x = sprite1.x; + point.y = sprite1.y; + this.addChild(point, 10); + //----end33---- + }, + // + // Automation + // + testDuration:1, + pixel:{"0":255, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(3 * winSize.width / 4 - 87, winSize.height / 2 - 99, 5, 5); + var ret2 = this.readPixels(2 * winSize.width / 4 - 59, winSize.height / 2 - 66, 5, 5); + var ret3 = this.readPixels(winSize.width / 4 - 15, winSize.height / 2 - 6, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel) ? "yes" : "no", "pixel2":this.containsPixel(ret2, this.pixel) ? "yes" : "no", "pixel3":this.containsPixel(ret3, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteBatchNodeChildrenAnchorPoint +// +//------------------------------------------------------------------ +var SpriteBatchNodeChildrenAnchorPoint = SpriteTestDemo.extend({ + + _title:"SpriteBatchNode: children + anchor", + + ctor:function () { + //----start34----ctor + this._super(); + + spriteFrameCache.addSpriteFrames(s_grossiniPlist); + // + // SpriteBatchNode + // + // parents + var aParent = new cc.SpriteBatchNode(s_grossini, 50); + this.addChild(aParent, 0); + + // anchor (0,0) + var sprite1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_08.png")); + sprite1.x = winSize.width / 4; + sprite1.y = winSize.height / 2; + sprite1.anchorX = 0; + sprite1.anchorY = 0; + + var sprite2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_02.png")); + sprite2.x = 20; + sprite2.y = 30; + + var sprite3 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_03.png")); + sprite3.x = -20; + sprite3.y = 30; + + var sprite4 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_04.png")); + sprite4.x = 0; + sprite4.y = 0; + sprite4.scale = 0.5; + + aParent.addChild(sprite1); + sprite1.addChild(sprite2, -2); + sprite1.addChild(sprite3, -2); + sprite1.addChild(sprite4, 3); + + var point = new cc.Sprite(s_pathR1); + point.scale = 0.25; + point.x = sprite1.x; + point.y = sprite1.y; + this.addChild(point, 10); + + // anchor (0.5, 0.5) + sprite1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_08.png")); + sprite1.x = winSize.width / 2; + sprite1.y = winSize.height / 2; + sprite1.anchorX = 0.5; + sprite1.anchorY = 0.5; + + sprite2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_02.png")); + sprite2.x = 20; + sprite2.y = 30; + + sprite3 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_03.png")); + sprite3.x = -20; + sprite3.y = 30; + + sprite4 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_04.png")); + sprite4.x = 0; + sprite4.y = 0; + sprite4.scale = 0.5; + + aParent.addChild(sprite1); + sprite1.addChild(sprite2, -2); + sprite1.addChild(sprite3, -2); + sprite1.addChild(sprite4, 3); + + point = new cc.Sprite(s_pathR1); + point.scale = 0.25; + point.x = sprite1.x; + point.y = sprite1.y; + this.addChild(point, 10); + + + // anchor (1,1) + sprite1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_08.png")); + sprite1.x = winSize.width / 2 + winSize.width / 4; + sprite1.y = winSize.height / 2; + sprite1.anchorX = 1; + sprite1.anchorY = 1; + + sprite2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_02.png")); + sprite2.x = 20; + sprite2.y = 30; + + sprite3 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_03.png")); + sprite3.x = -20; + sprite3.y = 30; + + sprite4 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossini_dance_04.png")); + sprite4.x = 0; + sprite4.y = 0; + sprite4.scale = 0.5; + + aParent.addChild(sprite1); + sprite1.addChild(sprite2, -2); + sprite1.addChild(sprite3, -2); + sprite1.addChild(sprite4, 3); + + point = new cc.Sprite(s_pathR1); + point.scale = 0.25; + point.x = sprite1.x; + point.y = sprite1.y; + this.addChild(point, 10); + //----end34---- + }, + // + // Automation + // + testDuration:1, + pixel:{"0":255, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(3 * winSize.width / 4 - 87, winSize.height / 2 - 99, 5, 5); + var ret2 = this.readPixels(2 * winSize.width / 4 - 59, winSize.height / 2 - 66, 5, 5); + var ret3 = this.readPixels(winSize.width / 4 - 15, winSize.height / 2 - 6, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel) ? "yes" : "no", "pixel2":this.containsPixel(ret2, this.pixel) ? "yes" : "no", "pixel3":this.containsPixel(ret3, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteBatchNodeChildrenScale +// +//------------------------------------------------------------------ +var SpriteBatchNodeChildrenScale = SpriteTestDemo.extend({ + + _title:"Sprite/BatchNode + child + scale + rot", + + ctor:function () { + //----start35----ctor + this._super(); + spriteFrameCache.addSpriteFrames(s_grossini_familyPlist); + + var rot = cc.rotateBy(10, 360); + var seq = rot.repeatForever(); + + // + // Children + Scale using Sprite + // Test 1 + // + var aParent = new cc.Node(); + var sprite1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossinis_sister1.png")); + sprite1.x = winSize.width / 4; + sprite1.y = winSize.height / 4; + sprite1.scaleX = 0.5; + sprite1.scaleY = 2.0; + sprite1.runAction(seq); + + + var sprite2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossinis_sister2.png")); + sprite2.x = 50; + sprite2.y = 0; + + this.addChild(aParent); + aParent.addChild(sprite1); + sprite1.addChild(sprite2); + + rot = cc.rotateBy(10, 360); + seq = rot.repeatForever(); + // + // Children + Scale using SpriteBatchNode + // Test 2 + // + aParent = new cc.SpriteBatchNode(s_grossini_family); + sprite1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossinis_sister1.png")); + sprite1.x = 3 * winSize.width / 4; + sprite1.y = winSize.height / 4; + sprite1.scaleX = 0.5; + sprite1.scaleY = 2.0; + sprite1.runAction(seq); + + sprite2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossinis_sister2.png")); + sprite2.x = 50; + sprite2.y = 0; + + this.addChild(aParent); + aParent.addChild(sprite1); + sprite1.addChild(sprite2); + + rot = cc.rotateBy(10, 360); + seq = rot.repeatForever(); + // + // Children + Scale using Sprite + // Test 3 + // + aParent = new cc.Node(); + sprite1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossinis_sister1.png")); + sprite1.x = winSize.width / 4; + sprite1.y = 2 * winSize.height / 3; + sprite1.scaleX = 1.5; + sprite1.scaleY = 0.5; + sprite1.runAction(seq); + + sprite2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossinis_sister2.png")); + sprite2.x = 50; + sprite2.y = 0; + + this.addChild(aParent); + aParent.addChild(sprite1); + sprite1.addChild(sprite2); + + rot = cc.rotateBy(10, 360); + seq = rot.repeatForever(); + // + // Children + Scale using Sprite + // Test 4 + // + aParent = new cc.SpriteBatchNode(s_grossini_family); + sprite1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossinis_sister1.png")); + sprite1.x = 3 * winSize.width / 4; + sprite1.y = 2 * winSize.height / 3; + sprite1.scaleX = 1.5; + sprite1.scaleY = 0.5; + sprite1.runAction(seq); + + sprite2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("grossinis_sister2.png")); + sprite2.x = 50; + sprite2.y = 0; + + this.addChild(aParent); + aParent.addChild(sprite1); + sprite1.addChild(sprite2); + //----end35---- + }, + // + // Automation + // + testDuration:2.5, + pixel1:{"0":56, "1":116, "2":142, "3":255}, + pixel2:{"0":0, "1":0, "2":0, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes", "pixel4":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 4 - 31, 2 * winSize.height / 3 + 16, 5, 5); + var ret2 = this.readPixels(winSize.width / 4 - 38, 2 * winSize.height / 3 + 16, 3, 3); + var ret3 = this.readPixels(3 * winSize.width / 4 - 31, 2 * winSize.height / 3 + 16, 5, 5); + var ret4 = this.readPixels(3 * winSize.width / 4 - 38, 2 * winSize.height / 3 + 16, 3, 3); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2) ? "yes" : "no", + "pixel3":this.containsPixel(ret3, this.pixel1) ? "yes" : "no", + "pixel4":this.containsPixel(ret4, this.pixel2) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteChildrenChildren +// +//------------------------------------------------------------------ +var SpriteChildrenChildren = SpriteTestDemo.extend({ + _title:"Sprite multiple levels of children", + + ctor:function () { + //----start36----ctor + this._super(); + + spriteFrameCache.addSpriteFrames(s_ghostsPlist); + + var rot = cc.rotateBy(10, 360); + var seq = rot.repeatForever(); + + var rot_back = rot.reverse(); + var rot_back_fe = rot_back.repeatForever(); + + // + // SpriteBatchNode: 3 levels of children + // + var aParent = new cc.Node(); + this.addChild(aParent); + + // parent + var l1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("father.gif")); + l1.x = winSize.width / 2; + l1.y = winSize.height / 2; + l1.runAction(seq.clone()); + aParent.addChild(l1); + var l1W = l1.width, l1H = l1.height; + + // child left + var l2a = new cc.Sprite(spriteFrameCache.getSpriteFrame("sister1.gif")); + l2a.x = -50 + l1W / 2; + l2a.y = 0 + l1H / 2; + l2a.runAction(rot_back_fe.clone()); + l1.addChild(l2a); + var l2aW = l2a.width, l2aH = l2a.height; + + + // child right + var l2b = new cc.Sprite(spriteFrameCache.getSpriteFrame("sister2.gif")); + l2b.x = +50 + l1W / 2; + l2b.y = 0 + l1H / 2; + l2b.runAction(rot_back_fe.clone()); + l1.addChild(l2b); + var l2bW = l2b.width, l2bH = l2b.height; + + + // child left bottom + var l3a1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("child1.gif")); + l3a1.scale = 0.45; + l3a1.x = 0 + l2aW / 2; + l3a1.y = -100 + l2aH / 2; + l2a.addChild(l3a1); + + // child left top + var l3a2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("child1.gif")); + l3a2.scale = 0.45; + l3a2.x = 0 + l2aW / 2; + l3a2.y = +100 + l2aH / 2; + l2a.addChild(l3a2); + + // child right bottom + var l3b1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("child1.gif")); + l3b1.scale = 0.45; + l3b1.setFlippedY(true); + l3b1.x = 0 + l2bW / 2; + l3b1.y = -100 + l2bH / 2; + l2b.addChild(l3b1); + + // child right top + var l3b2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("child1.gif")); + l3b2.scale = 0.45; + l3b2.setFlippedY(true); + l3b2.x = 0 + l2bW / 2; + l3b2.y = +100 + l2bH / 2; + l2b.addChild(l3b2); + //----end36---- + }, + // + // Automation + // + testDuration:4, + pixel:{"0":153, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes", "pixel4":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 2 + 42, winSize.height / 2 + 145, 5, 5); + var ret2 = this.readPixels(winSize.width / 2 - 39, winSize.height / 2 + 55, 5, 5); + var ret3 = this.readPixels(winSize.width / 2 - 39, winSize.height / 2 - 146, 5, 5); + var ret4 = this.readPixels(winSize.width / 2 + 42, winSize.height / 2 - 56, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel) ? "yes" : "no", + "pixel3":this.containsPixel(ret3, this.pixel) ? "yes" : "no", + "pixel4":this.containsPixel(ret4, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteBatchNodeChildrenChildren +// +//------------------------------------------------------------------ +var SpriteBatchNodeChildrenChildren = SpriteTestDemo.extend({ + + _title:"SpriteBatchNode multiple levels of children", + + ctor:function () { + //----start37----ctor + this._super(); + + spriteFrameCache.addSpriteFrames(s_ghostsPlist); + + var rot = cc.rotateBy(10, 360); + var seq = rot.repeatForever(); + + var rot_back = rot.reverse(); + var rot_back_fe = rot_back.repeatForever(); + + // + // SpriteBatchNode: 3 levels of children + // + var aParent = new cc.SpriteBatchNode(s_ghosts); + if ("opengl" in cc.sys.capabilities) + aParent.texture.generateMipmap(); + this.addChild(aParent); + + // parent + var l1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("father.gif")); + l1.x = winSize.width / 2; + l1.y = winSize.height / 2; + l1.runAction(seq.clone()); + aParent.addChild(l1); + var l1W = l1.width, l1H = l1.height; + + // child left + var l2a = new cc.Sprite(spriteFrameCache.getSpriteFrame("sister1.gif")); + l2a.x = -50 + l1W / 2; + l2a.y = 0 + l1H / 2; + l2a.runAction(rot_back_fe.clone()); + l1.addChild(l2a); + var l2aW = l2a.width, l2aH = l2a.height; + + + // child right + var l2b = new cc.Sprite(spriteFrameCache.getSpriteFrame("sister2.gif")); + l2b.x = 50 + l1W / 2; + l2b.y = 0 + l1H / 2; + l2b.runAction(rot_back_fe.clone()); + l1.addChild(l2b); + var l2bW = l2b.width, l2bH = l2b.height; + + + // child left bottom + var l3a1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("child1.gif")); + l3a1.scale = 0.45; + l3a1.x = 0 + l2aW / 2; + l3a1.y = -100 + l2aH / 2; + l2a.addChild(l3a1); + + // child left top + var l3a2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("child1.gif")); + l3a2.scale = 0.45; + l3a2.x = 0 + l2aW / 2; + l3a2.y = +100 + l2aH / 2; + l2a.addChild(l3a2); + + // child right bottom + var l3b1 = new cc.Sprite(spriteFrameCache.getSpriteFrame("child1.gif")); + l3b1.scale = 0.45; + l3b1.setFlippedY(true); + l3b1.x = 0 + l2bW / 2; + l3b1.y = -100 + l2bH / 2; + l2b.addChild(l3b1); + + // child right top + var l3b2 = new cc.Sprite(spriteFrameCache.getSpriteFrame("child1.gif")); + l3b2.scale = 0.45; + l3b2.setFlippedY(true); + l3b2.x = 0 + l2bW / 2; + l3b2.y = +100 + l2bH / 2; + l2b.addChild(l3b2); + //----end37---- + }, + // + // Automation + // + testDuration:4, + pixel:{"0":153, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes", "pixel4":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 2 + 42, winSize.height / 2 + 145, 5, 5); + var ret2 = this.readPixels(winSize.width / 2 - 39, winSize.height / 2 + 55, 5, 5); + var ret3 = this.readPixels(winSize.width / 2 - 39, winSize.height / 2 - 146, 5, 5); + var ret4 = this.readPixels(winSize.width / 2 + 42, winSize.height / 2 - 56, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel) ? "yes" : "no", + "pixel3":this.containsPixel(ret3, this.pixel) ? "yes" : "no", + "pixel4":this.containsPixel(ret4, this.pixel) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteNilTexture +// +//------------------------------------------------------------------ +var SpriteNilTexture = SpriteTestDemo.extend({ + + _title:"Sprite without texture", + _subtitle:"opacity and color should work", + + ctor:function () { + //----start38----ctor + this._super(); + + // TEST: If no texture is given, then Opacity + Color should work. + var sprite = new cc.Sprite(); + sprite.setTextureRect(cc.rect(0, 0, 300, 300)); + // sprite.color = cc.color.RED; + sprite.color = cc.color(255, 0, 0); + sprite.opacity = 128; + sprite.x = 3 * winSize.width / 4; + sprite.y = winSize.height / 2; + this.addChild(sprite, 100); + + sprite = new cc.Sprite(); + sprite.setTextureRect(cc.rect(0, 0, 300, 300)); + //sprite.color = cc.color.BLUE; + sprite.color = cc.color(0, 0, 255); + sprite.opacity = 128; + sprite.x = winSize.width / 4; + sprite.y = winSize.height / 2; + this.addChild(sprite, 100); + //----end38---- + }, + // + // Automation + // + testDuration:1, + pixel1:{"0":0, "1":0, "2":128, "3":255}, + pixel2:{"0":128, "1":0, "2":0, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 4, winSize.height / 2, 5, 5); + var ret2 = this.readPixels(3 * winSize.width / 4, winSize.height / 2, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1) ? "yes" : "no", "pixel2":this.containsPixel(ret2, this.pixel2) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// SpriteSubclass +// +//------------------------------------------------------------------ +var MySprite1 = cc.Sprite.extend({ + _ivar:0, + ctor: function(spriteFrameName) { + this._super(spriteFrameName); + } +}); + +var MySprite2 = cc.Sprite.extend({ + _ivar:0, + ctor: function(name) { + this._super(name); + } +}); + +var SpriteSubclass = SpriteTestDemo.extend({ + _title:"Sprite subclass", + _subtitle:"Testing initWithTexture:rect method", + + ctor:function () { + //----start39----ctor + this._super(); + + spriteFrameCache.addSpriteFrames(s_ghostsPlist); + var aParent = new cc.SpriteBatchNode(s_ghosts); + + // MySprite1 + var sprite = new MySprite1("#father.gif"); + sprite.x = winSize.width / 4; + sprite.y = winSize.height / 2; + aParent.addChild(sprite); + this.addChild(aParent); + + // MySprite2 + var sprite2 = new MySprite2(s_pathGrossini); + this.addChild(sprite2); + sprite2.x = winSize.width / 4 * 3; + sprite2.y = winSize.height / 2; + //----end39---- + }, + // + // Automation + // + testDuration:1, + pixel1:{"0":249, "1":30, "2":20, "3":255}, + pixel2:{"0":255, "1":204, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 4, winSize.height / 2 - 15, 5, 5); + var ret2 = this.readPixels(winSize.width / 4 * 3, winSize.height / 2 + 44, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1) ? "yes" : "no", "pixel2":this.containsPixel(ret2, this.pixel2) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// AnimationCache +// +//------------------------------------------------------------------ +var AnimationCacheTest = SpriteTestDemo.extend({ + + _title:"AnimationCache", + _subtitle:"Sprite should be animated", + + ctor:function () { + //----start40----ctor + this._super(); + spriteFrameCache.addSpriteFrames(s_grossiniPlist); + spriteFrameCache.addSpriteFrames(s_grossini_grayPlist); + spriteFrameCache.addSpriteFrames(s_grossini_bluePlist); + + // + // create animation "dance" + // + var animFrames = []; + var frame, animFrame; + var str = ""; + for (var i = 1; i < 15; i++) { + str = "grossini_dance_" + (i < 10 ? ("0" + i) : i) + ".png"; + frame = spriteFrameCache.getSpriteFrame(str); + animFrame = new cc.AnimationFrame(frame, 1); + animFrames.push(animFrame); + } + + var animation = new cc.Animation(animFrames, 0.2); + + // Add an animation to the Cache + cc.animationCache.addAnimation(animation, "dance"); + + // + // create animation "dance gray" + // + animFrames = []; + for (i = 1; i < 15; i++) { + str = "grossini_dance_gray_" + (i < 10 ? ("0" + i) : i) + ".png"; + frame = spriteFrameCache.getSpriteFrame(str); + animFrames.push(frame); + } + + animation = new cc.Animation(animFrames, 0.2); + + // Add an animation to the Cache + cc.animationCache.addAnimation(animation, "dance_gray"); + + // + // create animation "dance blue" + // + animFrames = []; + for (i = 1; i < 4; i++) { + str = "grossini_blue_0" + i + ".png"; + frame = spriteFrameCache.getSpriteFrame(str); + animFrames.push(frame); + } + + animation = new cc.Animation(animFrames, 0.2); + + // Add an animation to the Cache + cc.animationCache.addAnimation(animation, "dance_blue"); + + var animCache = cc.animationCache; + + var normal = animCache.getAnimation("dance"); + normal.setRestoreOriginalFrame(true); + var dance_grey = animCache.getAnimation("dance_gray"); + dance_grey.setRestoreOriginalFrame(true); + var dance_blue = animCache.getAnimation("dance_blue"); + dance_blue.setRestoreOriginalFrame(true); + + var animN = cc.animate(normal); + var animG = cc.animate(dance_grey); + var animB = cc.animate(dance_blue); + + var seq = cc.sequence(animN, animG, animB); + + frame = spriteFrameCache.getSpriteFrame("grossini_dance_01.png"); + var grossini = new cc.Sprite(frame); + + grossini.x = winSize.width / 2; + + grossini.y = winSize.height / 2; + this.addChild(grossini); + + // run the animation + grossini.runAction(seq); + //----end40---- + }, + // + // Automation + // + testDuration:6.5, + ePixel1:{"0":51, "1":0, "2":51, "3":255}, + ePixel2:{"0":15, "1":15, "2":15, "3":255}, + ePixel3:{"0":0, "1":38, "2":0, "3":255}, + cPixel1:null, + cPixel2:null, + cPixel3:null, + setupAutomation:function () { + //----start40----setupAutomation + var fun1 = function () { + this.cPixel1 = this.readPixels(winSize.width / 2, winSize.height / 2, 5, 5); + } + this.scheduleOnce(fun1, 0.4); + + var fun2 = function () { + this.cPixel2 = this.readPixels(winSize.width / 2, winSize.height / 2, 5, 5); + } + this.scheduleOnce(fun2, 3.2); + + var fun3 = function () { + this.cPixel3 = this.readPixels(winSize.width / 2, winSize.height / 2, 5, 5); + } + this.scheduleOnce(fun3, 6); + //----end40---- + }, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret = {"pixel1":this.containsPixel(this.cPixel1, this.ePixel1) ? "yes" : "no", "pixel2":this.containsPixel(this.cPixel2, this.ePixel2) ? "yes" : "no", "pixel3":this.containsPixel(this.cPixel3, this.ePixel3, true, 5) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +var NodeSort = SpriteTestDemo.extend({ + _node:null, + _sprite1:null, + _sprite2:null, + _sprite3:null, + _sprite4:null, + _sprite5:null, + + _title:"node sort same index", + _subtitle:"tag order in console should be 2,1,3,4,5", + + ctor:function () { + //----start49----ctor + this._super(); + this._node = new cc.Node(); + this.addChild(this._node, 0, 0); + + this._sprite1 = new cc.Sprite(s_piece, cc.rect(128, 0, 64, 64)); + this._sprite1.x = 100; + this._sprite1.y = 160; + this._node.addChild(this._sprite1, -6, 1); + + this._sprite2 = new cc.Sprite(s_piece, cc.rect(128, 0, 64, 64)); + this._sprite2.x = 164; + this._sprite2.y = 160; + this._node.addChild(this._sprite2, -6, 2); + + this._sprite4 = new cc.Sprite(s_piece, cc.rect(128, 0, 64, 64)); + this._sprite4.x = 292; + this._sprite4.y = 160; + this._node.addChild(this._sprite4, -3, 4); + + this._sprite3 = new cc.Sprite(s_piece, cc.rect(128, 0, 64, 64)); + this._sprite3.x = 228; + this._sprite3.y = 160; + this._node.addChild(this._sprite3, -4, 3); + + this._sprite5 = new cc.Sprite(s_piece, cc.rect(128, 0, 64, 64)); + this._sprite5.x = 356; + this._sprite5.y = 160; + this._node.addChild(this._sprite5, -3, 5); + + this.schedule(this.reorderSprite); + //----end49---- + }, + + reorderSprite:function (dt) { + //----start49----reorderSprite + this.unschedule(this.reorderSprite); + + cc.log("Before reorder--"); + + var i = 0; + var child; + var nodeChildren = this._node.children; + for (i = 0; i < nodeChildren.length; i++) { + child = nodeChildren[i]; + cc.log("tag:" + child.tag + " z: " + child.zIndex); + } + + //z-4 + this._node.reorderChild(this._node.children[0], -6); + this._node.sortAllChildren(); + + cc.log("After reorder--"); + nodeChildren = this._node.children; + for (i = 0; i < nodeChildren.length; i++) { + child = nodeChildren[i]; + cc.log("tag:" + child.tag + " z: " + + child.zIndex); + this.testOrders.push(child.tag); + } + //----end49---- + }, + // + // Automation + // + testDuration:1, + testOrders:[], + getExpectedResult:function () { + return JSON.stringify([2, 1, 3, 4, 5]); + }, + getCurrentResult:function () { + return JSON.stringify(this.testOrders); + } +}); + +var SpriteBatchNodeReorderSameIndex = SpriteTestDemo.extend({ + _batchNode:null, + _sprite1:null, + _sprite2:null, + _sprite3:null, + _sprite4:null, + _sprite5:null, + + _title:"SpriteBatchNodeReorder same index", + _subtitle:"tag order in console should be 2,3,4,5,1", + + ctor:function () { + //----start47----ctor + this._super(); + this._batchNode = new cc.SpriteBatchNode(s_piece, 15); + this.addChild(this._batchNode, 1, 0); + + this._sprite1 = new cc.Sprite(this._batchNode.texture, cc.rect(128, 0, 64, 64)); + this._sprite1.x = 100; + this._sprite1.y = 160; + this._batchNode.addChild(this._sprite1, 3, 1); + + this._sprite2 = new cc.Sprite(this._batchNode.texture, cc.rect(128, 0, 64, 64)); + this._sprite2.x = 164; + this._sprite2.y = 160; + this._batchNode.addChild(this._sprite2, 4, 2); + + this._sprite3 = new cc.Sprite(this._batchNode.texture, cc.rect(128, 0, 64, 64)); + this._sprite3.x = 228; + this._sprite3.y = 160; + this._batchNode.addChild(this._sprite3, 4, 3); + + this._sprite4 = new cc.Sprite(this._batchNode.texture, cc.rect(128, 0, 64, 64)); + this._sprite4.x = 292; + this._sprite4.y = 160; + this._batchNode.addChild(this._sprite4, 5, 4); + + this._sprite5 = new cc.Sprite(this._batchNode.texture, cc.rect(128, 0, 64, 64)); + this._sprite5.x = 356; + this._sprite5.y = 160; + this._batchNode.addChild(this._sprite5, 6, 5); + + this.scheduleOnce(this.reorderSprite, 2); + //----end47---- + }, + + reorderSprite:function (dt) { + //----start47----reorderSprite + this._batchNode.reorderChild(this._sprite4, 4); + this._batchNode.reorderChild(this._sprite5, 4); + this._batchNode.reorderChild(this._sprite1, 4); + + this._batchNode.sortAllChildren(); + + var descendants = this._batchNode.descendants; + + for (var i = 0; i < descendants.length; i++) { + var child = descendants[i]; + cc.log("tag:" + child.tag); + this.testDescendants.push(child.tag); + } + //----end47---- + }, + // + // Automation + // + testDuration:2.2, + testDescendants:[], + getExpectedResult:function () { + return JSON.stringify([2, 3, 4, 5, 1]); + }, + getCurrentResult:function () { + return JSON.stringify(this.testDescendants); + } +}); + +var SpriteBatchNodeReorderOneChild = SpriteTestDemo.extend({ + _batchNode:null, + _reoderSprite:null, + + _title:"SpriteBatchNode reorder 1 child", + ctor:function () { + //----start48----ctor + this._super(); + + spriteFrameCache.addSpriteFrames(s_ghostsPlist); + // + // SpriteBatchNode: 3 levels of children + // + var aParent = new cc.SpriteBatchNode(s_ghosts); + + this._batchNode = aParent; + //[[aParent texture] generateMipmap]; + if ("opengl" in cc.sys.capabilities) + aParent.texture.generateMipmap(); + this.addChild(aParent); + + // parent + var l1 = new cc.Sprite("#father.gif"); + l1.x = winSize.width / 2; + l1.y = winSize.height / 2; + + aParent.addChild(l1); + var l1W = l1.width, l1H = l1.height; + + // child left + var l2a = new cc.Sprite("#sister1.gif"); + l2a.x = -10 + l1W / 2; + l2a.y = 0 + l1H / 2; + + l1.addChild(l2a, 1); + var l2aW = l2a.width, l2aH = l2a.height; + + // child right + var l2b = new cc.Sprite("#sister2.gif"); + l2b.x = +50 + l1W / 2; + l2b.y = 0 + l1H / 2; + + l1.addChild(l2b, 2); + var l2bW = l2b.width, l2bH = l2b.height; + + // child left bottom + var l3a1 = new cc.Sprite("#child1.gif"); + l3a1.scale = 0.45; + l3a1.x = 0 + l2aW / 2; + l3a1.y = -50 + l2aH / 2; + l2a.addChild(l3a1, 1); + + // child left top + var l3a2 = new cc.Sprite("#child1.gif"); + l3a2.scale = 0.45; + l3a2.x = 0 + l2aW / 2; + l3a2.y = +50 + l2aH / 2; + l2a.addChild(l3a2, 2); + + this._reoderSprite = l2a; + + // child right bottom + var l3b1 = new cc.Sprite("#child1.gif"); + l3b1.scale = 0.45; + l3b1.setFlippedY(true); + l3b1.x = 0 + l2bW / 2; + l3b1.y = -50 + l2bH / 2; + l2b.addChild(l3b1); + + // child right top + var l3b2 = new cc.Sprite("#child1.gif"); + l3b2.scale = 0.45; + l3b2.setFlippedY(true); + l3b2.x = 0 + l2bW / 2; + l3b2.y = 50 + l2bH / 2; + l2b.addChild(l3b2); + + this.scheduleOnce(this.reorderSprite, 2.0); + //----end48---- + }, + + reorderSprite:function (dt) { + this._reoderSprite.parent.reorderChild(this._reoderSprite, -1); + this._batchNode.sortAllChildren(); + //cc.Sprite* child; + //CCARRAY_FOREACH(batchNode.descendants,child) NSLog(@"tag %i",child.tag); + }, + // + // Automation + // + testDuration:2.5, + pixel:{"0":0, "1":102, "2":255, "3":255}, + getExpectedResult:function () { + var ret = {"pixel":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 2 - 11, winSize.height / 2 + 33, 3, 3); + var ret = {"pixel":this.containsPixel(ret1, this.pixel, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +var SpriteBatchNodeSkewNegativeScaleChildren = SpriteTestDemo.extend({ + _title:"SpriteBatchNode + children + skew", + _subtitle:"SpriteBatchNode skew + negative scale with children", + + ctor:function () { + //----start51----ctor + this._super(); + + var cache = spriteFrameCache; + cache.addSpriteFrames(s_grossiniPlist); + cache.addSpriteFrames(s_grossini_grayPlist, s_grossini_gray); + + var spritebatch = new cc.SpriteBatchNode(s_grossini); + this.addChild(spritebatch); + + for (var i = 0; i < 2; i++) { + var sprite = new cc.Sprite("#grossini_dance_01.png"); + sprite.x = winSize.width / 4 * (i + 1); + sprite.y = winSize.height / 2; + + // Skew + var skewX = cc.skewBy(2, 45, 0); + var skewX_back = skewX.reverse(); + var skewY = cc.skewBy(2, 0, 45); + var skewY_back = skewY.reverse(); + + if (i === 1) + sprite.scale = -1.0; + + var seq_skew = cc.sequence(skewX, skewX_back, skewY, skewY_back); + sprite.runAction(seq_skew.repeatForever()); + + var child1 = new cc.Sprite("#grossini_dance_01.png"); + child1.x = sprite.width / 2.0; + child1.y = sprite.height / 2.0; + + child1.scale = 0.8; + sprite.addChild(child1); + spritebatch.addChild(sprite, i); + } + //----end51---- + }, + // + // Automation + // + testDuration:6, + pixel1:{"0":51, "1":0, "2":51, "3":255}, + pixel2:{"0":0, "1":0, "2":0, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 4 + 21, winSize.height / 2 + 22, 5, 5); + var ret2 = this.readPixels(winSize.width / 4 + 11, winSize.height / 2 + 14, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1) ? "yes" : "no", + "pixel2":!this.containsPixel(ret2, this.pixel2) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +var SpriteSkewNegativeScaleChildren = SpriteTestDemo.extend({ + _title:"Sprite + children + skew", + _subtitle:"Sprite skew + negative scale with children", + + ctor:function () { + //----start50----ctor + this._super(); + + var cache = spriteFrameCache; + cache.addSpriteFrames(s_grossiniPlist); + cache.addSpriteFrames(s_grossini_grayPlist, s_grossini_gray); + + var parent = new cc.Node(); + this.addChild(parent); + + for (var i = 0; i < 2; i++) { + var sprite = new cc.Sprite("#grossini_dance_01.png"); + sprite.x = winSize.width / 4 * (i + 1); + sprite.y = winSize.height / 2; + + // Skew + var skewX = cc.skewBy(2, 45, 0); + var skewX_back = skewX.reverse(); + var skewY = cc.skewBy(2, 0, 45); + var skewY_back = skewY.reverse(); + + if (i === 1) + sprite.scale = -1.0; + + var seq_skew = cc.sequence(skewX, skewX_back, skewY, skewY_back); + sprite.runAction(seq_skew.repeatForever()); + + var child1 = new cc.Sprite("#grossini_dance_01.png"); + child1.x = sprite.width / 2.0; + child1.y = sprite.height / 2.0; + + sprite.addChild(child1); + child1.scale = 0.8; + parent.addChild(sprite, i); + } + //----end50---- + }, + // + // Automation + // + testDuration:6, + pixel1:{"0":51, "1":0, "2":51, "3":255}, + pixel2:{"0":0, "1":0, "2":0, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 4 + 21, winSize.height / 2 + 22, 5, 5); + var ret2 = this.readPixels(winSize.width / 4 + 11, winSize.height / 2 + 14, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1, false) ? "yes" : "no", + "pixel2":!this.containsPixel(ret2, this.pixel2, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +var DoubleSprite = cc.Sprite.extend({ + HD:false, + + ctor:function (fileName) { + this._super(fileName); + //var resolutionType = texture.getResolutionType(); + //this.HD = ( resolutionType == cc.kCCResolutioniPhoneRetinaDisplay || resolutionType == kCCResolutioniPadRetinaDisplay ); + }, + + setContentSize:function (size) { + var newSize = cc.size(size.width, size.height); + // If Retina Display and Texture is in HD then scale the vertex rect + if (cc.contentScaleFactor() == 2 && !this.HD) { + newSize.width *= 2; + newSize.height *= 2; + } + this._super(newSize); + }, + _setWidth:function (value) { + // If Retina Display and Texture is in HD then scale the vertex rect + if (cc.contentScaleFactor() == 2 && !this.HD) { + value *= 2; + } + this._super(value); + }, + _setHeight:function (value) { + // If Retina Display and Texture is in HD then scale the vertex rect + if (cc.contentScaleFactor() == 2 && !this.HD) { + value *= 2; + } + this._super(value); + }, + + setVertexRect:function (rect) { + // If Retina Display and Texture is in HD then scale the vertex rect + if (cc.contentScaleFactor() == 2 && !this.HD) { + rect.width *= 2; + rect.height *= 2; + } + this._super(rect); + } +}); + +cc.defineGetterSetter(DoubleSprite.prototype, "width", DoubleSprite.prototype._getWidth, DoubleSprite.prototype._setWidth); +cc.defineGetterSetter(DoubleSprite.prototype, "height", DoubleSprite.prototype._getHeight, DoubleSprite.prototype._setHeight); + +var SpriteDoubleResolution = SpriteTestDemo.extend({ + + _title:"Sprite Double resolution", + _subtitle:"Retina Display. SD (left) should be equal to HD (right)", + + ctor:function () { + //----start52----ctor + this._super(); + + // + // LEFT: SD sprite + // + // there is no HD resolution file of grossini_dance_08. + var spriteSD = new DoubleSprite(s_grossiniDance08); + this.addChild(spriteSD); + spriteSD.x = winSize.width / 4; + spriteSD.y = winSize.height / 2; + + var child1_left = new DoubleSprite(s_grossiniDance08); + spriteSD.addChild(child1_left); + child1_left.x = -30; + child1_left.y = 0; + + var child1_right = new cc.Sprite(s_pathGrossini); + spriteSD.addChild(child1_right); + child1_left.x = spriteSD.height; + child1_left.y = 0; + + // + // RIGHT: HD sprite + // + // there is an HD version of grossini.png + var spriteHD = new cc.Sprite(s_pathGrossini); + this.addChild(spriteHD); + spriteHD.x = winSize.width / 4 * 3; + spriteHD.y = winSize.height / 2; + + var child2_left = new DoubleSprite(s_grossiniDance08); + spriteHD.addChild(child2_left); + child2_left.x = -30; + child2_left.y = 0; + + var child2_right = new cc.Sprite(s_pathGrossini); + spriteHD.addChild(child2_right); + child2_left.x = spriteHD.height; + child2_left.y = 0; + + + // Actions + var scale = cc.scaleBy(2, 0.5); + var scale_back = scale.reverse(); + var seq = cc.sequence(scale, scale_back); + + var seq_copy = seq.clone(); + + spriteSD.runAction(seq); + spriteHD.runAction(seq_copy); + //----end52---- + } +}); + +var AnimationCacheFile = SpriteTestDemo.extend({ + + _title:"AnimationCache - Load file", + _subtitle:"Sprite should be animated", + + ctor:function () { + //----start54----ctor + this._super(); + var frameCache = spriteFrameCache; + frameCache.addSpriteFrames(s_grossiniPlist); + frameCache.addSpriteFrames(s_grossini_grayPlist); + frameCache.addSpriteFrames(s_grossini_bluePlist); + + // Purge previously loaded animation + if(cc.animationCache._clear) + cc.animationCache._clear(); + var animCache = cc.animationCache; + + // Add an animation to the Cache + // XXX API-FIX XXX + // renamed from addAnimationsWithFile to addAnimations + animCache.addAnimations(s_animationsPlist); + + var normal = animCache.getAnimation("dance_1"); + normal.setRestoreOriginalFrame(true); + var dance_grey = animCache.getAnimation("dance_2"); + dance_grey.setRestoreOriginalFrame(true); + var dance_blue = animCache.getAnimation("dance_3"); + dance_blue.setRestoreOriginalFrame(true); + + var animN = cc.animate(normal); + var animG = cc.animate(dance_grey); + var animB = cc.animate(dance_blue); + + var seq = cc.sequence(animN, animG, animB); + + // create an sprite with frame name + // texture-less sprites are not supported + var grossini = new cc.Sprite("#grossini_dance_01.png"); + + grossini.x = winSize.width / 2; + + grossini.y = winSize.height / 2; + this.addChild(grossini); + + // run the animation + grossini.runAction(seq); + //----end54---- + }, + // + // Automation + // + testDuration:6.5, + ePixel1:{"0":51, "1":0, "2":51, "3":255}, + ePixel2:{"0":15, "1":15, "2":15, "3":255}, + ePixel3:{"0":0, "1":38, "2":0, "3":255}, + cPixel1:null, + cPixel2:null, + cPixel3:null, + setupAutomation:function () { + this.scheduleOnce(this.getPixel1, 0.4); + this.scheduleOnce(this.getPixel2, 3.2); + this.scheduleOnce(this.getPixel3, 6); + }, + getPixel1:function () { + this.cPixel1 = this.readPixels(winSize.width / 2, winSize.height / 2, 5, 5); + }, + getPixel2:function () { + this.cPixel2 = this.readPixels(winSize.width / 2, winSize.height / 2, 5, 5); + }, + getPixel3:function () { + this.cPixel3 = this.readPixels(winSize.width / 2, winSize.height / 2, 5, 5); + }, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret = {"pixel1":this.containsPixel(this.cPixel1, this.ePixel1) ? "yes" : "no", "pixel2":this.containsPixel(this.cPixel2, this.ePixel2) ? "yes" : "no", "pixel3":this.containsPixel(this.cPixel3, this.ePixel3, true, 5) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +var SpriteBatchBug1217 = SpriteTestDemo.extend({ + + _title:"SpriteBatch - Bug 1217", + _subtitle:"Adding big family to spritebatch. You shall see 3 heads", + + ctor:function () { + //----start53----ctor + this._super(); + var bn = new cc.SpriteBatchNode(s_grossini_dance_atlas, 15); + + var s1 = new cc.Sprite(bn.texture, cc.rect(0, 0, 57, 57)); + var s2 = new cc.Sprite(bn.texture, cc.rect(0, 0, 57, 57)); + var s3 = new cc.Sprite(bn.texture, cc.rect(0, 0, 57, 57)); + + s1.color = cc.color(255, 0, 0); + s2.color = cc.color(0, 255, 0); + s3.color = cc.color(0, 0, 255); + + s1.x = 20; + + s1.y = 200; + s2.x = 100; + s2.y = 0; + s3.x = 100; + s3.y = 0; + + bn.x = 0; + + bn.y = 0; + + //!!!!! + s1.addChild(s2); + s2.addChild(s3); + bn.addChild(s1); + + this.addChild(bn); + //----end53---- + }, + // Automation + testDuration:2.1, + pixel1:{"0":51, "1":0, "2":0, "3":255}, + pixel2:{"0":0, "1":0, "2":0, "3":255}, + pixel3:{"0":0, "1":0, "2":51, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(20, 174, 3, 3); + var ret2 = this.readPixels(90, 145, 3, 3); + var ret3 = this.readPixels(163, 116, 3, 3); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1, false) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2, false) ? "yes" : "no", + "pixel3":this.containsPixel(ret3, this.pixel3, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +var TextureColorCacheIssue = SpriteTestDemo.extend({ + + _title:"Texture Color Cache Issue Test", + _subtitle:"You should see two different sprites colored green and blue", + + ctor:function () { + //----start55----ctor + this._super(); + + var spriteFrameCache = cc.spriteFrameCache; + spriteFrameCache.addSpriteFrames(s_tcc_issue_1_plist, s_tcc_issue_1); + spriteFrameCache.addSpriteFrames(s_tcc_issue_2_plist, s_tcc_issue_2); + + var grossini = new cc.Sprite('#tcc_grossini_dance_01.png'); + grossini.x = winSize.width / 3; + grossini.y = winSize.height / 2; + + var sister = new cc.Sprite('#tcc_grossinis_sister1.png'); + sister.x = winSize.width / 3 * 2; + sister.y = winSize.height / 2; + + this.addChild(grossini); + this.addChild(sister); + + grossini.color = cc.color(1, 255, 1); + sister.color = cc.color(1, 1, 255); + //----end55---- + }, + onExit:function () { + //----start55----onExit + spriteFrameCache.removeSpriteFramesFromFile(s_tcc_issue_1_plist); + spriteFrameCache.removeSpriteFramesFromFile(s_tcc_issue_2_plist); + this._super(); + //----end55---- + }, + // Automation + pixel1:{"0":0, "1":204, "2":0, "3":255}, + pixel2:{"0":0, "1":0, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 3, winSize.height / 2 + 43, 5, 5); + var ret2 = this.readPixels(winSize.width / 3 * 2, winSize.height / 2 - 6, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1, true, 3) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2, true, 3) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +var TextureColorCacheIssue2 = SpriteTestDemo.extend({ + + _title:"Texture Color Cache Issue Test #2", + _subtitle:"You should see two different sprites magenta and yellow", + + ctor:function () { + //----start56----ctor + this._super(); + + var spriteFrameCache = cc.spriteFrameCache; + spriteFrameCache.addSpriteFrames(s_tcc_issue_1_plist, s_tcc_issue_1); + spriteFrameCache.addSpriteFrames(s_tcc_issue_2_plist, s_tcc_issue_2); + + var grossini = new cc.Sprite('#tcc_grossini_dance_01.png'); + grossini.x = winSize.width / 3; + grossini.y = winSize.height / 2; + + var sister = new cc.Sprite('#tcc_grossinis_sister1.png'); + sister.x = winSize.width / 3 * 2; + sister.y = winSize.height / 2; + + this.addChild(grossini); + this.addChild(sister); + + grossini.color = cc.color(255, 255, 0); + sister.color = cc.color(255, 0, 255); + //----end56---- + }, + onExit:function () { + //----start56----onExit + spriteFrameCache.removeSpriteFramesFromFile(s_tcc_issue_1_plist); + spriteFrameCache.removeSpriteFramesFromFile(s_tcc_issue_2_plist); + this._super(); + //----end56---- + }, + // Automation + pixel1:{"0":255, "1":204, "2":0, "3":255}, + pixel2:{"0":255, "1":0, "2":153, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 3, winSize.height / 2 + 43, 5, 5); + var ret2 = this.readPixels(winSize.width / 3 * 2, winSize.height / 2 - 3, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1, true, 5) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2, true, 5) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +var TextureRotatedSpriteFrame = SpriteTestDemo.extend({ + + _title:"Sub Sprite (rotated source)", + _subtitle:"createWithSpriteFrameName(); sub sprite", + + ctor:function () { + //----start57----ctor + this._super(); + + cc.spriteFrameCache.addSpriteFrames(s_s9s_blocks9_plist); + + var block = new cc.Sprite('#blocks9r.png'); + + var x = winSize.width / 2; + var y = 0 + (winSize.height / 2); + + block.setTextureRect(cc.rect(32, 32, 32, 32), true, cc.rect(32, 32, 32, 32)); + + block.x = x; + + block.y = y; + this.addChild(block); + //----end57---- + }, + // Automation + pixel1:{"0":255, "1":204, "2":153, "3":255}, + pixel2:{"0":51, "1":0, "2":51, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(winSize.width / 2 - 14, winSize.height / 2 - 8, 5, 5); + var ret2 = this.readPixels(winSize.width / 2 + 12, winSize.height / 2, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1, true, 5) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2, true, 5) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +var SpriteWithRepeatingTexture = SpriteTestDemo.extend({ + + _title:"Sprite with Repeating texture", + _subtitle:"aTexture.setTexParameters(cc.LINEAR, cc.LINEAR, cc.REPEAT, cc.REPEAT);", + + ctor:function () { + //----start58----ctor + this._super(); + var block = new cc.Sprite(s_pathBlock); + + var x = winSize.width / 2; + var y = (winSize.height / 2); + + block.setTextureRect(cc.rect(0,0, 320,240)); + block.setPosition(x, y); + block.getTexture().setTexParameters(cc.LINEAR, cc.LINEAR, cc.REPEAT, cc.REPEAT); + this.addChild(block); + //----end58---- + } +}); + +var SpriteBlendFuncTest = SpriteTestDemo.extend({ + //webgl only + _title: "", //Sprite BlendFunc test + _subtitle: "", + + ctor: function(){ + //----start59----ctor + this._super(); + + var destFactors = [gl.ZERO, gl.ONE, gl.SRC_COLOR, gl.ONE_MINUS_SRC_COLOR, gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA], + srcFactors = [gl.ZERO, gl.ONE, gl.DST_COLOR, gl.ONE_MINUS_DST_COLOR, gl.DST_ALPHA, gl.ONE_MINUS_DST_ALPHA]; + var destTitles = ["ZERO", "ONE", "SRC_COLOR", "ONE_MINUS_SRC_COLOR", "SRC_ALPHA", "ONE_MINUS_SRC_ALPHA"], + srcTitles = ["ZERO", "ONE", "DST_COLOR", "ONE_MINUS_DST_COLOR", "SRC_ALPHA", "ONE_MINUS_SRC_ALPHA"]; + + var sourceImg = "res/Images/dot.png", destImg = "res/Images/wood.jpg"; + var sourceTexture = cc.textureCache.addImage(sourceImg); + sourceTexture.handleLoadedTexture(true); + var sourceSprite = new cc.Sprite(sourceImg); + var destSprite = new cc.Sprite(destImg); + sourceSprite.setScale(0.8); + destSprite.setScale(0.8); + sourceSprite.setPosition(60,400); + destSprite.setPosition(120,400); + this.addChild(sourceSprite); + this.addChild(destSprite); + + var i, j, title, fontSize, titleLabel; + for(i = 0; i < destTitles.length; i++){ + title = destTitles[i]; + fontSize = (title.length > 10) ? 14 : 18; + titleLabel = new cc.LabelTTF(title, "Arial", fontSize); + titleLabel.setAnchorPoint(0, 0.5); + titleLabel.setPosition(0, 355 - 60 * i); + this.addChild(titleLabel); + } + + for(i = 0; i < srcTitles.length; i++){ + title = srcTitles[i]; + fontSize = (title.length > 10) ? 14 : 18; + titleLabel = new cc.LabelTTF(title, "Arial", fontSize); + titleLabel.setAnchorPoint(0, 0.5); + titleLabel.setPosition(220 + i * 60, 390); + titleLabel.setRotation(-20); + this.addChild(titleLabel); + } + //j = 0; + for(i = 0; i < srcFactors.length; i++){ + for(j = 0; j < destFactors.length; j++){ + sourceSprite = new cc.Sprite(sourceImg); + //sourceSprite.setScale(0.8); + sourceSprite.setPosition( 220 + i * 60, 355 - j * 60); + sourceSprite.setBlendFunc(srcFactors[i], destFactors[j]); + + + destSprite = new cc.Sprite(destImg); + //destSprite.setScale(0.8); + destSprite.setPosition( 220 + i * 60, 355 - j * 60); +// destSprite.setBlendFunc(srcFactors[j], destFactors[i]); + + this.addChild(destSprite,1); + this.addChild(sourceSprite,2); + } + } + //----end59---- + } +}); + +var SpriteTestScene = TestScene.extend({ + runThisTest:function (num) { + spriteTestIdx = (num || num == 0) ? (num - 1) : -1; + var layer = nextSpriteTest(); + this.addChild(layer); + + director.runScene(this); + } +}); + +// +// Flow control +// +var arrayOfSpriteTest = [ + Sprite1, + SpriteBatchNode1, + SpriteFrameTest, + SpriteFrameAliasNameTest, + SpriteAnchorPoint, + SpriteBatchNodeAnchorPoint, + SpriteOffsetAnchorRotation, + SpriteBatchNodeOffsetAnchorRotation, + SpriteOffsetAnchorScale, + SpriteBatchNodeOffsetAnchorScale, + SpriteAnimationSplit, + SpriteColorOpacity, + SpriteBatchNodeColorOpacity, + SpriteZOrder, + SpriteBatchNodeZOrder, + SpriteBatchNodeReorder, + SpriteBatchNodeReorderIssue744, + SpriteBatchNodeReorderIssue766, + SpriteBatchNodeReorderIssue767, + SpriteZVertex, + SpriteBatchNodeZVertex, + Sprite6, + SpriteFlip, + SpriteBatchNodeFlip, + SpriteAliased, + SpriteBatchNodeAliased, + SpriteNewTexture, + SpriteBatchNodeNewTexture, + SpriteHybrid, + SpriteBatchNodeChildren, + SpriteBatchNodeChildrenZ, + SpriteChildrenVisibility, + SpriteChildrenVisibilityIssue665, + SpriteChildrenAnchorPoint, + SpriteBatchNodeChildrenAnchorPoint, + SpriteBatchNodeChildrenScale, + SpriteChildrenChildren, + SpriteBatchNodeChildrenChildren, + SpriteNilTexture, + SpriteSubclass, + AnimationCacheTest, + SpriteOffsetAnchorSkew, + SpriteBatchNodeOffsetAnchorSkew, + SpriteOffsetAnchorSkewScale, + SpriteBatchNodeOffsetAnchorSkewScale, + SpriteOffsetAnchorFlip, + SpriteBatchNodeOffsetAnchorFlip, + SpriteBatchNodeReorderSameIndex, + SpriteBatchNodeReorderOneChild, + NodeSort, + SpriteSkewNegativeScaleChildren, + SpriteBatchNodeSkewNegativeScaleChildren, + SpriteDoubleResolution, + SpriteBatchBug1217, + AnimationCacheFile, + TextureColorCacheIssue, + TextureColorCacheIssue2, + TextureRotatedSpriteFrame, + SpriteWithRepeatingTexture, + SpriteBlendFuncTest +]; + +var nextSpriteTest = function () { + spriteTestIdx++; + spriteTestIdx = spriteTestIdx % arrayOfSpriteTest.length; + + if(window.sideIndexBar){ + spriteTestIdx = window.sideIndexBar.changeTest(spriteTestIdx, 36); + } + + return new arrayOfSpriteTest[spriteTestIdx ](); +}; +var previousSpriteTest = function () { + spriteTestIdx--; + if (spriteTestIdx < 0) + spriteTestIdx += arrayOfSpriteTest.length; + + if(window.sideIndexBar){ + spriteTestIdx = window.sideIndexBar.changeTest(spriteTestIdx, 36); + } + + return new arrayOfSpriteTest[spriteTestIdx ](); +}; +var restartSpriteTest = function () { + return new arrayOfSpriteTest[spriteTestIdx ](); +}; + diff --git a/tests/js-tests/src/SysTest/ScriptTestTempFile.js b/tests/js-tests/src/SysTest/ScriptTestTempFile.js new file mode 100644 index 0000000000..f9edd31553 --- /dev/null +++ b/tests/js-tests/src/SysTest/ScriptTestTempFile.js @@ -0,0 +1,38 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var ScriptTestTempLayer = cc.Layer.extend({ + ctor : function () { + this._super(); + + var labelTest = new cc.LabelTTF("this is the ScriptTestTempLayer old file", "Verdana", 32, cc.size(winSize.width, 50), cc.TEXT_ALIGNMENT_CENTER); + var size = cc.winSize; + labelTest.setPosition(size.width / 2, size.height / 4); + this.addChild(labelTest); + + } + +}); diff --git a/tests/js-tests/src/SysTest/SysTest.js b/tests/js-tests/src/SysTest/SysTest.js new file mode 100644 index 0000000000..bfa114b764 --- /dev/null +++ b/tests/js-tests/src/SysTest/SysTest.js @@ -0,0 +1,330 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var sysTestSceneIdx = -1; +//------------------------------------------------------------------ +// +// SysTestBase +// +//------------------------------------------------------------------ +var SysTestBase = BaseTestLayer.extend({ + _title:"", + _subtitle:"", + + ctor:function() { + this._super(cc.color(0,0,0,255), cc.color(98,99,117,255)); + }, + + onRestartCallback:function (sender) { + var s = new SysTestScene(); + s.addChild(restartSysTest()); + director.runScene(s); + }, + onNextCallback:function (sender) { + var s = new SysTestScene(); + s.addChild(nextSysTest()); + director.runScene(s); + }, + onBackCallback:function (sender) { + var s = new SysTestScene(); + s.addChild(previousSysTest()); + director.runScene(s); + }, + // automation + numberOfPendingTests:function() { + return ( (arrayOfSysTest.length-1) - sysTestSceneIdx ); + }, + + getTestNumber:function() { + return sysTestSceneIdx; + } + +}); + +//------------------------------------------------------------------ +// +// LocalStorageTest +// +//------------------------------------------------------------------ +var LocalStorageTest = SysTestBase.extend({ + _title:"LocalStorage Test ", + _subtitle:"See the console", + + ctor:function () { + this._super(); + + var key = 'key_' + Math.random(); + var ls = cc.sys.localStorage; + cc.log(1); + ls.setItem(key, "Hello world"); + + cc.log(2); + var r = ls.getItem(key); + cc.log(r); + + cc.log(3); + ls.removeItem(key); + + cc.log(4); + r = ls.getItem(key); + cc.log(r); + } + +}); + +//------------------------------------------------------------------ +// +// CapabilitiesTest +// +//------------------------------------------------------------------ +var CapabilitiesTest = SysTestBase.extend({ + _title:"Capabilities Test ", + _subtitle:"See the console", + + ctor:function () { + this._super(); + + var c = cc.sys.capabilities; + for( var i in c ) + cc.log( i + " = " + c[i] ); + } + +}); + +var SysTestScene = TestScene.extend({ + runThisTest:function (num) { + sysTestSceneIdx = (num || num == 0) ? (num - 1) : -1; + var layer = nextSysTest(); + this.addChild(layer); + + director.runScene(this); + } +}); + +//------------------------------------------------------------------ +// +// Script dynamic reload test +// +//------------------------------------------------------------------ +var tempJSFileName = "ScriptTestTempFile.js"; +var ScriptTestLayer = SysTestBase.extend({ + _tempLayer:null, + _am : null, + startDownload:function () { + if (!cc.sys.isNative) + { + return; + } + var manifestPath = "Manifests/ScriptTest/project.manifest"; + var storagePath = ((jsb.fileUtils ? jsb.fileUtils.getWritablePath() : "/") + "JSBTests/AssetsManagerTest/ScriptTest/"); + cc.log("Storage path for this test : " + storagePath); + + if (this._am) + { + this._am.release(); + this._am = null; + } + + this._am = new jsb.AssetsManager(manifestPath, storagePath); + this._am.retain(); + if (!this._am.getLocalManifest().isLoaded()) + { + cc.log("Fail to update assets, step skipped."); + that.clickMeShowTempLayer(); + } + else { + var that = this; + var listener = new jsb.EventListenerAssetsManager(this._am, function (event) { + var scene; + switch (event.getEventCode()) { + case jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST: + cc.log("No local manifest file found, skip assets update."); + that.clickMeShowTempLayer(); + break; + case jsb.EventAssetsManager.UPDATE_PROGRESSION: + cc.log(event.getPercent() + "%"); + break; + case jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST: + case jsb.EventAssetsManager.ERROR_PARSE_MANIFEST: + cc.log("Fail to download manifest file, update skipped."); + that.clickMeShowTempLayer(); + break; + case jsb.EventAssetsManager.ALREADY_UP_TO_DATE: + case jsb.EventAssetsManager.UPDATE_FINISHED: + cc.log("Update finished. " + event.getMessage()); + require(tempJSFileName); + that.clickMeShowTempLayer(); + break; + case jsb.EventAssetsManager.UPDATE_FAILED: + cc.log("Update failed. " + event.getMessage()); + break; + case jsb.EventAssetsManager.ERROR_UPDATING: + cc.log("Asset update error: " + event.getAssetId() + ", " + event.getMessage()); + break; + case jsb.EventAssetsManager.ERROR_DECOMPRESS: + cc.log(event.getMessage()); + break; + default: + break; + } + }); + cc.eventManager.addListener(listener, 1); + this._am.update(); + } + }, + clickMeShowTempLayer:function () { + this.removeChildByTag(233, true); + this._tempLayer = new ScriptTestTempLayer(); + this.addChild(this._tempLayer, 0, 233); + }, + clickMeReloadTempLayer:function(){ + cc.sys.cleanScript(tempJSFileName); + if (!cc.sys.isNative) + { + this.clickMeShowTempLayer(); + } + else + { + this.startDownload(); + } + + }, + onExit : function () { + if (this._am) + { + this._am.release(); + this._am = null; + } + + this._super(); + }, + ctor : function () { + this._super(); + + var menu = new cc.Menu(); + menu.setPosition(cc.p(0, 0)); + menu.width = winSize.width; + menu.height = winSize.height; + this.addChild(menu, 1); + var item1 = new cc.MenuItemLabel(new cc.LabelTTF("Click me show tempLayer", "Arial", 22), this.clickMeShowTempLayer, this); + menu.addChild(item1); + + var item2 = new cc.MenuItemLabel(new cc.LabelTTF("Click me reload tempLayer", "Arial", 22), this.clickMeReloadTempLayer, this); + menu.addChild(item2); + + menu.alignItemsVerticallyWithPadding(8); + menu.setPosition(cc.pAdd(cc.visibleRect.left, cc.p(+180, 0))); + }, + + getTitle : function() { + return "ScriptTest only used in native"; + } + +}); + +//------------------------------------------------------------------ +// +// Restart game test +// +//------------------------------------------------------------------ +var RestartGameLayerTest = SysTestBase.extend({ + getTitle : function() { + return "RestartGameTest only used in native"; + }, + restartGame:function() + { + cc.game.restart(); + }, + ctor : function () { + this._super(); + var menu = new cc.Menu(); + menu.setPosition(cc.p(0, 0)); + menu.width = winSize.width; + menu.height = winSize.height; + this.addChild(menu, 1); + var item1 = new cc.MenuItemLabel(new cc.LabelTTF("restartGame", "Arial", 22), this.restartGame, this); + menu.addChild(item1); + menu.setPosition(cc.pAdd(cc.visibleRect.left, cc.p(+180, 0))); + } +}); + +var OpenURLTest = SysTestBase.extend({ + getTitle:function(){ + return "Open URL Test"; + }, + + ctor:function(){ + this._super(); + + var label = new cc.LabelTTF("Touch the screen to open\nthe cocos2d-x home page", "Arial", 22); + this.addChild(label); + label.setPosition(cc.winSize.width/2, cc.winSize.height/2); + + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches: true, + onTouchBegan: function(){ + return true; + }, + onTouchEnded: function(){ + cc.sys.openURL("http://www.cocos2d-x.org/"); + } + }, this); + + } +}); + +// +// Flow control +// + +var arrayOfSysTest = [ + LocalStorageTest, + CapabilitiesTest, + OpenURLTest +]; + +if (cc.sys.isNative && cc.sys.OS_WINDOWS != cc.sys.os) { + arrayOfSysTest.push(ScriptTestLayer); + arrayOfSysTest.push(RestartGameLayerTest); +} + +var nextSysTest = function () { + sysTestSceneIdx++; + sysTestSceneIdx = sysTestSceneIdx % arrayOfSysTest.length; + + return new arrayOfSysTest[sysTestSceneIdx](); +}; +var previousSysTest = function () { + sysTestSceneIdx--; + if (sysTestSceneIdx < 0) + sysTestSceneIdx += arrayOfSysTest.length; + + return new arrayOfSysTest[sysTestSceneIdx](); +}; +var restartSysTest = function () { + return new arrayOfSysTest[sysTestSceneIdx](); +}; + diff --git a/tests/js-tests/src/TextInputTest/TextInputTest.js b/tests/js-tests/src/TextInputTest/TextInputTest.js new file mode 100644 index 0000000000..a2714cd4d6 --- /dev/null +++ b/tests/js-tests/src/TextInputTest/TextInputTest.js @@ -0,0 +1,424 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var TEXT_INPUT_FONT_NAME = "Thonburi"; +var TEXT_INPUT_FONT_SIZE = 36; + +var sceneIdx = -1; + +var textInputGetRect = function (node) { + var rc = cc.rect(node.x, node.y, node.width, node.height); + rc.x -= rc.width / 2; + rc.y -= rc.height / 2; + return rc; +}; + +/** + @brief TextInputTest for retain prev, reset, next, main menu buttons. + */ +var TextInputTest = cc.Layer.extend({ + notificationLayer:null, + ctor:function() { + this._super(); + this.init(); + }, + + restartCallback:function (sender) { + var scene = new TextInputTestScene(); + scene.addChild(restartTextInputTest()); + cc.director.runScene(scene); + }, + nextCallback:function (sender) { + var scene = new TextInputTestScene(); + scene.addChild(nextTextInputTest()); + cc.director.runScene(scene); + }, + backCallback:function (sender) { + var scene = new TextInputTestScene(); + scene.addChild(previousTextInputTest()); + cc.director.runScene(scene); + }, + + title:function () { + return "text input test"; + }, + + addKeyboardNotificationLayer:function (layer) { + this.notificationLayer = layer; + this.addChild(layer); + }, + + onEnter:function () { + this._super(); + + var winSize = cc.director.getWinSize(); + + var label = new cc.LabelTTF(this.title(), "Arial", 24); + this.addChild(label); + label.x = winSize.width / 2; + label.y = winSize.height - 50; + + var subTitle = this.subtitle(); + if (subTitle && subTitle !== "") { + var l = new cc.LabelTTF(subTitle, "Thonburi", 16); + this.addChild(l, 1); + l.x = winSize.width / 2; + l.y = winSize.height - 80; + } + + var item1 = new cc.MenuItemImage(s_pathB1, s_pathB2, this.backCallback, this); + var item2 = new cc.MenuItemImage(s_pathR1, s_pathR2, this.restartCallback, this); + var item3 = new cc.MenuItemImage(s_pathF1, s_pathF2, this.nextCallback, this); + + var menu = new cc.Menu(item1, item2, item3); + menu.x = 0; + menu.y = 0; + item1.x = winSize.width / 2 - 100; + item1.y = 30; + item2.x = winSize.width / 2; + item2.y = 30; + item3.x = winSize.width / 2 + 100; + item3.y = 30; + + this.addChild(menu, 1); + } +}); + +////////////////////////////////////////////////////////////////////////// +// KeyboardNotificationLayer for test IME keyboard notification. +////////////////////////////////////////////////////////////////////////// +var KeyboardNotificationLayer = TextInputTest.extend({ + _trackNode:null, + _beginPos:null, + + ctor:function () { + this._super(); + + if( 'touches' in cc.sys.capabilities ){ + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesEnded: this.onTouchesEnded + }, this); + } else if ('mouse' in cc.sys.capabilities ) + cc.eventManager.addListener({ + event: cc.EventListener.MOUSE, + onMouseUp: this.onMouseUp + }, this); + }, + + subtitle:function () { + return ""; + }, + + onClickTrackNode:function (clicked) { + }, + + keyboardWillShow:function (info) { + cc.log("TextInputTest:keyboardWillShowAt(origin:" + info.end.x + "," + info.end.y + + ", size:" + info.end.width + "," + info.end.height + ")"); + + if (!this._trackNode) + return; + + var rectTracked = textInputGetRect(this._trackNode); + cc.log("TextInputTest:trackingNodeAt(origin:" + info.end.x + "," + info.end.y + + ", size:" + info.end.width + "," + info.end.height + ")"); + + // if the keyboard area doesn't intersect with the tracking node area, nothing need to do. + if (!cc.rectIntersectsRect(rectTracked, info.end)) + return; + + // assume keyboard at the bottom of screen, calculate the vertical adjustment. + var adjustVert = cc.rectGetMaxY(info.end) - cc.rectGetMinY(rectTracked); + cc.log("TextInputTest:needAdjustVerticalPosition(" + adjustVert + ")"); + + // move all the children node of KeyboardNotificationLayer + var children = this.children; + for (var i = 0; i < children.length; ++i) { + var node = children[i]; + node.y += adjustVert; + } + }, + + onTouchesEnded:function (touches, event) { + var target = event.getCurrentTarget(); + if (!target._trackNode) + return; + + // grab first touch + if(touches.length == 0) + return; + + var touch = touches[0]; + var point = touch.getLocation(); + + // decide the trackNode is clicked. + cc.log("KeyboardNotificationLayer:clickedAt(" + point.x + "," + point.y + ")"); + + var rect = textInputGetRect(target._trackNode); + cc.log("KeyboardNotificationLayer:TrackNode at(origin:" + rect.x + "," + rect.y + + ", size:" + rect.width + "," + rect.height + ")"); + + target.onClickTrackNode(cc.rectContainsPoint(rect, point)); + cc.log("----------------------------------"); + }, + + onMouseUp:function (event) { + var target = event.getCurrentTarget(); + if (!target._trackNode) + return; + + var point = event.getLocation(); + + // decide the trackNode is clicked. + cc.log("KeyboardNotificationLayer:clickedAt(" + point.x + "," + point.y + ")"); + + var rect = textInputGetRect(target._trackNode); + cc.log("KeyboardNotificationLayer:TrackNode at(origin:" + rect.x + "," + rect.y + + ", size:" + rect.width + "," + rect.height + ")"); + + target.onClickTrackNode(cc.rectContainsPoint(rect, point)); + cc.log("----------------------------------"); + } +}); + +////////////////////////////////////////////////////////////////////////// +// TextFieldTTFDefaultTest for test TextFieldTTF default behavior. +////////////////////////////////////////////////////////////////////////// +var TextFieldTTFDefaultTest = KeyboardNotificationLayer.extend({ + subtitle:function () { + return "TextFieldTTF with default behavior test"; + }, + onClickTrackNode:function (clicked) { + var textField = this._trackNode; + if (clicked) { + // TextFieldTTFTest be clicked + cc.log("TextFieldTTFDefaultTest:CCTextFieldTTF attachWithIME"); + textField.attachWithIME(); + } else { + // TextFieldTTFTest not be clicked + cc.log("TextFieldTTFDefaultTest:CCTextFieldTTF detachWithIME"); + textField.detachWithIME(); + } + }, + + onEnter:function () { + this._super(); + + // add CCTextFieldTTF + var winSize = cc.director.getWinSize(); + + var textField = new cc.TextFieldTTF("", + TEXT_INPUT_FONT_NAME, + TEXT_INPUT_FONT_SIZE); + this.addChild(textField); + textField.x = winSize.width / 2; + textField.y = winSize.height / 2; + + this._trackNode = textField; + } +}); + +////////////////////////////////////////////////////////////////////////// +// TextFieldTTFActionTest +////////////////////////////////////////////////////////////////////////// +var TextFieldTTFActionTest = KeyboardNotificationLayer.extend({ + _textField:null, + _textFieldAction:null, + _action:false, + _charLimit:0, // the textfield max char limit + + ctor:function () { + this._super(); + }, + + callbackRemoveNodeWhenDidAction:function (node) { + this.removeChild(node, true); + }, + + // KeyboardNotificationLayer + subtitle:function () { + return "CCTextFieldTTF with action and char limit test"; + }, + onClickTrackNode:function (clicked) { + var textField = this._trackNode; + if (clicked) { + // TextFieldTTFTest be clicked + cc.log("TextFieldTTFActionTest:CCTextFieldTTF attachWithIME"); + textField.attachWithIME(); + } else { + // TextFieldTTFTest not be clicked + cc.log("TextFieldTTFActionTest:CCTextFieldTTF detachWithIME"); + textField.detachWithIME(); + } + }, + + //CCLayer + onEnter:function () { + this._super(); + + this._charLimit = 20; + this._textFieldAction = cc.sequence( + cc.fadeOut(0.25), + cc.fadeIn(0.25) + ).repeatForever(); + this._action = false; + + // add CCTextFieldTTF + var winSize = cc.director.getWinSize(); + + this._textField = new cc.TextFieldTTF("", + TEXT_INPUT_FONT_NAME, + TEXT_INPUT_FONT_SIZE); + this.addChild(this._textField); + this._textField.setDelegate(this); + + this._textField.x = winSize.width / 2; + this._textField.y = winSize.height / 2; + this._trackNode = this._textField; + }, + + //CCTextFieldDelegate + onTextFieldAttachWithIME:function (sender) { + if (!this._action) { + this._textField.runAction(this._textFieldAction); + this._action = true; + } + return false; + }, + onTextFieldDetachWithIME:function (sender) { + if (this._action) { + this._textField.stopAction(this._textFieldAction); + this._textField.opacity = 255; + this._action = false; + } + return false; + }, + onTextFieldInsertText:function (sender, text, len) { + // if insert enter, treat as default to detach with ime + if ('\n' == text) { + return false; + } + + // if the textfield's char count more than m_nCharLimit, doesn't insert text anymore. + if (sender.getCharCount() >= this._charLimit) { + return true; + } + + // create a insert text sprite and do some action + var label = new cc.LabelTTF(text, TEXT_INPUT_FONT_NAME, TEXT_INPUT_FONT_SIZE); + this.addChild(label); + var color = cc.color(226, 121, 7); + label.color = color; + + // move the sprite from top to position + var endX = sender.x, endY = sender.y; + if (sender.getCharCount()) { + endX += sender.width / 2; + } + + var duration = 0.5; + label.x = endX; + label.y = cc.director.getWinSize().height - label.height * 2; + label.scale = 8; + + var seq = cc.sequence( + cc.spawn( + cc.moveTo(duration, cc.p(endX, endY)), + cc.scaleTo(duration, 1), + cc.fadeOut(duration)), + cc.callFunc(this.callbackRemoveNodeWhenDidAction, this)); + label.runAction(seq); + return false; + }, + + onTextFieldDeleteBackward:function (sender, delText, len) { + // create a delete text sprite and do some action + var label = new cc.LabelTTF(delText, TEXT_INPUT_FONT_NAME, TEXT_INPUT_FONT_SIZE); + this.addChild(label); + + // move the sprite to fly out + var beginX = sender.x, beginY = sender.y; + beginX += (sender.width - label.width) / 2.0; + + var winSize = cc.director.getWinSize(); + var endPos = cc.p(-winSize.width / 4.0, winSize.height * (0.5 + Math.random() / 2.0)); + + var duration = 1; + var rotateDuration = 0.2; + var repeatTime = 5; + label.x = beginX; + label.y = beginY; + + var seq = cc.sequence( + cc.spawn( + cc.moveTo(duration, endPos), + cc.rotateBy(rotateDuration, (Math.random() % 2) ? 360 : -360).repeat(repeatTime), + cc.fadeOut(duration)), + cc.callFunc(this.callbackRemoveNodeWhenDidAction, this)); + label.runAction(seq); + return false; + }, + onDraw:function (sender) { + return false; + } +}); + +var TextInputTestScene = TestScene.extend({ + runThisTest:function (num) { + sceneIdx = (num || num == 0) ? (num - 1) : -1; + var layer = nextTextInputTest(); + + this.addChild(layer); + cc.director.runScene(this); + } +}); + +// +// Flow control +// +var arrayOfTextInputTest = [ + TextFieldTTFDefaultTest, + TextFieldTTFActionTest +]; + +var nextTextInputTest = function () { + sceneIdx++; + sceneIdx = sceneIdx % arrayOfTextInputTest.length; + + return new arrayOfTextInputTest[sceneIdx](); +}; +var previousTextInputTest = function () { + sceneIdx--; + if (sceneIdx < 0) + sceneIdx += arrayOfTextInputTest.length; + + return new arrayOfTextInputTest[sceneIdx](); +}; +var restartTextInputTest = function () { + return new arrayOfTextInputTest[sceneIdx](); +}; + diff --git a/tests/js-tests/src/TextureCacheTest/TextureCacheTest.js b/tests/js-tests/src/TextureCacheTest/TextureCacheTest.js new file mode 100644 index 0000000000..0b6b819726 --- /dev/null +++ b/tests/js-tests/src/TextureCacheTest/TextureCacheTest.js @@ -0,0 +1,266 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var TextureCacheTestBase = BaseTestLayer.extend({ + _title:"", + _subtitle:"", + + ctor:function() { + this._super(cc.color(0,0,0,255), cc.color(98,99,117,255)); + }, + + onRestartCallback:function (sender) { + var s = new TexCacheTestScene(); + s.addChild(restartTexCacheTest()); + director.runScene(s); + }, + onNextCallback:function (sender) { + var s = new TexCacheTestScene(); + s.addChild(nextTexCacheTest()); + director.runScene(s); + }, + onBackCallback:function (sender) { + var s = new TexCacheTestScene(); + s.addChild(previousTexCacheTest()); + director.runScene(s); + } +}); + +var TextureCacheTest = TextureCacheTestBase.extend({ + _title:"Texture Cache Loading Test", + _labelLoading:null, + _labelPercent:null, + _numberOfSprites:20, + _numberOfLoadedSprites:0, + ctor:function () { + this._super(); + + var size = cc.director.getWinSize(); + + this._labelLoading = new cc.LabelTTF("loading...", "Arial", 15); + this._labelPercent = new cc.LabelTTF("%0", "Arial", 15); + + this._labelLoading.x = size.width / 2; + + this._labelLoading.y = size.height / 2 - 20; + this._labelPercent.x = size.width / 2; + this._labelPercent.y = size.height / 2 + 20; + + this.addChild(this._labelLoading); + this.addChild(this._labelPercent); + + var texCache = cc.textureCache; + // load textrues + texCache.addImageAsync("res/Images/HelloWorld.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_01.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_02.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_03.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_04.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_05.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_06.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_07.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_08.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_09.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_10.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_11.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_12.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_13.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_14.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/background1.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/background2.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/background3.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/blocks.png", this.loadingCallBack, this); + }, + addSprite:function () { + var size = cc.director.getWinSize(); + + // create sprites + var bg = new cc.Sprite("res/Images/HelloWorld.png"); + bg.x = size.width / 2; + bg.y = size.height / 2; + //bg.scale = 1.7; + + var s1 = new cc.Sprite("res/Images/grossini.png"); + var s2 = new cc.Sprite("res/Images/grossini_dance_01.png"); + var s3 = new cc.Sprite("res/Images/grossini_dance_02.png"); + var s4 = new cc.Sprite("res/Images/grossini_dance_03.png"); + var s5 = new cc.Sprite("res/Images/grossini_dance_04.png"); + var s6 = new cc.Sprite("res/Images/grossini_dance_05.png"); + var s7 = new cc.Sprite("res/Images/grossini_dance_06.png"); + var s8 = new cc.Sprite("res/Images/grossini_dance_07.png"); + var s9 = new cc.Sprite("res/Images/grossini_dance_08.png"); + var s10 = new cc.Sprite("res/Images/grossini_dance_09.png"); + var s11 = new cc.Sprite("res/Images/grossini_dance_10.png"); + var s12 = new cc.Sprite("res/Images/grossini_dance_11.png"); + var s13 = new cc.Sprite("res/Images/grossini_dance_12.png"); + var s14 = new cc.Sprite("res/Images/grossini_dance_13.png"); + var s15 = new cc.Sprite("res/Images/grossini_dance_14.png"); + + // just loading textures to slow down + var s16 = new cc.Sprite("res/Images/background1.png"); + var s17 = new cc.Sprite("res/Images/background2.png"); + var s18 = new cc.Sprite("res/Images/background3.png"); + var s19 = new cc.Sprite("res/Images/blocks.png"); + + s1.x = 50; + s1.y = 50; + s2.x = 60; + s2.y = 50; + s3.x = 70; + s3.y = 50; + s4.x = 80; + s4.y = 50; + s5.x = 90; + s5.y = 50; + s6.x = 100; + s6.y = 50; + + s7.x = 50; + s7.y = 180; + s8.x = 60; + s8.y = 180; + s9.x = 70; + s9.y = 180; + s10.x = 80; + s10.y = 180; + s11.x = 90; + s11.y = 180; + s12.x = 100; + s12.y = 180; + + s13.x = 50; + s13.y = 270; + s14.x = 60; + s14.y = 270; + s15.x = 70; + s15.y = 270; + + this.addChild(bg); + + this.addChild(s1); + this.addChild(s2); + this.addChild(s3); + this.addChild(s4); + this.addChild(s5); + this.addChild(s6); + this.addChild(s7); + this.addChild(s8); + this.addChild(s9); + this.addChild(s10); + this.addChild(s11); + this.addChild(s12); + this.addChild(s13); + this.addChild(s14); + this.addChild(s15); + }, + loadingCallBack:function (obj) { + ++this._numberOfLoadedSprites; + this._labelPercent.setString((this._numberOfLoadedSprites / this._numberOfSprites) * 100 + ''); + if (this._numberOfLoadedSprites == this._numberOfSprites) { + this.removeChild(this._labelLoading, true); + this.removeChild(this._labelPercent, true); + this.addSprite(); + } + } +}); + +var RemoteTextureTest = TextureCacheTestBase.extend({ + _title:"Remote Texture Test", + _subtitle:"", + _remoteTex: "http://cn.cocos2d-x.org/image/logo.png", + _sprite : null, + onEnter:function () { + this._super(); + if('opengl' in cc.sys.capabilities && !cc.sys.isNative){ + var label = new cc.LabelTTF("Not support Loading texture from remote site on HTML5-WebGL", "Times New Roman", 28); + label.x = winSize.width / 2; + label.y = winSize.height / 2; + this.addChild(label, 100); + } else + this.scheduleOnce(this.startDownload, 0.1); + }, + + startDownload: function() { + cc.textureCache.addImageAsync(this._remoteTex, this.texLoaded, this); + }, + + texLoaded: function(texture) { + if (texture instanceof cc.Texture2D) { + cc.log("Remote texture loaded: " + this._remoteTex); + if (this._sprite) { + this.removeChild(this._sprite); + } + this._sprite = new cc.Sprite(texture); + this._sprite.x = cc.winSize.width/2; + this._sprite.y = cc.winSize.height/2; + this.addChild(this._sprite); + } + else { + cc.log("Fail to load remote texture"); + } + } +}); + + +// +// Flow control +// + +var texCacheTestSceneIdx = -1; + +var TexCacheTestScene = TestScene.extend({ + runThisTest:function (num) { + texCacheTestSceneIdx = (num || num == 0) ? (num - 1) : -1; + var layer = nextTexCacheTest(); + this.addChild(layer); + + cc.director.runScene(this); + } +}); + +var arrayOfTexCacheTest = [ + TextureCacheTest, + RemoteTextureTest +]; + +var nextTexCacheTest = function () { + texCacheTestSceneIdx++; + texCacheTestSceneIdx = texCacheTestSceneIdx % arrayOfTexCacheTest.length; + + return new arrayOfTexCacheTest[texCacheTestSceneIdx](); +}; +var previousTexCacheTest = function () { + texCacheTestSceneIdx--; + if (texCacheTestSceneIdx < 0) + texCacheTestSceneIdx += arrayOfTexCacheTest.length; + + return new arrayOfTexCacheTest[texCacheTestSceneIdx](); +}; +var restartTexCacheTest = function () { + return new arrayOfTexCacheTest[texCacheTestSceneIdx](); +}; + diff --git a/tests/js-tests/src/TileMapTest/TileMapTest.js b/tests/js-tests/src/TileMapTest/TileMapTest.js new file mode 100644 index 0000000000..7cf21293dc --- /dev/null +++ b/tests/js-tests/src/TileMapTest/TileMapTest.js @@ -0,0 +1,1733 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var TAG_TILE_MAP = 1; +var tileTestSceneIdx = -1; +//------------------------------------------------------------------ +// +// TileDemo +// +//------------------------------------------------------------------ +var TileDemoProps = { + ctor:function () { + this._super(); + + if ('touches' in cc.sys.capabilities){ + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesMoved: function (touches, event) { + var touch = touches[0]; + var delta = touch.getDelta(); + + var node = event.getCurrentTarget().getChildByTag(TAG_TILE_MAP); + node.x += delta.x; + node.y += delta.y; + } + }, this); + } else if ('mouse' in cc.sys.capabilities) + cc.eventManager.addListener({ + event: cc.EventListener.MOUSE, + onMouseMove: function(event){ + if(event.getButton() == cc.EventMouse.BUTTON_LEFT){ + var node = event.getCurrentTarget().getChildByTag(TAG_TILE_MAP); + node.x += event.getDeltaX(); + node.y += event.getDeltaY(); + } + } + }, this); + }, + title:function () { + return "No title"; + }, + subtitle:function () { + return "drag the screen"; + }, + + onRestartCallback:function (sender) { + var s = new TileMapTestScene(); + s.addChild(restartTileMapTest()); + director.runScene(s); + }, + onNextCallback:function (sender) { + var s = new TileMapTestScene(); + s.addChild(nextTileMapTest()); + director.runScene(s); + }, + onBackCallback:function (sender) { + var s = new TileMapTestScene(); + s.addChild(previousTileMapTest()); + director.runScene(s); + }, + // automation + numberOfPendingTests:function () { + return ( (arrayOfTileMapTest.length - 1) - tileTestSceneIdx ); + }, + getTestNumber:function () { + return tileTestSceneIdx; + } +}; +var TileDemo = BaseTestLayer.extend(TileDemoProps); + +/******************for vertexz bug**************/ +var FixBugBaseTest = cc.Layer.extend(BaseTestLayerProps); +var TMXFixBugLayer = FixBugBaseTest.extend(TileDemoProps); +/***********************************************************/ + +var TileMapTest = TileDemo.extend({ + ctor:function () { + this._super(); + var map = new cc.TileMapAtlas(s_tilesPng, s_levelMapTga, 16, 16); + if ("opengl" in cc.sys.capabilities) + map.texture.setAntiAliasTexParameters(); + + this.log("ContentSize: " + map.width + " " + map.height); + + map.releaseMap(); + + this.addChild(map, 0, TAG_TILE_MAP); + + map.anchorX = 0; + map.anchorY = 0.5; + + var scale = cc.scaleBy(4, 0.8); + var scaleBack = scale.reverse(); + + var seq = cc.sequence(scale, scaleBack); + + map.runAction(seq.repeatForever()); + }, + title:function () { + return "TileMapAtlas"; + } +}); + +var TileMapEditTest = TileDemo.extend({ + ctor:function () { + this._super(); + var map = new cc.TileMapAtlas(s_tilesPng, s_levelMapTga, 16, 16); + // Create an Aliased Atlas + map.texture.setAliasTexParameters(); + this.log("ContentSize: " + map.width + " " + map.height); + + // If you are not going to use the Map, you can free it now + // [tilemap releaseMap); + // And if you are going to use, it you can access the data with: + + this.schedule(this.updateMap, 0.2);//:@selector(updateMap:) interval:0.2f); + + this.addChild(map, 0, TAG_TILE_MAP); + + map.anchorX = 0; + map.anchorY = 0; + map.x = -20; + map.y = -200; + + }, + title:function () { + return "Editable TileMapAtlas"; + }, + updateMap:function (dt) { + // IMPORTANT + // The only limitation is that you cannot change an empty, or assign an empty tile to a tile + // The value 0 not rendered so don't assign or change a tile with value 0 + + var tilemap = this.getChildByTag(TAG_TILE_MAP); + + // NEW since v0.7 + var c = tilemap.getTileAt(cc.p(13, 21)); + c.r++; + c.r %= 50; + if (c.r == 0) + c.r = 1; + + // NEW since v0.7 + tilemap.setTile(c, cc.p(13, 21)); + } +}); + +//------------------------------------------------------------------ +// +// TMXOrthoTest +// +//------------------------------------------------------------------ +var TMXOrthoTest = TileDemo.extend({ + ctor:function () { + this._super(); + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test1.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + map.runAction(new cc.ScaleBy(2, 0.5)); + }, + title:function () { + return "TMX Ortho test"; + }, + + // Automation + testDuration:2.1, + pixel1:{"0":218, "1":218, "2":208, "3":255}, + pixel2:{"0":193, "1":143, "2":72, "3":255}, + pixel3:{"0":200, "1":15, "2":160, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(82, 114, 10, 10); + var ret2 = this.readPixels(475, 100, 10, 10); + var ret3 = this.readPixels(312, 196, 10, 10); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1, false) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2, false) ? "yes" : "no", + "pixel3":this.containsPixel(ret3, this.pixel3, true,5) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TMXOrthoTest2 +// +//------------------------------------------------------------------ +var TMXOrthoTest2 = TileDemo.extend({ + ctor:function () { + this._super(); + // + // Test orthogonal with 3d camera and anti-alias textures + // + // it should not flicker. No artifacts should appear + // + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test2.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + }, + title:function () { + return "TMX Orthogonal test 2"; + }, + onEnter:function () { + this._super(); + director.setProjection(cc.Director.PROJECTION_3D); + }, + onExit:function () { + this._super(); + director.setProjection(cc.Director.PROJECTION_2D); + }, + + // Automation + pixel1:{"0":192, "1":144, "2":16, "3":255}, + pixel2:{"0":255, "1":255, "2":255, "3":255}, + pixel3:{"0":40, "1":0, "2":0, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(99, 142, 5, 5); + var ret2 = this.readPixels(238, 270, 5, 5); + var ret3 = this.readPixels(419, 239, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1, false) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2, false) ? "yes" : "no", + "pixel3":this.containsPixel(ret3, this.pixel3, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + + +//------------------------------------------------------------------ +// +// TMXOrthoTest3 +// +//------------------------------------------------------------------ +var TMXOrthoTest3 = TileDemo.extend({ + ctor:function () { + this._super(); + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test3.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + map.scale = 0.2; + map.anchorX = 0.5; + map.anchorY = 0.5; + }, + title:function () { + return "TMX anchorPoint test"; + }, + + // Automation + pixel1:{"0":247, "1":196, "2":131, "3":255}, + pixel2:{"0":0, "1":0, "2":0, "3":255}, + pixel3:{"0":0, "1":0, "2":0, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(0, 0, 10, 10); + var ret2 = this.readPixels(107, 58, 10, 10); + var ret3 = this.readPixels(58, 107, 10, 10); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1, false) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2, false) ? "yes" : "no", + "pixel3":this.containsPixel(ret3, this.pixel3, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TMXOrthoTest4 +// +//------------------------------------------------------------------ +var TMXOrthoTest4 = TileDemo.extend({ + ctor:function () { + this._super(); + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test4.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + map.anchorX = 0; + map.anchorY = 0; + + var layer = map.getLayer("Layer 0"); + var s = layer.getLayerSize(); + + this.tx = s.width - 10; + this.ty = s.height - 1; + + var sprite; + sprite = layer.getTileAt(cc.p(0, 0)); + sprite.scale = 2; + + sprite = layer.getTileAt(cc.p(s.width - 1, 0)); + sprite.scale = 2; + + sprite = layer.getTileAt(cc.p(0, s.height - 1)); + sprite.scale = 2; + + sprite = layer.getTileAt(cc.p(s.width - 1, s.height - 1)); + sprite.scale = 2; + + this.scheduleOnce(this.onRemoveSprite, 0.2); + }, + onRemoveSprite:function (dt) { + var map = this.getChildByTag(TAG_TILE_MAP); + + var layer = map.getLayer("Layer 0"); + var layerSize = layer.getLayerSize(); + + var sprite = layer.getTileAt(cc.p(layerSize.width - 1, 0)); + layer.removeChild(sprite, true); + + this.testLayerSize = layerSize; + }, + title:function () { + return "TMX width/height test"; + }, + + // + // Automation + // + testDuration:3, + testLayerSize:null, + pixel:{"0":0, "1":0, "2":0, "3":255}, + getExpectedResult:function () { + var ret = {"width":14, "height":8, "pixel":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(433, 240, 10, 10); + var ret = {"width":this.testLayerSize.width, "height":this.testLayerSize.height, "pixel":this.containsPixel(ret1, this.pixel, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + + +//------------------------------------------------------------------ +// +// TMXReadWriteTest +// +//------------------------------------------------------------------ +var TMXReadWriteTest = TileDemo.extend({ + gid:0, + ctor:function () { + this._super(); + + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test2.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + var layer = map.getLayer("Layer 0"); + if ("opengl" in cc.sys.capabilities) + layer.texture.setAntiAliasTexParameters(); + + map.scale = 1; + + var tile0 = layer.getTileAt(cc.p(1, 63)); + var tile1 = layer.getTileAt(cc.p(2, 63)); + var tile2 = layer.getTileAt(cc.p(3, 62));//cc.p(1,62)); + var tile3 = layer.getTileAt(cc.p(2, 62)); + + tile0.anchorX = 0.5; + tile0.anchorY = 0.5; + tile1.anchorX = 0.5; + tile1.anchorY = 0.5; + tile2.anchorX = 0.5; + tile2.anchorY = 0.5; + tile3.anchorX = 0.5; + tile3.anchorY = 0.5; + + var move = cc.moveBy(0.5, cc.p(0, 160)); + var rotate = cc.rotateBy(2, 360); + var scale = cc.scaleBy(2, 5); + var opacity = cc.fadeOut(2); + var fadein = cc.fadeIn(2); + var scaleback = cc.scaleTo(1, 1); + var finish = cc.callFunc(this.onRemoveSprite); // 'this' is optional. Since it is not used, it is not passed. + + var seq0 = cc.sequence(move, rotate, scale, opacity, fadein, scaleback, finish); + + tile0.runAction(seq0); + tile1.runAction(seq0.clone()); + tile2.runAction(seq0.clone()); + tile3.runAction(seq0.clone()); + + this.gid = layer.getTileGIDAt(cc.p(0, 63)); + + this.schedule(this.updateCol, 2.0); + this.schedule(this.repaintWithGID, 2.0); + this.schedule(this.removeTiles, 1.0); + + this.gid2 = 0; + }, + onRemoveSprite:function (sender) { + var p = sender.parent; + if (p) { + p.removeChild(sender, true); + } + }, + updateCol:function (dt) { + var map = this.getChildByTag(TAG_TILE_MAP); + var layer = map.getChildByTag(0); + + var s = layer.getLayerSize(); + + for (var y = 0; y < s.height; y++) { + layer.setTileGID(this.gid2, cc.p(3, y)); + } + + this.gid2 = (this.gid2 + 1) % 80; + }, + repaintWithGID:function (dt) { + + var map = this.getChildByTag(TAG_TILE_MAP); + var layer = map.getChildByTag(0); + + var s = layer.getLayerSize(); + for (var x = 0; x < s.width; x++) { + var y = s.height - 1; + var tmpgid = layer.getTileGIDAt(cc.p(x, y)); + layer.setTileGID(tmpgid + 1, cc.p(x, y)); + } + }, + removeTiles:function (dt) { + this.unschedule(this.removeTiles); + + var map = this.getChildByTag(TAG_TILE_MAP); + + var layer = map.getChildByTag(0); + var s = layer.getLayerSize(); + + for (var y = 0; y < s.height; y++) { + layer.removeTileAt(cc.p(5.0, y)); + } + }, + title:function () { + return "TMX Read/Write test"; + }, + + // + // Automation + // + testDuration:2.2, + pixel1:{"0":0, "1":144, "2":0, "3":255}, + pixel2:{"0":192, "1":144, "2":16, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(168, 203, 5, 5); + var ret2 = this.readPixels(239, 239, 5, 5); + var ret = {"pixel1":!this.containsPixel(ret1, this.pixel1, false) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TMXHexTest +// +//------------------------------------------------------------------ +var TMXHexTest = TileDemo.extend({ + ctor:function () { + this._super(); + var color = new cc.LayerColor(cc.color(64, 64, 64, 255)); + this.addChild(color, -1); + + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/hexa-test.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + }, + title:function () { + return "TMX Hex test"; + }, + + // + // Automation + // + pixel1:{"0":250, "1":202, "2":73, "3":255}, + pixel2:{"0":150, "1":219, "2":10, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(438, 226, 10, 10); + var ret2 = this.readPixels(195, 0, 10, 10); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1, false) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TMXIsoTest +// +//------------------------------------------------------------------ +var TMXIsoTest = TileDemo.extend({ + ctor:function () { + this._super(); + var color = new cc.LayerColor(cc.color(64, 64, 64, 255)); + this.addChild(color, -1); + + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + // move map to the center of the screen + var ms = map.getMapSize(); + var ts = map.getTileSize(); + map.runAction(cc.moveTo(1.0, cc.p(-ms.width * ts.width / 2, -ms.height * ts.height / 2))); + }, + title:function () { + return "TMX Isometric test 0"; + }, + + // + // Automation + // + pixel:{"0":0, "1":0, "2":0, "3":255}, + getExpectedResult:function () { + var ret = {"pixel":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = true; + for (var i = 0; i < 6; i++) { + var item = this.readPixels(438, 226, 3, 3); + if (!this.containsPixel(item, this.pixel, false)) { + ret1 = false; + } + } + var ret = { "pixel":ret1 == true ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TMXIsoTest1 +// +//------------------------------------------------------------------ +var TMXIsoTest1 = TileDemo.extend({ + ctor:function () { + this._super(); + var color = new cc.LayerColor(cc.color(64, 64, 64, 255)); + this.addChild(color, -1); + + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test1.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + map.anchorX = 0.5; + map.anchorY = 0.5; + }, + title:function () { + return "TMX Isometric test + anchorPoint"; + }, + + // + // Automation + // + pixel:{"0":0, "1":0, "2":0, "3":255}, + getExpectedResult:function () { + var ret = {"pixel":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = true; + for (var i = 0; i < 6; i++) { + var item = this.readPixels(438, 226, 3, 3); + if (!this.containsPixel(item, this.pixel, false)) { + ret1 = false; + } + } + var ret = { "pixel":ret1 == true ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TMXIsoTest2 +// +//------------------------------------------------------------------ +var TMXIsoTest2 = TileDemo.extend({ + ctor:function () { + this._super(); + var color = new cc.LayerColor(cc.color(64, 64, 64, 255)); + this.addChild(color, -1); + + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test2.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + // move map to the center of the screen + var ms = map.getMapSize(); + var ts = map.getTileSize(); + map.runAction(cc.moveTo(1.0, cc.p(-ms.width * ts.width / 2, -ms.height * ts.height / 2))); + }, + title:function () { + return "TMX Isometric test 2"; + }, + + // + // Automation + // + testDuration:1.2, + pixel:{"0":0, "1":0, "2":0, "3":255}, + getExpectedResult:function () { + var ret = {"pixel":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = true; + for (var i = 1; i < 6; i++) { + var item = this.readPixels(62 * i, 191, 5, 5); + if (!this.containsPixel(item, this.pixel, true, 2)) { + ret1 = false; + } + } + var ret = { "pixel":ret1 == true ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TMXUncompressedTest +// +//------------------------------------------------------------------ +var TMXUncompressedTest = TileDemo.extend({ + ctor:function () { + this._super(); + var color = new cc.LayerColor(cc.color(64, 64, 64, 255)); + this.addChild(color, -1); + + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test2-uncompressed.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + // move map to the center of the screen + var ms = map.getMapSize(); + var ts = map.getTileSize(); + map.runAction(cc.moveTo(1.0, cc.p(-ms.width * ts.width / 2, -ms.height * ts.height / 2))); + + // testing release map + var childrenArray = map.children; + var layer = null; + for (var i = 0, len = childrenArray.length; i < len; i++) { + layer = childrenArray[i]; + if (!layer) + break; + + layer.releaseMap(); + } + }, + title:function () { + return "TMX Uncompressed test"; + }, + + // + // Automation + // + testDuration:1.2, + pixel:{"0":0, "1":0, "2":0, "3":255}, + getExpectedResult:function () { + var ret = {"pixel":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = true; + for (var i = 1; i < 6; i++) { + var item = this.readPixels(62 * i, 191, 5, 5); + if (!this.containsPixel(item, this.pixel, true, 2)) { + ret1 = false; + } + } + var ret = { "pixel":ret1 == true ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TMXTilesetTest +// +//------------------------------------------------------------------ +var TMXTilesetTest = TileDemo.extend({ + ctor:function () { + this._super(); + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test5.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + if ("opengl" in cc.sys.capabilities) { + var layer; + layer = map.getLayer("Layer 0"); + layer.texture.setAntiAliasTexParameters(); + + layer = map.getLayer("Layer 1"); + layer.texture.setAntiAliasTexParameters(); + + layer = map.getLayer("Layer 2"); + layer.texture.setAntiAliasTexParameters(); + } + }, + title:function () { + return "TMX Tileset test"; + }, + // Automation + testDuration:1, + pixel1:{"0":255, "1":0, "2":0, "3":255}, + pixel2:{"0":213, "1":202, "2":190, "3":255}, + pixel3:{"0":61, "1":118, "2":71, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(53, 80, 5, 5); + var ret2 = this.readPixels(38, 151, 5, 5); + var ret3 = this.readPixels(345, 202, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1, false) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2, false) ? "yes" : "no", + "pixel3":this.containsPixel(ret3, this.pixel3, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TMXOrthoObjectsTest +// +//------------------------------------------------------------------ +var TMXOrthoObjectsTest = TileDemo.extend({ + ctor:function () { + this._super(); + var drawNode = new cc.DrawNode(); + drawNode.setLineWidth(3); + drawNode.setDrawColor(cc.color(255,255,255,255)); + this.addChild(drawNode); + + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/ortho-objects.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + var group = map.getObjectGroup("Object Group 1"); + var array = group.getObjects(); + var dict; + + for (var i = 0, len = array.length; i < len; i++) { + dict = array[i]; + if (!dict) + break; + for (var k in dict) { + this.log(k + ' = ' + dict[k]); + } + + var x = dict["x"], y = dict["y"]; + var width = dict["width"], height = dict["height"]; + + drawNode.drawSegment(cc.p(x, y), cc.p((x + width), y)); + drawNode.drawSegment(cc.p((x + width), y), cc.p((x + width), (y + height))); + drawNode.drawSegment(cc.p((x + width), (y + height)), cc.p(x, (y + height))); + drawNode.drawSegment(cc.p(x, (y + height)), cc.p(x, y)); + } + + //Automation parameters + this.testObjects = array; + }, + onEnter:function () { + this._super(); + this.anchorX = 0; + this.anchorY = 0; + }, + title:function () { + return "TMX Ortho object test"; + }, + subtitle:function () { + return "You should see a white box around the 3 platforms"; + }, + + // + // Automation + // + testObjects:null, + getExpectedResult:function () { + var ret = []; + ret.push({"name":"Object", "type":"", "x":0, "y":0, "width":352, "height":32}); + ret.push({"name":"Object", "type":"", "x":224, "y":64, "width":160, "height":32 }); + ret.push({"name":"platform", "type":"platform", "x":2, "y":131, "width":125, "height":60}); + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret = []; + var obj = null; + for (var i = 0; i < this.testObjects.length; i++) { + obj = this.testObjects[i]; + ret.push({"name":obj["name"] || "", "type":obj["type"] || "", "x":parseFloat(obj["x"]), "y":parseFloat(obj["y"]), "width":parseFloat(obj["width"]), "height":parseFloat(obj["height"])}); + } + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TMXIsoObjectsTest +// +//------------------------------------------------------------------ +var TMXIsoObjectsTest = TileDemo.extend({ + ctor:function () { + this._super(); + + var drawNode = new cc.DrawNode(); + drawNode.setLineWidth(3); + drawNode.setDrawColor(cc.color(255,255,255,255)); + this.addChild(drawNode); + + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test-objectgroup.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + var group = map.getObjectGroup("Object Group 1"); + var array = group.getObjects(); + var dict; + for (var i = 0, len = array.length; i < len; i++) { + dict = array[i]; + if (!dict) + break; + for (var k in dict) { + this.log(k + ' = ' + dict[k]); + } + + var x = dict["x"], y = dict["y"]; + var width = dict["width"], height = dict["height"]; + + drawNode.drawSegment(cc.p(x, y), cc.p((x + width), y)); + drawNode.drawSegment(cc.p((x + width), y), cc.p((x + width), (y + height))); + drawNode.drawSegment(cc.p((x + width), (y + height)), cc.p(x, (y + height))); + drawNode.drawSegment(cc.p(x, (y + height)), cc.p(x, y)); + } + + //Automation parameters + this.testObjects = array; + }, + + onEnter:function () { + this._super(); + this.anchorX = 0; + this.anchorY = 0; + }, + + title:function () { + return "TMX Iso object test"; + }, + subtitle:function () { + return "You need to parse them manually. See bug #810"; + }, + + // + // Automation + // + testObjects:null, + getExpectedResult:function () { + var ret = []; + ret.push({"name":"platform 1", "type":"", "x":0, "y":0, "width":32, "height":30}); + ret.push({"name":"", "type":"", "x":0, "y":285, "width":31, "height":32}); + ret.push({"name":"", "type":"", "x":130, "y":129, "width":29, "height":29}); + ret.push({"name":"", "type":"", "x":290, "y":1, "width":28, "height":29}); + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret = []; + var obj = null; + for (var i = 0; i < this.testObjects.length; i++) { + obj = this.testObjects[i]; + ret.push({"name":obj["name"] || "", "type":obj["type"] || "", "x":parseFloat(obj["x"]), "y":parseFloat(obj["y"]), "width":parseFloat(obj["width"]), "height":parseFloat(obj["height"])}); + } + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TMXResizeTest +// +//------------------------------------------------------------------ +var TMXResizeTest = TileDemo.extend({ + ctor:function () { + this._super(); + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test5.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + var layer; + layer = map.getLayer("Layer 0"); + + var ls = layer.getLayerSize(); + for (var y = 0; y < ls.height; y++) { + for (var x = 0; x < ls.width; x++) { + layer.setTileGID(1, cc.p(x, y)); + } + } + }, + title:function () { + return "TMX resize test"; + }, + subtitle:function () { + return "Should not crash. Testing issue #740"; + }, + // + // Automation + // + testDuration:0.25, + pixel:{"0":169, "1":120, "2":76, "3":255}, + getExpectedResult:function () { + var ret = {"pixel":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(156, 156, 5, 5); + var ret = {"pixel":this.containsPixel(ret1, this.pixel, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TMXIsoZorder +// +//------------------------------------------------------------------ +var TMXIsoZorder = TileDemo.extend({ + tamara:null, + ctor:function () { + this._super(); + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test-zorder.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + map.x = -map.width / 2; + map.y = 0; + + this.tamara = new cc.Sprite(s_pathSister1); + map.addChild(this.tamara, map.children.length); + var mapWidth = map.getMapSize().width * map.getTileSize().width; + this.tamara.x = mapWidth / 2; + this.tamara.y = 0; + this.tamara.anchorX = 0.5; + this.tamara.anchorY = 0; + + var move = cc.moveBy(5, cc.pMult(cc.p(300, 250), 0.75)); + var back = move.reverse(); + var delay = cc.delayTime(0.5); + var seq = cc.sequence(move, delay, back); + this.tamara.runAction(seq.repeatForever()); + + this.schedule(this.repositionSprite); + }, + title:function () { + return "TMX Iso Zorder"; + }, + subtitle:function () { + return "Sprite should hide behind the trees"; + }, + onExit:function () { + this.unschedule(this.repositionSprite); + this._super(); + }, + repositionSprite:function (dt) { + var map = this.getChildByTag(TAG_TILE_MAP); + + // there are only 4 layers. (grass and 3 trees layers) + // if tamara < 48, z=4 + // if tamara < 96, z=3 + // if tamara < 144, z=2 + + var newZ = 4 - (this.tamara.y / 48); + newZ = parseInt(Math.max(newZ, 0), 10); + map.reorderChild(this.tamara, newZ); + }, + // + // Automation + // + testDuration:5.2, + pixel:{"0":255, "1":255, "2":255, "3":255}, + getExpectedResult:function () { + var ret = {"pixel":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(223, 247, 5, 5); + var ret = {"pixel":this.containsPixel(ret1, this.pixel, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TMXOrthoZorder +// +//------------------------------------------------------------------ +var TMXOrthoZorder = TileDemo.extend({ + tamara:null, + ctor:function () { + this._super(); + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test-zorder.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + this.tamara = new cc.Sprite(s_pathSister1); + map.addChild(this.tamara, map.children.length, TAG_TILE_MAP); + this.tamara.anchorX = 0.5; + this.tamara.anchorY = 0; + + var move = cc.moveBy(5, cc.pMult(cc.p(400, 450), 0.58)); + var back = move.reverse(); + var seq = cc.sequence(move, back); + this.tamara.runAction(seq.repeatForever()); + + this.schedule(this.repositionSprite); + }, + title:function () { + return "TMX Ortho Zorder"; + }, + subtitle:function () { + return "Sprite should hide behind the trees"; + }, + repositionSprite:function (dt) { + var map = this.getChildByTag(TAG_TILE_MAP); + + // there are only 4 layers. (grass and 3 trees layers) + // if tamara < 81, z=4 + // if tamara < 162, z=3 + // if tamara < 243,z=2 + + // -10: customization for this particular sample + var newZ = 4 - ((this.tamara.y - 10) / 81); + newZ = Math.max(newZ, 0); + + map.reorderChild(this.tamara, newZ); + }, + // + // Automation + // + testDuration:2, + pixel1:{"0":117, "1":185, "2":63, "3":255}, + pixel2:{"0":91, "1":55, "2":20, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(86, 131, 5, 5); + var ret2 = this.readPixels(84, 200, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1, false) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2, true, 5) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TMXIsoVertexZ +// +//------------------------------------------------------------------ +var TMXIsoVertexZ = TMXFixBugLayer.extend({ + tamara:null, + ctor:function () { + this._super(); + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test-vertexz.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + map.x = -map.width / 2; + map.y = 0; + + // because I'm lazy, I'm reusing a tile as an sprite, but since this method uses vertexZ, you + // can use any cc.Sprite and it will work OK. + var layer = map.getLayer("Trees"); + this.tamara = layer.getTileAt(cc.p(29, 29)); + + var move = cc.moveBy(5, cc.pMult(cc.p(300, 250), 0.75)); + var back = move.reverse(); + var delay = cc.delayTime(0.5); + var seq = cc.sequence(move, delay, back); + this.tamara.runAction(seq.repeatForever()); + + if (!cc.sys.isNative && !("opengl" in cc.sys.capabilities)) { + var label = new cc.LabelTTF("Not supported on HTML5-canvas", "Times New Roman", 30); + this.addChild(label); + label.x = winSize.width / 2; + label.y = winSize.height / 2; + } + + this.schedule(this.repositionSprite); + }, + title:function () { + return "TMX Iso VertexZ"; + }, + subtitle:function () { + return "Sprite should hide behind the trees"; + }, + onEnter:function () { + this._super(); + // TIP: 2d projection should be used + director.setProjection(cc.Director.PROJECTION_2D); + }, + onExit:function () { + // At exit use any other projection. + // director.setProjection:cc.Director.PROJECTION_3D); + this._super(); + }, + repositionSprite:function (dt) { + // tile height is 64x32 + // map size: 30x30 + var z = -( (this.tamara.y + 32) / 16); + this.tamara.vertexZ = z; + }, + // + // Automation + // + testDuration:5.2, + pixel:{"0":255, "1":255, "2":255, "3":255}, + getExpectedResult:function () { + var ret = {"pixel":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(224, 246, 4, 4); + var ret = {"pixel":this.containsPixel(ret1, this.pixel, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TMXOrthoVertexZ +// +//------------------------------------------------------------------ +var TMXOrthoVertexZ = TMXFixBugLayer.extend({ + tamara:null, + ctor:function () { + this._super(); + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test-vertexz.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + // because I'm lazy, I'm reusing a tile as an sprite, but since this method uses vertexZ, you + // can use any cc.Sprite and it will work OK. + var layer = map.getLayer("trees"); + this.tamara = layer.getTileAt(cc.p(0, 11)); + this.log("vertexZ: " + this.tamara.vertexZ); + + var move = cc.moveBy(5, cc.pMult(cc.p(400, 450), 0.55)); + var back = move.reverse(); + var delay = cc.delayTime(0.5); + var seq = cc.sequence(move, delay, back); + this.tamara.runAction(seq.repeatForever()); + + if (!cc.sys.isNative && !("opengl" in cc.sys.capabilities)) { + var label = new cc.LabelTTF("Not supported on HTML5-canvas", "Times New Roman", 30); + this.addChild(label); + label.x = winSize.width / 2; + label.y = winSize.height / 2; + } + + this.schedule(this.repositionSprite); + + this.log("DEPTH BUFFER MUST EXIST IN ORDER"); + }, + title:function () { + return "TMX Ortho vertexZ"; + }, + subtitle:function () { + return "Sprite should hide behind the trees"; + }, + onEnter:function () { + this._super(); + + // TIP: 2d projection should be used + director.setProjection(cc.Director.PROJECTION_2D); + }, + onExit:function () { + // At exit use any other projection. + // director.setProjection:cc.Director.PROJECTION_3D); + this._super(); + }, + repositionSprite:function (dt) { + // tile height is 101x81 + // map size: 12x12 + this.tamara.vertexZ = -(this.tamara.y + 81) / 81; + }, + // + // Automation + // + testDuration:5.2, + pixel:{"0":119, "1":205, "2":73, "3":255}, + getExpectedResult:function () { + var ret = {"pixel":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(266, 331, 5, 5); + var ret = {"pixel":this.containsPixel(ret1, this.pixel, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TMXIsoMoveLayer +// +//------------------------------------------------------------------ +var TMXIsoMoveLayer = TileDemo.extend({ + ctor:function () { + this._super(); + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test-movelayer.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + map.x = -700; + map.y = -50; + }, + title:function () { + return "TMX Iso Move Layer"; + }, + subtitle:function () { + return "Trees should be horizontally aligned"; + } +}); + +//------------------------------------------------------------------ +// +// TMXOrthoMoveLayer +// +//------------------------------------------------------------------ +var TMXOrthoMoveLayer = TileDemo.extend({ + ctor:function () { + this._super(); + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test-movelayer.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + }, + title:function () { + return "TMX Ortho Move Layer"; + }, + subtitle:function () { + return "Trees should be horizontally aligned"; + } +}); + +//------------------------------------------------------------------ +// +// TMXTilePropertyTest +// +//------------------------------------------------------------------ +var TMXTilePropertyTest = TileDemo.extend({ + ctor:function () { + this._super(); + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/ortho-tile-property.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + for (var i = 1; i <= 6; i++) { + var properties = map.getPropertiesForGID(i); + this.log("GID:" + i + ", Properties:" + JSON.stringify(properties)); + this.propertiesList.push(properties) + } + }, + title:function () { + return "TMX Tile Property Test"; + }, + subtitle:function () { + return "In the console you should see tile properties"; + }, + // + // Automation + // + testDuration:0.25, + propertiesList:[], + getExpectedResult:function () { + var ret = []; + ret.push({"test":"sss", "type":"object"}); + ret.push({"type":"object"}); + ret.push({"type":"object"}); + ret.push({"type":"platform"}); + ret.push({"type":"platform"}); + ret.push({"type":"platform"}); + return JSON.stringify(ret); + }, + getCurrentResult:function () { + return JSON.stringify(this.propertiesList); + } +}); + +//------------------------------------------------------------------ +// +// TMXOrthoFlipTest +// +//------------------------------------------------------------------ +var TMXOrthoFlipTest = TileDemo.extend({ + ctor:function () { + this._super(); + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/ortho-rotation-test.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + this.log("ContentSize:" + map.width + "," + map.height); + + var action = new cc.ScaleBy(2, 0.5); + map.runAction(action); + }, + title:function () { + return "TMX tile flip test"; + }, + // + // Automation + // + testDuration:2.2, + pixel:{"0":41, "1":42, "2":54, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(93, 153, 5, 5); + var ret2 = this.readPixels(105, 153, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel, false) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TMXOrthoFlipRunTimeTest +// +//------------------------------------------------------------------ +var TMXOrthoFlipRunTimeTest = TileDemo.extend({ + ctor:function () { + this._super(); + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/ortho-rotation-test.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + this.log("ContentSize:" + map.width + "," + map.height); + + var action = new cc.ScaleBy(2, 0.5); + map.runAction(action); + + this.schedule(this.onFlipIt, 1); + }, + title:function () { + return "TMX tile flip run time test"; + }, + subtitle:function () { + return "in 2 sec bottom left tiles will flip"; + }, + onFlipIt:function () { + var map = this.getChildByTag(TAG_TILE_MAP); + var layer = map.getLayer("Layer 0"); + + //blue diamond + var tileCoord = cc.p(1, 10); + var flags = layer.getTileFlagsAt(tileCoord); + var GID = layer.getTileGIDAt(tileCoord); + // Vertical + if ((flags & cc.TMX_TILE_VERTICAL_FLAG) >>> 0) { + flags = (flags & ~cc.TMX_TILE_VERTICAL_FLAG >>> 0) >>> 0; + } else { + flags = (flags | cc.TMX_TILE_VERTICAL_FLAG) >>> 0; + } + layer.setTileGID(GID, tileCoord, flags); + + tileCoord = cc.p(1, 8); + flags = layer.getTileFlagsAt(tileCoord); + GID = layer.getTileGIDAt(tileCoord); + // Vertical + if ((flags & cc.TMX_TILE_VERTICAL_FLAG) >>> 0) + flags = (flags & ~cc.TMX_TILE_VERTICAL_FLAG >>> 0) >>> 0; + else + flags = (flags | cc.TMX_TILE_VERTICAL_FLAG) >>> 0; + layer.setTileGID(GID, tileCoord, flags); + + tileCoord = cc.p(2, 8); + flags = layer.getTileFlagsAt(tileCoord); + GID = layer.getTileGIDAt(tileCoord); + // Horizontal + if ((flags & cc.TMX_TILE_HORIZONTAL_FLAG) >>> 0) + flags = (flags & ~cc.TMX_TILE_HORIZONTAL_FLAG >>> 0) >>> 0; + else + flags = (flags | cc.TMX_TILE_HORIZONTAL_FLAG) >>> 0; + layer.setTileGID(GID, tileCoord, flags); + }, + // + // Automation + // + testDuration:3.2, + pixel:{"0":41, "1":42, "2":54, "3":255}, + pixel1:null, + setupAutomation:function () { + var fun = function () { + this.pixel1 = this.readPixels(104, 154, 5, 5); + } + this.scheduleOnce(fun, 2.2); + }, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + this.pixel2 = this.readPixels(145, 154, 5, 5); + var ret = {"pixel1":this.containsPixel(this.pixel1, this.pixel, false) ? "yes" : "no", + "pixel2":this.containsPixel(this.pixel2, this.pixel, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TMXOrthoFromXMLTest +// +//------------------------------------------------------------------ +var TMXOrthoFromXMLTest = TileDemo.extend({ + ctor:function () { + this._super(); + + var resources = s_resprefix + "TileMaps"; + var filePath = s_resprefix + "TileMaps/orthogonal-test1.tmx"; + var xmlStr = cc.loader.getRes(filePath); + var map = new cc.TMXTiledMap(xmlStr, resources); + this.addChild(map, 0, TAG_TILE_MAP); + + cc.log("ContentSize: " + map.width + ", " + map.height); + + if ("opengl" in cc.sys.capabilities) { + var mapChildren = map.children; + for (var i = 0; i < mapChildren.length; i++) { + var child = mapChildren[i]; + if (child) + child.texture.setAntiAliasTexParameters(); + } + } + + var action = new cc.ScaleBy(2, 0.5); + map.runAction(action); + }, + title:function () { + return "TMX created from XML test"; + }, + // + // Automation + // + testDuration:2.2, + pixel1:{"0":210, "1":210, "2":200, "3":255}, + pixel2:{"0":243, "1":202, "2":86, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(326, 120, 5, 5); + var ret2 = this.readPixels(124, 246, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1, false) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TMXBug987 +// +//------------------------------------------------------------------ +var TMXBug987 = TileDemo.extend({ + ctor:function () { + this._super(); + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test6.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + this.log("ContentSize:" + map.width + "," + map.height); + + var childs = map.children; + var node = null; + for (var i = 0, len = childs.length; i < len; i++) { + node = childs[i]; + if (!node) break; + if ("opengl" in cc.sys.capabilities) + node.texture.setAntiAliasTexParameters(); + } + + map.anchorX = 0; + map.anchorY = 0; + var layer = map.getLayer("Tile Layer 1"); + layer.setTileGID(3, cc.p(2, 2)); + }, + title:function () { + return "TMX Bug 987"; + }, + subtitle:function () { + return "You should see an square"; + }, + // + // Automation + // + testDuration:0.25, + pixel1:{"0":162, "1":152, "2":98, "3":255}, + pixel2:{"0":255, "1":208, "2":148, "3":255}, + pixel3:{"0":182, "1":182, "2":146, "3":255}, + getExpectedResult:function () { + var ret = {"pixel1":"yes", "pixel2":"yes", "pixel3":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(64, 224, 5, 5); + var ret2 = this.readPixels(4, 165, 5, 5); + var ret3 = this.readPixels(144, 140, 5, 5); + var ret = {"pixel1":this.containsPixel(ret1, this.pixel1, false) ? "yes" : "no", + "pixel2":this.containsPixel(ret2, this.pixel2, false) ? "yes" : "no", + "pixel3":this.containsPixel(ret3, this.pixel3, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +//------------------------------------------------------------------ +// +// TMXBug787 +// +//------------------------------------------------------------------ +var TMXBug787 = TileDemo.extend({ + ctor:function () { + this._super(); + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test-bug787.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + map.scale = 0.25; + }, + title:function () { + return "TMX Bug 787"; + }, + subtitle:function () { + return "You should see a map"; + }, + // + // Automation + // + testDuration:0.25, + pixel:{"0":255, "1":255, "2":255, "3":255}, + getExpectedResult:function () { + var ret = {"pixel":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(364, 243, 5, 5); + var ret = {"pixel":this.containsPixel(ret1, this.pixel, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +var TMXGIDObjectsTest = TileDemo.extend({ + ctor:function () { + this._super(); + + var drawNode = new cc.DrawNode(); + drawNode.setLineWidth(3); + drawNode.setDrawColor(cc.color(255,255,255,255)); + this.addChild(drawNode); + + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/test-object-layer.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + this.log("ContentSize:" + map.width + "," + map.height); + this.log("---. Iterating over all the group objets"); + + var group = map.getObjectGroup("Object Layer 1"); + var array = group.getObjects(); + var dict; + for (var i = 0, len = array.length; i < len; i++) { + dict = array[i]; + if (!dict) + break; + for (var k in dict) { + this.log(k + ' = ' + dict[k]); + } + + var x = dict["x"], y = dict["y"]; + var width = dict["width"], height = dict["height"]; + + if (width != 0 && height != 0) { + drawNode.drawSegment(cc.p(x, y), cc.p((x + width), y)); + drawNode.drawSegment(cc.p((x + width), y), cc.p((x + width), (y + height))); + drawNode.drawSegment(cc.p((x + width), (y + height)), cc.p(x, (y + height))); + drawNode.drawSegment(cc.p(x, (y + height)), cc.p(x, y)); + } + } + this.testObjects = array; + }, + title:function () { + return "TMX GID objects"; + }, + subtitle:function () { + return "Tiles are created from an object group"; + }, + // + // Automation + // + testObjects:[], + getExpectedResult:function () { + var ret = []; + ret.push({"name":"sandro", "type":"", "x":97, "y":6, "width":0, "height":0}); + ret.push({"name":"", "type":"", "x":119, "y":19, "width":0, "height":0}); + ret.push({"name":"", "type":"", "x":140, "y":38, "width":0, "height":0}); + ret.push({"name":"", "type":"", "x":160, "y":57, "width":0, "height":0}); + ret.push({"name":"", "type":"", "x":180, "y":71, "width":0, "height":0}); + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret = []; + var obj = null; + for (var i = 0; i < this.testObjects.length; i++) { + obj = this.testObjects[i]; + ret.push({"name":obj["name"] || "", "type":obj["type"] || "", "x":parseFloat(obj["x"]), "y":parseFloat(obj["y"]), "width":parseFloat(obj["width"] || 0), "height":parseFloat(obj["height"] || 0)}); + } + return JSON.stringify(ret); + } +}); + + +var TMXIsoOffsetTest = TileDemo.extend({ + ctor:function () { + this._super(); + var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/tile_iso_offset.tmx"); + this.addChild(map, 0, TAG_TILE_MAP); + + }, + title:function () { + return "TMX Tile Offset"; + }, + subtitle:function () { + return "Testing offset of tiles"; + }, + // + // Automation + // + testDuration:0.25, + pixel:{"0":168, "1":168, "2":168, "3":255}, + getExpectedResult:function () { + var ret = {"pixel":"yes"}; + return JSON.stringify(ret); + }, + getCurrentResult:function () { + var ret1 = this.readPixels(150, 260, 5, 5); + var ret = {"pixel":this.containsPixel(ret1, this.pixel, false) ? "yes" : "no"}; + return JSON.stringify(ret); + } +}); + +var TileMapTestScene = TestScene.extend({ + runThisTest:function (num) { + tileTestSceneIdx = (num || num == 0) ? (num - 1) : -1; + var layer = nextTileMapTest(); + this.addChild(layer); + // fix bug #486, #419. + // "test" is the default value in CCDirector::setGLDefaultValues() + // but TransitionTest may setDepthTest(false), we should revert it here + cc.director.setDepthTest(true); + + director.runScene(this); + } +}); + +// +// Flow control +// +var arrayOfTileMapTest = [ + TMXOrthoTest, + TMXOrthoTest2, + TMXOrthoTest3, + TMXOrthoTest4, + TMXReadWriteTest, + TMXHexTest, + TMXIsoTest, + TMXIsoTest1, + TMXIsoTest2, + TMXUncompressedTest, + TMXTilesetTest, + TMXOrthoObjectsTest, + TMXIsoObjectsTest, + TMXResizeTest, + TMXIsoZorder, + TMXOrthoZorder, + TMXIsoVertexZ, + TMXOrthoVertexZ, + TMXIsoMoveLayer, + TMXOrthoMoveLayer, + TMXTilePropertyTest, + TMXOrthoFlipTest, + TMXOrthoFlipRunTimeTest, + TMXOrthoFromXMLTest, + TMXBug987, + TMXBug787, + TMXIsoOffsetTest +]; + +if ( !cc.sys.isNative ){ + //This test is supported only in HTML5 + arrayOfTileMapTest.push(TMXGIDObjectsTest); +} + +var nextTileMapTest = function () { + tileTestSceneIdx++; + tileTestSceneIdx = tileTestSceneIdx % arrayOfTileMapTest.length; + + return new arrayOfTileMapTest[tileTestSceneIdx](); +}; +var previousTileMapTest = function () { + tileTestSceneIdx--; + if (tileTestSceneIdx < 0) + tileTestSceneIdx += arrayOfTileMapTest.length; + + return new arrayOfTileMapTest[tileTestSceneIdx](); +}; +var restartTileMapTest = function () { + return new arrayOfTileMapTest[tileTestSceneIdx](); +}; + diff --git a/tests/js-tests/src/TouchesTest/Ball.js b/tests/js-tests/src/TouchesTest/Ball.js new file mode 100644 index 0000000000..a7bf5dddd6 --- /dev/null +++ b/tests/js-tests/src/TouchesTest/Ball.js @@ -0,0 +1,98 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var Ball = cc.Sprite.extend({ + _velocity:cc.p(0,0), + _radius:0, + radius:function () { + return this._radius; + }, + setRadius:function (rad) { + this._radius = rad; + }, + move:function (delta) { + this.x += this._velocity.x * delta; + this.y += this._velocity.y * delta; + var winSize = cc.director.getWinSize(); + if (this.x > winSize.width - this.radius()) { + this.x = winSize.width - this.radius(); + this._velocity.x *= -1; + } else if (this.x < this.radius()) { + this.x = this.radius(); + this._velocity.x *= -1; + } + }, + collideWithPaddle:function (paddle) { + var paddleRect = paddle.rect(); + + paddleRect.x += paddle.x; + paddleRect.y += paddle.y; + + var lowY = cc.rectGetMinY(paddleRect); + var midY = cc.rectGetMidY(paddleRect); + var highY = cc.rectGetMaxY(paddleRect); + + var leftX = cc.rectGetMinX(paddleRect); + var rightX = cc.rectGetMaxX(paddleRect); + + if ((this.x > leftX) && (this.x < rightX)) { + var hit = false; + var angleOffset = 0.0; + if ((this.y > midY) && (this.y <= (highY + this.radius()))) { + this.y = highY + this.radius(); + hit = true; + angleOffset = Math.PI / 2; + } else if (this.y < midY && this.y >= lowY - this.radius()) { + this.y = lowY - this.radius(); + hit = true; + angleOffset = -Math.PI / 2; + } + + if (hit) { + var hitAngle = cc.pToAngle(cc.p(paddle.x - this.x, paddle.y - this.y)) + angleOffset; + + var scalarVelocity = cc.pLength(this._velocity) * 1.00000005; + var velocityAngle = -cc.pToAngle(this._velocity) + 0.00000005 * hitAngle; + //this._velocity = -this._velocity.y; + this._velocity = cc.pMult(cc.pForAngle(velocityAngle), scalarVelocity); + } + } + }, + setVelocity:function (velocity) { + this._velocity = velocity; + }, + getVelocity:function () { + return this._velocity; + } +}); +Ball.ballWithTexture = function (texture) { + var ball = new Ball(); + ball.initWithTexture(texture); + if (texture instanceof cc.Texture2D) + ball.setRadius(texture.width / 2); + else if ((texture instanceof HTMLImageElement) || (texture instanceof HTMLCanvasElement)) + ball.setRadius(texture.width / 2); + return ball; +}; diff --git a/tests/js-tests/src/TouchesTest/Paddle.js b/tests/js-tests/src/TouchesTest/Paddle.js new file mode 100644 index 0000000000..1509f77daf --- /dev/null +++ b/tests/js-tests/src/TouchesTest/Paddle.js @@ -0,0 +1,106 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var PADDLE_STATE_GRABBED = 0; +var PADDLE_STATE_UNGRABBED = 1; + +var Paddle = cc.Sprite.extend({ + _state:PADDLE_STATE_UNGRABBED, + _rect:null, + + ctor: function(){ + this._super(); + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches: true, + onTouchBegan: this.onTouchBegan, + onTouchMoved: this.onTouchMoved, + onTouchEnded: this.onTouchEnded + }, this); + }, + + rect:function () { + return cc.rect(-this._rect.width / 2, -this._rect.height / 2, this._rect.width, this._rect.height); + }, + initWithTexture:function (aTexture) { + if (this._super(aTexture)) { + this._state = PADDLE_STATE_UNGRABBED; + } + if (aTexture instanceof cc.Texture2D) { + this._rect = cc.rect(0, 0, aTexture.width, aTexture.height); + } else if ((aTexture instanceof HTMLImageElement) || (aTexture instanceof HTMLCanvasElement)) { + this._rect = cc.rect(0, 0, aTexture.width, aTexture.height); + } + return true; + }, + + containsTouchLocation:function (touch) { + var getPoint = touch.getLocation(); + var myRect = this.rect(); + + myRect.x += this.x; + myRect.y += this.y; + return cc.rectContainsPoint(myRect, getPoint);//this.convertTouchToNodeSpaceAR(touch)); + }, + + onTouchBegan:function (touch, event) { + var target = event.getCurrentTarget(); + if (target._state != PADDLE_STATE_UNGRABBED) return false; + if (!target.containsTouchLocation(touch)) return false; + + target._state = PADDLE_STATE_GRABBED; + return true; + }, + onTouchMoved:function (touch, event) { + var target = event.getCurrentTarget(); + // If it weren't for the TouchDispatcher, you would need to keep a reference + // to the touch from touchBegan and check that the current touch is the same + // as that one. + // Actually, it would be even more complicated since in the Cocos dispatcher + // you get Array instead of 1 cc.Touch, so you'd need to loop through the set + // in each touchXXX method. + cc.assert(target._state == PADDLE_STATE_GRABBED, "Paddle - Unexpected state!"); + + var touchPoint = touch.getLocation(); + //touchPoint = cc.director.convertToGL( touchPoint ); + + target.x = touchPoint.x; + }, + onTouchEnded:function (touch, event) { + var target = event.getCurrentTarget(); + cc.assert(target._state == PADDLE_STATE_GRABBED, "Paddle - Unexpected state!"); + target._state = PADDLE_STATE_UNGRABBED; + }, + touchDelegateRetain:function () { + }, + touchDelegateRelease:function () { + } +}); +Paddle.paddleWithTexture = function (aTexture) { + var paddle = new Paddle(); + paddle.initWithTexture(aTexture); + + return paddle; +}; diff --git a/tests/js-tests/src/TouchesTest/TouchesTest.js b/tests/js-tests/src/TouchesTest/TouchesTest.js new file mode 100644 index 0000000000..fb74472355 --- /dev/null +++ b/tests/js-tests/src/TouchesTest/TouchesTest.js @@ -0,0 +1,123 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +var HIGH_PLAYER = 0; +var LOW_PLAYER = 1; +var STATUS_BAR_HEIGHT = 20.0; +var SPRITE_TAG = 0; + +var TouchesTestScene = TestScene.extend({ + ctor:function () { + this._super(true); + var pongLayer = new PongLayer(); + this.addChild(pongLayer); + }, + runThisTest:function () { + cc.director.runScene(this); + }, + MainMenuCallback:function (sender) { + this._super(sender); + } +}); + +var PongLayer = cc.Layer.extend({ + _ball:null, + _paddles:[], + _ballStartingVelocity:null, + _winSize:null, + + ctor:function () { + this._super(); + this._ballStartingVelocity = cc.p(20.0, -100.0); + this._winSize = cc.director.getWinSize(); + + this._ball = Ball.ballWithTexture(cc.textureCache.addImage(s_ball)); + this._ball.x = this._winSize.width / 2; + this._ball.y = this._winSize.height / 2; + this._ball.setVelocity(this._ballStartingVelocity); + this.addChild(this._ball); + + var paddleTexture = cc.textureCache.addImage(s_paddle); + + this._paddles = []; + + var paddle = Paddle.paddleWithTexture(paddleTexture); + paddle.x = this._winSize.width / 2; + paddle.y = 15; + this._paddles.push(paddle); + + paddle = Paddle.paddleWithTexture(paddleTexture); + paddle.x = this._winSize.width / 2; + paddle.y = this._winSize.height - STATUS_BAR_HEIGHT - 15; + this._paddles.push(paddle); + + paddle = Paddle.paddleWithTexture(paddleTexture); + paddle.x = this._winSize.width / 2; + paddle.y = 100; + this._paddles.push(paddle); + + paddle = Paddle.paddleWithTexture(paddleTexture); + paddle.x = this._winSize.width / 2; + paddle.y = this._winSize.height - STATUS_BAR_HEIGHT - 100; + this._paddles.push(paddle); + + for (var i = 0; i < this._paddles.length; i++) { + if (!this._paddles[i]) + break; + + this.addChild(this._paddles[i]); + } + + this.schedule(this.doStep); + }, + resetAndScoreBallForPlayer:function (player) { + if (Math.abs(this._ball.getVelocity().y) < 300) { + this._ballStartingVelocity = cc.pMult(this._ballStartingVelocity, -1.1); + } else { + this._ballStartingVelocity = cc.pMult(this._ballStartingVelocity, -1); + } + this._ball.setVelocity(this._ballStartingVelocity); + this._ball.x = this._winSize.width / 2; + this._ball.y = this._winSize.height / 2; + + // TODO -- scoring + }, + doStep:function (delta) { + this._ball.move(delta); + + for (var i = 0; i < this._paddles.length; i++) { + if (!this._paddles[i]) + break; + + this._ball.collideWithPaddle(this._paddles[i]); + } + + if (this._ball.y > this._winSize.height - STATUS_BAR_HEIGHT + this._ball.radius()) + this.resetAndScoreBallForPlayer(LOW_PLAYER); + else if (this._ball.y < -this._ball.radius()) + this.resetAndScoreBallForPlayer(HIGH_PLAYER); + this._ball.draw(); + } +}); diff --git a/tests/js-tests/src/TransitionsTest/TransitionsTest.js b/tests/js-tests/src/TransitionsTest/TransitionsTest.js new file mode 100644 index 0000000000..f6f0173e6b --- /dev/null +++ b/tests/js-tests/src/TransitionsTest/TransitionsTest.js @@ -0,0 +1,458 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ +TRANSITION_DURATION = 1.2; + +var arrayOfTransitionsTest = [ + + {title:"JumpZoomTransition", transitionFunc:function (t, s) { + return new JumpZoomTransition(t, s); + }}, + + {title:"TransitionProgressRadialCCW", transitionFunc:function (t, s) { + return new cc.TransitionProgressRadialCCW(t, s); + }}, + + {title:"TransitionProgressRadialCW", transitionFunc:function (t, s) { + return new cc.TransitionProgressRadialCW(t, s); + }}, + + {title:"TransitionProgressHorizontal", transitionFunc:function (t, s) { + return new cc.TransitionProgressHorizontal(t, s); + }}, + + {title:"TransitionProgressVertical", transitionFunc:function (t, s) { + return new cc.TransitionProgressVertical(t, s); + }}, + + {title:"TransitionProgressInOut", transitionFunc:function (t, s) { + return new cc.TransitionProgressInOut(t, s); + }}, + + {title:"TransitionProgressOutIn", transitionFunc:function (t, s) { + return new cc.TransitionProgressOutIn(t, s); + }}, + + //ok + {title:"FadeTransition", transitionFunc:function (t, s) { + return FadeTransition(t, s); + }}, + {title:"FadeWhiteTransition", transitionFunc:function (t, s) { + return FadeWhiteTransition(t, s); + }}, + + {title:"ShrinkGrowTransition", transitionFunc:function (t, s) { + return ShrinkGrowTransition(t, s); + }}, + {title:"RotoZoomTransition", transitionFunc:function (t, s) { + return RotoZoomTransition(t, s); + }}, + {title:"MoveInLTransition", transitionFunc:function (t, s) { + return MoveInLTransition(t, s); + }}, + {title:"MoveInRTransition", transitionFunc:function (t, s) { + return MoveInRTransition(t, s); + }}, + {title:"MoveInTTransition", transitionFunc:function (t, s) { + return MoveInTTransition(t, s); + }}, + {title:"MoveInBTransition", transitionFunc:function (t, s) { + return MoveInBTransition(t, s); + }}, + {title:"SlideInLTransition", transitionFunc:function (t, s) { + return SlideInLTransition(t, s); + }}, + {title:"SlideInRTransition", transitionFunc:function (t, s) { + return SlideInRTransition(t, s); + }}, + {title:"SlideInTTransition", transitionFunc:function (t, s) { + return SlideInTTransition(t, s); + }}, + {title:"SlideInBTransition", transitionFunc:function (t, s) { + return SlideInBTransition(t, s); + }}, + {title:"CCTransitionRadialCCW", transitionFunc:function (t, s) { + return CCTransitionRadialCCW(t, s); + }}, + {title:"CCTransitionRadialCW", transitionFunc:function (t, s) { + return CCTransitionRadialCW(t, s); + }} +]; + +if ('opengl' in cc.sys.capabilities) { + arrayOfTransitionsTest = arrayOfTransitionsTest.concat( + [ + {title: "FlipXLeftOver", transitionFunc: function (t, s) { + return FlipXLeftOver(t, s); + }}, + {title: "FlipXRightOver", transitionFunc: function (t, s) { + return FlipXRightOver(t, s); + }}, + {title: "FlipYUpOver", transitionFunc: function (t, s) { + return FlipYUpOver(t, s); + }}, + {title: "FlipYDownOver", transitionFunc: function (t, s) { + return FlipYDownOver(t, s); + }}, + {title: "FlipAngularLeftOver", transitionFunc: function (t, s) { + return FlipAngularLeftOver(t, s); + }}, + {title: "FlipAngularRightOver", transitionFunc: function (t, s) { + return FlipAngularRightOver(t, s); + }}, + {title: "ZoomFlipXLeftOver", transitionFunc: function (t, s) { + return ZoomFlipXLeftOver(t, s); + }}, + {title: "ZoomFlipXRightOver", transitionFunc: function (t, s) { + return ZoomFlipXRightOver(t, s); + }}, + {title: "ZoomFlipYUpOver", transitionFunc: function (t, s) { + return ZoomFlipYUpOver(t, s); + }}, + {title: "ZoomFlipYDownOver", transitionFunc: function (t, s) { + return ZoomFlipYDownOver(t, s); + }}, + {title: "ZoomFlipAngularLeftOver", transitionFunc: function (t, s) { + return ZoomFlipAngularLeftOver(t, s); + }}, + {title: "ZoomFlipAngularRightOver", transitionFunc: function (t, s) { + return ZoomFlipAngularRightOver(t, s); + }}, + {title: "PageTransitionForward", transitionFunc: function (t, s) { + return PageTransitionForward(t, s); + }}, + {title: "PageTransitionBackward", transitionFunc: function (t, s) { + return PageTransitionBackward(t, s); + }}, + {title: "FadeTRTransition", transitionFunc: function (t, s) { + return FadeTRTransition(t, s); + }}, + {title: "FadeBLTransition", transitionFunc: function (t, s) { + return FadeBLTransition(t, s); + }}, + {title: "FadeUpTransition", transitionFunc: function (t, s) { + return FadeUpTransition(t, s); + }}, + {title: "FadeDownTransition", transitionFunc: function (t, s) { + return FadeDownTransition(t, s); + }}, + {title: "TurnOffTilesTransition", transitionFunc: function (t, s) { + return TurnOffTilesTransition(t, s); + }}, + {title: "SplitRowsTransition", transitionFunc: function (t, s) { + return SplitRowsTransition(t, s); + }}, + {title: "CCTransitionCrossFade", transitionFunc: function (t, s) { + return CCTransitionCrossFade(t, s); + }}, + {title: "SplitColsTransition", transitionFunc: function (t, s) { + return SplitColsTransition(t, s); + }} + ]); +} + +var transitionsIdx = 0; + +// the class inherit from TestScene +// every .Scene each test used must inherit from TestScene, +// make sure the test have the menu item for back to main menu +var TransitionsTestScene = TestScene.extend({ + runThisTest:function () { + var layer = new TestLayer1(); + this.addChild(layer); + director.runScene(this); + } +}); + +var TransitionBase = BaseTestLayer.extend({ + + testDuration:TRANSITION_DURATION + 0.1, + title:function() { + return arrayOfTransitionsTest[transitionsIdx].title; + }, + ctor:function () { + this._super(this.colorA, this.colorB); + + var x, y; + var size = director.getWinSize(); + x = size.width; + y = size.height; + + var bg1 = new cc.Sprite(this.backgroundImage); + bg1.x = size.width / 2; + bg1.y = size.height / 2; + bg1.scale = 1.7; + this.addChild(bg1); + + var title = new cc.LabelTTF(this.title(), "Thonburi", 32); + this.addChild(title); + title.color = cc.color(255, 32, 32); + title.x = x / 2; + title.y = y - 100; + + var label = new cc.LabelTTF(this.sceneName, "Marker Felt", 38); + label.color = cc.color(16, 16, 255); + label.x = x / 2; + label.y = y / 2; + this.addChild(label); + + this.schedule(this.step, 1.0); + }, + onRestartCallback:function (sender) { + var s = new TransitionsTestScene(); + + var layer = this.createNextScene(); + s.addChild(layer); + var scene = arrayOfTransitionsTest[transitionsIdx].transitionFunc(TRANSITION_DURATION, s); + + if (scene) + director.runScene(scene); + }, + onNextCallback:function (sender) { + transitionsIdx++; + transitionsIdx = transitionsIdx % arrayOfTransitionsTest.length; + + var s = new TransitionsTestScene(); + + var layer = this.createNextScene(); + s.addChild(layer); + + var scene = arrayOfTransitionsTest[transitionsIdx].transitionFunc(TRANSITION_DURATION, s); + if (scene) + director.runScene(scene); + }, + onBackCallback:function (sender) { + transitionsIdx--; + if (transitionsIdx < 0) + transitionsIdx += arrayOfTransitionsTest.length; + + var s = new TransitionsTestScene(); + var layer = this.createNextScene(); + s.addChild(layer); + + var scene = arrayOfTransitionsTest[transitionsIdx].transitionFunc(TRANSITION_DURATION, s); + if (scene) + director.runScene(scene); + }, + + step:function (dt) { + }, + + onEnter:function () { + this._super(); + this.log("" + this.sceneName + " onEnter"); + }, + onEnterTransitionDidFinish:function () { + this._super(); + this.log("" + this.sceneName + " onEnterTransitionDidFinish"); + }, + + onExitTransitionDidStart:function () { + this._super(); + this.log("" + this.sceneName + " onExitTransitionDidStart"); + }, + + onExit:function () { + this._super(); + this.log("" + this.sceneName + " onExit"); + }, + // automation + numberOfPendingTests:function() { + return ( (arrayOfTransitionsTest.length-1) - transitionsIdx ); + }, + + getTestNumber:function() { + return transitionsIdx; + } + +}); +var TestLayer1 = TransitionBase.extend({ + backgroundImage:s_back1, + colorA:cc.color(0,0,0,255), + colorB:cc.color(160,99,117,255), + sceneName:"Scene 1", + createNextScene:function() { + return new TestLayer2(); + } +}); + +var TestLayer2 = TransitionBase.extend({ + backgroundImage:s_back2, + colorA:cc.color(0,0,0,255), + colorB:cc.color(99,160,117,255), + sceneName:"Scene 2", + createNextScene:function() { + return new TestLayer1(); + } +}); + +var JumpZoomTransition = function (t, s) { + return new cc.TransitionJumpZoom(t, s); +}; +var FadeTransition = function (t, s) { + return new cc.TransitionFade(t, s); +}; + +var FadeWhiteTransition = function (t, s) { + return new cc.TransitionFade(t, s, cc.color(255, 255, 255)); +}; + +var FlipXLeftOver = function (t, s) { + return new cc.TransitionFlipX(t, s, cc.TRANSITION_ORIENTATION_LEFT_OVER); +}; + +var FlipXRightOver = function (t, s) { + return new cc.TransitionFlipX(t, s, cc.TRANSITION_ORIENTATION_RIGHT_OVER); +}; + +var FlipYUpOver = function (t, s) { + return new cc.TransitionFlipY(t, s, cc.TRANSITION_ORIENTATION_UP_OVER); +}; + +var FlipYDownOver = function (t, s) { + return new cc.TransitionFlipY(t, s, cc.TRANSITION_ORIENTATION_DOWN_OVER); +}; + +var FlipAngularLeftOver = function (t, s) { + return new cc.TransitionFlipAngular(t, s, cc.TRANSITION_ORIENTATION_LEFT_OVER); +}; + +var FlipAngularRightOver = function (t, s) { + return new cc.TransitionFlipAngular(t, s, cc.TRANSITION_ORIENTATION_RIGHT_OVER); +}; + +var ZoomFlipXLeftOver = function (t, s) { + return new cc.TransitionZoomFlipX(t, s, cc.TRANSITION_ORIENTATION_LEFT_OVER); +}; + +var ZoomFlipXRightOver = function (t, s) { + return new cc.TransitionZoomFlipX(t, s, cc.TRANSITION_ORIENTATION_RIGHT_OVER); +}; + +var ZoomFlipYUpOver = function (t, s) { + return new cc.TransitionZoomFlipY(t, s, cc.TRANSITION_ORIENTATION_UP_OVER); +}; + +var ZoomFlipYDownOver = function (t, s) { + return new cc.TransitionZoomFlipY(t, s, cc.TRANSITION_ORIENTATION_DOWN_OVER); +}; + +var ZoomFlipAngularLeftOver = function (t, s) { + return new cc.TransitionZoomFlipAngular(t, s, cc.TRANSITION_ORIENTATION_LEFT_OVER); +}; + +var ZoomFlipAngularRightOver = function (t, s) { + return new cc.TransitionZoomFlipAngular(t, s, cc.TRANSITION_ORIENTATION_RIGHT_OVER); +}; + +var ShrinkGrowTransition = function (t, s) { + return new cc.TransitionShrinkGrow(t, s); +}; + +var RotoZoomTransition = function (t, s) { + return new cc.TransitionRotoZoom(t, s); +}; + +var MoveInLTransition = function (t, s) { + return new cc.TransitionMoveInL(t, s); +}; + +var MoveInRTransition = function (t, s) { + return new cc.TransitionMoveInR(t, s); +}; + +var MoveInTTransition = function (t, s) { + return new cc.TransitionMoveInT(t, s); +}; + +var MoveInBTransition = function (t, s) { + return new cc.TransitionMoveInB(t, s); +}; + +var SlideInLTransition = function (t, s) { + return new cc.TransitionSlideInL(t, s); +}; + +var SlideInRTransition = function (t, s) { + return new cc.TransitionSlideInR(t, s); +}; + +var SlideInTTransition = function (t, s) { + return new cc.TransitionSlideInT(t, s); +}; + +var SlideInBTransition = function (t, s) { + return new cc.TransitionSlideInB(t, s); +}; + +var CCTransitionCrossFade = function (t, s) { + return new cc.TransitionCrossFade(t, s); +}; + +var CCTransitionRadialCCW = function (t, s) { + return new cc.TransitionProgressRadialCCW(t, s); +}; + +var CCTransitionRadialCW = function (t, s) { + return new cc.TransitionProgressRadialCW(t, s); +}; + +var PageTransitionForward = function (t, s) { + director.setDepthTest(true); + return new cc.TransitionPageTurn(t, s, false); +}; + +var PageTransitionBackward = function (t, s) { + director.setDepthTest(true); + return new cc.TransitionPageTurn(t, s, true); +}; + +var FadeTRTransition = function (t, s) { + return new cc.TransitionFadeTR(t, s); +}; + +var FadeBLTransition = function (t, s) { + return new cc.TransitionFadeBL(t, s); +}; + +var FadeUpTransition = function (t, s) { + return new cc.TransitionFadeUp(t, s); +}; + +var FadeDownTransition = function (t, s) { + return new cc.TransitionFadeDown(t, s); +}; + +var TurnOffTilesTransition = function (t, s) { + return new cc.TransitionTurnOffTiles(t, s); +}; + +var SplitRowsTransition = function (t, s) { + return new cc.TransitionSplitRows(t, s); +}; + +var SplitColsTransition = function (t, s) { + return new cc.TransitionSplitCols(t, s); +}; diff --git a/tests/js-tests/src/UnitTest/UnitTest.js b/tests/js-tests/src/UnitTest/UnitTest.js new file mode 100644 index 0000000000..18cb060356 --- /dev/null +++ b/tests/js-tests/src/UnitTest/UnitTest.js @@ -0,0 +1,284 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +var unitTestSceneIdx = -1; + +//------------------------------------------------------------------ +// +// UnitTestBase +// +//------------------------------------------------------------------ +var UnitTestBase = BaseTestLayer.extend({ + _title:"", + _subtitle:"", + + onRestartCallback:function (sender) { + var s = new UnitTestScene(); + s.addChild(restartUnitTest()); + director.runScene(s); + }, + onNextCallback:function (sender) { + var s = new UnitTestScene(); + s.addChild(nextUnitTest()); + director.runScene(s); + }, + onBackCallback:function (sender) { + var s = new UnitTestScene(); + s.addChild(previousUnitTest()); + director.runScene(s); + }, + + // automation + numberOfPendingTests:function() { + return ( (arrayOfUnitTest.length-1) - unitTestSceneIdx ); + }, + + getTestNumber:function() { + return unitTestSceneIdx; + } + +}); + +//------------------------------------------------------------------ +// +// RectUnitTest +// +//------------------------------------------------------------------ +var RectUnitTest = UnitTestBase.extend({ + _title:"Rect Unit Test", + _subtitle:"See console for possible errors", + + onEnter:function () { + this._super(); + this.runTest(); + }, + + runTest:function () { + + var ret = []; + var rectA; + var rectB; + var rectC; + var point; + var r; + + this.log("Test 1: rectIntersectsRect 1"); + rectA = cc.rect(0,0,5,10); + rectB = cc.rect(4,9,5,10); + r = cc.rectIntersectsRect(rectA, rectB); + if(!r) + throw "Fail rectIntersectsRect 1"; + ret.push(r); + + this.log("Test 2: rectIntersectsRect 2"); + rectA = cc.rect(0,0,5,10); + rectB = cc.rect(40,90,5,10); + r = cc.rectIntersectsRect(rectA, rectB); + if(r) + throw "Fail rectIntersectsRect 2"; + ret.push(r); + + this.log("Test 3: rectIntersection"); + rectA = cc.rect(0,0,5,10); + rectB = cc.rect(4,9,5,10); + rectC = cc.rectIntersection(rectA, rectB); + r = cc.rectEqualToRect(rectC, cc.rect(4,9,1,1) ); + if(!r) + throw "Fail rectIntersection"; + ret.push(r); + + this.log("Test 4: rectUnion"); + rectA = cc.rect(0,0,5,10); + rectB = cc.rect(4,9,5,10); + rectC = cc.rectUnion(rectA, rectB); + r = cc.rectEqualToRect(rectC, cc.rect(0,0,9,19) ); + if(!r) + throw "Fail rectUnion"; + ret.push(r); + + this.log("Test 5: rectContainsPoint 1"); + rectA = cc.rect(0,0,5,10); + point = cc.p(1,1); + r = cc.rectContainsPoint(rectA, point); + if(!r) + throw "Fail rectContainsPoint 1"; + ret.push(r); + + this.log("Test 6: rectContainsPoint 2"); + rectA = cc.rect(0,0,5,10); + point = cc.p(1,-1); + r = cc.rectContainsPoint(rectA, point); + if(r) + throw "Fail rectContainsPoint 2"; + ret.push(r); + + this.log("Test 7: rect property x"); + rectA = cc.rect(1,2,3,4); + if( rectA.x != 1) + throw "Fail rect property x"; + ret.push(rectA.x); + + this.log("Test 8: rect property y"); + rectA = cc.rect(1,2,3,4); + if( rectA.y != 2) + throw "Fail rect property y"; + ret.push(rectA.y); + + this.log("Test 9: rect property width"); + rectA = cc.rect(1,2,3,4); + if( rectA.width != 3) + throw "Fail rect property width"; + ret.push(rectA.width); + + this.log("Test 10: rect property height"); + rectA = cc.rect(1,2,3,4); + if( rectA.height != 4) + throw "Fail rect property height"; + ret.push(rectA.height); + + this.log("Test 11: getBoundingBox()"); + var node = new cc.Node(); + node.width = 99; + node.height = 101; + var bb = node.getBoundingBox(); + if( bb.height != 101 || bb.width != 99) + throw "Fail getBoundingBox()"; + ret.push( bb.height ); + ret.push( bb.width ); + return ret; + }, + + // + // Automation + // + testDuration:0.1, + + getExpectedResult:function() { + var ret = [true,false,true,true,true,false,1,2,3,4,101,99]; + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = this.runTest(); + return JSON.stringify(ret); + } + +}); + +//------------------------------------------------------------------ +// +// DictionaryToFromTest +// +//------------------------------------------------------------------ +var DictionaryToFromTest = UnitTestBase.extend({ + _title:"Dictionary To/From Test", + _subtitle:"Sends and receives a dictionary to JSB", + + ctor:function() { + this._super(); + + this.runTest(); + }, + + runTest:function() { + var frameCache = cc.spriteFrameCache; + frameCache.addSpriteFrames(s_grossiniPlist); + + // Purge previously loaded animation + var animCache = cc.animationCache; + animCache.addAnimations(s_animations2Plist); + + var normal = animCache.getAnimation("dance_1"); + var frame = normal.getFrames()[0]; + var dict = frame.getUserInfo(); + this.log( JSON.stringify(dict) ); + frame.setUserInfo( { + "array":[1,2,3,"hello world"], + "bool0":0, // false XXX + "bool1":1, // true XXX + "dict":{"key1":"value1", "key2":2}, + "number":42, + "string":"hello!" + }); + + dict = frame.getUserInfo(); + this.log(JSON.stringify(dict)); + return dict; + }, + + // + // Automation + // + testDuration:0.1, + + getExpectedResult:function() { + var ret = this.sortObject( {"array":[1,2,3,"hello world"],"bool0":0,"bool1":1,"dict":{"key1":"value1","key2":2},"number":42,"string":"hello!"} ); + + return JSON.stringify(ret); + }, + + getCurrentResult:function() { + var ret = this.sortObject( this.runTest() ); + return JSON.stringify(ret); + } +}); + +var UnitTestScene = TestScene.extend({ + runThisTest:function (num) { + unitTestSceneIdx = (num || num == 0) ? (num - 1) : -1; + var layer = nextUnitTest(); + this.addChild(layer); + + director.runScene(this); + } +}); + +// +// Flow control +// + +var arrayOfUnitTest = [ + + RectUnitTest, + DictionaryToFromTest + +]; + +var nextUnitTest = function () { + unitTestSceneIdx++; + unitTestSceneIdx = unitTestSceneIdx % arrayOfUnitTest.length; + + return new arrayOfUnitTest[unitTestSceneIdx](); +}; +var previousUnitTest = function () { + unitTestSceneIdx--; + if (unitTestSceneIdx < 0) + unitTestSceneIdx += arrayOfUnitTest.length; + + return new arrayOfUnitTest[unitTestSceneIdx](); +}; +var restartUnitTest = function () { + return new arrayOfUnitTest[unitTestSceneIdx](); +}; + diff --git a/tests/js-tests/src/XHRTest/XHRArrayBufferTest.js b/tests/js-tests/src/XHRTest/XHRArrayBufferTest.js new file mode 100644 index 0000000000..e155546948 --- /dev/null +++ b/tests/js-tests/src/XHRTest/XHRArrayBufferTest.js @@ -0,0 +1,121 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +//some utils functions +function ensureLeftAligned (label) { + label.anchorX = 0; + label.anchorY = 1; + label.textAlign = cc.TEXT_ALIGNMENT_LEFT; +} + +function streamXHREventsToLabel ( xhr, label, textbox, method ) { + // Simple events + ['loadstart', 'abort', 'error', 'load', 'loadend', 'timeout'].forEach(function (eventname) { + xhr["on" + eventname] = function () { + label.string += "\nEvent : " + eventname + } + }); + + // Special event + xhr.onreadystatechange = function () { + if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 207)) { + var httpStatus = xhr.statusText; + var response = xhr.responseText.substring(0, 100) + "..."; + textbox.string = method + " Response (100 chars):\n" + textbox.string += response + label.string += "\nStatus: Got " + method + " response! " + httpStatus + } + } +} + + +var XHRArrayBufferTestScene = TestScene.extend({ + ctor:function () { + this._super(true); + var xhrLayer = new XHRArrayBufferTestLayer(); + this.addChild(xhrLayer); + }, + runThisTest:function () { + cc.director.runScene(this); + }, + MainMenuCallback:function (sender) { + this._super(sender); + } +}); + +var XHRArrayBufferTestLayer = cc.Layer.extend({ + ctor:function () { + this._super(); + }, + + onEnter: function() { + this._super(); + var l = new cc.LabelTTF("Get infos via XHR", "Thonburi", 16); + this.addChild(l, 1); + l.x = winSize.width / 2; + l.y = winSize.height - 60; + + this.sendPostArrayBuffer(); + }, + + sendPostArrayBuffer: function() { + var statusPostLabel = new cc.LabelTTF("Status:", "Thonburi", 12); + this.addChild(statusPostLabel, 1); + + statusPostLabel.x = 10; + statusPostLabel.y = winSize.height - 100; + ensureLeftAligned(statusPostLabel); + statusPostLabel.setString("Status: Send Post Request to httpbin.org with ArrayBuffer"); + + + var responseLabel = new cc.LabelTTF("", "Thonburi", 16); + this.addChild(responseLabel, 1); + ensureLeftAligned(responseLabel); + responseLabel.x = 10; + responseLabel.y = winSize.height / 2; + + var xhr = cc.loader.getXMLHttpRequest(); + streamXHREventsToLabel(xhr, statusPostLabel, responseLabel, "POST"); + + xhr.open("POST", "http://httpbin.org/post"); + //set Content-type "text/plain" to post ArrayBuffer or ArrayBufferView + xhr.setRequestHeader("Content-Type","text/plain"); + // Uint8Array is an ArrayBufferView + xhr.send(new Uint8Array([1,2,3,4,5])); + }, + + scrollViewDidScroll:function (view) { + }, + scrollViewDidZoom:function (view) { + } +}); + +var runXHRArrayBufferTest = function () { + var pScene = new cc.Scene(); + var pLayer = new XHRArrayBufferTestLayer(); + pScene.addChild(pLayer); + cc.director.runScene(pScene); +}; diff --git a/tests/js-tests/src/XHRTest/XHRTest.js b/tests/js-tests/src/XHRTest/XHRTest.js new file mode 100644 index 0000000000..002da553db --- /dev/null +++ b/tests/js-tests/src/XHRTest/XHRTest.js @@ -0,0 +1,181 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +//some utils functions +function ensureLeftAligned (label) { + label.anchorX = 0; + label.anchorY = 1; + label.textAlign = cc.TEXT_ALIGNMENT_LEFT; +} + +function streamXHREventsToLabel ( xhr, label, textbox, method ) { + // Simple events + ['loadstart', 'abort', 'error', 'load', 'loadend', 'timeout'].forEach(function (eventname) { + xhr["on" + eventname] = function () { + label.string += "\nEvent : " + eventname + } + }); + + // Special event + xhr.onreadystatechange = function () { + if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 207)) { + var httpStatus = xhr.statusText; + var response = xhr.responseText.substring(0, 100) + "..."; + textbox.string = method + " Response (100 chars):\n" + textbox.string += response + label.string += "\nStatus: Got " + method + " response! " + httpStatus + } + } +} + + +var XHRTestScene = TestScene.extend({ + ctor:function () { + this._super(true); + var xhrLayer = new XHRTestLayer(); + this.addChild(xhrLayer); + }, + runThisTest:function () { + cc.director.runScene(this); + }, + MainMenuCallback:function (sender) { + this._super(sender); + } +}); + +var XHRTestLayer = cc.Layer.extend({ + ctor:function () { + this._super(); + }, + + onEnter: function() { + this._super(); + var l = new cc.LabelTTF("Get infos via XHR", "Thonburi", 16); + this.addChild(l, 1); + l.x = winSize.width / 2; + l.y = winSize.height - 60; + + this.sendGetRequest(); + this.sendPostPlainText(); + this.sendPostForms(); + }, + + sendGetRequest: function() { + var statusGetLabel = new cc.LabelTTF("Status:", "Thonburi", 12); + this.addChild(statusGetLabel, 1); + + statusGetLabel.x = 10 + statusGetLabel.y = winSize.height - 100; + ensureLeftAligned(statusGetLabel); + statusGetLabel.setString("Status: Send Get Request to httpbin.org"); + + var responseLabel = new cc.LabelTTF("", "Thonburi", 16); + this.addChild(responseLabel, 1); + + ensureLeftAligned(responseLabel); + responseLabel.x = 10; + responseLabel.y = winSize.height / 2; + + var xhr = cc.loader.getXMLHttpRequest(); + streamXHREventsToLabel(xhr, statusGetLabel, responseLabel, "GET"); + // 5 seconds for timeout + xhr.timeout = 5000; + + //set arguments with ?xxx=xxx&yyy=yyy + xhr.open("GET", "http://httpbin.org/get?show_env=1", true); + xhr.send(); + }, + + sendPostPlainText: function() { + var statusPostLabel = new cc.LabelTTF("Status:", "Thonburi", 12); + this.addChild(statusPostLabel, 1); + + statusPostLabel.x = winSize.width / 10 * 3; + statusPostLabel.y = winSize.height - 100; + ensureLeftAligned(statusPostLabel); + statusPostLabel.setString("Status: Send Post Request to httpbin.org with plain text"); + + + var responseLabel = new cc.LabelTTF("", "Thonburi", 16); + this.addChild(responseLabel, 1); + ensureLeftAligned(responseLabel); + responseLabel.x = winSize.width / 10 * 3; + responseLabel.y = winSize.height / 2; + + var xhr = cc.loader.getXMLHttpRequest(); + streamXHREventsToLabel(xhr, statusPostLabel, responseLabel, "POST"); + + xhr.open("POST", "http://httpbin.org/post"); + //set Content-type "text/plain;charset=UTF-8" to post plain text + xhr.setRequestHeader("Content-Type","text/plain;charset=UTF-8"); + xhr.send("plain text message"); + }, + + sendPostForms: function() { + var statusPostLabel = new cc.LabelTTF("Status:", "Thonburi", 12); + this.addChild(statusPostLabel, 1); + + statusPostLabel.x = winSize.width / 10 * 7; + statusPostLabel.y = winSize.height - 100; + ensureLeftAligned(statusPostLabel); + statusPostLabel.setString("Status: Send Post Request to httpbin.org width form data"); + + var responseLabel = new cc.LabelTTF("", "Thonburi", 16); + this.addChild(responseLabel, 1); + + ensureLeftAligned(responseLabel); + responseLabel.x = winSize.width / 10 * 7; + responseLabel.y = winSize.height / 2; + + var xhr = cc.loader.getXMLHttpRequest(); + streamXHREventsToLabel(xhr, statusPostLabel, responseLabel, "POST"); + + xhr.open("POST", "http://httpbin.org/post"); + //set Content-Type "application/x-www-form-urlencoded" to post form data + //mulipart/form-data for upload + xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); + /** + form : { + "a" : "hello", + "b" : "world" + } + **/ + var args = "a=hello&b=world"; + xhr.send(args); + }, + + scrollViewDidScroll:function (view) { + }, + scrollViewDidZoom:function (view) { + } +}); + +var runXHRTest = function () { + var pScene = new cc.Scene(); + var pLayer = new XHRTestLayer(); + pScene.addChild(pLayer); + cc.director.runScene(pScene); +}; \ No newline at end of file diff --git a/tests/js-tests/src/tests-main.js b/tests/js-tests/src/tests-main.js new file mode 100644 index 0000000000..63a321e51c --- /dev/null +++ b/tests/js-tests/src/tests-main.js @@ -0,0 +1,688 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies 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. + ****************************************************************************/ + +// globals +var director = null; +var winSize = null; + +var PLATFORM_JSB = 1 << 0; +var PLATFORM_HTML5 = 1 << 1; +var PLATFORM_HTML5_WEBGL = 1 << 2; +var PLATFROM_ANDROID = 1 << 3; +var PLATFROM_IOS = 1 << 4; +var PLATFORM_MAC = 1 << 5; +var PLATFORM_JSB_AND_WEBGL = PLATFORM_JSB | PLATFORM_HTML5_WEBGL; +var PLATFORM_ALL = PLATFORM_JSB | PLATFORM_HTML5 | PLATFORM_HTML5_WEBGL | PLATFROM_ANDROID | PLATFROM_IOS; +var PLATFROM_APPLE = PLATFROM_IOS | PLATFORM_MAC; + +// automation vars +var autoTestEnabled = autoTestEnabled || false; +var autoTestCurrentTestName = autoTestCurrentTestName || "N/A"; + +var TestScene = cc.Scene.extend({ + ctor:function (bPortrait) { + this._super(); + this.init(); + + var label = new cc.LabelTTF("Main Menu", "Arial", 20); + var menuItem = new cc.MenuItemLabel(label, this.onMainMenuCallback, this); + + var menu = new cc.Menu(menuItem); + menu.x = 0; + menu.y = 0; + menuItem.x = winSize.width - 50; + menuItem.y = 25; + + if(!window.sideIndexBar){ + this.addChild(menu, 1); + } + }, + onMainMenuCallback:function () { + var scene = new cc.Scene(); + var layer = new TestController(); + scene.addChild(layer); + var transition = new cc.TransitionProgressRadialCCW(0.5,scene); + director.runScene(transition); + }, + + runThisTest:function () { + // override me + } + +}); + +//Controller stuff +var LINE_SPACE = 40; +var curPos = cc.p(0,0); + +var TestController = cc.LayerGradient.extend({ + _itemMenu:null, + _beginPos:0, + isMouseDown:false, + + ctor:function() { + this._super(cc.color(0,0,0,255), cc.color(0x46,0x82,0xB4,255)); + + // globals + director = cc.director; + winSize = director.getWinSize(); + + // add close menu + var closeItem = new cc.MenuItemImage(s_pathClose, s_pathClose, this.onCloseCallback, this); + closeItem.x = winSize.width - 30; + closeItem.y = winSize.height - 30; + + var subItem1 = new cc.MenuItemFont("Automated Test: Off"); + subItem1.fontSize = 18; + var subItem2 = new cc.MenuItemFont("Automated Test: On"); + subItem2.fontSize = 18; + + var toggleAutoTestItem = new cc.MenuItemToggle(subItem1, subItem2); + toggleAutoTestItem.setCallback(this.onToggleAutoTest, this); + toggleAutoTestItem.x = winSize.width - toggleAutoTestItem.width / 2 - 10; + toggleAutoTestItem.y = 20; + toggleAutoTestItem.setVisible(false); + if( autoTestEnabled ) + toggleAutoTestItem.setSelectedIndex(1); + + + var menu = new cc.Menu(closeItem, toggleAutoTestItem);//pmenu is just a holder for the close button + menu.x = 0; + menu.y = 0; + + // add menu items for tests + this._itemMenu = new cc.Menu();//item menu is where all the label goes, and the one gets scrolled + + for (var i = 0, len = testNames.length; i < len; i++) { + var label = new cc.LabelTTF(testNames[i].title, "Arial", 24); + var menuItem = new cc.MenuItemLabel(label, this.onMenuCallback, this); + this._itemMenu.addChild(menuItem, i + 10000); + menuItem.x = winSize.width / 2; + menuItem.y = (winSize.height - (i + 1) * LINE_SPACE); + + // enable disable + if ( !cc.sys.isNative) { + if( 'opengl' in cc.sys.capabilities ){ + menuItem.enabled = (testNames[i].platforms & PLATFORM_HTML5) | (testNames[i].platforms & PLATFORM_HTML5_WEBGL); + }else{ + menuItem.setEnabled( testNames[i].platforms & PLATFORM_HTML5 ); + } + } else { + if (cc.sys.os == cc.sys.OS_ANDROID) { + menuItem.setEnabled( testNames[i].platforms & ( PLATFORM_JSB | PLATFROM_ANDROID ) ); + } else if (cc.sys.os == cc.sys.OS_IOS) { + menuItem.setEnabled( testNames[i].platforms & ( PLATFORM_JSB | PLATFROM_IOS) ); + } else if (cc.sys.os == cc.sys.OS_OSX) { + menuItem.setEnabled( testNames[i].platforms & ( PLATFORM_JSB | PLATFORM_MAC) ); + } else { + menuItem.setEnabled( testNames[i].platforms & PLATFORM_JSB ); + } + } + } + + this._itemMenu.width = winSize.width; + this._itemMenu.height = (testNames.length + 1) * LINE_SPACE; + this._itemMenu.x = curPos.x; + this._itemMenu.y = curPos.y; + this.addChild(this._itemMenu); + this.addChild(menu, 1); + + // 'browser' can use touches or mouse. + // The benefit of using 'touches' in a browser, is that it works both with mouse events or touches events + if ('touches' in cc.sys.capabilities) + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ALL_AT_ONCE, + onTouchesMoved: function (touches, event) { + var target = event.getCurrentTarget(); + var delta = touches[0].getDelta(); + target.moveMenu(delta); + return true; + } + }, this); + else if ('mouse' in cc.sys.capabilities) { + cc.eventManager.addListener({ + event: cc.EventListener.MOUSE, + onMouseMove: function (event) { + if(event.getButton() == cc.EventMouse.BUTTON_LEFT) + event.getCurrentTarget().moveMenu(event.getDelta()); + }, + onMouseScroll: function (event) { + var delta = cc.sys.isNative ? event.getScrollY() * 6 : -event.getScrollY(); + event.getCurrentTarget().moveMenu({y : delta}); + return true; + } + }, this); + } + }, + onEnter:function(){ + this._super(); + this._itemMenu.y = TestController.YOffset; + }, + onMenuCallback:function (sender) { + TestController.YOffset = this._itemMenu.y; + var idx = sender.getLocalZOrder() - 10000; + // get the userdata, it's the index of the menu item clicked + // create the test scene and run it + + autoTestCurrentTestName = testNames[idx].title; + + var testCase = testNames[idx]; + var res = testCase.resource || []; + cc.LoaderScene.preload(res, function () { + var scene = testCase.testScene(); + if (scene) { + scene.runThisTest(); + } + }, this); + }, + onCloseCallback:function () { + window.history && window.history.go(-1); + }, + onToggleAutoTest:function() { + autoTestEnabled = !autoTestEnabled; + }, + + moveMenu:function(delta) { + var newY = this._itemMenu.y + delta.y; + if (newY < 0 ) + newY = 0; + + if( newY > ((testNames.length + 1) * LINE_SPACE - winSize.height)) + newY = ((testNames.length + 1) * LINE_SPACE - winSize.height); + + this._itemMenu.y = newY; + } +}); +TestController.YOffset = 0; +var testNames = [ + { + title:"ActionManager Test", + platforms: PLATFORM_ALL, + linksrc:"src/ActionManagerTest/ActionManagerTest.js", + testScene:function () { + return new ActionManagerTestScene(); + } + }, + { + title:"Actions Test", + platforms: PLATFORM_ALL, + linksrc:"src/ActionsTest/ActionsTest.js", + testScene:function () { + return new ActionsTestScene(); + } + }, + { + title:"Bake Layer Test", + platforms: PLATFORM_HTML5, + linksrc:"src/BakeLayerTest/BakeLayerTest.js", + testScene:function () { + return new BakeLayerTestScene(); + } + }, + { + title:"BillBoard Test", + platforms: PLATFORM_JSB, + linksrc:"src/BillBoardTest/BillBoardTest.js", + testScene:function () { + return new BillBoardTestScene(); + } + }, + { + title:"Box2D Test", + resource:g_box2d, + platforms: PLATFORM_HTML5, + linksrc:"src/Box2dTest/Box2dTest.js", + testScene:function () { + return new Box2DTestScene(); + } + }, + { + title:"Camera3D Test", + platforms: PLATFORM_JSB, + linksrc:"src/Camera3DTest/Camera3DTest.js", + testScene:function () { + return new Camera3DTestScene(); + } + }, + { + title:"Chipmunk Test", + platforms: PLATFORM_ALL, + linksrc:"src/ChipmunkTest/ChipmunkTest.js", + testScene:function () { + return new ChipmunkTestScene(); + } + }, + //"BugsTest", + { + title:"Click and Move Test", + platforms: PLATFORM_ALL, + linksrc:"src/ClickAndMoveTest/ClickAndMoveTest.js", + testScene:function () { + return new ClickAndMoveTestScene(); + } + }, + { + title:"ClippingNode Test", + platforms: PLATFORM_ALL, + linksrc:"src/ClippingNodeTest/ClippingNodeTest.js", + testScene:function () { + return new ClippingNodeTestScene(); + } + }, + { + title:"CocosDenshion Test", + resource:g_cocosdeshion, + platforms: PLATFORM_ALL, + linksrc:"src/CocosDenshionTest/CocosDenshionTest.js", + testScene:function () { + return new CocosDenshionTestScene(); + } + }, + { + title:"CocoStudio Test", + resource:g_cocoStudio, + platforms: PLATFORM_ALL, + linksrc:"", + testScene:function () { + return new CocoStudioTestScene(); + } + }, + { + title:"CurrentLanguage Test", + platforms: PLATFORM_ALL, + linksrc:"src/CurrentLanguageTest/CurrentLanguageTest.js", + testScene:function () { + return new CurrentLanguageTestScene(); + } + }, + //"CurlTest", + { + title:"DrawPrimitives Test", + platforms: PLATFORM_ALL, + linksrc:"src/DrawPrimitivesTest/DrawPrimitivesTest.js", + testScene:function () { + return new DrawPrimitivesTestScene(); + } + }, + { + title:"EaseActions Test", + platforms: PLATFORM_ALL, + linksrc:"src/EaseActionsTest/EaseActionsTest.js", + testScene:function () { + return new EaseActionsTestScene(); + } + }, + { + title:"Event Manager Test", + resource:g_eventDispatcher, + platforms: PLATFORM_ALL, + linksrc:"src/NewEventManagerTest/NewEventManagerTest.js", + testScene:function () { + return new EventDispatcherTestScene(); + } + }, + { + title:"Event Test", + platforms: PLATFORM_ALL, + linksrc:"src/EventTest/EventTest.js", + testScene:function () { + return new EventTestScene(); + } + }, + { + title:"Extensions Test", + resource:g_extensions, + platforms: PLATFORM_ALL, + linksrc:"", + testScene:function () { + return new ExtensionsTestScene(); + } + }, + { + title:"Effects Test", + platforms: PLATFORM_JSB_AND_WEBGL, + linksrc:"src/EffectsTest/EffectsTest.js", + testScene:function () { + return new EffectsTestScene(); + } + }, + { + title:"Effects Advanced Test", + platforms: PLATFORM_JSB_AND_WEBGL, + linksrc:"src/EffectsAdvancedTest/EffectsAdvancedTest.js", + testScene:function () { + return new EffectAdvanceScene(); + } + }, + { + title:"Facebook SDK Test", + platforms: PLATFROM_ANDROID | PLATFROM_IOS | PLATFORM_HTML5, + linksrc:"src/FacebookTest/FacebookTestsManager.js", + testScene:function () { + return new FacebookTestScene(); + } + }, + { + title:"Font Test", + resource:g_fonts, + platforms: PLATFORM_ALL, + linksrc:"src/FontTest/FontTest.js", + testScene:function () { + return new FontTestScene(); + } + }, + { + title:"UI Test", + resource:g_ui, + platforms: PLATFORM_ALL, + linksrc:"", + testScene:function () { + return new GUITestScene(); + } + }, + //"HiResTest", + { + title:"Interval Test", + platforms: PLATFORM_ALL, + linksrc:"src/IntervalTest/IntervalTest.js", + testScene:function () { + return new IntervalTestScene(); + } + }, + { + title:"Label Test", + resource:g_label, + platforms: PLATFORM_ALL, + linksrc:"src/LabelTest/LabelTest.js", + testScene:function () { + return new LabelTestScene(); + } + }, + { + title:"Layer Test", + platforms: PLATFORM_ALL, + linksrc:"src/LayerTest/LayerTest.js", + testScene:function () { + return new LayerTestScene(); + } + }, + { + title:"Light Test", + platforms: PLATFORM_JSB, + linksrc:"src/LightTest/LightTest.js", + testScene:function () { + return new LightTestScene(); + } + }, + { + title:"Loader Test", + platforms: PLATFORM_ALL, + linksrc:"src/LoaderTest/LoaderTest.js", + testScene:function () { + return new LoaderTestScene(); + } + }, + { + title:"Menu Test", + resource:g_menu, + platforms: PLATFORM_ALL, + linksrc:"src/MenuTest/MenuTest.js", + testScene:function () { + return new MenuTestScene(); + } + }, + { + title:"MotionStreak Test", + platforms: PLATFORM_JSB_AND_WEBGL, + linksrc:"src/MotionStreakTest/MotionStreakTest.js", + testScene:function () { + return new MotionStreakTestScene(); + } + }, + { + title:"Node Test", + platforms: PLATFORM_ALL, + linksrc:"src/CocosNodeTest/CocosNodeTest.js", + testScene:function () { + return new NodeTestScene(); + } + }, + { + title:"OpenGL Test", + resource:g_opengl_resources, + platforms: PLATFORM_JSB_AND_WEBGL, + linksrc:"src/OpenGLTest/OpenGLTest.js", + testScene:function () { + return new OpenGLTestScene(); + } + }, + { + title:"Parallax Test", + resource:g_parallax, + platforms: PLATFORM_ALL, + linksrc:"src/ParallaxTest/ParallaxTest.js", + testScene:function () { + return new ParallaxTestScene(); + } + }, + { + title:"Particle Test", + platforms: PLATFORM_ALL, + linksrc:"", + resource:g_particle, + testScene:function () { + return new ParticleTestScene(); + } + }, + { + title:"Path Tests", + platforms: PLATFORM_ALL, + linksrc:"src/PathTest/PathTest.js", + testScene:function () { + return new PathTestScene(); + } + }, + { + title:"Performance Test", + platforms: PLATFORM_ALL, + linksrc:"", + resource:g_performace, + testScene:function () { + return new PerformanceTestScene(); + } + }, + { + title:"ProgressActions Test", + platforms: PLATFORM_ALL, + linksrc:"src/ProgressActionsTest/ProgressActionsTest.js", + testScene:function () { + return new ProgressActionsTestScene(); + } + }, + { + title:"Reflection Test", + platforms: PLATFROM_ANDROID | PLATFROM_APPLE, + linksrc:"src/ReflectionTest/ReflectionTest.js", + testScene:function () { + return new ReflectionTestScene(); + } + }, + { + title:"RenderTexture Test", + platforms: PLATFORM_ALL, + linksrc:"src/RenderTextureTest/RenderTextureTest.js", + testScene:function () { + return new RenderTextureTestScene(); + } + }, + { + title:"RotateWorld Test", + platforms: PLATFORM_ALL, + linksrc:"src/RotateWorldTest/RotateWorldTest.js", + testScene:function () { + return new RotateWorldTestScene(); + } + }, + { + title:"Scene Test", + platforms: PLATFORM_ALL, + linksrc:"src/SceneTest/SceneTest.js", + testScene:function () { + return new SceneTestScene(); + } + }, + { + title:"Scheduler Test", + platforms: PLATFORM_ALL, + linksrc:"src/SchedulerTest/SchedulerTest.js", + testScene:function () { + return new SchedulerTestScene(); + } + }, + { + title:"Spine Test", + resource: g_spine, + platforms: PLATFORM_ALL, + linksrc:"src/SpineTest/SpineTest.js", + testScene:function () { + return new SpineTestScene(); + } + }, + { + title:"Sprite3D Test", + platforms: PLATFORM_JSB, + linksrc:"src/Sprite3DTest/Sprite3DTest.js", + testScene:function () { + return new Sprite3DTestScene(); + } + }, + { + title:"Sprite Test", + resource:g_sprites, + platforms: PLATFORM_ALL, + linksrc:"src/SpriteTest/SpriteTest.js", + testScene:function () { + return new SpriteTestScene(); + } + }, + { + title:"Scale9Sprite Test", + resource:g_s9s_blocks, + platforms: PLATFORM_ALL, + linksrc:"src/ExtensionsTest/S9SpriteTest/S9SpriteTest.js", + testScene:function () { + return new S9SpriteTestScene(); + } + }, + { + title:"TextInput Test", + platforms: PLATFORM_HTML5, + linksrc:"src/TextInputTest/TextInputTest.js", + testScene:function () { + return new TextInputTestScene(); + } + }, + //"Texture2DTest", + { + title:"TextureCache Test", + platforms: PLATFORM_ALL, + linksrc:"src/TextureCacheTest/TextureCacheTest.js", + testScene:function () { + return new TexCacheTestScene(); + } + }, + { + title:"TileMap Test", + resource:g_tilemaps, + platforms: PLATFORM_ALL, + linksrc:"src/TileMapTest/TileMapTest.js", + testScene:function () { + return new TileMapTestScene(); + } + }, + { + title:"Touches Test", + resource:g_touches, + platforms: PLATFORM_HTML5, + linksrc:"src/TouchesTest/TouchesTest.js", + testScene:function () { + return new TouchesTestScene(); + } + }, + { + title:"Transitions Test", + resource:g_transitions, + platforms: PLATFORM_ALL, + linksrc:"", + testScene:function () { + return new TransitionsTestScene(); + } + }, + { + title:"Unit Tests", + platforms: PLATFORM_ALL, + linksrc:"src/UnitTest/UnitTest.js", + testScene:function () { + return new UnitTestScene(); + } + }, + { + title:"Sys Tests", + platforms: PLATFORM_ALL, + linksrc:"src/SysTest/SysTest.js", + testScene:function () { + return new SysTestScene(); + } + }, + { + title:"cocos2d JS Presentation", + platforms: PLATFORM_JSB, + linksrc:"src/Presentation/Presentation.js", + testScene:function () { + return new PresentationScene(); + } + }, + { + title:"XMLHttpRequest", + platforms: PLATFORM_ALL, + linksrc:"src/XHRTest/XHRTest.js", + testScene:function () { + return new XHRTestScene(); + } + }, + { + title:"XMLHttpRequest send ArrayBuffer", + platforms: PLATFORM_ALL, + linksrc:"src/XHRTest/XHRArrayBufferTest.js", + testScene:function () { + return new XHRArrayBufferTestScene(); + } + } + + //"UserDefaultTest", + //"ZwoptexTest", +]; \ No newline at end of file diff --git a/tests/js-tests/src/tests_resources.js b/tests/js-tests/src/tests_resources.js new file mode 100644 index 0000000000..5fea0155aa --- /dev/null +++ b/tests/js-tests/src/tests_resources.js @@ -0,0 +1,1092 @@ +// Resources prefix +var s_resprefix = "res/"; + +var s_pathGrossini = "res/Images/grossini.png"; +var s_pathSister1 = "res/Images/grossinis_sister1.png"; +var s_pathSister2 = "res/Images/grossinis_sister2.png"; +var s_pathB1 = "res/Images/b1.png"; +var s_pathB2 = "res/Images/b2.png"; +var s_pathR1 = "res/Images/r1.png"; +var s_pathR2 = "res/Images/r2.png"; +var s_pathF1 = "res/Images/f1.png"; +var s_pathF2 = "res/Images/f2.png"; +var s_pathBlock = "res/Images/blocks.png"; +var s_back = "res/Images/background.png"; +var s_back1 = "res/Images/background1.png"; +var s_back2 = "res/Images/background2.png"; +var s_back3 = "res/Images/background3.png"; +var s_stars1 = "res/Images/stars.png"; +var s_stars2 = "res/Images/stars2.png"; +var s_fire = "res/Images/fire.png"; +var s_snow = "res/Images/snow.png"; +var s_streak = "res/Images/streak.png"; +var s_playNormal = "res/Images/btn-play-normal.png"; +var s_playSelect = "res/Images/btn-play-selected.png"; +var s_aboutNormal = "res/Images/btn-about-normal.png"; +var s_aboutSelect = "res/Images/btn-about-selected.png"; +var s_highNormal = "res/Images/btn-highscores-normal.png"; +var s_highSelect = "res/Images/btn-highscores-selected.png"; +var s_ball = "res/Images/ball.png"; +var s_paddle = "res/Images/paddle.png"; +var s_pathClose = "res/Images/close.png"; +var s_menuItem = "res/Images/menuitemsprite.png"; +var s_shapeModeMenuItem = "res/Images/shapemode.png"; +var s_textureModeMenuItem = "res/Images/texturemode.png"; +var s_MovementMenuItem = "res/Images/movement.png"; +var s_sendScore = "res/Images/SendScoreButton.png"; +var s_pressSendScore = "res/Images/SendScoreButtonPressed.png"; +var s_power = "res/Images/powered.png"; +var s_atlasTest = "res/Images/atlastest.png"; +var s_stars2Grayscale = "res/Images/stars2-grayscale.png"; +var s_starsGrayscale = "res/Images/stars-grayscale.png"; +var s_grossini_dance_atlas = "res/Images/grossini_dance_atlas.png"; +var s_piece = "res/Images/piece.png"; +var s_grossini_dance_atlas_mono = "res/Images/grossini_dance_atlas-mono.png"; +var s_lookup_desktop_plist = "res/Images/lookup-desktop.plist"; +var s_lookup_mobile_plist = "res/Images/lookup-mobile.plist"; +var s_lookup_html5_plist = "res/Images/lookup-html5.plist"; + +var s_grossini = "res/animations/grossini.png"; +var s_grossini_gray = "res/animations/grossini_gray.png"; +var s_grossini_blue = "res/animations/grossini_blue.png"; +var s_grossini_aliases = "res/animations/grossini-aliases.png"; +var s_dragon_animation = "res/animations/dragon_animation.png"; +var s_ghosts = "res/animations/ghosts.png"; +var s_grossini_family = "res/animations/grossini_family.png"; + +var s_tcc_issue_1 = "res/animations/tcc_issue_1.png"; +var s_tcc_issue_2 = "res/animations/tcc_issue_2.png"; +var s_tcc_issue_1_plist = "res/animations/tcc_issue_1.plist"; +var s_tcc_issue_2_plist = "res/animations/tcc_issue_2.plist"; + +var s_Cowboy_json = "res/armatures/Cowboy.ExportJson"; +var s_Cowboy_plist = "res/armatures/Cowboy0.plist"; +var s_Cowboy_png = "res/armatures/Cowboy0.png"; +var s_hero_json = "res/armatures/hero.ExportJson"; +var s_hero0_plist = "res/armatures/hero0.plist"; +var s_hero0_png = "res/armatures/hero0.png"; +var s_horse_json = "res/armatures/horse.ExportJson"; +var s_horse0_plist = "res/armatures/horse0.plist"; +var s_horse0_png = "res/armatures/horse0.png"; +var s_bear_json = "res/armatures/bear.ExportJson"; +var s_bear0_plist = "res/armatures/bear0.plist"; +var s_bear0_png = "res/armatures/bear0.png"; +var s_blood_plist = "res/armatures/blood.plist"; +var s_HeroAnimation_json = "res/armatures/HeroAnimation.ExportJson"; +var s_HeroAnimation0_plist = "res/armatures/HeroAnimation0.plist"; +var s_HeroAnimation0_png = "res/armatures/HeroAnimation0.png"; +var s_cyborg_plist = "res/armatures/cyborg.plist"; +var s_cyborg_png = "res/armatures/cyborg.png"; +var s_cyborg_xml = "res/armatures/cyborg.xml"; +var s_Dragon_plist = "res/armatures/Dragon.plist"; +var s_Dragon_png = "res/armatures/Dragon.png"; +var s_Dragon_xml = "res/armatures/Dragon.xml"; +var s_knight_plist = "res/armatures/knight.plist"; +var s_knight_png = "res/armatures/knight.png"; +var s_knight_xml = "res/armatures/knight.xml"; +var s_robot_plist = "res/armatures/robot.plist"; +var s_robot_png = "res/armatures/robot.png"; +var s_robot_xml = "res/armatures/robot.xml"; +var s_weapon_plist = "res/armatures/weapon.plist"; +var s_weapon_png = "res/armatures/weapon.png"; +var s_weapon_xml = "res/armatures/weapon.xml"; +var s_testEasing_json = "res/armatures/testEasing.ExportJson"; +var s_testEasing0_plist = "res/armatures/testEasing0.plist"; +var s_testEasing0_png = "res/armatures/testEasing0.png"; + +var s_s9s_blocks9 = "res/Images/blocks9ss.png"; +var s_s9s_blocks9_plist = "res/Images/blocks9ss.plist"; +var s_blocks9 = "res/Images/blocks9.png"; + +var s_s9s_ui = "res/Images/ui.png"; +var s_s9s_ui_plist = "res/Images/ui.plist"; + +var s_boilingFoamPlist = "res/Images/BoilingFoam.plist"; +var s_grossiniPlist = "res/animations/grossini.plist"; +var s_grossini_grayPlist = "res/animations/grossini_gray.plist"; +var s_grossini_bluePlist = "res/animations/grossini_blue.plist"; +var s_grossini_aliasesPlist = "res/animations/grossini-aliases.plist"; +var s_ghostsPlist = "res/animations/ghosts.plist"; +var s_grossini_familyPlist = "res/animations/grossini_family.plist"; +var s_animations2Plist = "res/animations/animations-2.plist"; +var s_animationsPlist = "res/animations/animations.plist"; + +var s_helloWorld = "res/Images/HelloWorld.png"; +var s_grossiniDance01 = "res/Images/grossini_dance_01.png"; +var s_grossiniDance02 = "res/Images/grossini_dance_02.png"; +var s_grossiniDance03 = "res/Images/grossini_dance_03.png"; +var s_grossiniDance04 = "res/Images/grossini_dance_04.png"; +var s_grossiniDance05 = "res/Images/grossini_dance_05.png"; +var s_grossiniDance06 = "res/Images/grossini_dance_06.png"; +var s_grossiniDance07 = "res/Images/grossini_dance_07.png"; +var s_grossiniDance08 = "res/Images/grossini_dance_08.png"; +var s_grossiniDance09 = "res/Images/grossini_dance_09.png"; +var s_grossiniDance10 = "res/Images/grossini_dance_10.png"; +var s_grossiniDance11 = "res/Images/grossini_dance_11.png"; +var s_grossiniDance12 = "res/Images/grossini_dance_12.png"; +var s_grossiniDance13 = "res/Images/grossini_dance_13.png"; +var s_grossiniDance14 = "res/Images/grossini_dance_14.png"; + +var s_arrows = "res/Images/arrows.png"; +var s_arrowsBar = "res/Images/arrowsBar.png"; +var s_arrows_hd = "res/Images/arrows-hd.png"; +var s_arrowsBar_hd = "res/Images/arrowsBar-hd.png"; + +// tilemaps resource +var s_tilesPng = "res/TileMaps/tiles.png"; +var s_levelMapTga = "res/TileMaps/levelmap.tga"; +var s_fixedOrthoTest2Png = "res/TileMaps/fixed-ortho-test2.png"; +var s_hexaTilesPng = "res/TileMaps/hexa-tiles.png"; +var s_isoTestPng = "res/TileMaps/iso-test.png"; +var s_isoTest2Png = "res/TileMaps/iso-test2.png"; +var s_isoPng = "res/TileMaps/iso.png"; +var s_orthoTest1BwPng = "res/TileMaps/ortho-test1_bw.png"; +var s_orthoTest1Png = "res/TileMaps/ortho-test1.png"; +var s_tilesHdPng = "res/TileMaps/tiles-hd.png"; +var s_tmwDesertSpacingHdPng = "res/TileMaps/tmw_desert_spacing-hd.png"; +var s_tmwDesertSpacingPng = "res/TileMaps/tmw_desert_spacing.png"; +var s_tileISOOffsetPng = "res/TileMaps/tile_iso_offset.png"; +var s_tileISOOffsetTmx = "res/TileMaps/tile_iso_offset.tmx"; + +var s_fnTuffyBoldItalicCharmapPng = "res/fonts/tuffy_bold_italic-charmap.png"; +var s_fpsImages = "res/fonts/fps_images.png"; +var s_bitmapFontTest = "res/fonts/bitmapFontTest.png"; +var s_bitmapFontTest2 = "res/fonts/bitmapFontTest2.png"; +var s_bitmapFontTest3 = "res/fonts/bitmapFontTest3.png"; +var s_bitmapFontTest4 = "res/fonts/bitmapFontTest4.png"; +var s_bitmapFontTest5 = "res/fonts/bitmapFontTest5.png"; +var s_konqa32 = "res/fonts/konqa32.png"; +var s_konqa32_hd = "res/fonts/konqa32-hd.png"; +var s_bitmapFontChinese = "res/fonts/bitmapFontChinese.png"; +var s_arial16 = "res/fonts/arial16.png"; +var s_larabie_16 = "res/fonts/larabie-16.png"; +var s_larabie_16_hd = "res/fonts/larabie-16-hd.png"; +var s_futura48 = "res/fonts/futura-48.png"; +var s_arial_unicode_26 = "res/fonts/arial-unicode-26.png"; + +var s_bitmapFontTest_fnt = "res/fonts/bitmapFontTest.fnt"; +var s_bitmapFontTest2_fnt = "res/fonts/bitmapFontTest2.fnt"; +var s_bitmapFontTest3_fnt = "res/fonts/bitmapFontTest3.fnt"; +var s_bitmapFontTest4_fnt = "res/fonts/bitmapFontTest4.fnt"; +var s_bitmapFontTest5_fnt = "res/fonts/bitmapFontTest5.fnt"; +var s_konqa32_fnt = "res/fonts/konqa32.fnt"; +var s_konqa32_hd_fnt = "res/fonts/konqa32-hd.fnt"; +var s_bitmapFontChinese_fnt = "res/fonts/bitmapFontChinese.fnt"; +var s_arial16_fnt = "res/fonts/arial16.fnt"; +var s_futura48_fnt = "res/fonts/futura-48.fnt"; +var s_helvetica32_fnt = "res/fonts/helvetica-32.fnt"; +var s_geneva32_fnt = "res/fonts/geneva-32.fnt"; +var s_helvetica_helvetica_32_png = "res/fonts/helvetica-geneva-32.png"; +var s_arial_unicode_26_fnt = "res/fonts/arial-unicode-26.fnt"; +var s_markerFelt_fnt = "res/fonts/markerFelt.fnt"; +var s_markerFelt_png = "res/fonts/markerFelt.png"; +var s_markerFelt_hd_fnt = "res/fonts/markerFelt-hd.fnt"; +var s_markerFelt_hd_png = "res/fonts/markerFelt-hd.png"; + +var s_larabie_16_plist = "res/fonts/larabie-16.plist"; +var s_larabie_16_hd_plist = "res/fonts/larabie-16-hd.plist"; +var s_tuffy_bold_italic_charmap = "res/fonts/tuffy_bold_italic-charmap.plist"; +var s_tuffy_bold_italic_charmap_hd = "res/fonts/tuffy_bold_italic-charmap-hd.plist"; + +var s_particles = "res/Images/particles.png"; +var s_particles_hd = "res/Images/particles-hd.png"; +var s_texture512 = "res/Images/texture512x512.png"; +var s_hole_effect_png = "res/Images/hole_effect.png"; +var s_hole_stencil_png = "res/Images/hole_stencil.png"; +var s_pathFog = "res/Images/Fog.png"; +var s_circle_plist = "res/Images/bugs/circle.plist"; +var s_circle_png = "res/Images/bugs/circle.png"; + +var s_extensions_background = "res/extensions/background.png"; +var s_extensions_buttonBackground = "res/extensions/buttonBackground.png"; +var s_extensions_button = "res/extensions/button.png"; +var s_extensions_buttonHighlighted = "res/extensions/buttonHighlighted.png"; +var s_extensions_ribbon = "res/extensions/ribbon.png"; +var s_image_icon = "res/Images/Icon.png"; +var s_html5_logo = "res/Images/cocos-html5.png"; + +var g_resources = [ + //global + s_grossini_dance_atlas, + s_pathFog, + s_circle_plist, + s_circle_png, + s_texture512, + s_hole_effect_png, + s_hole_stencil_png, + s_pathB1, + s_pathB2, + s_pathR1, + s_pathR2, + s_pathF1, + s_pathF2, + s_pathBlock, + s_back3, + s_fire, + s_pathClose, + s_pathGrossini, + s_pathSister1, + s_pathSister2, + s_grossiniDance01, + s_grossiniDance02, + s_grossiniDance03, + s_grossiniDance04, + s_grossiniDance05, + s_grossiniDance06, + s_grossiniDance07, + s_grossiniDance08, + s_grossiniDance09, + s_grossiniDance10, + s_grossiniDance11, + s_grossiniDance12, + s_grossiniDance13, + s_grossiniDance14, + + s_grossini, + s_grossiniPlist, + + s_animations2Plist, + s_grossini_blue, + s_grossini_bluePlist, + s_grossini_family, + s_grossini_familyPlist, + s_helloWorld, + s_bitmapFontTest5, + s_playNormal, + s_playSelect, + s_bitmapFontTest5_fnt, + s_extensions_background, + s_extensions_ribbon +]; + +var g_sprites = [ + s_piece, + s_grossini_gray, + s_grossini_blue, + s_grossini_aliases, + s_dragon_animation, + s_ghosts, + s_grossini_family, + + s_grossini_dance_atlas_mono, + s_animationsPlist, + s_grossini_grayPlist, + s_grossini_bluePlist, + s_grossini_aliasesPlist, + s_ghostsPlist, + s_grossini_familyPlist, + + s_tcc_issue_1_plist, + s_tcc_issue_2_plist, + s_tcc_issue_1, + s_tcc_issue_2, + + s_s9s_blocks9_plist, + s_s9s_blocks9, + "res/Images/dot.png", + "res/Images/wood.jpg" +]; + +var g_menu = [ + s_bitmapFontTest3_fnt, + s_bitmapFontTest3, + s_aboutNormal, + s_aboutSelect, + s_highNormal, + s_highSelect, + s_menuItem, + s_sendScore, + s_pressSendScore, + s_fpsImages +]; + +var g_touches = [ + s_ball, + s_paddle +]; + +var g_s9s_blocks = [ + s_s9s_blocks9_plist, + s_s9s_blocks9, + s_blocks9, + s_s9s_ui, + s_s9s_ui_plist +]; + +var g_opengl_resources = [ + //preload shader source + "res/Shaders/example_Outline.fsh", + "res/Shaders/example_Outline.vsh", + "res/Shaders/example_Blur.fsh", + "res/Shaders/example_ColorBars.fsh", + "res/Shaders/example_ColorBars.vsh", + "res/Shaders/example_Flower.fsh", + "res/Shaders/example_Flower.vsh", + "res/Shaders/example_Heart.fsh", + "res/Shaders/example_Heart.vsh", + "res/Shaders/example_Julia.fsh", + "res/Shaders/example_Julia.vsh", + "res/Shaders/example_Mandelbrot.fsh", + "res/Shaders/example_Mandelbrot.vsh", + "res/Shaders/example_Monjori.fsh", + "res/Shaders/example_Monjori.vsh", + "res/Shaders/example_Plasma.fsh", + "res/Shaders/example_Plasma.vsh", + "res/Shaders/example_Twist.fsh", + "res/Shaders/example_Twist.vsh", + + "res/fonts/west_england-64.fnt", + "res/fonts/west_england-64.png" +]; + +var g_label = [ + //s_atlasTest, + s_bitmapFontTest, + s_bitmapFontTest2, + s_bitmapFontTest3, + s_bitmapFontTest4, + s_konqa32, + s_konqa32_hd, + s_bitmapFontChinese, + s_arial16, + s_larabie_16, + s_larabie_16_hd, + s_futura48, + s_arial_unicode_26, + s_fnTuffyBoldItalicCharmapPng, + + s_arrows, + s_arrowsBar, + s_arrows_hd, + s_arrowsBar_hd, + s_larabie_16_plist, + s_larabie_16_hd_plist, + s_tuffy_bold_italic_charmap, + s_tuffy_bold_italic_charmap_hd, + s_bitmapFontTest_fnt, + s_bitmapFontTest2_fnt, + s_bitmapFontTest3_fnt, + s_bitmapFontTest4_fnt, + s_konqa32_fnt, + s_konqa32_hd_fnt, + s_bitmapFontChinese_fnt, + s_arial16_fnt, + s_futura48_fnt, + s_helvetica32_fnt, + s_geneva32_fnt, + s_helvetica_helvetica_32_png, + s_arial_unicode_26_fnt, + s_markerFelt_fnt, + s_markerFelt_png, + s_markerFelt_hd_fnt, + s_markerFelt_hd_png, + "res/fonts/strings.xml" +]; + +var g_transitions = [ + s_back1, + s_back2 +]; + +var g_box2d = [ + s_pathBlock +]; + +var g_cocosdeshion = [ + "res/Sound/background.mp3", + "res/Sound/effect2.mp3" + //"res/Sound/background.ogg", //one sound only, cc.audio can auto select other format to load if the sound format isn't supported on some browser. + //"res/Sound/effect2.ogg" +]; + +var g_parallax = [ + "res/TileMaps/orthogonal-test2.tmx", + s_fixedOrthoTest2Png, + s_power, + s_back +]; + +var g_eventDispatcher = [ + "res/Images/CyanSquare.png", + "res/Images/MagentaSquare.png", + "res/Images/YellowSquare.png", + "res/Images/ball.png", + s_extensions_button, + s_extensions_buttonHighlighted, + s_extensions_buttonBackground +]; + +var g_particle = [ + s_fpsImages, + s_starsGrayscale, + s_stars2Grayscale, + s_textureModeMenuItem, + s_shapeModeMenuItem, + s_MovementMenuItem, + s_stars1, + s_stars2, + s_snow, + s_particles, + s_particles_hd, + "res/Particles/BoilingFoam.plist", + "res/Particles/BurstPipe.plist", + "res/Particles/Comet.plist", + "res/Particles/debian.plist", + "res/Particles/ExplodingRing.plist", + "res/Particles/Flower.plist", + "res/Particles/Galaxy.plist", + "res/Particles/LavaFlow.plist", + "res/Particles/Phoenix.plist", + "res/Particles/SmallSun.plist", + "res/Particles/SpinningPeas.plist", + "res/Particles/Spiral.plist", + "res/Particles/SpookyPeas.plist", + "res/Particles/TestPremultipliedAlpha.plist", + "res/Particles/Upsidedown.plist" +]; + +var g_fonts = [ + //@face-font for WebFonts + { + type:"font", + name:"Thonburi", + srcs:["res/fonts/Thonburi.eot", "res/fonts/Thonburi.ttf"] + }, + { + type:"font", + name:"Schwarzwald Regular", + srcs:["res/fonts/Schwarzwald_Regular.eot", "res/fonts/Schwarzwald Regular.ttf"] + }, + { + type:"font", + name:"ThonburiBold", + srcs:["res/fonts/ThonburiBold.eot", "res/fonts/ThonburiBold.ttf"] + }, + { + type:"font", + name:"Courier New", + srcs:["res/fonts/Courier New.eot", "res/fonts/Courier New.ttf"] + } +]; + +var g_extensions = [ + s_image_icon, + s_extensions_background, + s_extensions_buttonBackground, + s_extensions_button, + s_extensions_buttonHighlighted, + s_extensions_ribbon, + + //ccbi resource + "res/ccb/HelloCocosBuilder.ccbi", + "res/ccb/ccb/TestAnimations.ccbi", + "res/ccb/ccb/TestAnimationsSub.ccbi", + "res/ccb/ccb/TestButtons.ccbi", + "res/ccb/ccb/TestHeader.ccbi", + "res/ccb/ccb/TestLabels.ccbi", + "res/ccb/ccb/TestMenus.ccbi", + "res/ccb/ccb/TestParticleSystems.ccbi", + "res/ccb/ccb/TestScrollViews.ccbi", + "res/ccb/ccb/TestScrollViewsContentA.ccbi", + "res/ccb/ccb/TestSprites.ccbi", + + "res/ccb/ccbParticleStars.png", + "res/ccb/btn-test-0.png", + "res/ccb/animated-grossini.png", + "res/ccb/btn-a-0.png", + "res/ccb/btn-a-1.png", + "res/ccb/btn-a-2.png", + "res/ccb/btn-b-0.png", + "res/ccb/btn-b-1.png", + "res/ccb/btn-b-2.png", + "res/ccb/btn-back-0.png", + "res/ccb/btn-back-1.png", + "res/ccb/btn-test-0.png", + "res/ccb/btn-test-1.png", + "res/ccb/btn-test-2.png", + "res/ccb/burst.png", + "res/ccb/flower.jpg", + "res/ccb/grossini-generic.png", + "res/ccb/jungle.png", + "res/ccb/jungle-left.png", + "res/ccb/jungle-right.png", + "res/ccb/logo.png", + "res/ccb/logo-icon.png", + "res/ccb/markerfelt24shadow.png", + "res/ccb/particle-fire.png", + "res/ccb/particle-smoke.png", + "res/ccb/particle-snow.png", + "res/ccb/particle-stars.png", + "res/ccb/scale-9-demo.png", + "res/extensions/green_edit.png", + "res/extensions/orange_edit.png", + "res/extensions/yellow_edit.png", + "res/extensions/switch-mask.png", + "res/extensions/switch-on.png", + "res/extensions/switch-off.png", + "res/extensions/switch-thumb.png", + "res/extensions/sliderProgress.png", + "res/extensions/sliderProgress2.png", + "res/extensions/sliderThumb.png", + "res/extensions/sliderTrack.png", + "res/extensions/sliderTrack2.png", + "res/extensions/stepper-minus.png", + "res/extensions/stepper-plus.png", + "res/extensions/potentiometerButton.png", + "res/extensions/potentiometerProgress.png", + "res/extensions/potentiometerTrack.png", + "res/extensions/CCControlColourPickerSpriteSheet.plist", + "res/extensions/CCControlColourPickerSpriteSheet.png", + + "res/ccb/markerfelt24shadow.fnt", + + "res/ccb/grossini-generic.plist", + "res/ccb/animated-grossini.plist" +]; + +var g_cocoStudio = [ + //Armature + s_Cowboy_json , + s_Cowboy_plist, + s_Cowboy_png, + s_hero_json, + s_hero0_plist, + s_hero0_png, + s_horse_json, + s_horse0_plist, + s_horse0_png, + s_bear_json, + s_bear0_plist, + s_bear0_png, + s_blood_plist, + s_HeroAnimation_json, + s_HeroAnimation0_plist, + s_HeroAnimation0_png, + s_cyborg_plist , + s_cyborg_png , + s_cyborg_xml , + s_Dragon_plist , + s_Dragon_png , + s_Dragon_xml , + s_knight_plist , + s_knight_png , + s_knight_xml , + s_robot_plist , + s_robot_png , + s_robot_xml , + s_weapon_plist , + s_weapon_png , + s_weapon_xml , + s_testEasing_json , + s_testEasing0_plist , + s_testEasing0_png , + +//GUI + "res/Particles/SmallSun.plist", + "res/Images/b1.png", + "res/Images/b2.png", + "res/Images/f1.png", + "res/Images/f2.png", + "res/cocosui/CCS/Button/background.png", + "res/cocosui/CCS/Button/buttonBackground.png", + "res/cocosui/CCS/Button/buttonHighlighted.png", + "res/cocosui/CCS/Button/button_n.png", + "res/cocosui/CCS/Button/button_p.png", + "res/cocosui/CCS/Button/ribbon.png", + "res/cocosui/CCS/Button/Button_1.json", + "res/cocosui/CCS/CheckBox/background.png", + "res/cocosui/CCS/CheckBox/buttonBackground.png", + "res/cocosui/CCS/CheckBox/ribbon.png", + "res/cocosui/CCS/CheckBox/selected01.png", + "res/cocosui/CCS/CheckBox/selected02.png", + "res/cocosui/CCS/CheckBox/checkbox_1.json", + "res/cocosui/CCS/CheckBox/MainScene.json", + "res/cocosui/CCS/CheckBox/Default/CheckBox_Disable.png", + "res/cocosui/CCS/CheckBox/img/btn_music.png", + "res/cocosui/CCS/CheckBox/img/btn_sound_off.png", + "res/cocosui/CCS/ImageView/background.png", + "res/cocosui/CCS/ImageView/buttonBackground.png", + "res/cocosui/CCS/ImageView/buttonHighlighted.png", + "res/cocosui/CCS/ImageView/GUI/image.png", + "res/cocosui/CCS/ImageView/ribbon.png", + "res/cocosui/CCS/ImageView/ImageView_1.json", + "res/cocosui/CCS/LabelAtlas/background.png", + "res/cocosui/CCS/LabelAtlas/buttonBackground.png", + "res/cocosui/CCS/LabelAtlas/GUI/labelatlasimg.png", + "res/cocosui/CCS/LabelAtlas/ribbon.png", + "res/cocosui/CCS/LabelAtlas/labelatlas_1.json", + "res/cocosui/CCS/LabelBMFont/background.png", + "res/cocosui/CCS/LabelBMFont/buttonBackground.png", + "res/cocosui/CCS/LabelBMFont/GUI/missing-font.fnt", + "res/cocosui/CCS/LabelBMFont/GUI/missing-font.png", + "res/cocosui/CCS/LabelBMFont/ribbon.png", + "res/cocosui/CCS/LabelBMFont/labelbmfont_1.json", + "res/cocosui/CCS/Label/background.png", + "res/cocosui/CCS/Label/buttonBackground.png", + "res/cocosui/CCS/Label/ribbon.png", + "res/cocosui/CCS/Label/label_1.json", + "res/cocosui/CCS/Layout/BackgroundImage/background.png", + "res/cocosui/CCS/Layout/BackgroundImage/buttonBackground.png", + "res/cocosui/CCS/Layout/BackgroundImage/button_n.png", + "res/cocosui/CCS/Layout/BackgroundImage/button_p.png", + "res/cocosui/CCS/Layout/BackgroundImage/GUI/image.png", + "res/cocosui/CCS/Layout/BackgroundImage/Hello.png", + "res/cocosui/CCS/Layout/BackgroundImage/ribbon.png", + "res/cocosui/CCS/Layout/BackgroundImage/selected01.png", + "res/cocosui/CCS/Layout/BackgroundImage/selected02.png", + "res/cocosui/CCS/Layout/BackgroundImage/backgroundimage_1.json", + "res/cocosui/CCS/Layout/Color/background.png", + "res/cocosui/CCS/Layout/Color/buttonBackground.png", + "res/cocosui/CCS/Layout/Color/button_n.png", + "res/cocosui/CCS/Layout/Color/button_p.png", + "res/cocosui/CCS/Layout/Color/GUI/image.png", + "res/cocosui/CCS/Layout/Color/ribbon.png", + "res/cocosui/CCS/Layout/Color/selected01.png", + "res/cocosui/CCS/Layout/Color/selected02.png", + "res/cocosui/CCS/Layout/Color/color_1.json", + "res/cocosui/CCS/Layout/Layout/background.png", + "res/cocosui/CCS/Layout/Layout/buttonBackground.png", + "res/cocosui/CCS/Layout/Layout/button_n.png", + "res/cocosui/CCS/Layout/Layout/button_p.png", + "res/cocosui/CCS/Layout/Layout/GUI/image.png", + "res/cocosui/CCS/Layout/Layout/ribbon.png", + "res/cocosui/CCS/Layout/Layout/selected01.png", + "res/cocosui/CCS/Layout/Layout/selected02.png", + "res/cocosui/CCS/Layout/Layout/layout_1.json", + "res/cocosui/CCS/Layout/Gradient_Color/background.png", + "res/cocosui/CCS/Layout/Gradient_Color/buttonBackground.png", + "res/cocosui/CCS/Layout/Gradient_Color/button_n.png", + "res/cocosui/CCS/Layout/Gradient_Color/button_p.png", + "res/cocosui/CCS/Layout/Gradient_Color/GUI/image.png", + "res/cocosui/CCS/Layout/Gradient_Color/ribbon.png", + "res/cocosui/CCS/Layout/Gradient_Color/selected01.png", + "res/cocosui/CCS/Layout/Gradient_Color/selected02.png", + "res/cocosui/CCS/Layout/Gradient_Color/gradient_color_1.json", + "res/cocosui/CCS/Layout/Linear_Horizontal/background.png", + "res/cocosui/CCS/Layout/Linear_Horizontal/buttonBackground.png", + "res/cocosui/CCS/Layout/Linear_Horizontal/button_n.png", + "res/cocosui/CCS/Layout/Linear_Horizontal/button_p.png", + "res/cocosui/CCS/Layout/Linear_Horizontal/GUI/image.png", + "res/cocosui/CCS/Layout/Linear_Horizontal/ribbon.png", + "res/cocosui/CCS/Layout/Linear_Horizontal/selected01.png", + "res/cocosui/CCS/Layout/Linear_Horizontal/selected02.png", + "res/cocosui/CCS/Layout/Linear_Horizontal/linear_horizontal.json", + "res/cocosui/CCS/Layout/Linear_Vertical/background.png", + "res/cocosui/CCS/Layout/Linear_Vertical/buttonBackground.png", + "res/cocosui/CCS/Layout/Linear_Vertical/button_n.png", + "res/cocosui/CCS/Layout/Linear_Vertical/button_p.png", + "res/cocosui/CCS/Layout/Linear_Vertical/GUI/image.png", + "res/cocosui/CCS/Layout/Linear_Vertical/ribbon.png", + "res/cocosui/CCS/Layout/Linear_Vertical/selected01.png", + "res/cocosui/CCS/Layout/Linear_Vertical/selected02.png", + "res/cocosui/CCS/Layout/Linear_Vertical/linear_vertical.json", + "res/cocosui/CCS/Layout/Relative_Align_Location/background.png", + "res/cocosui/CCS/Layout/Relative_Align_Location/buttonBackground.png", + "res/cocosui/CCS/Layout/Relative_Align_Location/button_n.png", + "res/cocosui/CCS/Layout/Relative_Align_Location/button_p.png", + "res/cocosui/CCS/Layout/Relative_Align_Location/GUI/image.png", + "res/cocosui/CCS/Layout/Relative_Align_Location/ribbon.png", + "res/cocosui/CCS/Layout/Relative_Align_Location/selected01.png", + "res/cocosui/CCS/Layout/Relative_Align_Location/selected02.png", + "res/cocosui/CCS/Layout/Relative_Align_Location/relative_align_location.json", + "res/cocosui/CCS/Layout/Relative_Align_Parent/background.png", + "res/cocosui/CCS/Layout/Relative_Align_Parent/buttonBackground.png", + "res/cocosui/CCS/Layout/Relative_Align_Parent/button_n.png", + "res/cocosui/CCS/Layout/Relative_Align_Parent/button_p.png", + "res/cocosui/CCS/Layout/Relative_Align_Parent/GUI/image.png", + "res/cocosui/CCS/Layout/Relative_Align_Parent/ribbon.png", + "res/cocosui/CCS/Layout/Relative_Align_Parent/selected01.png", + "res/cocosui/CCS/Layout/Relative_Align_Parent/selected02.png", + "res/cocosui/CCS/Layout/Relative_Align_Parent/relative_align_parent.json", + "res/cocosui/CCS/Layout/Scale9/background.png", + "res/cocosui/CCS/Layout/Scale9/buttonBackground.png", + "res/cocosui/CCS/Layout/Scale9/button_n.png", + "res/cocosui/CCS/Layout/Scale9/button_p.png", + "res/cocosui/CCS/Layout/Scale9/GUI/image.png", + "res/cocosui/CCS/Layout/Scale9/ribbon.png", + "res/cocosui/CCS/Layout/Scale9/selected01.png", + "res/cocosui/CCS/Layout/Scale9/selected02.png", + "res/cocosui/CCS/Layout/Scale9/slider_bar.png", + "res/cocosui/CCS/Layout/Scale9/scale9.json", + "res/cocosui/CCS/ListView/Horizontal/background.png", + "res/cocosui/CCS/ListView/Horizontal/buttonBackground.png", + "res/cocosui/CCS/ListView/Horizontal/button_p.png", + "res/cocosui/CCS/ListView/Horizontal/GUI/button.png", + "res/cocosui/CCS/ListView/Horizontal/GUI/image.png", + "res/cocosui/CCS/ListView/Horizontal/ribbon.png", + "res/cocosui/CCS/ListView/Horizontal/horizontal_1.json", + "res/cocosui/CCS/ListView/Vertical/background.png", + "res/cocosui/CCS/ListView/Vertical/buttonBackground.png", + "res/cocosui/CCS/ListView/Vertical/button_p.png", + "res/cocosui/CCS/ListView/Vertical/GUI/button.png", + "res/cocosui/CCS/ListView/Vertical/GUI/image.png", + "res/cocosui/CCS/ListView/Vertical/ribbon.png", + "res/cocosui/CCS/ListView/Vertical/vertical_1.json", + "res/cocosui/CCS/LoadingBar/background.png", + "res/cocosui/CCS/LoadingBar/buttonBackground.png", + "res/cocosui/CCS/LoadingBar/GUI/loadingbar.png", + "res/cocosui/CCS/LoadingBar/ribbon.png", + "res/cocosui/CCS/LoadingBar/loadingbar_1.json", + "res/cocosui/CCS/PageView/background.png", + "res/cocosui/CCS/PageView/buttonBackground.png", + "res/cocosui/CCS/PageView/button_n.png", + "res/cocosui/CCS/PageView/ribbon.png", + "res/cocosui/CCS/PageView/pageview_1.json", + "res/cocosui/CCS/ScrollView/Both/background.png", + "res/cocosui/CCS/ScrollView/Both/buttonBackground.png", + "res/cocosui/CCS/ScrollView/Both/button_n.png", + "res/cocosui/CCS/ScrollView/Both/button_p.png", + "res/cocosui/CCS/ScrollView/Both/GUI/image.png", + "res/cocosui/CCS/ScrollView/Both/ribbon.png", + "res/cocosui/CCS/ScrollView/Both/selected01.png", + "res/cocosui/CCS/ScrollView/Both/selected02.png", + "res/cocosui/CCS/ScrollView/Both/both_1.json", + "res/cocosui/CCS/ScrollView/Horizontal/background.png", + "res/cocosui/CCS/ScrollView/Horizontal/buttonBackground.png", + "res/cocosui/CCS/ScrollView/Horizontal/button_n.png", + "res/cocosui/CCS/ScrollView/Horizontal/button_p.png", + "res/cocosui/CCS/ScrollView/Horizontal/GUI/image.png", + "res/cocosui/CCS/ScrollView/Horizontal/ribbon.png", + "res/cocosui/CCS/ScrollView/Horizontal/selected01.png", + "res/cocosui/CCS/ScrollView/Horizontal/selected02.png", + "res/cocosui/CCS/ScrollView/Horizontal/horizontal_1.json", + "res/cocosui/CCS/ScrollView/Vertical/background.png", + "res/cocosui/CCS/ScrollView/Vertical/buttonBackground.png", + "res/cocosui/CCS/ScrollView/Vertical/button_n.png", + "res/cocosui/CCS/ScrollView/Vertical/button_p.png", + "res/cocosui/CCS/ScrollView/Vertical/GUI/image.png", + "res/cocosui/CCS/ScrollView/Vertical/ribbon.png", + "res/cocosui/CCS/ScrollView/Vertical/selected01.png", + "res/cocosui/CCS/ScrollView/Vertical/selected02.png", + "res/cocosui/CCS/ScrollView/Vertical/vertical_1.json", + "res/cocosui/CCS/Slider/2014-1-26 11-42-09.png", + "res/cocosui/CCS/Slider/2014-1-26 11-43-52.png", + "res/cocosui/CCS/Slider/background.png", + "res/cocosui/CCS/Slider/buttonBackground.png", + "res/cocosui/CCS/Slider/ribbon.png", + "res/cocosui/CCS/Slider/silder_progressBar.png", + "res/cocosui/CCS/Slider/slider_bar.png", + "res/cocosui/CCS/Slider/slider_bar_button.png", + "res/cocosui/CCS/Slider/slider_1.json", + "res/cocosui/CCS/TextField/background.png", + "res/cocosui/CCS/TextField/buttonBackground.png", + "res/cocosui/CCS/TextField/ribbon.png", + "res/cocosui/CCS/TextField/textfield_1.json", + "res/cocosui/CCS/WidgetAddNode/background.png", + "res/cocosui/CCS/WidgetAddNode/buttonBackground.png", + "res/cocosui/CCS/WidgetAddNode/ribbon.png", + "res/cocosui/CCS/WidgetAddNode/widget_add_node.json", + "res/Sound/background-music-aac.wav", + "res/Sound/pew-pew-lei.wav", + //Components + "res/components/Player.png", + "res/components/Projectile.png", + "res/components/Target.png", + //Scene + "res/scenetest/ArmatureComponentTest/ArmatureComponentTest.json", + "res/scenetest/ArmatureComponentTest/fishes/blowFish/Blowfish.ExportJson", + "res/scenetest/ArmatureComponentTest/fishes/blowFish/Blowfish0.plist", + "res/scenetest/ArmatureComponentTest/fishes/blowFish/Blowfish0.png", + "res/scenetest/ArmatureComponentTest/fishes/Butterflyfish/Butterflyfish.ExportJson", + "res/scenetest/ArmatureComponentTest/fishes/Butterflyfish/Butterflyfish0.plist", + "res/scenetest/ArmatureComponentTest/fishes/Butterflyfish/Butterflyfish0.png", + "res/scenetest/ArmatureComponentTest/Images/startMenuBG.png", + "res/scenetest/AttributeComponentTest/AttributeComponentTest.json", + "res/scenetest/AttributeComponentTest/grossinis_sister1.png", + "res/scenetest/AttributeComponentTest/grossinis_sister2.png", + "res/scenetest/AttributeComponentTest/PlayerAttribute.json", + "res/scenetest/BackgroundComponentTest/BackgroundComponentTest.json", + "res/scenetest/BackgroundComponentTest/Images/startMenuBG.png", + "res/scenetest/BackgroundComponentTest/Misc/music_logo.mp3", + "res/scenetest/BackgroundComponentTest/Misc/music_logo.wav", + "res/scenetest/BackgroundComponentTest/Particles/qipao01.plist", + "res/scenetest/BackgroundComponentTest/Particles/qipao01.png", + "res/scenetest/BackgroundComponentTest/startMenu/Fish_UI/starMenuButton01.png", + "res/scenetest/BackgroundComponentTest/startMenu/Fish_UI/starMenuButton02.png", + "res/scenetest/BackgroundComponentTest/startMenu/Fish_UI/ui_logo_001-hd.png", + "res/scenetest/BackgroundComponentTest/startMenu/startMenu_1.json", + "res/scenetest/EffectComponentTest/CowBoy/Cowboy.ExportJson", + "res/scenetest/EffectComponentTest/CowBoy/Cowboy0.plist", + "res/scenetest/EffectComponentTest/CowBoy/Cowboy0.png", + "res/scenetest/EffectComponentTest/EffectComponentTest.json", + "res/scenetest/EffectComponentTest/pew-pew-lei.wav", + "res/scenetest/LoadSceneEdtiorFileTest/fishes/blowFish/Blowfish.ExportJson", + "res/scenetest/LoadSceneEdtiorFileTest/fishes/blowFish/Blowfish0.plist", + "res/scenetest/LoadSceneEdtiorFileTest/fishes/blowFish/Blowfish0.png", + "res/scenetest/LoadSceneEdtiorFileTest/fishes/Butterflyfish/Butterflyfish.ExportJson", + "res/scenetest/LoadSceneEdtiorFileTest/fishes/Butterflyfish/Butterflyfish0.plist", + "res/scenetest/LoadSceneEdtiorFileTest/fishes/Butterflyfish/Butterflyfish0.png", + "res/scenetest/LoadSceneEdtiorFileTest/FishJoy2.json", + "res/scenetest/LoadSceneEdtiorFileTest/Images/startMenuBG.png", + "res/scenetest/LoadSceneEdtiorFileTest/Misc/music_logo.mp3", + "res/scenetest/LoadSceneEdtiorFileTest/Misc/music_logo.wav", + "res/scenetest/LoadSceneEdtiorFileTest/Particles/qipao01.plist", + "res/scenetest/LoadSceneEdtiorFileTest/Particles/qipao01.png", + "res/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/starMenuButton01.png", + "res/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/starMenuButton02.png", + "res/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/ui_logo_001-hd.png", + "res/scenetest/LoadSceneEdtiorFileTest/startMenu/startMenu_1.json", + "res/scenetest/ParticleComponentTest/ParticleComponentTest.json", + "res/scenetest/ParticleComponentTest/SmallSun.plist", + "res/scenetest/ParticleComponentTest/Upsidedown.plist", + "res/scenetest/SpriteComponentTest/grossinis_sister1.png", + "res/scenetest/SpriteComponentTest/grossinis_sister2.png", + "res/scenetest/SpriteComponentTest/SpriteComponentTest.json", + "res/scenetest/TmxMapComponentTest/iso-test.png", + "res/scenetest/TmxMapComponentTest/iso-test.tmx", + "res/scenetest/TmxMapComponentTest/TmxMapComponentTest.json", + "res/scenetest/TriggerTest/fishes/blowFish/Blowfish.ExportJson", + "res/scenetest/TriggerTest/fishes/blowFish/Blowfish0.plist", + "res/scenetest/TriggerTest/fishes/blowFish/Blowfish0.png", + "res/scenetest/TriggerTest/fishes/Butterflyfish/Butterflyfish.ExportJson", + "res/scenetest/TriggerTest/fishes/Butterflyfish/Butterflyfish0.plist", + "res/scenetest/TriggerTest/fishes/Butterflyfish/Butterflyfish0.png", + "res/scenetest/TriggerTest/Images/startMenuBG.png", + "res/scenetest/TriggerTest/TriggerTest.json", + "res/scenetest/UIComponentTest/fishes/blowFish/Blowfish.ExportJson", + "res/scenetest/UIComponentTest/fishes/blowFish/Blowfish0.plist", + "res/scenetest/UIComponentTest/fishes/blowFish/Blowfish0.png", + "res/scenetest/UIComponentTest/fishes/Butterflyfish/Butterflyfish.ExportJson", + "res/scenetest/UIComponentTest/fishes/Butterflyfish/Butterflyfish0.plist", + "res/scenetest/UIComponentTest/fishes/Butterflyfish/Butterflyfish0.png", + "res/scenetest/UIComponentTest/Images/startMenuBG.png", + "res/scenetest/UIComponentTest/starMenuButton/starMenuButton.ExportJson", + "res/scenetest/UIComponentTest/starMenuButton/starMenuButton0.plist", + "res/scenetest/UIComponentTest/starMenuButton/starMenuButton0.png", + "res/scenetest/UIComponentTest/UIComponentTest.json", + + //parser + "res/cocosui/CCS/ccs1_3/CCSV1_3_1.ExportJson", + "res/cocosui/CCS/ccs1_3/CocostudioV1_30.plist", + "res/cocosui/CCS/ccs1_3/CocostudioV1_30.png", + "res/cocosui/CCS/ccs1_3/SmallSun.plist", + "res/cocosui/CCS/ccs1_3/GUI/labelatlasimg.png", + "res/cocosui/CCS/ccs1_3/GUI/missing-font.fnt", + "res/cocosui/CCS/ccs1_3/GUI/missing-font.png", + "res/cocosui/CCS/ccs1_4/CCS1_4_1.ExportJson", + "res/cocosui/CCS/ccs1_4/Cocostudio1_40.plist", + "res/cocosui/CCS/ccs1_4/Cocostudio1_40.png", + "res/cocosui/CCS/ccs1_4/SmallSun.plist", + "res/cocosui/CCS/ccs1_4/GUI/labelatlasimg.png", + "res/cocosui/CCS/ccs1_4/GUI/missing-font.fnt", + "res/cocosui/CCS/ccs1_4/GUI/missing-font.png", + "res/cocosui/CCS/ccs1_5/CCS1_5_1.ExportJson", + "res/cocosui/CCS/ccs1_5/Cocostudio1_50.plist", + "res/cocosui/CCS/ccs1_5/Cocostudio1_50.png", + "res/cocosui/CCS/ccs1_5/SmallSun.plist", + "res/cocosui/CCS/ccs1_5/GUI/labelatlasimg.png", + "res/cocosui/CCS/ccs1_5/GUI/missing-font.fnt", + "res/cocosui/CCS/ccs1_5/GUI/missing-font.png", + + "res/cocosui/CCS/2.1/MainScene.json", + "res/cocosui/CCS/2.1/plist1/Plist.plist", + "res/cocosui/CCS/2.1/Plist/ui.plist", + "res/cocosui/CCS/2.1/LoadingBar/pipe2.png", + "res/cocosui/CCS/2.1/Slider/2013-8-13 15-44-11.png", + "res/cocosui/CCS/2.1/Slider/teehanlax - iOS 6 - iPhone_slider01.png", + "res/cocosui/CCS/2.1/particle/blue.plist", + "res/cocosui/CCS/2.1/Default/Slider_Back.png", + "res/cocosui/CCS/2.1/Default/SliderNode_Normal.png", + "res/cocosui/CCS/2.1/Default/SliderNode_Press.png", + "res/cocosui/CCS/2.1/Default/SliderNode_Disable.png", + "res/cocosui/CCS/2.1/Default/Slider_PressBar.png", + "res/cocosui/CCS/2.1/Default/defaultParticle.plist", + "res/cocosui/CCS/2.1/Default/TextAtlas.png", + "res/cocosui/CCS/2.1/fonts_weapon_001-hd.png", + "res/cocosui/CCS/2.1/FNT/futura.fnt", + "res/cocosui/CCS/2.1/Default/defaultBMFont.fnt", + "res/cocosui/CCS/2.1/FNT/Heiti18.fnt", + + "res/Particles/BoilingFoam.plist", + "res/cocosui/CustomImageViewTest/NewProject_2_1.ExportJson", + "res/cocosui/CustomImageViewTest/NewProject_20.plist", + "res/cocosui/CustomImageViewTest/NewProject_20.png" +]; + +var g_ui = [ + "res/cocosui/switch-mask.png", + "res/cocosui/animationbuttonnormal.png", + "res/cocosui/animationbuttonpressed.png", + "res/cocosui/arrow.png", + "res/cocosui/b11.png", + "res/cocosui/backtotopnormal.png", + "res/cocosui/backtotoppressed.png", + "res/cocosui/bitmapFontTest2.fnt", + "res/cocosui/bitmapFontTest2.png", + "res/cocosui/button.png", + "res/cocosui/buttonHighlighted.png", + "res/cocosui/ccicon.png", + "res/cocosui/check_box_active.png", + "res/cocosui/check_box_active_disable.png", + "res/cocosui/check_box_active_press.png", + "res/cocosui/check_box_normal.png", + "res/cocosui/check_box_normal_disable.png", + "res/cocosui/check_box_normal_press.png", + "res/cocosui/CloseNormal.png", + "res/cocosui/CloseSelected.png", + "res/cocosui/green_edit.png", + "res/cocosui/grossini-aliases.png", + "res/cocosui/Hello.png", + "res/cocosui/labelatlas.png", + "res/cocosui/loadingbar.png", + {type:"font", name:"Marker Felt", srcs:["res/cocosui/Marker Felt.ttf"]}, + "res/cocosui/scrollviewbg.png", + "res/cocosui/slidbar.png", + "res/cocosui/sliderballnormal.png", + "res/cocosui/sliderballpressed.png", + "res/cocosui/sliderProgress.png", + "res/cocosui/sliderProgress2.png", + "res/cocosui/sliderThumb.png", + "res/cocosui/sliderTrack.png", + "res/cocosui/sliderTrack2.png", + "res/cocosui/slider_bar_active_9patch.png", + "res/cocosui/UITest/b1.png", + "res/cocosui/UITest/b2.png", + "res/cocosui/UITest/background.png", + "res/cocosui/UITest/buttonBackground.png", + "res/cocosui/UITest/f1.png", + "res/cocosui/UITest/f2.png", + "res/cocosui/UITest/r1.png", + "res/cocosui/UITest/r2.png", + "res/cocosui/UITest/ribbon.png", + "res/cocosui/UITest/UITest.json", + "res/cocosui/100/100.ExportJson", + "res/cocosui/100/1000.plist", + "res/cocosui/100/1000.png", + s_s9s_blocks9_plist, + "res/cocosui/CloseSelected.png" +]; + +var g_performace = [ + "res/animations/crystals.plist", + "res/animations/crystals.png", + "res/Images/fps_images.png", + "res/Images/spritesheet1.png", + "res/Images/sprites_test/sprite-0-0.png", + "res/Images/sprites_test/sprite-0-1.png", + "res/Images/sprites_test/sprite-0-2.png", + "res/Images/sprites_test/sprite-0-3.png", + "res/Images/sprites_test/sprite-0-4.png", + "res/Images/sprites_test/sprite-0-5.png", + "res/Images/sprites_test/sprite-0-6.png", + "res/Images/sprites_test/sprite-0-7.png", + "res/Images/sprites_test/sprite-1-0.png", + "res/Images/sprites_test/sprite-1-1.png", + "res/Images/sprites_test/sprite-1-2.png", + "res/Images/sprites_test/sprite-1-3.png", + "res/Images/sprites_test/sprite-1-4.png", + "res/Images/sprites_test/sprite-1-5.png", + "res/Images/sprites_test/sprite-1-6.png", + "res/Images/sprites_test/sprite-1-7.png", + "res/Images/sprites_test/sprite-2-0.png", + "res/Images/sprites_test/sprite-2-1.png", + "res/Images/sprites_test/sprite-2-2.png", + "res/Images/sprites_test/sprite-2-3.png", + "res/Images/sprites_test/sprite-2-4.png", + "res/Images/sprites_test/sprite-2-5.png", + "res/Images/sprites_test/sprite-2-6.png", + "res/Images/sprites_test/sprite-2-7.png", + "res/Images/sprites_test/sprite-3-0.png", + "res/Images/sprites_test/sprite-3-1.png", + "res/Images/sprites_test/sprite-3-2.png", + "res/Images/sprites_test/sprite-3-3.png", + "res/Images/sprites_test/sprite-3-4.png", + "res/Images/sprites_test/sprite-3-5.png", + "res/Images/sprites_test/sprite-3-6.png", + "res/Images/sprites_test/sprite-3-7.png", + "res/Images/sprites_test/sprite-4-0.png", + "res/Images/sprites_test/sprite-4-1.png", + "res/Images/sprites_test/sprite-4-2.png", + "res/Images/sprites_test/sprite-4-3.png", + "res/Images/sprites_test/sprite-4-4.png", + "res/Images/sprites_test/sprite-4-5.png", + "res/Images/sprites_test/sprite-4-6.png", + "res/Images/sprites_test/sprite-4-7.png", + "res/Images/sprites_test/sprite-5-0.png", + "res/Images/sprites_test/sprite-5-1.png", + "res/Images/sprites_test/sprite-5-2.png", + "res/Images/sprites_test/sprite-5-3.png", + "res/Images/sprites_test/sprite-5-4.png", + "res/Images/sprites_test/sprite-5-5.png", + "res/Images/sprites_test/sprite-5-6.png", + "res/Images/sprites_test/sprite-5-7.png", + "res/Images/sprites_test/sprite-6-0.png", + "res/Images/sprites_test/sprite-6-1.png", + "res/Images/sprites_test/sprite-6-2.png", + "res/Images/sprites_test/sprite-6-3.png", + "res/Images/sprites_test/sprite-6-4.png", + "res/Images/sprites_test/sprite-6-5.png", + "res/Images/sprites_test/sprite-6-6.png", + "res/Images/sprites_test/sprite-6-7.png", + "res/Images/sprites_test/sprite-7-0.png", + "res/Images/sprites_test/sprite-7-1.png", + "res/Images/sprites_test/sprite-7-2.png", + "res/Images/sprites_test/sprite-7-3.png", + "res/Images/sprites_test/sprite-7-4.png", + "res/Images/sprites_test/sprite-7-5.png", + "res/Images/sprites_test/sprite-7-6.png", + "res/Images/sprites_test/sprite-7-7.png" +]; + +var g_tilemaps = [ + //image + s_fixedOrthoTest2Png, + s_hexaTilesPng, + s_isoTestPng, + s_isoTest2Png, + s_isoPng, + s_orthoTest1BwPng, + s_orthoTest1Png, + s_tilesHdPng, + s_tmwDesertSpacingHdPng, + s_tmwDesertSpacingPng, + s_tilesPng, + s_tileISOOffsetPng, + s_tileISOOffsetTmx, + "res/TileMaps/ortho-test2.png", + + //tmx + "res/TileMaps/orthogonal-test1.tmx", + "res/TileMaps/orthogonal-test1.tsx", + "res/TileMaps/orthogonal-test2.tmx", + "res/TileMaps/orthogonal-test3.tmx", + "res/TileMaps/orthogonal-test4.tmx", + "res/TileMaps/orthogonal-test4-hd.tmx", + "res/TileMaps/orthogonal-test5.tmx", + "res/TileMaps/orthogonal-test6.tmx", + "res/TileMaps/orthogonal-test6-hd.tmx", + "res/TileMaps/hexa-test.tmx", + "res/TileMaps/iso-test.tmx", + "res/TileMaps/iso-test1.tmx", + "res/TileMaps/iso-test2.tmx", + "res/TileMaps/iso-test2-uncompressed.tmx", + "res/TileMaps/ortho-objects.tmx", + "res/TileMaps/iso-test-objectgroup.tmx", + "res/TileMaps/iso-test-zorder.tmx", + "res/TileMaps/orthogonal-test-zorder.tmx", + "res/TileMaps/iso-test-vertexz.tmx", + "res/TileMaps/orthogonal-test-vertexz.tmx", + "res/TileMaps/iso-test-movelayer.tmx", + "res/TileMaps/orthogonal-test-movelayer.tmx", + "res/TileMaps/iso-test-bug787.tmx", + "res/TileMaps/test-object-layer.tmx", + "res/TileMaps/ortho-tile-property.tmx", + "res/TileMaps/ortho-rotation-test.tmx" +]; + +var g_spine = [ + "res/skeletons/spineboy.atlas", + "res/skeletons/spineboy.json", + "res/skeletons/spineboy.png", + "res/skeletons/sprite.png", + "res/skeletons/goblins-ffd.png", + "res/skeletons/goblins-ffd.atlas", + "res/skeletons/goblins-ffd.json" +]; + +var g_ccs2 = [ + "res/ActionTimeline/boy_1.csb", + "res/ActionTimeline/armature/Cowboy0.plist", + "res/cocosui/UIEditorTest/UILabelBMFont_Editor/GUI/missing-font.fnt", + "res/cocosui/UIEditorTest/UILabelBMFont_Editor/GUI/missing-font.png" +]; \ No newline at end of file diff --git a/tools/bindings-generator b/tools/bindings-generator index af67671bfd..ca96fc9301 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit af67671bfd8394e8a5e13d702e57f3fd7eaa5c78 +Subproject commit ca96fc9301c1fd7eceff05f033eb96cb09d74a47 diff --git a/tools/tojs/README.mdown b/tools/tojs/README.mdown new file mode 100644 index 0000000000..9b31226156 --- /dev/null +++ b/tools/tojs/README.mdown @@ -0,0 +1,57 @@ +How to Use bindings-generator +================== + +On Windows: +------------ + +* Make sure that you have installed `android-ndk-r9b`. +* Download python2.7.3 (32bit) from (http://www.python.org/ftp/python/2.7.3/python-2.7.3.msi). +* Add the installed path of python (e.g. C:\Python27) to windows environment variable named 'PATH'. +* Download pyyaml from http://pyyaml.org/download/pyyaml/PyYAML-3.10.win32-py2.7.exe and install it. +* Download pyCheetah from https://raw.github.com/dumganhar/cocos2d-x/download/downloads/Cheetah.zip, unzip it to "C:\Python27\Lib\site-packages" +* Set environment variables (`NDK_ROOT`) +* Go to "cocos2d-x/tools/tojs" folder, and run "genbindings.py". The generated codes will be under "cocos\scripting\auto-generated\js-bindings". + + +On MAC: +---------- + +* The OSX 10.9 has a built-in python2.7 and if your os don't have python2.7 then use [Homebrew](http://brew.sh/) to install the python and use pip install the python dependencies. +
+	brew install python
+
+ +* Install python dependices by pip. +
+    sudo easy_install pip
+    sudo pip install PyYAML
+	sudo pip install Cheetah
+
+ +* Download [64bit ndk-r9b-x86_64](http://dl.google.com/android/ndk/android-ndk-r9b-darwin-x86_64.tar.bz2) from [google](http://developer.android.com/tools/sdk/ndk/index.html) +* Run +
+	export NDK_ROOT=/path/to/android-ndk-r9b
+    ./genbindings.py
+
+ + +On Ubuntu Linux 12.04 64bit +------------ + +* Install python +
+	sudo apt-get install python2.7
+
+* Install python dependices by pip. +
+	sudo apt-get install python-pip
+	sudo pip install PyYAML
+	sudo pip install Cheetah
+
+* Download [64bit ndk-r9b-x86_64]( https://dl.google.com/android/ndk/android-ndk-r9b-linux-x86_64.tar.bz2) from [google](http://developer.android.com/tools/sdk/ndk/index.html) +* Go to "cocos2d-x/tools/tojs", Run +
+	export NDK_ROOT=/path/to/android-ndk-r9b
+    ./genbindings.py
+
diff --git a/tools/tojs/cocos2dx.ini b/tools/tojs/cocos2dx.ini new file mode 100644 index 0000000000..27a5f7718e --- /dev/null +++ b/tools/tojs/cocos2dx.ini @@ -0,0 +1,187 @@ +[cocos2d-x] +# the prefix to be added to the generated functions. You might or might not use this in your own +# templates +prefix = cocos2dx + +# 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 -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/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 -U __SSE__ + +cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/platform/android +cocos_flags = -DANDROID + +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/cocos2d.h %(cocosdir)s/cocos/audio/include/SimpleAudioEngine.h %(cocosdir)s/cocos/2d/CCProtectedNode.h %(cocosdir)s/cocos/base/CCAsyncTaskPool.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 = New.* Sprite SpriteBatchNode SpriteFrame SpriteFrameCache Scene Node.* Director Layer.* Menu.* Touch .*Action.* Move.* Rotate.* Blink.* Tint.* Sequence Repeat.* Fade.* Ease.* Scale.* Transition.* Spawn ReverseTime Animate AnimationFrame Animation AnimationCache Flip.* Delay.* Skew.* Jump.* Place.* Show.* Progress.* PointArray ToggleVisibility.* RemoveSelf Hide Particle.* Label.* Atlas.* TextureCache.* Texture2D Cardinal.* CatmullRom.* ParallaxNode TileMap.* TMX.* CallFunc CallFuncN RenderTexture GridAction Grid3DAction Grid3D TiledGrid3D GridBase$ .+Grid Shaky3D Waves3D FlipX3D FlipY3D Lens3D Ripple3D PageTurn3D ShakyTiles3D ShatteredTiles3D WavesTiles3D JumpTiles3D Speed ActionManager Set SimpleAudioEngine Scheduler Orbit.* Follow.* Bezier.* CardinalSpline.* Camera.* DrawNode Liquid$ Waves$ ShuffleTiles$ TurnOffTiles$ Split.* Twirl$ FileUtils$ GLProgram GLProgramCache Application ClippingNode MotionStreak TextFieldTTF GLViewProtocol GLView Component ComponentContainer __NodeRGBA __LayerRGBA SAXParser Event(?!.*(Physics).*).* Device Configuration ProtectedNode GLProgramState Image .*Light$ AsyncTaskPool + +classes_need_extend = Node __NodeRGBA Layer.* Sprite SpriteBatchNode SpriteFrame Menu MenuItem.* Scene DrawNode Component .*Action.* GridBase Grid3D TiledGrid3D MotionStreak ParticleBatchNode ParticleSystem TextFieldTTF RenderTexture TileMapAtlas TMXLayer TMXTiledMap TMXMapInfo TransitionScene ProgressTimer ParallaxNode Label.* GLProgram + +# 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 = Node::[^setPosition$ setGLServerState description getUserObject .*UserData getGLServerState .*schedule setContentSize setAnchorPoint setColor pause resume setAdditionalTransform], + Sprite::[getQuad ^setPosition$], + NodeGrid::[setGrid], + SpriteBatchNode::[getDescendants], + MotionStreak::[draw update], + DrawNode::[drawPolygon listenBackToForeground], + Director::[getAccelerometer getProjection getFrustum getRenderer getConsole], + Layer.*::[didAccelerate keyPressed keyReleased], + Menu.*::[.*Target getSubItems create initWithItems alignItemsInRows alignItemsInColumns], + MenuItem.*::[create setCallback], + MenuItemToggle::[initWithCallback], + Copying::[*], + LabelProtocol::[*], + LabelTextFormatProtocol::[*], + Label::[getLettersInfo createWithTTF setTTFConfig getFontAtlas listenToBackground listenToFontAtlasPurge], + .*Delegate::[*], + PoolManager::[*], + Texture2D::[initWithPVRTCData addPVRTCImage releaseData setTexParameters initWithData keepData getPixelFormatInfoMap updateWithData], + Set::[begin end acceptVisitor], + IMEDispatcher::[*], + Thread::[*], + Profiler::[*], + ProfilingTimer::[*], + CallFunc::[create initWithFunction (g|s)etTargetCallback], + CallFuncN::[create initWithFunction], + SAXParser::[(?!(init))], + SAXDelegator::[*], + Color3bObject::[*], + TouchDispatcher::[*], + EGLTouchDelegate::[*], + ScriptEngineManager::[*], + KeypadHandler::[*], + Invocation::[*], + GLView::[end swapBuffers getAllTouches], + GLViewProtocol::[pollInputEvents handleTouches.* setScissorInPoints getScissorRect isScissorEnabled swapBuffers], + SchedulerScriptHandlerEntry::[*], + Size::[*], + Point::[*], + PointArray::[*], + Rect::[*], + String::[*], + Data::[*], + Dictionary::[*], + Array::[*], + Range::[*], + NotificationObserver::[*], + Image::[initWithString initWithImageData], + Sequence::[create], + Spawn::[create], + RotateTo::[calculateAngles], + GLProgram::[getProgram setUniformLocationWith(1|2|3|4)fv setUniformLocationWith(2|3|4)iv setUniformLocationWithMatrix(2|3|4)fv], + GLProgramState::[setUniformVec4 setVertexAttribPointer], + Grid3DAction::[create actionWith.* vertex originalVertex (g|s)etVertex getOriginalVertex], + Grid3D::[vertex originalVertex (g|s)etVertex getOriginalVertex], + TiledGrid3DAction::[create actionWith.* tile originalTile getOriginalTile (g|s)etTile], + TiledGrid3D::[tile originalTile getOriginalTile (g|s)etTile], + TMXLayer::[getTiles], + TMXMapInfo::[startElement endElement textHandler], + ParticleSystemQuad::[postStep setBatchNode draw setTexture$ setTotalParticles updateQuadWithParticle setupIndices listenBackToForeground initWithTotalParticles particleWithFile node], + LayerMultiplex::[create layerWith.* initWithLayers], + CatmullRom.*::[create actionWithDuration initWithDuration], + Bezier.*::[create actionWithDuration initWithDuration], + CardinalSpline.*::[create actionWithDuration setPoints initWithDuration], + Scheduler::[pause resume ^unschedule$ unscheduleUpdate unscheduleAllForTarget schedule isTargetPaused isScheduled], + TextureCache::[addPVRTCImage], + *::[copyWith.* onEnter.* onExit.* ^description$ getObjectType onTouch.* onAcc.* onKey.* onRegisterTouchListener], + FileUtils::[getFileData getDataFromFile setFilenameLookupDictionary destroyInstance getFullPathCache], + Application::[^application.* ^run$ getCurrentLanguageCode setAnimationInterval], + Camera::[getEyeXYZ getCenterXYZ getUpXYZ], + ccFontDefinition::[*], + NewTextureAtlas::[*], + RenderTexture::[listenToBackground listenToForeground saveToFile], + TextFieldTTF::[(g|s)etDelegate], + EventListenerVector::[*], + EventListener(Touch|Keyboard|Mouse|Focus).*::[create], + EventTouch::[(s|g)etTouches], + EventKeyboard::[*], + Device::[getTextureDataForText], + EventDispatcher::[dispatchCustomEvent], + EventCustom::[getUserData setUserData], + Component::[serialize], + EventListenerCustom::[init], + EventListener::[init], + Scene::[getCameras getLights initWithPhysics createWithPhysics getPhysicsWorld], + Animate3D::[*], + Sprite3D::[*], + AttachNode::[*], + Animation3D::[*], + Skeleton3D::[*], + Mesh::[*], + Animation3DCache::[*], + Sprite3DMaterialCache::[*], + Sprite3DCache::[*], + Bone3D::[*], + Device::[getTextureDataForText], + BillBoard::[*], + Camera::[unproject isVisibleInFrustum], + ClippingNode::[init] + +rename_functions = SpriteFrameCache::[addSpriteFramesWithFile=addSpriteFrames getSpriteFrameByName=getSpriteFrame], + MenuItemFont::[setFontNameObj=setFontName setFontSizeObj=setFontSize getFontSizeObj=getFontSize getFontNameObj=getFontName], + ProgressTimer::[setReverseProgress=setReverseDirection], + Animation::[create=createWithAnimationFrames], + AnimationCache::[addAnimationsWithFile=addAnimations], + GLProgram::[initWithByteArrays=initWithString initWithFilenames=init setUniformLocationWith1i=setUniformLocationI32 bindAttribLocation=addAttribute], + Node::[getGLProgram=getShaderProgram setGLProgram=setShaderProgram getPositionZ=getVertexZ setPositionZ=setVertexZ removeFromParentAndCleanup=removeFromParent removeAllChildrenWithCleanup=removeAllChildren setRotationSkewX=setRotationX setRotationSkewY=setRotationY getRotationSkewX=getRotationX getRotationSkewY=getRotationY getNodeToParentTransform=getNodeToParentTransform3D getParentToNodeTransform=getParentToNodeTransform3D getNodeToWorldTransform=getNodeToWorldTransform3D getWorldToNodeTransform=getWorldToNodeTransform3D getNodeToWorldAffineTransform=getNodeToWorldTransform getNodeToParentAffineTransform=getNodeToParentTransform getParentToNodeAffineTransform=getParentToNodeTransform getWorldToNodeAffineTransform=getWorldToNodeTransform], + LabelAtlas::[create=_create], + Sprite::[getPositionZ=getVertexZ setPositionZ=setVertexZ], + SpriteBatchNode::[removeAllChildrenWithCleanup=removeAllChildren], + DrawNode::[drawQuadraticBezier=drawQuadBezier], + FileUtils::[loadFilenameLookupDictionaryFromFile=loadFilenameLookup], + SimpleAudioEngine::[preloadBackgroundMusic=preloadMusic setBackgroundMusicVolume=setMusicVolume getBackgroundMusicVolume=getMusicVolume playBackgroundMusic=playMusic stopBackgroundMusic=stopMusic pauseBackgroundMusic=pauseMusic resumeBackgroundMusic=resumeMusic rewindBackgroundMusic=rewindMusic isBackgroundMusicPlaying=isMusicPlaying willPlayBackgroundMusic=willPlayMusic], + EventDispatcher::[addCustomEventListener=addCustomListener removeEventListener=removeListener removeEventListenersForType=removeListeners removeEventListenersForTarget=removeListeners removeCustomEventListeners=removeCustomListeners removeAllEventListeners=removeAllListeners pauseEventListenersForTarget=pauseTarget resumeEventListenersForTarget=resumeTarget], + EventMouse::[getMouseButton=getButton setMouseButton=setButton setCursorPosition=setLocation getCursorX=getLocationX getCursorY=getLocationY], + Configuration::[getInfo=dumpInfo], + ComponentContainer::[get=getComponent], + LayerColor::[initWithColor=init], + GLProgramCache::[getGLProgram=getProgram addGLProgram=addProgram reloadDefaultGLPrograms=reloadDefaultShaders loadDefaultGLPrograms=loadDefaultShaders], + TextFieldTTF::[textFieldWithPlaceHolder=create], + Texture2D::[getGLProgram=getShaderProgram setGLProgram=setShaderProgram], + Speed::[setSpeed=_setSpeed getSpeed=_getSpeed] + +rename_classes = ParticleSystemQuad::ParticleSystem, + SimpleAudioEngine::AudioEngine, + __NodeRGBA::NodeRGBA, + __LayerRGBA::LayerRGBA, + SAXParser::PlistParser, + GLProgramCache::ShaderCache, + CallFunc::_CallFunc, + CallFuncN::CallFunc + +# 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 = Node Director SimpleAudioEngine FileUtils TMXMapInfo Application GLViewProtocol SAXParser Configuration + +# base classes which will be skipped when their sub-classes found them. +base_classes_to_skip = Ref 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 GLViewProtocol GLView ComponentContainer SAXParser Configuration EventListener BaseLight AsyncTaskPool + +# 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_3d.ini b/tools/tojs/cocos2dx_3d.ini new file mode 100644 index 0000000000..c8f598bc91 --- /dev/null +++ b/tools/tojs/cocos2dx_3d.ini @@ -0,0 +1,68 @@ +[cocos2dx_3d] +# the prefix to be added to the generated functions. You might or might not use this in your own +# templates +prefix = cocos2dx_3d + +# 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 = jsb + +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 -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/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 -U __SSE__ + +cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/platform/android +cocos_flags = -DANDROID + +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/cocos2d.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 = Animate3D Sprite3D Animation3D Skeleton3D ^Mesh$ AttachNode BillBoard Sprite3DCache TextureCube Skybox Terrain + +classes_need_extend = Sprite3D + +# 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 = Skeleton3D::[create], + Sprite3D::[getAABB getMeshArrayByName createAsync], + Mesh::[create getMeshCommand getAABB getDefaultGLProgram getMeshVertexAttribute], + Sprite3DCache::[addSprite3DData getSpriteData], + Animation3D::[getBoneCurves], + TextureCube::[setTexParameters], + Terrain::[getAABB getQuadTree create] + + +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 = Clonable Ref + +# classes that create no constructor +# Set is special and we will use a hand-written constructor +abstract_classes = Sprite3DCache + +# 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_3d_ext.ini b/tools/tojs/cocos2dx_3d_ext.ini new file mode 100644 index 0000000000..880f537410 --- /dev/null +++ b/tools/tojs/cocos2dx_3d_ext.ini @@ -0,0 +1,61 @@ +[cocos2dx_3d_extension] +# the prefix to be added to the generated functions. You might or might not use this in your own +# templates +prefix = cocos2dx_3d_extension + +# 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 = jsb + +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 -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/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 -U __SSE__ + +cocos_headers = -I%(cocosdir)s -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/platform/android -I%(cocosdir)s/external +cocos_flags = -DANDROID + +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 + +# 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 = ParticleSystem3D PUParticleSystem3D + +classes_need_extend = + +# 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 = ParticleSystem3D::[draw setEmitter setRender .*Affector getParticlePool], + PUParticleSystem3D::[get.*ParticlePool forceEmission addEmitter getAffector getEmitter addListener removeListener .*Observer .*BehaviourTemplate makeParticleLocal] + +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 = + +# 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_builder.ini b/tools/tojs/cocos2dx_builder.ini new file mode 100644 index 0000000000..8b0ee4f904 --- /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 -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/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 -U __SSE__ + +cocos_headers = -I%(cocosdir)s -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s/cocos/platform/android + +cocos_flags = -DANDROID + +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 addNode getSequences getDelegate], + .*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 = Ref + +# 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_extension.ini b/tools/tojs/cocos2dx_extension.ini new file mode 100644 index 0000000000..8bb67dbbc9 --- /dev/null +++ b/tools/tojs/cocos2dx_extension.ini @@ -0,0 +1,75 @@ +[cocos2dx_extension] +# the prefix to be added to the generated functions. You might or might not use this in your own +# templates +prefix = cocos2dx_extension + +# 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 -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/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 -U __SSE__ + +cocos_headers = -I%(cocosdir)s -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/platform/android -I%(cocosdir)s/external + +cocos_flags = -DANDROID + +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 + +# 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 = AssetsManagerEx Manifest EventListenerAssetsManagerEx EventAssetsManagerEx Control.* ControlButton.* ScrollView$ TableView$ TableViewCell$ + +# 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 = ScrollView::[(g|s)etDelegate$], + .*Delegate::[*], + .*Loader.*::[*], + *::[^visit$ copyWith.* onEnter.* onExit.* ^description$ getObjectType .*HSV onTouch.* onAcc.* onKey.* onRegisterTouchListener], + TableView::[create (g|s)etDataSource$ (g|s)etDelegate], + Control::[removeHandleOfControlEvent addHandleOfControlEvent], + ControlUtils::[*], + ControlSwitchSprite::[*], + ActionManagerEx::[initWithDictionary], + ActionNode::[initWithDictionary], + ActionObject::[initWithDictionary], + Manifest::[getAssets], + AssetsManagerEx::[getFailedAssets updateAssets] + +rename_functions = + +rename_classes = AssetsManagerEx::AssetsManager, + EventAssetsManagerEx::EventAssetsManager, + EventListenerAssetsManagerEx::EventListenerAssetsManager + +# 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 = Ref + +# classes that create no constructor +# Set is special and we will use a hand-written constructor +abstract_classes = Manifest + +# 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 + +classes_need_extend = ScrollView TableView TableViewCell ControlButton ControlStepper ControlSwitch ControlSlider ControlColourPicker ControlPotentiometer diff --git a/tools/tojs/cocos2dx_spine.ini b/tools/tojs/cocos2dx_spine.ini new file mode 100644 index 0000000000..bd5762aca1 --- /dev/null +++ b/tools/tojs/cocos2dx_spine.ini @@ -0,0 +1,43 @@ +[cocos2dx_spine] +prefix = cocos2dx_spine + +target_namespace = sp + +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 -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/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 -U __SSE__ -DNO_JS_ASSERT -DUINT32_MAX=0xffffffff + +cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s/cocos/platform/android -I%(cocosdir)s/external/spidermonkey/include/android + +cocos_flags = -DANDROID + +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 + +headers = %(cocosdir)s/cocos/editor-support/spine/spine-cocos2dx.h %(jsbdir)s/manual/spine/jsb_cocos2dx_spine_manual.h + +classes = SkeletonRenderer SkeletonAnimation + +classes_need_extend = SkeletonAnimation + +skip = SkeletonRenderer::[createWithData findBone findSlot getAttachment], + SkeletonAnimation::[createWithData getCurrent setAnimation addAnimation] + +remove_prefix = + +classes_have_no_parents = + +base_classes_to_skip = + +abstract_classes = + +script_control_cpp = + +rename_functions = SkeletonAnimation::[createWithFile=create], + SkeletonRenderer::[createWithFile=create] + +rename_classes = SkeletonRenderer::Skeleton \ No newline at end of file diff --git a/tools/tojs/cocos2dx_studio.ini b/tools/tojs/cocos2dx_studio.ini new file mode 100644 index 0000000000..a5cd6d2cbf --- /dev/null +++ b/tools/tojs/cocos2dx_studio.ini @@ -0,0 +1,82 @@ +[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 -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/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 -U __SSE__ -DNO_JS_ASSERT -DUINT32_MAX=0xffffffff + +cocos_headers = -I%(cocosdir)s/external -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s/cocos/platform/android -I%(jsbdir)s/manual -I%(cocosdir)s/external/spidermonkey/include/android + +cocos_flags = -DANDROID + +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/editor-support/cocostudio/CCObjectExtensionData.h %(jsbdir)s/manual/cocostudio/jsb_cocos2dx_studio_conversions.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 ColliderDetector ColliderBody ArmatureDataManager InputDelegate ComController ComAudio ComAttribute ComRender ActionManagerEx SceneReader GUIReader BatchNode ActionObject BaseData Tween ColliderFilter DisplayManager DecorativeDisplay ProcessBase AnimationData MovementData ContourData TextureData ActionTimelineData ActionTimeline ActionTimelineCache Frame TextureFrame RotationFrame SkewFrame VisibleFrame RotationSkewFrame PositionFrame ScaleFrame AnchorPointFrame InnerActionFrame ColorFrame AlphaFrame EventFrame ZOrderFrame NodeReader Timeline CSLoader ObjectExtensionData + +# 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 = *::[createInstance ^visit$ copyWith.* onEnter.* onExit.* ^description$ getObjectType .*HSV onTouch.* onAcc.* onKey.* onRegisterTouchListener (s|g)etUserObject ccTouch.*], + InputDelegate::[didAccelerate on.*], + GUIReader::[*], + ComAttribute::[getDict], + BatchNode::[init draw], + Armature::[createBone updateBlendType getBody setBody getShapeList], + Skin::[getSkinData setSkinData], + ArmatureAnimation::[updateHandler updateFrameData frameEvent setMovementEventCallFunc setFrameEventCallFunc], + ArmatureDataManager::[getTextureDatas], + ActionManagerEx::[initWithDictionary purgeActionManager], + Bone::[getTweenData getBoneData], + BaseData::[copy subtract], + ColliderFilter::[updateShape], + Tween::[(s|g)etMovementBoneData], + ActionNode::[initWithDictionary], + ActionObject::[initWithDictionary], + ColliderDetector::[addContourData.* removeContourData], + ColliderBody::[getContourData getCalculatedVertexList], + SceneReader::[*], + CSLoader::[*], + ActionTimelineCache::[*], + Frame::[(s|g)etEasingParams] + +rename_functions = Armature::[getBoundingBox=boundingBox] + +rename_classes = ActionManagerEx::ActionManager + +# 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 = InputDelegate SceneReader DecorativeDisplay ActionTimelineCache NodeReader CSLoader + +# base classes which will be skipped when their sub-classes found them. +base_classes_to_skip = Ref + +# classes that create no constructor +# Set is special and we will use a hand-written constructor +abstract_classes = ColliderDetector ColliderBody ArmatureDataManager InputDelegate InputDelegate ActionManagerEx SceneReader GUIReader BatchNode ColliderFilter DecorativeDisplay ActionTimelineCache NodeReader CSLoader + +# 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 + +classes_need_extend = Armature ComController diff --git a/tools/tojs/cocos2dx_ui.ini b/tools/tojs/cocos2dx_ui.ini new file mode 100644 index 0000000000..fd91a94c01 --- /dev/null +++ b/tools/tojs/cocos2dx_ui.ini @@ -0,0 +1,73 @@ +[cocos2dx_ui] +# the prefix to be added to the generated functions. You might or might not use this in your own +# templates +prefix = cocos2dx_ui + +# 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 = ccui + +# the native namespace in which this module locates, this parameter is used for avoid conflict of the same class name in different modules, as "cocos2d::Label" <-> "cocos2d::ui::Label". +cpp_namespace = cocos2d::ui + +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 -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/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 -U __SSE__ + +cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/editor-support -I%(cocosdir)s/cocos/platform/android + +cocos_flags = -DANDROID + +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/ui/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 = Helper Layout Widget Button CheckBox ImageView Text TextAtlas TextBMFont RichText RichElement RichElementText RichElementImage RichElementCustomNode LoadingBar Slider TextField UICCTextField ScrollView PageView ListView LayoutParameter LinearLayoutParameter RelativeLayoutParameter VideoPlayer HBox VBox RelativeBox Scale9Sprite EditBox$ LayoutComponent + +classes_need_extend = Layout Widget Button CheckBox ImageView Text TextAtlas TextBMFont RichText RichElement RichElementText RichElementImage RichElementCustomNode LoadingBar Slider TextField ScrollView PageView ListView VideoPlayer HBox VBox RelativeBox Scale9Sprite EditBox$ LayoutComponent + +# 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 = *::[^visit$ copyWith.* onEnter.* onExit.* ^description$ getObjectType .*HSV onTouch.* onAcc.* onKey.* onRegisterTouchListener ccTouch.* addEventListener addTouchEventListener], + Widget::[(s|g)etUserObject], + Layer::[getInputManager], + LayoutParameter::[(s|g)etMargin], + ImageView::[doubleClickEvent checkDoubleClick], + RichText::[getVirtualRendererSize], + EditBox::[(g|s)etDelegate ^keyboard.* touchDownAction getScriptEditBoxHandler registerScriptEditBoxHandler unregisterScriptEditBoxHandler] + +rename_functions = Widget::[init=_init], + ImageView::[init=_init], + EditBox::[getText=getString setText=setString] + +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 = Helper + +# base classes which will be skipped when their sub-classes found them. +base_classes_to_skip = Ref + +# classes that create no constructor +# Set is special and we will use a hand-written constructor +abstract_classes = Helper LayoutManager + +# 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.py b/tools/tojs/genbindings.py new file mode 100755 index 0000000000..d02e29cc89 --- /dev/null +++ b/tools/tojs/genbindings.py @@ -0,0 +1,189 @@ +#!/usr/bin/python + +# This script is used to generate luabinding glue codes. +# Android ndk version must be ndk-r9b. + + +import sys +import os, os.path +import shutil +import ConfigParser +import subprocess +import re +from contextlib import contextmanager + + +def _check_ndk_root_env(): + ''' 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 _check_python_bin_env(): + ''' Checking the environment PYTHON_BIN, which will be used for building + ''' + + try: + PYTHON_BIN = os.environ['PYTHON_BIN'] + except Exception: + print "PYTHON_BIN not defined, use current python." + PYTHON_BIN = sys.executable + + return PYTHON_BIN + + +class CmdError(Exception): + pass + + +@contextmanager +def _pushd(newDir): + previousDir = os.getcwd() + os.chdir(newDir) + yield + os.chdir(previousDir) + +def _run_cmd(command): + ret = subprocess.call(command, shell=True) + if ret != 0: + message = "Error running command" + raise CmdError(message) + +def main(): + + cur_platform= '??' + llvm_path = '??' + ndk_root = _check_ndk_root_env() + # del the " in the path + ndk_root = re.sub(r"\"", "", ndk_root) + python_bin = _check_python_bin_env() + + platform = sys.platform + if platform == 'win32': + cur_platform = 'windows' + elif platform == 'darwin': + cur_platform = platform + elif 'linux' in platform: + cur_platform = 'linux' + else: + print 'Your platform is not supported!' + sys.exit(1) + + if platform == 'win32': + x86_llvm_path = os.path.abspath(os.path.join(ndk_root, 'toolchains/llvm-3.3/prebuilt', '%s' % cur_platform)) + if not os.path.exists(x86_llvm_path): + x86_llvm_path = os.path.abspath(os.path.join(ndk_root, 'toolchains/llvm-3.4/prebuilt', '%s' % cur_platform)) + else: + x86_llvm_path = os.path.abspath(os.path.join(ndk_root, 'toolchains/llvm-3.3/prebuilt', '%s-%s' % (cur_platform, 'x86'))) + if not os.path.exists(x86_llvm_path): + x86_llvm_path = os.path.abspath(os.path.join(ndk_root, 'toolchains/llvm-3.4/prebuilt', '%s-%s' % (cur_platform, 'x86'))) + x64_llvm_path = os.path.abspath(os.path.join(ndk_root, 'toolchains/llvm-3.3/prebuilt', '%s-%s' % (cur_platform, 'x86_64'))) + if not os.path.exists(x64_llvm_path): + x64_llvm_path = os.path.abspath(os.path.join(ndk_root, 'toolchains/llvm-3.4/prebuilt', '%s-%s' % (cur_platform, 'x86_64'))) + + if os.path.isdir(x86_llvm_path): + llvm_path = x86_llvm_path + elif os.path.isdir(x64_llvm_path): + llvm_path = x64_llvm_path + else: + print 'llvm toolchain not found!' + print 'path: %s or path: %s are not valid! ' % (x86_llvm_path, x64_llvm_path) + sys.exit(1) + + project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) + cocos_root = os.path.abspath(project_root) + jsb_root = os.path.abspath(os.path.join(project_root, 'cocos/scripting/js-bindings')) + cxx_generator_root = os.path.abspath(os.path.join(project_root, 'tools/bindings-generator')) + + # save config to file + config = ConfigParser.ConfigParser() + config.set('DEFAULT', 'androidndkdir', ndk_root) + config.set('DEFAULT', 'clangllvmdir', llvm_path) + config.set('DEFAULT', 'cocosdir', cocos_root) + config.set('DEFAULT', 'jsbdir', jsb_root) + config.set('DEFAULT', 'cxxgeneratordir', cxx_generator_root) + config.set('DEFAULT', 'extra_flags', '') + + # To fix parse error on windows, we must difine __WCHAR_MAX__ and undefine __MINGW32__ . + if platform == 'win32': + config.set('DEFAULT', 'extra_flags', '-D__WCHAR_MAX__=0x7fffffff -U__MINGW32__') + + conf_ini_file = os.path.abspath(os.path.join(os.path.dirname(__file__), 'userconf.ini')) + + print 'generating userconf.ini...' + with open(conf_ini_file, 'w') as configfile: + config.write(configfile) + + + # set proper environment variables + if 'linux' in platform or platform == 'darwin': + os.putenv('LD_LIBRARY_PATH', '%s/libclang' % cxx_generator_root) + if platform == 'win32': + path_env = os.environ['PATH'] + os.putenv('PATH', r'%s;%s\libclang;%s\tools\win32;' % (path_env, cxx_generator_root, cxx_generator_root)) + + + try: + + tojs_root = '%s/tools/tojs' % project_root + output_dir = '%s/cocos/scripting/js-bindings/auto' % project_root + + cmd_args = {'cocos2dx.ini' : ('cocos2d-x', 'jsb_cocos2dx_auto'), \ + 'cocos2dx_extension.ini' : ('cocos2dx_extension', 'jsb_cocos2dx_extension_auto'), \ + 'cocos2dx_builder.ini' : ('cocos2dx_builder', 'jsb_cocos2dx_builder_auto'), \ + 'cocos2dx_ui.ini' : ('cocos2dx_ui', 'jsb_cocos2dx_ui_auto'), \ + 'cocos2dx_studio.ini' : ('cocos2dx_studio', 'jsb_cocos2dx_studio_auto'), \ + 'cocos2dx_spine.ini' : ('cocos2dx_spine', 'jsb_cocos2dx_spine_auto'), \ + 'cocos2dx_3d.ini' : ('cocos2dx_3d', 'jsb_cocos2dx_3d_auto'), \ + 'cocos2dx_3d_ext.ini' : ('cocos2dx_3d_extension', 'jsb_cocos2dx_3d_extension_auto') + } + target = 'spidermonkey' + generator_py = '%s/generator.py' % cxx_generator_root + for key in cmd_args.keys(): + args = cmd_args[key] + cfg = '%s/%s' % (tojs_root, key) + print 'Generating bindings for %s...' % (key[:-4]) + command = '%s %s %s -s %s -t %s -o %s -n %s' % (python_bin, generator_py, cfg, args[0], target, output_dir, args[1]) + _run_cmd(command) + + if platform == 'win32': + with _pushd(output_dir): + _run_cmd('dos2unix *') + + + custom_cmd_args = {} + if len(custom_cmd_args) > 0: + output_dir = '%s/frameworks/custom/auto' % project_root + for key in custom_cmd_args.keys(): + args = custom_cmd_args[key] + cfg = '%s/%s' % (tojs_root, key) + print 'Generating bindings for %s...' % (key[:-4]) + command = '%s %s %s -s %s -t %s -o %s -n %s' % (python_bin, generator_py, cfg, args[0], target, output_dir, args[1]) + _run_cmd(command) + if platform == 'win32': + with _pushd(output_dir): + _run_cmd('dos2unix *') + + print '----------------------------------------' + print 'Generating javascript bindings succeeds.' + print '----------------------------------------' + + except Exception as e: + if e.__class__.__name__ == 'CmdError': + print '-------------------------------------' + print 'Generating javascript bindings fails.' + print '-------------------------------------' + sys.exit(1) + else: + raise + + +# -------------- main -------------- +if __name__ == '__main__': + main() diff --git a/tools/travis-scripts/generate-template-files.py b/tools/travis-scripts/generate-template-files.py index f629d71f68..43df0dfc87 100755 --- a/tools/travis-scripts/generate-template-files.py +++ b/tools/travis-scripts/generate-template-files.py @@ -42,8 +42,10 @@ class CocosFileList: self.rootDir = "" self.fileList_com=[] self.fileList_lua=[] + self.fileList_js=[] self.luaPath = ["cocos/scripting/lua-bindings", "external/lua", "tools/bindings-generator", "tools/tolua"] + self.jsPath = ["cocos/scripting/js-bindings", "external/spidermonkey", "tools/bindings-generator", "tools/tojs", "web"] def readIngoreFile(self, fileName): """ @@ -93,8 +95,17 @@ class CocosFileList: if relativePath.upper().find(luaPath.upper()) == 0: foundLuaModule = True break + + foundJSModule = False + for jsPath in self.jsPath: + if relativePath.upper().find(jsPath.upper()) == 0: + foundJSModule = True + break + if foundLuaModule: self.fileList_lua.append("%s/" %relativePath) + elif foundJSModule: + self.fileList_js.append("%s/" %relativePath) else: self.fileList_com.append("%s/" %relativePath) self.__parseFileList(path) @@ -123,8 +134,17 @@ class CocosFileList: if relativePath.upper().find(luaPath.upper()) == 0: foundLuaModule = True break + + foundJSModule = False + for jsPath in self.jsPath: + if relativePath.upper().find(jsPath.upper()) == 0: + foundJSModule = True + break + if foundLuaModule: self.fileList_lua.append(relativePath) + elif foundJSModule: + self.fileList_js.append(relativePath) else: self.fileList_com.append(relativePath) @@ -151,7 +171,8 @@ class CocosFileList: f = open(fileName,"w") self.fileList_com.sort() self.fileList_lua.sort() - content ={'common':self.fileList_com,'lua':self.fileList_lua} + self.fileList_js.sort() + content ={'common':self.fileList_com,'lua':self.fileList_lua,'js':self.fileList_js} json.dump(content,f,sort_keys=True,indent=4) f.close() return True diff --git a/web b/web new file mode 160000 index 0000000000..3b0958d192 --- /dev/null +++ b/web @@ -0,0 +1 @@ +Subproject commit 3b0958d1927000f9f7414f7ffa2e489660f9e541