diff --git a/native/.gitignore b/native/.gitignore index 899acd917f..98f29c5afb 100644 --- a/native/.gitignore +++ b/native/.gitignore @@ -51,7 +51,6 @@ BundleArtifacts .vs/ # Ignore files build by ndk and eclipse -libs/ bin/ obj/ gen/ diff --git a/native/.travis.yml b/native/.travis.yml index 2cde41c24c..a45fc4bdbb 100644 --- a/native/.travis.yml +++ b/native/.travis.yml @@ -8,7 +8,7 @@ before_install: - tools/travis-scripts/before-install.sh branches: only: - - develop + - v1.1 env: global: - secure: bUrk522Qw5Mc3SfDXHZtJ/aF9QbLXYDnUVSOJXt1wUB1d8xAQphTcZ1ARNYu7I5m3ZXqRfzTS4POOT58qeS3sYPpJ8urWW18hgX3I/dmsL1WJXmwnOV+0J3xLt6AT3ttqj7/emaf0xxuBvZ0szyRz0rU4wprtWftWMFiUrsF8G1an2Qa/g/f5LhilnDiKAqFdHMkn0ogaggL0PbgliHeHo7SEOfSF2gQaSIBta7jzE/BEZZ3R4AuReB3oNDwxr+1E4BpPaGO1lMLzdr8MAjWBGVLBRlpVDihgFTTmdka8UYasjEWDs6GbSjJRsTZQkluOo+1UylSiLn5o1tnWMqINo5DDaayBSKWRV/x+Sx+KMG221BwHLGFHrhEm8Jwc3g5IBiFrc9Xn/PAoCL3Zi/m0m8Y/TVIlA2nWuU0jeMZYXOb0ALCplAQMrG/Yt7euzgSjZ9iPvO7HO8BkaRkUxafcp6svWyMedNeDczG6liLSquJak+XIbOpWCOW+KVxc2S2Unz37MSOQR/aB9dJ8fKI/4e3LCdYrSKW9MSKAz9BSYA2IK2F8Fgr6zY3IPTANQCi6o8i/N54wsmpY17uvzqNDGuag5m/FkNpFWVQUy/TdONanXV6m1jvREaxtDHucSnP3olmvx6pi1awRspDfRmcILK08yvul+yLol0nQwenlx0= diff --git a/native/build/cocos2d_libs.xcodeproj/project.pbxproj b/native/build/cocos2d_libs.xcodeproj/project.pbxproj index a662db87ca..4fcde1661a 100644 --- a/native/build/cocos2d_libs.xcodeproj/project.pbxproj +++ b/native/build/cocos2d_libs.xcodeproj/project.pbxproj @@ -634,6 +634,10 @@ 29394CF519B01DBA00D2DE1A /* UIWebViewImpl-ios.h in Headers */ = {isa = PBXBuildFile; fileRef = 29394CEE19B01DBA00D2DE1A /* UIWebViewImpl-ios.h */; }; 29394CF619B01DBA00D2DE1A /* UIWebViewImpl-ios.mm in Sources */ = {isa = PBXBuildFile; fileRef = 29394CEF19B01DBA00D2DE1A /* UIWebViewImpl-ios.mm */; }; 29394CF719B01DBA00D2DE1A /* UIWebViewImpl-ios.mm in Sources */ = {isa = PBXBuildFile; fileRef = 29394CEF19B01DBA00D2DE1A /* UIWebViewImpl-ios.mm */; }; + 294D7D9A1D0E93A2002CE7B7 /* CCDevice-apple.h in Headers */ = {isa = PBXBuildFile; fileRef = 294D7D981D0E93A2002CE7B7 /* CCDevice-apple.h */; }; + 294D7D9B1D0E93A2002CE7B7 /* CCDevice-apple.h in Headers */ = {isa = PBXBuildFile; fileRef = 294D7D981D0E93A2002CE7B7 /* CCDevice-apple.h */; }; + 294D7D9C1D0E93A2002CE7B7 /* CCDevice-apple.mm in Sources */ = {isa = PBXBuildFile; fileRef = 294D7D991D0E93A2002CE7B7 /* CCDevice-apple.mm */; }; + 294D7D9D1D0E93A2002CE7B7 /* CCDevice-apple.mm in Sources */ = {isa = PBXBuildFile; fileRef = 294D7D991D0E93A2002CE7B7 /* CCDevice-apple.mm */; }; 2980F0221BA9A5550059E678 /* CCUIEditBoxIOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 2980F0171BA9A5550059E678 /* CCUIEditBoxIOS.h */; }; 2980F0231BA9A5550059E678 /* CCUIEditBoxIOS.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2980F0181BA9A5550059E678 /* CCUIEditBoxIOS.mm */; }; 2980F0241BA9A5550059E678 /* CCUIMultilineTextField.h in Headers */ = {isa = PBXBuildFile; fileRef = 2980F0191BA9A5550059E678 /* CCUIMultilineTextField.h */; }; @@ -680,6 +684,14 @@ 464AD6E6197EBB1400E502D8 /* pvr.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 464AD6E3197EBB1400E502D8 /* pvr.cpp */; }; 464AD6E7197EBB1400E502D8 /* pvr.h in Headers */ = {isa = PBXBuildFile; fileRef = 464AD6E4197EBB1400E502D8 /* pvr.h */; }; 464AD6E8197EBB1400E502D8 /* pvr.h in Headers */ = {isa = PBXBuildFile; fileRef = 464AD6E4197EBB1400E502D8 /* pvr.h */; }; + 4D2E69071CC543B40032DD5C /* CCGraphicsNode.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4D2E69031CC543B40032DD5C /* CCGraphicsNode.cpp */; }; + 4D2E69081CC543B40032DD5C /* CCGraphicsNode.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4D2E69031CC543B40032DD5C /* CCGraphicsNode.cpp */; }; + 4D2E69091CC543B40032DD5C /* CCGraphicsNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 4D2E69041CC543B40032DD5C /* CCGraphicsNode.h */; }; + 4D2E690A1CC543B40032DD5C /* CCGraphicsNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 4D2E69041CC543B40032DD5C /* CCGraphicsNode.h */; }; + 4D2E690B1CC543B40032DD5C /* Triangulate.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4D2E69051CC543B40032DD5C /* Triangulate.cpp */; }; + 4D2E690C1CC543B40032DD5C /* Triangulate.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4D2E69051CC543B40032DD5C /* Triangulate.cpp */; }; + 4D2E690D1CC543B40032DD5C /* Triangulate.h in Headers */ = {isa = PBXBuildFile; fileRef = 4D2E69061CC543B40032DD5C /* Triangulate.h */; }; + 4D2E690E1CC543B40032DD5C /* Triangulate.h in Headers */ = {isa = PBXBuildFile; fileRef = 4D2E69061CC543B40032DD5C /* Triangulate.h */; }; 4D76BE3A1A4AAF0A00102962 /* CCActionTimelineNode.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4D76BE381A4AAF0A00102962 /* CCActionTimelineNode.cpp */; }; 4D76BE3B1A4AAF0A00102962 /* CCActionTimelineNode.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4D76BE381A4AAF0A00102962 /* CCActionTimelineNode.cpp */; }; 4D76BE3C1A4AAF0A00102962 /* CCActionTimelineNode.h in Headers */ = {isa = PBXBuildFile; fileRef = 4D76BE391A4AAF0A00102962 /* CCActionTimelineNode.h */; }; @@ -1740,6 +1752,8 @@ 29394CED19B01DBA00D2DE1A /* UIWebView.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = UIWebView.mm; sourceTree = ""; }; 29394CEE19B01DBA00D2DE1A /* UIWebViewImpl-ios.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIWebViewImpl-ios.h"; sourceTree = ""; }; 29394CEF19B01DBA00D2DE1A /* UIWebViewImpl-ios.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = "UIWebViewImpl-ios.mm"; sourceTree = ""; }; + 294D7D981D0E93A2002CE7B7 /* CCDevice-apple.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "CCDevice-apple.h"; sourceTree = ""; }; + 294D7D991D0E93A2002CE7B7 /* CCDevice-apple.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = "CCDevice-apple.mm"; sourceTree = ""; }; 2958244919873D8E00F9746D /* UIScale9Sprite.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = UIScale9Sprite.cpp; sourceTree = ""; }; 2958244A19873D8E00F9746D /* UIScale9Sprite.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UIScale9Sprite.h; sourceTree = ""; }; 2980F0171BA9A5550059E678 /* CCUIEditBoxIOS.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCUIEditBoxIOS.h; sourceTree = ""; }; @@ -1834,6 +1848,10 @@ 46A168631807AF4E005B8026 /* CCTableView.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CCTableView.h; sourceTree = ""; }; 46A168641807AF4E005B8026 /* CCTableViewCell.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = CCTableViewCell.cpp; sourceTree = ""; }; 46A168651807AF4E005B8026 /* CCTableViewCell.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CCTableViewCell.h; sourceTree = ""; }; + 4D2E69031CC543B40032DD5C /* CCGraphicsNode.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCGraphicsNode.cpp; path = creator/CCGraphicsNode.cpp; sourceTree = ""; }; + 4D2E69041CC543B40032DD5C /* CCGraphicsNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCGraphicsNode.h; path = creator/CCGraphicsNode.h; sourceTree = ""; }; + 4D2E69051CC543B40032DD5C /* Triangulate.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = Triangulate.cpp; path = creator/Triangulate.cpp; sourceTree = ""; }; + 4D2E69061CC543B40032DD5C /* Triangulate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Triangulate.h; path = creator/Triangulate.h; sourceTree = ""; }; 4D76BE381A4AAF0A00102962 /* CCActionTimelineNode.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCActionTimelineNode.cpp; sourceTree = ""; }; 4D76BE391A4AAF0A00102962 /* CCActionTimelineNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionTimelineNode.h; sourceTree = ""; }; 4DFA4C151CBCE34100E3B736 /* CCScale9Sprite.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCScale9Sprite.cpp; path = creator/CCScale9Sprite.cpp; sourceTree = ""; }; @@ -3289,6 +3307,10 @@ 4DFA4C141CBCE32800E3B736 /* creator */ = { isa = PBXGroup; children = ( + 4D2E69031CC543B40032DD5C /* CCGraphicsNode.cpp */, + 4D2E69041CC543B40032DD5C /* CCGraphicsNode.h */, + 4D2E69051CC543B40032DD5C /* Triangulate.cpp */, + 4D2E69061CC543B40032DD5C /* Triangulate.h */, 4DFA4C151CBCE34100E3B736 /* CCScale9Sprite.cpp */, 4DFA4C161CBCE34100E3B736 /* CCScale9Sprite.h */, ); @@ -3488,6 +3510,8 @@ 50ABBF1A1926664700A911A9 /* apple */ = { isa = PBXGroup; children = ( + 294D7D981D0E93A2002CE7B7 /* CCDevice-apple.h */, + 294D7D991D0E93A2002CE7B7 /* CCDevice-apple.mm */, 50ABBF1B1926664700A911A9 /* CCFileUtils-apple.h */, 50ABBF1C1926664700A911A9 /* CCFileUtils-apple.mm */, 50ABBF1D1926664700A911A9 /* CCLock-apple.cpp */, @@ -3767,6 +3791,7 @@ B276EF5F1988D1D500CD400F /* CCVertexIndexData.h in Headers */, 1A57007F180BC5A10088DEC7 /* CCActionInterval.h in Headers */, 15AE188719AAD33D00C27E9E /* CCBSequenceProperty.h in Headers */, + 4D2E690D1CC543B40032DD5C /* Triangulate.h in Headers */, 1A570083180BC5A10088DEC7 /* CCActionManager.h in Headers */, 4DFA4C191CBCE34100E3B736 /* CCScale9Sprite.h in Headers */, 1A570087180BC5A10088DEC7 /* CCActionPageTurn3D.h in Headers */, @@ -3841,6 +3866,7 @@ 1A5701E0180BCB8C0088DEC7 /* CCLayer.h in Headers */, 1A5701E4180BCB8C0088DEC7 /* CCScene.h in Headers */, 15AE1BDD19AAE01E00C27E9E /* CCControlUtils.h in Headers */, + 294D7D9A1D0E93A2002CE7B7 /* CCDevice-apple.h in Headers */, A6F0D7A21C2796020029CC44 /* CCStencilStateManager.hpp in Headers */, B29A7E0919EE1B7700872B35 /* AttachmentLoader.h in Headers */, B29A7E3319EE1B7700872B35 /* SlotData.h in Headers */, @@ -3865,6 +3891,7 @@ 1A57020A180BCBDF0088DEC7 /* CCMotionStreak.h in Headers */, 1A570212180BCBF40088DEC7 /* CCProgressTimer.h in Headers */, 1A570216180BCBF40088DEC7 /* CCRenderTexture.h in Headers */, + 4D2E69091CC543B40032DD5C /* CCGraphicsNode.h in Headers */, A679D1351C74C28800620A6C /* CCColliderDetector.h in Headers */, 1A570223180BCC1A0088DEC7 /* CCParticleBatchNode.h in Headers */, 15AE1BD519AAE01E00C27E9E /* CCControlSaturationBrightnessPicker.h in Headers */, @@ -4134,6 +4161,7 @@ B5CE6DCB1B3C05BA002B0419 /* UIRadioButton.h in Headers */, 15AE1BFC19AAE01E00C27E9E /* CCControlUtils.h in Headers */, 15AE193519AAD35100C27E9E /* CCActionObject.h in Headers */, + 4D2E690E1CC543B40032DD5C /* Triangulate.h in Headers */, 50ABBEC21925AB6F00A911A9 /* CCValue.h in Headers */, 2980F0241BA9A5550059E678 /* CCUIMultilineTextField.h in Headers */, 50ABBECA1925AB6F00A911A9 /* firePngData.h in Headers */, @@ -4142,6 +4170,7 @@ 15AE193119AAD35100C27E9E /* CCActionManagerEx.h in Headers */, 15AE185B19AAD31200C27E9E /* CDOpenALSupport.h in Headers */, 1A570064180BC5A10088DEC7 /* CCAction.h in Headers */, + 294D7D9B1D0E93A2002CE7B7 /* CCDevice-apple.h in Headers */, 15AE1BA819AADFDF00C27E9E /* UIRelativeBox.h in Headers */, 503DD8EC1926736A00CD74DD /* CCGLViewImpl-ios.h in Headers */, 15AE18D819AAD33D00C27E9E /* CCScrollViewLoader.h in Headers */, @@ -4315,6 +4344,7 @@ 50ABBE441925AB6F00A911A9 /* CCDirector.h in Headers */, 5034CA4A191D591100CE6051 /* ccShader_Label_df.frag in Headers */, A679D14F1C74C49B00620A6C /* CCProcessBase.h in Headers */, + 4D2E690A1CC543B40032DD5C /* CCGraphicsNode.h in Headers */, 2980F0221BA9A5550059E678 /* CCUIEditBoxIOS.h in Headers */, 15AE1B7519AADA9A00C27E9E /* UILoadingBar.h in Headers */, 15AE1BF219AAE01E00C27E9E /* CCControlPotentiometer.h in Headers */, @@ -4554,6 +4584,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 4D2E69071CC543B40032DD5C /* CCGraphicsNode.cpp in Sources */, 50ABBE2B1925AB6F00A911A9 /* ccCArray.cpp in Sources */, B29A7E3B19EE1B7700872B35 /* Animation.c in Sources */, 15AE1BDE19AAE01E00C27E9E /* CCInvocation.cpp in Sources */, @@ -4561,6 +4592,7 @@ 15AE1BE219AAE01E00C27E9E /* CCScrollView.cpp in Sources */, 50ABBD581925AB0000A911A9 /* Vec2.cpp in Sources */, 50ABBE311925AB6F00A911A9 /* CCConfiguration.cpp in Sources */, + 4D2E690B1CC543B40032DD5C /* Triangulate.cpp in Sources */, 15AE1BDA19AAE01E00C27E9E /* CCControlSwitch.cpp in Sources */, A679D0FB1C74BA3600620A6C /* CCArmatureDefine.cpp in Sources */, 15AE18DC19AAD35000C27E9E /* CocoLoader.cpp in Sources */, @@ -4600,6 +4632,7 @@ 1A570061180BC5A10088DEC7 /* CCAction.cpp in Sources */, 15AE1BDC19AAE01E00C27E9E /* CCControlUtils.cpp in Sources */, B29A7DE919EE1B7700872B35 /* EventData.c in Sources */, + 294D7D9C1D0E93A2002CE7B7 /* CCDevice-apple.mm in Sources */, 50ABBEC51925AB6F00A911A9 /* etc1.cpp in Sources */, 15AE1B5B19AADA9900C27E9E /* UITextAtlas.cpp in Sources */, 1A570065180BC5A10088DEC7 /* CCActionCamera.cpp in Sources */, @@ -4958,6 +4991,7 @@ 15AE194B19AAD35100C27E9E /* CCComRender.cpp in Sources */, 50ABBE7E1925AB6F00A911A9 /* CCEventTouch.cpp in Sources */, B29A7DCA19EE1B7700872B35 /* SlotData.c in Sources */, + 4D2E690C1CC543B40032DD5C /* Triangulate.cpp in Sources */, 15AE18C519AAD33D00C27E9E /* CCLayerLoader.cpp in Sources */, 15AE1BF719AAE01E00C27E9E /* CCControlStepper.cpp in Sources */, 50ABBE6E1925AB6F00A911A9 /* CCEventListenerKeyboard.cpp in Sources */, @@ -5042,6 +5076,7 @@ B5CE6DC91B3C05BA002B0419 /* UIRadioButton.cpp in Sources */, 15AE18AB19AAD33D00C27E9E /* CCBAnimationManager.cpp in Sources */, 15AE1B7219AADA9A00C27E9E /* UIListView.cpp in Sources */, + 4D2E69081CC543B40032DD5C /* CCGraphicsNode.cpp in Sources */, 1A5701BE180BCB5A0088DEC7 /* CCLabelAtlas.cpp in Sources */, 15FB20751AE7BF8600C31518 /* CCAutoPolygon.cpp in Sources */, A0E749F81BA8FD7F001A8332 /* UIEditBoxImpl-common.cpp in Sources */, @@ -5172,6 +5207,7 @@ 50ABBDB21925AB4100A911A9 /* ccShaders.cpp in Sources */, 50ABBD451925AB0000A911A9 /* CCVertex.cpp in Sources */, 50ABBEB01925AB6F00A911A9 /* CCUserDefault.cpp in Sources */, + 294D7D9D1D0E93A2002CE7B7 /* CCDevice-apple.mm in Sources */, 50ABBE521925AB6F00A911A9 /* CCEventDispatcher.cpp in Sources */, 52B47A2F1A5349A3004E4C60 /* HttpAsynConnection-apple.m in Sources */, 15AE1B8019AADA9A00C27E9E /* UITextAtlas.cpp in Sources */, diff --git a/native/cocos/2d/CCAction.cpp b/native/cocos/2d/CCAction.cpp index 431821d537..5b5e4332b2 100644 --- a/native/cocos/2d/CCAction.cpp +++ b/native/cocos/2d/CCAction.cpp @@ -58,6 +58,16 @@ Action::~Action() CCLOGINFO("deallocing Action: %p - tag: %i", this, _tag); } +void Action::sendUpdateEventToScript(float dt, Action *actionObject) +{ +#if CC_ENABLE_SCRIPT_BINDING + if (_scriptType == kScriptTypeJavascript) + { + ScriptEngineManager::sendActionEventToJS(actionObject, kActionUpdate, (void *)&dt); + } +#endif +} + std::string Action::description() const { return StringUtils::format("convertToWorldSpaceAR(Vec2::ZERO); + Vec2 followedWorldPos = _followedNode->convertToWorldSpaceAR(Vec2::ZERO); + // compute the offset between followed and target node + Vec2 delta = targetWorldPos - followedWorldPos; + Vec2 tempPos = _target->getParent()->convertToNodeSpaceAR(delta + _halfScreenSize); + if(_boundarySet) { // whole map fits inside a single screen, no need to modify the position - unless map boundaries are increased @@ -278,16 +294,15 @@ void Follow::step(float dt) { return; } - - Vec2 tempPos = _halfScreenSize - _followedNode->getPosition(); - _target->setPosition(clampf(tempPos.x, _leftBoundary, _rightBoundary), clampf(tempPos.y, _bottomBoundary, _topBoundary)); } else { - _target->setPosition(_halfScreenSize - _followedNode->getPosition()); + _target->setPosition(tempPos); } + + sendUpdateEventToScript(dt, this); } bool Follow::isDone() const diff --git a/native/cocos/2d/CCAction.h b/native/cocos/2d/CCAction.h index 99647cb498..1309f54e49 100644 --- a/native/cocos/2d/CCAction.h +++ b/native/cocos/2d/CCAction.h @@ -183,6 +183,10 @@ protected: #endif private: CC_DISALLOW_COPY_AND_ASSIGN(Action); + +protected: + void sendUpdateEventToScript(float dt, Action *actionObject); + }; /** @class FiniteTimeAction diff --git a/native/cocos/2d/CCLabel.cpp b/native/cocos/2d/CCLabel.cpp index 05a75873bc..817738c325 100644 --- a/native/cocos/2d/CCLabel.cpp +++ b/native/cocos/2d/CCLabel.cpp @@ -1630,6 +1630,7 @@ void Label::setSystemFontName(const std::string& systemFont) if (systemFont != _systemFont) { _systemFont = systemFont; + _currentLabelType = LabelType::STRING_TEXTURE; _systemFontDirty = true; } } @@ -1640,6 +1641,7 @@ void Label::setSystemFontSize(float fontSize) { _systemFontSize = fontSize; _originalFontSize = fontSize; + _currentLabelType = LabelType::STRING_TEXTURE; _systemFontDirty = true; } } @@ -1981,6 +1983,8 @@ FontDefinition Label::_getFontDefinition() const systemFontDef._fontFillColor.b = _textColor.b; systemFontDef._fontAlpha = _textColor.a; systemFontDef._shadow._shadowEnabled = false; + systemFontDef._enableWrap = _enableWrap; + systemFontDef._overflow = (int)_overflow; if (_currLabelEffect == LabelEffect::OUTLINE && _outlineSize > 0.f) { @@ -1999,7 +2003,7 @@ FontDefinition Label::_getFontDefinition() const #if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) && (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) if (systemFontDef._stroke._strokeEnabled) { - CCLOGERROR("Currently only supported on iOS and Android!"); + CCLOGERROR("Stroke Currently only supported on iOS and Android!"); } systemFontDef._stroke._strokeEnabled = false; #endif @@ -2037,8 +2041,7 @@ float Label::getRenderingFontSize()const void Label::enableWrap(bool enable) { - if(enable == _enableWrap || _overflow == Overflow::RESIZE_HEIGHT - || _currentLabelType == LabelType::STRING_TEXTURE){ + if(enable == _enableWrap || _overflow == Overflow::RESIZE_HEIGHT){ return; } @@ -2059,19 +2062,13 @@ void Label::setOverflow(Overflow overflow) if(_overflow == overflow){ return; } - + if (_currentLabelType == LabelType::CHARMAP) { if (overflow == Overflow::SHRINK) { return; } } - if (_currentLabelType == LabelType::STRING_TEXTURE) { - if (overflow == Overflow::CLAMP || overflow == Overflow::SHRINK) { - return; - } - } - if(overflow == Overflow::RESIZE_HEIGHT){ this->setDimensions(_labelDimensions.width,0); this->enableWrap(true); diff --git a/native/cocos/2d/CCLabel.h b/native/cocos/2d/CCLabel.h index 36741131c0..b7e174e32c 100644 --- a/native/cocos/2d/CCLabel.h +++ b/native/cocos/2d/CCLabel.h @@ -663,6 +663,8 @@ protected: bool isHorizontalClamped(float letterPositionX, int lineInex); void restoreFontSize(); void updateLetterSpriteScale(Sprite* sprite); + int getFirstCharLen(const std::u16string& utf16Text, int startIndex, int textLen); + int getFirstWordLen(const std::u16string& utf16Text, int startIndex, int textLen); void reset(); diff --git a/native/cocos/2d/CCLabelTextFormatter.cpp b/native/cocos/2d/CCLabelTextFormatter.cpp index 4924df05f7..f671f31782 100644 --- a/native/cocos/2d/CCLabelTextFormatter.cpp +++ b/native/cocos/2d/CCLabelTextFormatter.cpp @@ -72,12 +72,12 @@ void Label::computeAlignmentOffset() } } -static int getFirstCharLen(const std::u16string& utf16Text, int startIndex, int textLen) +int Label::getFirstCharLen(const std::u16string& utf16Text, int startIndex, int textLen) { return 1; } -static int getFirstWordLen(const std::u16string& utf16Text, int startIndex, int textLen) +int Label::getFirstWordLen(const std::u16string& utf16Text, int startIndex, int textLen) { auto character = utf16Text[startIndex]; if (StringUtils::isCJKUnicode(character) || StringUtils::isUnicodeSpace(character) || character == '\n') @@ -86,9 +86,26 @@ static int getFirstWordLen(const std::u16string& utf16Text, int startIndex, int } int len = 1; + FontLetterDefinition letterDef; + auto nextLetterX = 0; + auto contentScaleFactor = CC_CONTENT_SCALE_FACTOR(); for (int index = startIndex + 1; index < textLen; ++index) { character = utf16Text[index]; + if (_fontAtlas->getLetterDefinitionForChar(character, letterDef) == false) + { + break; + } + auto letterX = (nextLetterX + letterDef.offsetX * _bmfontScale) / contentScaleFactor; + if (_maxLineWidth > 0.f && letterX + letterDef.width * _bmfontScale > _maxLineWidth + && !StringUtils::isUnicodeSpace(character)) + { + if(len >= 2) { + return len -1; + } + } + + nextLetterX += letterDef.xAdvance * _bmfontScale + _additionalKerning; if (character == '\n' || StringUtils::isUnicodeSpace(character) || StringUtils::isCJKUnicode(character)) { break; @@ -239,12 +256,12 @@ bool Label::multilineTextWrap(std::functiongetLayerAttribs(); + tmxMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribCSV); + tmxMapInfo->setStoringCharacters(true); + } } else if (elementName == "object") { @@ -668,6 +674,45 @@ void TMXMapInfo::endElement(void *ctx, const char *name) tmxMapInfo->setCurrentString(""); } + else if (tmxMapInfo->getLayerAttribs() & TMXLayerAttribCSV) + { + unsigned char *buffer; + + TMXLayerInfo* layer = tmxMapInfo->getLayers().back(); + + tmxMapInfo->setStoringCharacters(false); + std::string currentString = tmxMapInfo->getCurrentString(); + + vector gidTokens; + istringstream filestr(currentString); + string sRow; + while(getline(filestr, sRow, '\n')) { + string sGID; + istringstream rowstr(sRow); + while (getline(rowstr, sGID, ',')) { + gidTokens.push_back(sGID); + } + } + + // 32-bits per gid + buffer = (unsigned char*)malloc(gidTokens.size() * 4); + if (!buffer) + { + CCLOG("cocos2d: TiledMap: CSV buffer not allocated."); + return; + } + + uint32_t* bufferPtr = reinterpret_cast(buffer); + for(auto gidToken : gidTokens) { + auto tileGid = (uint32_t)strtol(gidToken.c_str(), nullptr, 10); + *bufferPtr = tileGid; + bufferPtr++; + } + + layer->_tiles = reinterpret_cast(buffer); + + tmxMapInfo->setCurrentString(""); + } else if (tmxMapInfo->getLayerAttribs() & TMXLayerAttribNone) { _xmlTileIndex = 0; diff --git a/native/cocos/2d/CCTMXXMLParser.h b/native/cocos/2d/CCTMXXMLParser.h index bab9b3a42e..ae091d4238 100644 --- a/native/cocos/2d/CCTMXXMLParser.h +++ b/native/cocos/2d/CCTMXXMLParser.h @@ -62,6 +62,7 @@ enum { TMXLayerAttribBase64 = 1 << 1, TMXLayerAttribGzip = 1 << 2, TMXLayerAttribZlib = 1 << 3, + TMXLayerAttribCSV = 1 << 4, }; enum { diff --git a/native/cocos/base/ccTypes.h b/native/cocos/base/ccTypes.h index 799645a3e5..ae6fb672d5 100644 --- a/native/cocos/base/ccTypes.h +++ b/native/cocos/base/ccTypes.h @@ -546,6 +546,8 @@ public: , _dimensions(Size::ZERO) , _fontFillColor(Color3B::WHITE) , _fontAlpha(255) + , _enableWrap(true) + , _overflow(0) {} /// font name @@ -566,7 +568,10 @@ public: FontShadow _shadow; /// font stroke FontStroke _stroke; - + /// enable text wrap + bool _enableWrap; + /// enable shrink font size + int _overflow; }; /** diff --git a/native/cocos/editor-support/creator/Android.mk b/native/cocos/editor-support/creator/Android.mk index 3bb903ab99..29d3415a06 100644 --- a/native/cocos/editor-support/creator/Android.mk +++ b/native/cocos/editor-support/creator/Android.mk @@ -5,7 +5,9 @@ LOCAL_MODULE := creator_static LOCAL_MODULE_FILENAME := libcreator -LOCAL_SRC_FILES := CCScale9Sprite.cpp +LOCAL_SRC_FILES := CCScale9Sprite.cpp \ + CCGraphicsNode.cpp \ + Triangulate.cpp LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/.. diff --git a/native/cocos/editor-support/creator/CCGraphicsNode.cpp b/native/cocos/editor-support/creator/CCGraphicsNode.cpp new file mode 100644 index 0000000000..28ab3015a2 --- /dev/null +++ b/native/cocos/editor-support/creator/CCGraphicsNode.cpp @@ -0,0 +1,1266 @@ + +/**************************************************************************** + Copyright (c) 2016 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 "CCGraphicsNode.h" +#include "base/CCDirector.h" +#include "renderer/CCRenderer.h" +#include "renderer/ccGLStateCache.h" +#include "renderer/CCGLProgram.h" +#include "renderer/CCGLProgramState.h" + +#define STRINGIFY(A) #A +#include "CCGraphicsNode.vert" +#include "CCGraphicsNode.frag" + +#include "Triangulate.h" + + +#define PI 3.14159265358979323846264338327f +#define PI_2 (PI * 2) +#define PI_HALF (PI * 0.5) + +#define VECTOR_INIT_VERTS_SIZE 256 + +#define VECTOR_KAPPA90 0.5522847493f // Length proportional to radius of a cubic bezier handle for 90deg arcs. + +#define EPSILON 0.0000000001f + +USING_NS_CC; + +namespace creator { + + +GraphicsNode* GraphicsNode::create() +{ + GraphicsNode * ret = new (std::nothrow) GraphicsNode(); + if (ret && ret->init()) { + ret->autorelease(); + } + else { + CC_SAFE_DELETE(ret); + } + return ret; +} + +GraphicsNode::GraphicsNode() +: _vertsDirty(false) +, _indicesDirty(false) +, _needUpdatePathOffset(false) +, _lineWidth(1) +, _lineCap(CAP_BUTT) +, _lineJoin(JOIN_MITER) +, _nPoints(0) +, _nPath(0) +, _pathOffset(0) +, _vertsOffset(0) +, _nVerts(VECTOR_INIT_VERTS_SIZE) +, _indicesOffset(0) +, _nIndices(VECTOR_INIT_VERTS_SIZE*3) +, _nCommands(0) +, _curPath(nullptr) +{ + _miterLimit = 10.0f; + + setDeviceRatio(2); + + _strokeColor = Color4F::BLACK; + _fillColor = Color4F::WHITE; + + _verts = (VecVertex*)malloc(sizeof(VecVertex) * _nVerts); + _indices = (GLushort*)malloc(sizeof(GLushort) * _nIndices); + + auto glprogram = GLProgram::createWithByteArrays(ccGraphicsVert, ccGraphicsFrag); + auto glprogramstate = GLProgramState::getOrCreateWithGLProgram(glprogram); + + // shader state + setGLProgramState(glprogramstate); + + glGenBuffers(2, _buffersVBO); + + CHECK_GL_ERROR_DEBUG(); +} + +GraphicsNode::~GraphicsNode() +{ + clear(true); +} + +void GraphicsNode::moveTo(float x, float y) +{ + if (_needUpdatePathOffset) { + _pathOffset = _nPath; + _needUpdatePathOffset = false; + } + + addPath(); + addPoint(_curPath, x, y, PT_CORNER); + + _commandx = x; + _commandy = y; +} + +void GraphicsNode::lineTo(float x, float y) +{ + addPoint(_curPath, x, y, PT_CORNER); + + _commandx = x; + _commandy = y; +} + +void GraphicsNode::bezierCurveTo(float c1x, float c1y, float c2x, float c2y, float x, float y) +{ + VecPoint* last = _curPath->points.back(); + + if (last->x == c1x && last->y == c1y && c2x == x && c2y == y) { + this->lineTo(x, y); + return; + } + + tesselateBezier(last->x,last->y, c1x,c1y, c2x,c2y, x,y, 0, PT_CORNER); + + _commandx = x; + _commandy = y; +} + +void GraphicsNode::quadraticCurveTo(float cx, float cy, float x, float y) +{ + float x0 = _commandx; + float y0 = _commandy; + bezierCurveTo(x0 + 2.0f/3.0f*(cx - x0), y0 + 2.0f/3.0f*(cy - y0), + x + 2.0f/3.0f*(cx - x), y + 2.0f/3.0f*(cy - y), + x, y); +} + +void GraphicsNode::arcTo(float x1, float y1, float x2, float y2, float radius) +{ + float x0 = _commandx; + float y0 = _commandy; + float dx0,dy0, dx1,dy1, a, d, cx,cy, a0,a1; + bool counterclockwise; + + // Handle degenerate cases. + if (ptEquals(x0,y0, x1,y1, _distTol) || + ptEquals(x1,y1, x2,y2, _distTol) || + distPtSeg(x1,y1, x0,y0, x2,y2) < _distTol*_distTol || + radius < _distTol) { + lineTo(x1,y1); + return; + } + + // Calculate tangential circle to lines (x0,y0)-(x1,y1) and (x1,y1)-(x2,y2). + dx0 = x0-x1; + dy0 = y0-y1; + dx1 = x2-x1; + dy1 = y2-y1; + normalize(&dx0,&dy0); + normalize(&dx1,&dy1); + a = acosf(dx0*dx1 + dy0*dy1); + d = radius / tanf(a/2.0f); + + // printf("a=%f° d=%f\n", a/NVG_PI*180.0f, d); + + if (d > 10000.0f) { + lineTo(x1,y1); + return; + } + + if (cross(dx0,dy0, dx1,dy1) > 0.0f) { + cx = x1 + dx0*d + dy0*radius; + cy = y1 + dy0*d + -dx0*radius; + a0 = atan2f(dx0, -dy0); + a1 = atan2f(-dx1, dy1); + counterclockwise = false; + } else { + cx = x1 + dx0*d + -dy0*radius; + cy = y1 + dy0*d + dx0*radius; + a0 = atan2f(-dx0, dy0); + a1 = atan2f(dx1, -dy1); + counterclockwise = true; + } + + arc(cx, cy, radius, a0, a1, counterclockwise); +} + + +void GraphicsNode::arc(float cx, float cy, float r, float startAngle, float endAngle, bool counterclockwise) +{ + float a = 0, da = 0, hda = 0, kappa = 0; + float dx = 0, dy = 0, x = 0, y = 0, tanx = 0, tany = 0; + float px = 0, py = 0, ptanx = 0, ptany = 0; + int i, ndivs; + + // Clamp angles + da = endAngle - startAngle; + if (!counterclockwise) { + if (absf(da) >= PI_2) { + da = PI_2; + } else { + while (da < 0.0f) da += PI_2; + } + } else { + if (absf(da) >= PI_2) { + da = -PI_2; + } else { + while (da > 0.0f) da -= PI_2; + } + } + + // Split arc into max 90 degree segments. + ndivs = maxi(1, mini((int)(absf(da) / PI_HALF + 0.5f), 5)); + hda = (da / (float)ndivs) / 2.0f; + kappa = absf(4.0f / 3.0f * (1.0f - cosf(hda)) / sinf(hda)); + + if (counterclockwise) { + kappa = -kappa; + } + + for (i = 0; i <= ndivs; i++) { + a = startAngle + da * (i/(float)ndivs); + dx = cosf(a); + dy = sinf(a); + x = cx + dx*r; + y = cy + dy*r; + tanx = -dy*r*kappa; + tany = dx*r*kappa; + + if (i == 0) { + moveTo(x, y); + } else { + bezierCurveTo(px+ptanx, py+ptany, x-tanx, y-tany, x, y); + } + px = x; + py = y; + ptanx = tanx; + ptany = tany; + } + + // _curPath->complex = false; +} + +void GraphicsNode::rect(float x, float y, float w, float h) +{ + moveTo(x, y); + lineTo(x, y+h); + lineTo(x+w, y+h); + lineTo(x+w, y); + close(); + + _curPath->complex = false; +} + +void GraphicsNode::roundedRect(float x, float y, float w, float h, float r) +{ + if (r < 0.1f) { + rect(x,y,w,h); + return; + } + else { + float rx = minf(r, absf(w)*0.5f) * signf(w), ry = minf(r, absf(h)*0.5f) * signf(h); + + moveTo(x, y+ry); + lineTo(x, y+h-ry); + bezierCurveTo(x, y+h-ry*(1-VECTOR_KAPPA90), x+rx*(1-VECTOR_KAPPA90), y+h, x+rx, y+h); + lineTo(x+w-rx, y+h); + bezierCurveTo(x+w-rx*(1-VECTOR_KAPPA90), y+h, x+w, y+h-ry*(1-VECTOR_KAPPA90), x+w, y+h-ry); + lineTo(x+w, y+ry); + bezierCurveTo(x+w, y+ry*(1-VECTOR_KAPPA90), x+w-rx*(1-VECTOR_KAPPA90), y, x+w-rx, y); + lineTo(x+rx, y); + bezierCurveTo(x+rx*(1-VECTOR_KAPPA90), y, x, y+ry*(1-VECTOR_KAPPA90), x, y+ry); + close(); + + _curPath->complex = false; + } +} + +void GraphicsNode::ellipse(float cx, float cy, float rx, float ry) +{ + moveTo(cx-rx, cy); + bezierCurveTo(cx-rx, cy+ry*VECTOR_KAPPA90, cx-rx*VECTOR_KAPPA90, cy+ry, cx, cy+ry); + bezierCurveTo(cx+rx*VECTOR_KAPPA90, cy+ry, cx+rx, cy+ry*VECTOR_KAPPA90, cx+rx, cy); + bezierCurveTo(cx+rx, cy-ry*VECTOR_KAPPA90, cx+rx*VECTOR_KAPPA90, cy-ry, cx, cy-ry); + bezierCurveTo(cx-rx*VECTOR_KAPPA90, cy-ry, cx-rx, cy-ry*VECTOR_KAPPA90, cx-rx, cy); + + close(); + + _curPath->complex = false; +} + +void GraphicsNode::circle(float cx, float cy, float r) +{ + int divs = curveDivs(r, PI_2, _tessTol); + float step = PI_2 / divs; + + moveTo(cx, cy + r); + + for (int i = 1; i < divs; i++) { + float angle = step * i; + float x = r * sin(angle); + float y = r * cos(angle); + + lineTo(cx + x, cy + y); + } + + close(); + _curPath->complex = false; +} + +void GraphicsNode::fillRect(float x, float y, float w, float h) +{ + rect(x, y, w, h); + fill(); +} + +void GraphicsNode::close() +{ + _curPath->closed = true; +} +void GraphicsNode::beginPath() +{ + _pathOffset = _nPath; +} + + +void GraphicsNode::stroke() +{ + float scale = (_scaleX + _scaleY) / 2; + float strokeWidth = _lineWidth * scale; + + flattenPaths(); + + expandStroke(strokeWidth*0.5f + _fringeWidth*0.5f, _lineCap, _lineJoin, _miterLimit); + + _vertsDirty = true; + _indicesDirty = true; + _needUpdatePathOffset = true; +} + +void GraphicsNode::fill() +{ + flattenPaths(); + + expandFill(_fringeWidth, JOIN_MITER, 2.4f); + + _vertsDirty = true; + _indicesDirty = true; + _needUpdatePathOffset = true; +} + +void GraphicsNode::clear(bool clean) +{ + if (clean) { + for (int i = _paths.size() - 1; i >= 0; i--) { + Path* path = _paths[i]; + _paths.pop_back(); + delete path; + } + + for (int i = _points.size() - 1; i >=0; i--) { + VecPoint* p = _points[i]; + _points.pop_back(); + delete p; + } + + CC_SAFE_DELETE(_verts); + CC_SAFE_DELETE(_indices); + } + + _nPoints = 0; + + _nPath = 0; + _pathOffset = 0; + + _vertsOffset = 0; + _indicesOffset = 0; + + _curPath = nullptr; + + _nCommands = 0; +} + +// static function + +int GraphicsNode::ptEquals(float x1, float y1, float x2, float y2, float tol) +{ + float dx = x2 - x1; + float dy = y2 - y1; + return dx*dx + dy*dy < tol*tol; +} +float GraphicsNode::distPtSeg(float x, float y, float px, float py, float qx, float qy) +{ + float pqx, pqy, dx, dy, d, t; + pqx = qx-px; + pqy = qy-py; + dx = x-px; + dy = y-py; + d = pqx*pqx + pqy*pqy; + t = pqx*dx + pqy*dy; + if (d > 0) t /= d; + if (t < 0) t = 0; + else if (t > 1) t = 1; + dx = px + t*pqx - x; + dy = py + t*pqy - y; + return dx*dx + dy*dy; +} + +float GraphicsNode::normalize(float *x, float* y) +{ + float d = sqrtf((*x)*(*x) + (*y)*(*y)); + if (d > 1e-6f) { + float id = 1.0f / d; + *x *= id; + *y *= id; + } + return d; +} + +int GraphicsNode::curveDivs(float r, float arc, float tol) +{ + float da = acosf(r / (r + tol)) * 2.0f; + return maxi(2, (int)ceilf(arc / da)); +} + +void GraphicsNode::chooseBevel(int bevel, VecPoint* p0, VecPoint* p1, float w, + float* x0, float* y0, float* x1, float* y1) +{ + if (bevel) { + *x0 = p1->x + p0->dy * w; + *y0 = p1->y - p0->dx * w; + *x1 = p1->x + p1->dy * w; + *y1 = p1->y - p1->dx * w; + } else { + *x0 = p1->x + p1->dmx * w; + *y0 = p1->y + p1->dmy * w; + *x1 = p1->x + p1->dmx * w; + *y1 = p1->y + p1->dmy * w; + } +} + + +// protected function + +void GraphicsNode::tesselateBezier(float x1, float y1, float x2, float y2, + float x3, float y3, float x4, float y4, + int level, int type) +{ + float x12,y12,x23,y23,x34,y34,x123,y123,x234,y234,x1234,y1234; + float dx,dy,d2,d3; + + if (level > 10) return; + + x12 = (x1+x2)*0.5f; + y12 = (y1+y2)*0.5f; + x23 = (x2+x3)*0.5f; + y23 = (y2+y3)*0.5f; + x34 = (x3+x4)*0.5f; + y34 = (y3+y4)*0.5f; + x123 = (x12+x23)*0.5f; + y123 = (y12+y23)*0.5f; + + dx = x4 - x1; + dy = y4 - y1; + d2 = absf(((x2 - x4) * dy - (y2 - y4) * dx)); + d3 = absf(((x3 - x4) * dy - (y3 - y4) * dx)); + + if ((d2 + d3)*(d2 + d3) < _tessTol * (dx*dx + dy*dy)) { + addPoint(_curPath, x4, y4, type == 0 ? type | PT_BEVEL : type); + return; + } + + x234 = (x23+x34)*0.5f; + y234 = (y23+y34)*0.5f; + x1234 = (x123+x234)*0.5f; + y1234 = (y123+y234)*0.5f; + + tesselateBezier(x1,y1, x12,y12, x123,y123, x1234,y1234, level+1, 0); + tesselateBezier(x1234,y1234, x234,y234, x34,y34, x4,y4, level+1, type); +} + +void GraphicsNode::addPoint(Path* path, float x, float y, int flags) +{ + VecPoint* pt; + if (path == NULL) return; + + if (path->points.size() > 0) { + pt = path->points.back(); + if (pt->equals(Vec2(x, y))) { + pt->flags |= flags; + return; + } + } + + _nPoints ++; + if (_nPoints > _points.size()) { + pt = new VecPoint(x, y); + _points.push_back(pt); + } + else { + pt = _points[_nPoints - 1]; + pt->reset(); + pt->x = x; + pt->y = y; + } + + pt->flags = (unsigned char)flags; + path->points.push_back(pt); +} + +Path* GraphicsNode::addPath() +{ + if (!(_curPath && _curPath->points.size() <= 1)) { + _nPath ++; + } + + Path* path = nullptr; + + + if (_nPath > _paths.size()) { + path = new Path(); + _paths.push_back(path); + } + else { + + path = _paths[_nPath - 1]; + path->points.clear(); + } + + path->closed = false; + path->complex = true; + + _curPath = path; + + return path; +} + +void GraphicsNode::expandStroke(float w, int lineCap, int lineJoin, float miterLimit) +{ + + int cverts, i, j; + float aa = _fringeWidth; + int ncap = curveDivs(w, PI, _tessTol); + + calculateJoins(w, lineJoin, miterLimit); + + // Calculate max vertex usage. + cverts = 0; + for (i = _pathOffset; i < _nPath; i++) { + Path* path = _paths[i]; + int pathSize = path->points.size(); + + int loop = (path->closed == 0) ? 0 : 1; + if (lineJoin == JOIN_ROUND) + cverts += (pathSize + path->nbevel*(ncap+2) + 1) * 2; // plus one for loop + else + cverts += (pathSize + path->nbevel*5 + 1) * 2; // plus one for loop + if (loop == 0) { + // space for caps + if (lineCap == CAP_ROUND) { + cverts += (ncap*2 + 2)*2; + } else { + cverts += (3+3)*2; + } + } + } + + allocVerts(cverts); + allocIndices((cverts - 2*(_nPath-_pathOffset)) * 3); + + for (i = _pathOffset; i < _nPath; i++) { + VecVertex* verts = _verts + _vertsOffset; + int offset = _vertsOffset; + + Path* path = _paths[i]; + + VecPointVector& pts = path->points; + int pathSize = path->points.size(); + + VecPoint* p0; + VecPoint* p1; + int s, e, loop; + float dx, dy; + + // Calculate fringe or stroke + loop = (path->closed == 0) ? 0 : 1; + + if (loop) { + // Looping + p0 = pts.back(); + p1 = pts.front(); + s = 0; + e = pathSize; + } else { + // Add cap + p0 = pts[0]; + p1 = pts[1]; + s = 1; + e = pathSize-1; + } + + if (loop == 0) { + // Add cap + dx = p1->x - p0->x; + dy = p1->y - p0->y; + normalize(&dx, &dy); + if (lineCap == CAP_BUTT) + buttCapStart(p0, dx, dy, w, -aa*0.5f, aa); + else if (lineCap == CAP_BUTT || lineCap == CAP_SQUARE) + buttCapStart(p0, dx, dy, w, w-aa, aa); + else if (lineCap == CAP_ROUND) + roundCapStart(p0, dx, dy, w, ncap, aa); + } + + for (j = s; j < e; ++j) { + if (lineJoin == JOIN_ROUND) { + roundJoin(p0, p1, w, w, 0, 1, ncap, aa); + } + else if ((p1->flags & (PT_BEVEL | PT_INNERBEVEL)) != 0) { + bevelJoin(p0, p1, w, w, 0, 1, aa); + } else { + vset(p1->x + (p1->dmx * w), p1->y + (p1->dmy * w), 0,1); + vset(p1->x - (p1->dmx * w), p1->y - (p1->dmy * w), 1,1); + } + p0 = p1; + p1 = pts[j+1]; + } + + if (loop) { + // Loop it + vset(verts[0].x, verts[0].y, 0,1); + vset(verts[1].x, verts[1].y, 1,1); + } else { + // Add cap + dx = p1->x - p0->x; + dy = p1->y - p0->y; + normalize(&dx, &dy); + if (lineCap == CAP_BUTT) + buttCapEnd(p1, dx, dy, w, -aa*0.5f, aa); + else if (lineCap == CAP_BUTT || lineCap == CAP_SQUARE) + buttCapEnd(p1, dx, dy, w, w-aa, aa); + else if (lineCap == CAP_ROUND) + roundCapEnd(p1, dx, dy, w, ncap, aa); + } + + // stroke indices + int indicesOffset = _indicesOffset; + + for (int start = offset+2, end = _vertsOffset; start < end; start++) { + _indices[_indicesOffset++] = start - 2; + _indices[_indicesOffset++] = start - 1; + _indices[_indicesOffset++] = start; + } + + float strokeMult = (_lineWidth*0.5f + _fringeWidth*0.5f) / _fringeWidth; + pushCommand(_strokeColor, strokeMult, offset, _vertsOffset - offset, indicesOffset, _indicesOffset - indicesOffset); + } +} + +void GraphicsNode::expandFill(float w, int lineJoin, float miterLimit) +{ + int cverts, convex, i, j; + float aa = _fringeWidth; + int fringe = w > 0.0f; + + calculateJoins(w, lineJoin, miterLimit); + + // Calculate max vertex usage. + cverts = 0; + for (i = _pathOffset; i < _nPath; i++) { + Path* path = _paths[i]; + int pathSize = path->points.size(); + + cverts += pathSize;// + path->nbevel + 1; + if (fringe) { + cverts += (pathSize + path->nbevel*5 + 1) * 2; // plus one for loop +// cverts += (pathSize + 1) * 2; + } + } + + allocVerts(cverts); + + convex = _nPath == 1 && _paths[_pathOffset]->convex; + + for (i = _pathOffset; i < _nPath; i++) { + Path* path = _paths[i]; + + VecVertex* verts = _verts + _vertsOffset; + int offset = _vertsOffset; + + VecPointVector& pts = path->points; + int pathSize = pts.size(); + + VecPoint* p0; + VecPoint* p1; + float woff; + + // Calculate shape vertices. + woff = 0.5f*aa; + + if (fringe) { + // Looping + p0 = pts[pathSize-1]; + p1 = pts[0]; + for (j = 0; j < pathSize; ++j) { + if (p1->flags & PT_BEVEL) { + float dlx0 = p0->dy; + float dly0 = -p0->dx; + float dlx1 = p1->dy; + float dly1 = -p1->dx; + if (p1->flags & PT_LEFT) { + float lx = p1->x + p1->dmx * woff; + float ly = p1->y + p1->dmy * woff; + vset(lx, ly, 0.5f,1); + } else { + float lx0 = p1->x + dlx0 * woff; + float ly0 = p1->y + dly0 * woff; + float lx1 = p1->x + dlx1 * woff; + float ly1 = p1->y + dly1 * woff; + vset(lx0, ly0, 0.5f,1); + vset(lx1, ly1, 0.5f,1); + } + } else { + vset(p1->x + (p1->dmx * woff), p1->y + (p1->dmy * woff), 0.5f,1); + } + p0 = p1; + p1 = pts[j+1]; + } + } else { + for (j = 0; j < pathSize; ++j) { + vset(pts[j]->x, pts[j]->y, 0.5f,1); + } + } + + int nVerts = _vertsOffset - offset; + int indicesOffset = _indicesOffset; + + if (path->complex) { + // indices + std::vector indices; + Triangulate::process(verts, 0, _vertsOffset - offset, indices); + int nIndices = indices.size(); + + allocIndices(nIndices); + + for (j = 0; j < nIndices; j++) { + _indices[j + _indicesOffset] = indices[j] + offset; + } + + _indicesOffset += nIndices; + } + else { + allocIndices((nVerts - 2) * 3); + + int first = offset; + for (int start = offset+2, end = _vertsOffset; start < end; start++) { + _indices[_indicesOffset++] = first; + _indices[_indicesOffset++] = start - 1; + _indices[_indicesOffset++] = start; + } + } + + pushCommand(_fillColor, 1, offset, _vertsOffset - offset, indicesOffset, _indicesOffset - indicesOffset); + + // Calculate fringe + if (fringe) { + verts = _verts + _vertsOffset; + offset = _vertsOffset; + + float lw = w + woff; + float rw = w - woff; + float lu = 0; + float ru = 1; + + // Create only half a fringe for convex shapes so that + // the shape can be rendered without stenciling. + if (convex) { + lw = woff; // This should generate the same vertex as fill inset above. + lu = 0.5f; // Set outline fade at middle. + } + + // Looping + p0 = pts[pathSize-1]; + p1 = pts[0]; + + for (j = 0; j < pathSize; ++j) { + if ((p1->flags & (PT_BEVEL | PT_INNERBEVEL)) != 0) { + bevelJoin(p0, p1, lw, rw, lu, ru, _fringeWidth); + } else { + vset(p1->x + (p1->dmx * lw), p1->y + (p1->dmy * lw), lu,1); + vset(p1->x - (p1->dmx * rw), p1->y - (p1->dmy * rw), ru,1); + } + p0 = p1; + p1 = pts[j+1]; + } + + // Loop it + vset(verts[0].x, verts[0].y, lu,1); + vset(verts[1].x, verts[1].y, ru,1); + + // fill stroke indices + int nVerts = _vertsOffset - offset; + int indicesOffset = _indicesOffset; + + allocIndices((nVerts - 2) * 3); + + for (int start = offset+2, end = _vertsOffset; start < end; start++) { + _indices[_indicesOffset++] = start - 2; + _indices[_indicesOffset++] = start - 1; + _indices[_indicesOffset++] = start; + } + + pushCommand(_fillColor, 1, offset, nVerts, indicesOffset, _indicesOffset - indicesOffset); + } + } +} + +void GraphicsNode::flattenPaths() +{ + if (_curPath && _curPath->points.size() <= 1) { + _nPath --; + _curPath = _paths[_nPath - 1]; + } + + for (int i = _pathOffset; i < _nPath; i++) { + Path* path = _paths[i]; + VecPointVector& pts = path->points; + + VecPoint* p0 = pts.back(); + VecPoint* p1 = pts.front(); + + if(p0->equals(*p1)) { + path->closed = true; + pts.pop_back(); + p0 = pts.back(); + } + + for(int j = 0, size = pts.size(); j < size; j++) { + // Calculate segment direction and length + p0->dx = p1->x - p0->x; + p0->dy = p1->y - p0->y; + p0->len = normalize(&p0->dx, &p0->dy); + + // Advance + p0 = p1; + p1 = pts[j+1]; + } + } +} + + +void GraphicsNode::calculateJoins(float w, int lineJoin, float miterLimit) +{ + int i, j, il, jl; + float iw = 0.0f; + + if (w > 0.0f) + iw = 1.0f / w; + + // Calculate which joins needs extra vertices to append, and gather vertex count. + for (i = _pathOffset, il = _nPath; i < il; i++) { + Path* path = _paths[i]; + + VecPointVector& pts = path->points; + VecPoint* p0 = pts[pts.size()-1]; + VecPoint* p1 = pts[0]; + int nleft = 0; + + path->nbevel = 0; + + for (j = 0, jl = pts.size(); j < jl; j++) { + float dlx0, dly0, dlx1, dly1, dmr2, cross, limit; + dlx0 = p0->dy; + dly0 = -p0->dx; + dlx1 = p1->dy; + dly1 = -p1->dx; + // Calculate extrusions + p1->dmx = (dlx0 + dlx1) * 0.5f; + p1->dmy = (dly0 + dly1) * 0.5f; + dmr2 = p1->dmx*p1->dmx + p1->dmy*p1->dmy; + if (dmr2 > 0.000001f) { + float scale = 1.0f / dmr2; + if (scale > 600.0f) { + scale = 600.0f; + } + p1->dmx *= scale; + p1->dmy *= scale; + } + + // Clear flags, but keep the corner. + p1->flags = (p1->flags & PT_CORNER) ? PT_CORNER : 0; + + // Keep track of left turns. + cross = p1->dx * p0->dy - p0->dx * p1->dy; + if (cross > 0.0f) { + nleft++; + p1->flags |= PT_LEFT; + } + + // Calculate if we should use bevel or miter for inner join. + limit = maxf(1.01f, minf(p0->len, p1->len) * iw); + if ((dmr2 * limit*limit) < 1.0f) + p1->flags |= PT_INNERBEVEL; + + // Check to see if the corner needs to be beveled. + if (p1->flags & PT_CORNER) { + if ((dmr2 * miterLimit*miterLimit) < 1.0f || lineJoin == JOIN_BEVEL || lineJoin == JOIN_ROUND) { + p1->flags |= PT_BEVEL; + } + } + + if ((p1->flags & (PT_BEVEL | PT_INNERBEVEL)) != 0) + path->nbevel++; + + p0 = p1; + p1 = pts[j+1]; + } + + path->convex = nleft == pts.size(); + } +} + +void GraphicsNode::allocVerts(int count) +{ + int nverts = _vertsOffset + count; + + if (nverts > _nVerts) { + while (nverts > _nVerts) { + _nVerts *= 2; + } + _verts = (VecVertex*)realloc(_verts, sizeof(VecVertex) * _nVerts); + } +} + +void GraphicsNode::allocIndices(int count) +{ + int nIndices = _indicesOffset + count; + + if (nIndices > _nIndices) { + while (nIndices > _nIndices) { + _nIndices *= 2; + } + _indices = (GLushort*)realloc(_indices, sizeof(GLushort) * _nIndices); + } +} + + +void GraphicsNode::vset(float x, float y, float u, float v) +{ + VecVertex* vtx = &_verts[_vertsOffset]; + + vtx->x = x; + vtx->y = y; + vtx->u = u; + vtx->v = v; + + _vertsOffset ++; +} + +void GraphicsNode::pushCommand(cocos2d::Color4F& color, float strokeMult, int vertsOffset, int nVerts, int indicesOffset, int nIndices) +{ + Command* lastCmd = nullptr; + if (_commands.size() >= _nCommands && _nCommands > 0) { + lastCmd = _commands[_nCommands - 1]; + } + + if (lastCmd && + ((lastCmd->vertsOffset + lastCmd->nVerts) == vertsOffset) && + ((lastCmd->indicesOffset + lastCmd->nIndices) == indicesOffset) && + lastCmd->color.equals(color) && + lastCmd->strokeMult == strokeMult) { + lastCmd->nVerts += nVerts; + lastCmd->nIndices += nIndices; + } + else { + Command* cmd; + + _nCommands ++; + if (_nCommands > _commands.size()) { + cmd = new Command(); + _commands.push_back(cmd); + } + else { + cmd = _commands[_nCommands - 1]; + } + + cmd->color = color; + cmd->strokeMult = strokeMult; + cmd->vertsOffset = vertsOffset; + cmd->nVerts = nVerts; + cmd->indicesOffset = indicesOffset; + cmd->nIndices = nIndices; + } +} + +void GraphicsNode::buttCapStart(VecPoint* p, float dx, float dy, float w, float d, float aa) +{ + float px = p->x - dx*d; + float py = p->y - dy*d; + float dlx = dy; + float dly = -dx; + vset(px + dlx*w - dx*aa, py + dly*w - dy*aa, 0,0); + vset(px - dlx*w - dx*aa, py - dly*w - dy*aa, 1,0); + vset(px + dlx*w, py + dly*w, 0,1); + vset(px - dlx*w, py - dly*w, 1,1); +} + +void GraphicsNode::buttCapEnd(VecPoint* p, float dx, float dy, float w, float d, float aa) +{ + float px = p->x + dx*d; + float py = p->y + dy*d; + float dlx = dy; + float dly = -dx; + vset(px + dlx*w, py + dly*w, 0,1); + vset(px - dlx*w, py - dly*w, 1,1); + vset(px + dlx*w + dx*aa, py + dly*w + dy*aa, 0,0); + vset(px - dlx*w + dx*aa, py - dly*w + dy*aa, 1,0); +} + +void GraphicsNode::roundCapStart(VecPoint* p, float dx, float dy, float w, int ncap, float aa) +{ + int i; + float px = p->x; + float py = p->y; + float dlx = dy; + float dly = -dx; + + for (i = 0; i < ncap; i++) { + float a = i/(float)(ncap-1) * PI; + float ax = cosf(a) * w, ay = sinf(a) * w; + vset(px - dlx*ax - dx*ay, py - dly*ax - dy*ay, 0,1); + vset(px, py, 0.5f,1); + } + vset(px + dlx*w, py + dly*w, 0,1); + vset(px - dlx*w, py - dly*w, 1,1); +} + +void GraphicsNode::roundCapEnd(VecPoint* p, float dx, float dy, float w, int ncap, float aa) +{ + int i; + float px = p->x; + float py = p->y; + float dlx = dy; + float dly = -dx; + + vset(px + dlx*w, py + dly*w, 0,1); + vset(px - dlx*w, py - dly*w, 1,1); + for (i = 0; i < ncap; i++) { + float a = i/(float)(ncap-1)*PI; + float ax = cosf(a) * w, ay = sinf(a) * w; + vset(px, py, 0.5f,1); + vset(px - dlx*ax + dx*ay, py - dly*ax + dy*ay, 0,1); + } +} + +void GraphicsNode::roundJoin(VecPoint* p0, VecPoint* p1, float lw, float rw, float lu, float ru, int ncap, float fringe) +{ + int i, n; + float dlx0 = p0->dy; + float dly0 = -p0->dx; + float dlx1 = p1->dy; + float dly1 = -p1->dx; + + if (p1->flags & PT_LEFT) { + float lx0,ly0,lx1,ly1,a0,a1; + chooseBevel(p1->flags & PT_INNERBEVEL, p0, p1, lw, &lx0,&ly0, &lx1,&ly1); + a0 = atan2f(-dly0, -dlx0); + a1 = atan2f(-dly1, -dlx1); + if (a1 > a0) a1 -= PI_2; + + vset(lx0, ly0, lu,1); + vset(p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); + + n = clampi((int)ceilf(((a0 - a1) / PI) * ncap), 2, ncap); + for (i = 0; i < n; i++) { + float u = i/(float)(n-1); + float a = a0 + u*(a1-a0); + float rx = p1->x + cosf(a) * rw; + float ry = p1->y + sinf(a) * rw; + vset(p1->x, p1->y, 0.5f,1); + vset(rx, ry, ru,1); + } + + vset(lx1, ly1, lu,1); + vset(p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); + + } else { + float rx0,ry0,rx1,ry1,a0,a1; + chooseBevel(p1->flags & PT_INNERBEVEL, p0, p1, -rw, &rx0,&ry0, &rx1,&ry1); + a0 = atan2f(dly0, dlx0); + a1 = atan2f(dly1, dlx1); + if (a1 < a0) a1 += PI_2; + + vset(p1->x + dlx0*rw, p1->y + dly0*rw, lu,1); + vset(rx0, ry0, ru,1); + + n = clampi((int)ceilf(((a1 - a0) / PI) * ncap), 2, ncap); + for (i = 0; i < n; i++) { + float u = i/(float)(n-1); + float a = a0 + u*(a1-a0); + float lx = p1->x + cosf(a) * lw; + float ly = p1->y + sinf(a) * lw; + vset(lx, ly, lu,1); + vset(p1->x, p1->y, 0.5f,1); + } + + vset(p1->x + dlx1*rw, p1->y + dly1*rw, lu,1); + vset(rx1, ry1, ru,1); + + } +} + + +void GraphicsNode::bevelJoin(VecPoint* p0, VecPoint* p1, float lw, float rw, float lu, float ru, float fringe) +{ + float rx0,ry0,rx1,ry1; + float lx0,ly0,lx1,ly1; + float dlx0 = p0->dy; + float dly0 = -p0->dx; + float dlx1 = p1->dy; + float dly1 = -p1->dx; + + if (p1->flags & PT_LEFT) { + chooseBevel(p1->flags & PT_INNERBEVEL, p0, p1, lw, &lx0,&ly0, &lx1,&ly1); + + vset(lx0, ly0, lu,1); + vset(p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); + +// if (p1->flags & PT_BEVEL) { +// vset(lx0, ly0, lu,1); +// vset(p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); +// +// vset(lx1, ly1, lu,1); +// vset(p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); +// } else { +// rx0 = p1->x - p1->dmx * rw; +// ry0 = p1->y - p1->dmy * rw; +// +// vset(p1->x, p1->y, 0.5f,1); +// vset(p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); +// +// vset(rx0, ry0, ru,1); +// vset(rx0, ry0, ru,1); +// +// vset(p1->x, p1->y, 0.5f,1); +// vset(p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); +// } + + vset(lx1, ly1, lu,1); + vset(p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); + + } else { + chooseBevel(p1->flags & PT_INNERBEVEL, p0, p1, -rw, &rx0,&ry0, &rx1,&ry1); + + vset(p1->x + dlx0*lw, p1->y + dly0*lw, lu,1); + vset(rx0, ry0, ru,1); + +// if (p1->flags & PT_BEVEL) { +// vset(p1->x + dlx0*lw, p1->y + dly0*lw, lu,1); +// vset(rx0, ry0, ru,1); +// +// vset(p1->x + dlx1*lw, p1->y + dly1*lw, lu,1); +// vset(rx1, ry1, ru,1); +// } else { +// lx0 = p1->x + p1->dmx * lw; +// ly0 = p1->y + p1->dmy * lw; +// +// vset(p1->x + dlx0*lw, p1->y + dly0*lw, lu,1); +// vset(p1->x, p1->y, 0.5f,1); +// +// vset(lx0, ly0, lu,1); +// vset(lx0, ly0, lu,1); +// +// vset(p1->x + dlx1*lw, p1->y + dly1*lw, lu,1); +// vset(p1->x, p1->y, 0.5f,1); +// } + + vset(p1->x + dlx1*lw, p1->y + dly1*lw, lu,1); + vset(rx1, ry1, ru,1); + } +} + + +void GraphicsNode::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) +{ + _customCommand.init(_globalZOrder); + _customCommand.func = CC_CALLBACK_0(GraphicsNode::onDraw, this, transform, flags); + renderer->addCommand(&_customCommand); +} + + +void GraphicsNode::onDraw(const Mat4 &transform, uint32_t flags) +{ + if (!_verts || _nCommands <=0) return; + + auto program = getGLProgram(); + program->use(); + program->setUniformsForBuiltins(transform); + + glBlendFunc(BlendFunc::ALPHA_NON_PREMULTIPLIED.src, BlendFunc::ALPHA_NON_PREMULTIPLIED.dst); + + glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]); + + if (_vertsDirty) { + glBufferData(GL_ARRAY_BUFFER, sizeof(VecVertex) * _vertsOffset, _verts, GL_DYNAMIC_DRAW); + + _vertsDirty = false; + } + + if (_indicesDirty) { + glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(_indices[0]) * _indicesOffset, _indices, GL_STREAM_DRAW); + + _indicesDirty = false; + } + + GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POSITION | GL::VERTEX_ATTRIB_FLAG_TEX_COORD); + + glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(VecVertex), (const GLvoid*)(size_t)0); + glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORD, 2, GL_FLOAT, GL_FALSE, sizeof(VecVertex), (const GLvoid*)(0 + 2*sizeof(float))); + + + GLint colorLocation = program->getUniformLocation("color"); + GLint strokeMultLocation = program->getUniformLocation("strokeMult"); + + // draw paths + for (int i = 0; i < _nCommands; i++) { + Command* cmd = _commands[i]; + + if (cmd->nIndices) { + Color4F& color = cmd->color; + program->setUniformLocationWith4f(colorLocation, color.r, color.g, color.b, color.a); + program->setUniformLocationWith1f(strokeMultLocation, cmd->strokeMult); + + glDrawElements(GL_TRIANGLES, (GLsizei)cmd->nIndices, GL_UNSIGNED_SHORT, (const GLvoid *)((size_t)cmd->indicesOffset*2)); + + CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1, cmd->nVerts); + } + } + + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + + CHECK_GL_ERROR_DEBUG(); +} + +} \ No newline at end of file diff --git a/native/cocos/editor-support/creator/CCGraphicsNode.frag b/native/cocos/editor-support/creator/CCGraphicsNode.frag new file mode 100755 index 0000000000..19d6a067d1 --- /dev/null +++ b/native/cocos/editor-support/creator/CCGraphicsNode.frag @@ -0,0 +1,23 @@ + +const char* ccGraphicsFrag = STRINGIFY( +//\n#ifdef GL_ES\n +//precision mediump float; +//\n#endif\n + +varying vec2 v_texCoord; +uniform float strokeMult; +uniform vec4 color; + +// Stroke - from [0..1] to clipped pyramid, where the slope is 1px. +float strokeMask() { + return min(1.0, (1.0-abs(v_texCoord.x*2.0-1.0))*strokeMult) * min(1.0, v_texCoord.y); +} + +void main(void) { + + float strokeAlpha = strokeMask(); + + gl_FragColor = vec4(color.rgb, color.a * strokeAlpha); +} + +); \ No newline at end of file diff --git a/native/cocos/editor-support/creator/CCGraphicsNode.h b/native/cocos/editor-support/creator/CCGraphicsNode.h new file mode 100644 index 0000000000..23e2e558a2 --- /dev/null +++ b/native/cocos/editor-support/creator/CCGraphicsNode.h @@ -0,0 +1,295 @@ + +/**************************************************************************** + Copyright (c) 2016 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 __CREATOR_CCGRAPHICSNODE_H__ +#define __CREATOR_CCGRAPHICSNODE_H__ + +#include "2d/CCNode.h" +#include "renderer/CCCustomCommand.h" + +namespace creator { + +// join: bevel, round, miter +// cap : butt, round, square +enum LineCap +{ + CAP_BUTT, + CAP_ROUND, + CAP_SQUARE, +}; + +enum LineJoin +{ + JOIN_BEVEL, + JOIN_ROUND, + JOIN_MITER, +}; + +enum PointFlags +{ + PT_CORNER = 0x01, + PT_LEFT = 0x02, + PT_BEVEL = 0x04, + PT_INNERBEVEL = 0x08, +}; + +struct VecVertex { + float x,y,u,v; +}; +typedef struct VecVertex VecVertex; + +class VecPoint: public cocos2d::Vec2 +{ +public: + VecPoint() + { + reset(); + } + + VecPoint(float x, float y) + : Vec2(x, y) + { + reset(); + } + + void reset () { + dx = 0; + dy = 0; + dmx = 0; + dmy = 0; + flags = 0; + len = 0; + } + + float dx; + float dy; + float dmx; + float dmy; + unsigned char flags; + float len; +}; + +typedef std::vector< VecPoint* > VecPointVector; + +struct Path +{ + VecPointVector points; + bool closed; + bool convex; + int nbevel; + + bool complex; +}; +typedef struct Path Path; + +struct Command +{ + cocos2d::Color4F color; + float strokeMult; + + int nVerts; + int vertsOffset; + int nIndices; + int indicesOffset; +}; +typedef struct Command Command; +typedef std::vector< Command* > CommandVector; + + +class GraphicsNode: public cocos2d::Node +{ +public: + + static GraphicsNode* create(); + + void setLineCap(LineCap cap) { _lineCap = cap; } + LineCap getLineCap() { return _lineCap; } + + void setLineJoin(LineJoin join) { _lineJoin = join; } + LineJoin getLineJoin() { return _lineJoin; } + + void setLineWidth(float width) { _lineWidth = width; } + float getLineWidth() { return _lineWidth; } + + void setMiterLimit(float miterLimit) { _miterLimit = miterLimit; } + float getMiterLimit() { return _miterLimit; } + + void setStrokeColor(const cocos2d::Color4F& color) { + _strokeColor = color; + } + cocos2d::Color4F getStrokeColor() { return _strokeColor; } + + void setFillColor(const cocos2d::Color4F& color) { _fillColor = color; } + cocos2d::Color4F getFillColor() { return _fillColor; } + + void setDeviceRatio(float ratio) { + _ratio = ratio; + _fringeWidth = 1.0f / _ratio; + _tessTol = 0.25f / _ratio; + _distTol = 0.01f / _ratio; + } + float getDeviceRatio() { return _ratio; } + + // draw command + void moveTo(float x, float y); + void lineTo(float x, float y); + void bezierCurveTo(float c1x, float c1y, float c2x, float c2y, float x, float y); + void quadraticCurveTo(float cx, float cy, float x, float y); + void arcTo(float x1, float y1, float x2, float y2, float radius); + + void arc(float cx, float cy, float r, float startAngle, float endAngle, bool counterclockwise); + void rect(float x, float y, float w, float h); + void roundedRect(float x, float y, float w, float h, float r); + void ellipse(float cx, float cy, float rx, float ry); + void circle(float cx, float cy, float r); + + void fillRect(float x, float y, float w, float h); + + void close(); + + void beginPath(); + + void stroke(); + void fill(); + + void clear(bool clean=false); +public: + + void draw(cocos2d::Renderer *renderer, const cocos2d::Mat4 &transform, uint32_t flags); + void onDraw(const cocos2d::Mat4 &transform, uint32_t flags); + +public: + + GraphicsNode(); + virtual ~GraphicsNode(); + +protected: + + static int mini(int a, int b) { return a < b ? a : b; } + static int maxi(int a, int b) { return a > b ? a : b; } + static int clampi(int a, int mn, int mx) { return a < mn ? mn : (a > mx ? mx : a); } + static float minf(float a, float b) { return a < b ? a : b; } + static float maxf(float a, float b) { return a > b ? a : b; } + static float absf(float a) { return a >= 0.0f ? a : -a; } + static float signf(float a) { return a >= 0.0f ? 1.0f : -1.0f; } + static float clampf(float a, float mn, float mx) { return a < mn ? mn : (a > mx ? mx : a); } + static float cross(float dx0, float dy0, float dx1, float dy1) { return dx1*dy0 - dx0*dy1; } + + static int ptEquals(float x1, float y1, float x2, float y2, float tol); + static float distPtSeg(float x, float y, float px, float py, float qx, float qy); + + static float normalize(float *x, float* y); + static int curveDivs(float r, float arc, float tol); + + static void chooseBevel(int bevel, VecPoint* p0, VecPoint* p1, float w, + float* x0, float* y0, float* x1, float* y1); + +protected: + void tesselateBezier(float x1, float y1, float x2, float y2, + float x3, float y3, float x4, float y4, + int level, int type); + + void addPoint(Path* path, float x, float y, int flags); + Path* addPath(); + + void flattenPaths(); + + void expandStroke(float w, int lineCap, int lineJoin, float miterLimit); + void expandFill(float w, int lineJoin, float miterLimit); + + void calculateJoins(float w, int lineJoin, float miterLimit); + + void allocVerts(int count); + void allocIndices(int count); + + void vset(float x, float y, float u, float v); + + void pushCommand(cocos2d::Color4F& color, float strokeMult, int vertsOffset, int nVerts, int indicesOffset, int nIndices); + + void buttCapStart(VecPoint* p, float dx, float dy, float w, float d, float aa); + void buttCapEnd(VecPoint* p, float dx, float dy, float w, float d, float aa); + void roundCapStart(VecPoint* p, float dx, float dy, float w, int ncap, float aa); + void roundCapEnd(VecPoint* p, float dx, float dy, float w, int ncap, float aa); + + void roundJoin(VecPoint* p0, VecPoint* p1, float lw, float rw, float lu, float ru, int ncap, float fringe); + void bevelJoin(VecPoint* p0, VecPoint* p1, float lw, float rw, float lu, float ru, float fringe); +protected: + + cocos2d::CustomCommand _customCommand; + + bool _vertsDirty; + bool _indicesDirty; + bool _needUpdatePathOffset; + + + GLuint _buffersVBO[2]; + float _ratio; + + float _lineWidth; + float _miterLimit; + LineCap _lineCap; + LineJoin _lineJoin; + cocos2d::Color4F _strokeColor; + cocos2d::Color4F _fillColor; + + float _fringeWidth; + + float _tessTol; + float _distTol; + + float _commandx; + float _commandy; + + // points + int _nPoints; + VecPointVector _points; + + // commands + int _nCommands; + CommandVector _commands; + + + // path + int _nPath; + int _pathOffset; + std::vector _paths; + + Path* _curPath; + + // verts + int _nVerts; + int _vertsOffset; + VecVertex* _verts; + + // indices + int _nIndices; + int _indicesOffset; + GLushort* _indices; +}; + +} + +#endif /* defined(__CREATOR_CCGRAPHICSNODE_H__) */ diff --git a/native/cocos/editor-support/creator/CCGraphicsNode.vert b/native/cocos/editor-support/creator/CCGraphicsNode.vert new file mode 100755 index 0000000000..2d66ab4465 --- /dev/null +++ b/native/cocos/editor-support/creator/CCGraphicsNode.vert @@ -0,0 +1,18 @@ + +const char* ccGraphicsVert = STRINGIFY( +attribute vec4 a_position; +attribute vec2 a_texCoord; + +\n#ifdef GL_ES\n +varying mediump vec2 v_texCoord; +\n#else\n +varying vec2 v_texCoord; +\n#endif\n + +void main() +{ + gl_Position = CC_MVPMatrix * a_position; + v_texCoord = a_texCoord; +} + +); diff --git a/native/cocos/editor-support/creator/CCScale9Sprite.cpp b/native/cocos/editor-support/creator/CCScale9Sprite.cpp index 87ec089bfe..367730f577 100755 --- a/native/cocos/editor-support/creator/CCScale9Sprite.cpp +++ b/native/cocos/editor-support/creator/CCScale9Sprite.cpp @@ -296,12 +296,15 @@ public: auto hRepeat = contentSize.width / rectWidth; auto vRepeat = contentSize.height / rectHeight; - quads.resize(ceilf(hRepeat) * ceilf(vRepeat)); int quadIndex = 0; + if(ceilf(hRepeat) * ceilf(vRepeat) > (65536 / 4)) { + CCLOGERROR("too many tiles, only 16384 tiles will be show"); + } + quads.resize(fminf(ceilf(hRepeat) * ceilf(vRepeat), 65536 / 4)); for (int hindex = 0; hindex < ceilf(hRepeat); ++hindex) { for (int vindex = 0; vindex < ceilf(vRepeat); ++vindex) { auto& quad = quads[quadIndex++]; - + quad.bl.colors = colorOpacity; quad.br.colors = colorOpacity; quad.tl.colors = colorOpacity; @@ -324,6 +327,7 @@ public: quad.tr.texCoords = cocos2d::Tex2F(u0 + (u1 - u0) * fminf(1, vRepeat - vindex), v1 + (v0 - v1) * fminf(1, hRepeat - hindex)); } + if(quadIndex >= quads.size()) break; } } return quads; diff --git a/native/cocos/editor-support/creator/Triangulate.cpp b/native/cocos/editor-support/creator/Triangulate.cpp new file mode 100644 index 0000000000..267d78b1d5 --- /dev/null +++ b/native/cocos/editor-support/creator/Triangulate.cpp @@ -0,0 +1,139 @@ +#include +#include +#include +#include + +#include "triangulate.h" + +#define EPSILON 0.0000000001f + +float Triangulate::area(const VecVertex *contour, int offset, int n) { + float A=0.0f; + + for(int p=n-1,q=offset; q= 0.0f) && (bCROSScp >= 0.0f) && (cCROSSap >= 0.0f)); +}; + +bool Triangulate::snip(const VecVertex *contour, int offset, int n, int u, int v, int w, int *V) +{ + int p; + float Ax, Ay, Bx, By, Cx, Cy, Px, Py; + + Ax = contour[V[u]].x; + Ay = contour[V[u]].y; + + Bx = contour[V[v]].x; + By = contour[V[v]].y; + + Cx = contour[V[w]].x; + Cy = contour[V[w]].y; + + if ( EPSILON > (((Bx-Ax)*(Cy-Ay)) - ((By-Ay)*(Cx-Ax))) ) { + return false; + } + + for (p = offset; p < n; p++) { + if ( (p == u) || (p == v) || (p == w) ) { + continue; + } + Px = contour[V[p]].x; + Py = contour[V[p]].y; + if ( insideTriangle(Ax,Ay,Bx,By,Cx,Cy,Px,Py) ) { + return false; + } + } + + return true; +} + +bool Triangulate::process(const VecVertex *contour, int offset, int n, std::vector &result) +{ + /* allocate and initialize list of Vertices in polygon */ + + if ( n < 3 ) return false; + + int *V = new int[n]; + + /* we want a counter-clockwise polygon in V */ + + if ( 0.0f < area(contour, offset, n) ) + for (int v=0; v2; ) + { + /* if we loop, it is probably a non-simple polygon */ + if (0 >= (count--)) + { + //** Triangulate: ERROR - probable bad polygon! + return false; + } + + /* three consecutive vertices in current polygon, */ + int u = v ; if (nv <= u) u = 0; /* previous */ + v = u+1; if (nv <= v) v = 0; /* new v */ + int w = v+1; if (nv <= w) w = 0; /* next */ + + if ( snip(contour, offset, nv, u, v, w, V) ) + { + int a,b,c,s,t; + + /* true names of the vertices */ + a = V[u]; b = V[v]; c = V[w]; + + /* output Triangle */ + result.push_back( a ); + result.push_back( b ); + result.push_back( c ); + + m++; + + /* remove v from remaining polygon */ + for(s=v,t=v+1;t // Include STL vector class. +#include "CCGraphicsNode.h" + +using namespace creator; + +class Triangulate +{ + public: + + // triangulate a contour/polygon, places results in STL vector + // as series of triangles. + static bool process(const VecVertex *contour, int offset, int n, std::vector &result); + + // compute area of a contour/polygon + static float area(const VecVertex *contour, int offset, int n); + + // decide if point Px/Py is inside triangle defined by + // (Ax,Ay) (Bx,By) (Cx,Cy) + static bool insideTriangle(float Ax, float Ay, + float Bx, float By, + float Cx, float Cy, + float Px, float Py); + + + private: + static bool snip(const VecVertex *contour, int offset, int n, int u, int v, int w, int *V); + +}; + + +#endif \ No newline at end of file diff --git a/native/cocos/platform/android/CCDevice-android.cpp b/native/cocos/platform/android/CCDevice-android.cpp index 639a0b4c1a..c19a92f4b6 100644 --- a/native/cocos/platform/android/CCDevice-android.cpp +++ b/native/cocos/platform/android/CCDevice-android.cpp @@ -36,6 +36,7 @@ THE SOFTWARE. #include "platform/CCFileUtils.h" #define helperClassName "org/cocos2dx/lib/Cocos2dxHelper" +#define LOGD(...) __android_log_print(ANDROID_LOG_ERROR,"",__VA_ARGS__) NS_CC_BEGIN @@ -89,7 +90,7 @@ public: { JniMethodInfo methodInfo; if (! JniHelper::getStaticMethodInfo(methodInfo, "org/cocos2dx/lib/Cocos2dxBitmap", "createTextBitmapShadowStroke", - "(Ljava/lang/String;Ljava/lang/String;IIIIIIIIZFFFFZIIIIF)Z")) + "(Ljava/lang/String;Ljava/lang/String;IIIIIIIIZIIIIFZI)Z")) { CCLOG("%s %d: error to get methodInfo", __FILE__, __LINE__); return false; @@ -97,14 +98,18 @@ public: // Do a full lookup for the font path using FileUtils in case the given font name is a relative path to a font file asset, // or the path has been mapped to a different location in the app package: - std::string fullPathOrFontName = FileUtils::getInstance()->fullPathForFilename(textDefinition._fontName); + std::string fullPathOrFontName = textDefinition._fontName; + if(FileUtils::getInstance()->isFileExist(fullPathOrFontName)) + { + fullPathOrFontName = FileUtils::getInstance()->fullPathForFilename(textDefinition._fontName); + // If the path name returned includes the 'assets' dir then that needs to be removed, because the android.content.Context + // requires this portion of the path to be omitted for assets inside the app package. + if (fullPathOrFontName.find("assets/") == 0) + { + fullPathOrFontName = fullPathOrFontName.substr(strlen("assets/")); // Chop out the 'assets/' portion of the path. + } + } - // If the path name returned includes the 'assets' dir then that needs to be removed, because the android.content.Context - // requires this portion of the path to be omitted for assets inside the app package. - if (fullPathOrFontName.find("assets/") == 0) - { - fullPathOrFontName = fullPathOrFontName.substr(strlen("assets/")); // Chop out the 'assets/' portion of the path. - } /**create bitmap * this method call Cococs2dx.createBitmap()(java code) to create the bitmap, the java code @@ -115,15 +120,16 @@ public: auto jstrText = JniHelper::newStringUTFJNI(methodInfo.env, text); jstring jstrFont = methodInfo.env->NewStringUTF(fullPathOrFontName.c_str()); bool ret = true; - if(!methodInfo.env->CallStaticBooleanMethod(methodInfo.classID, methodInfo.methodID, jstrText, - jstrFont, textDefinition._fontSize, textDefinition._fontFillColor.r, textDefinition._fontFillColor.g, - textDefinition._fontFillColor.b, textDefinition._fontAlpha, - eAlignMask, nWidth, nHeight, - textDefinition._shadow._shadowEnabled, textDefinition._shadow._shadowOffset.width, -textDefinition._shadow._shadowOffset.height, - textDefinition._shadow._shadowBlur, textDefinition._shadow._shadowOpacity, - textDefinition._stroke._strokeEnabled, textDefinition._stroke._strokeColor.r, textDefinition._stroke._strokeColor.g, - textDefinition._stroke._strokeColor.b, textDefinition._stroke._strokeAlpha, textDefinition._stroke._strokeSize)) + jstrFont, textDefinition._fontSize, + textDefinition._fontFillColor.r, textDefinition._fontFillColor.g, + textDefinition._fontFillColor.b, textDefinition._fontAlpha, + eAlignMask, nWidth, nHeight, + textDefinition._stroke._strokeEnabled, + textDefinition._stroke._strokeColor.r, textDefinition._stroke._strokeColor.g, + textDefinition._stroke._strokeColor.b, textDefinition._stroke._strokeAlpha, + textDefinition._stroke._strokeSize, + textDefinition._enableWrap, textDefinition._overflow)) { ret = false; } diff --git a/native/templates/js-template-binary/frameworks/runtime-src/proj.android/libs/android-async-http-1.4.8.jar b/native/cocos/platform/android/java/libs/android-async-http-1.4.8.jar old mode 100755 new mode 100644 similarity index 100% rename from native/templates/js-template-binary/frameworks/runtime-src/proj.android/libs/android-async-http-1.4.8.jar rename to native/cocos/platform/android/java/libs/android-async-http-1.4.8.jar diff --git a/native/cocos/platform/android/java/project.properties b/native/cocos/platform/android/java/project.properties index 88ca83f9d0..61afc8fe54 100755 --- a/native/cocos/platform/android/java/project.properties +++ b/native/cocos/platform/android/java/project.properties @@ -12,4 +12,4 @@ android.library=true # Project target. -target=android-10 +target=android-19 diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java index 074b90b23a..05d97985e8 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java @@ -38,6 +38,7 @@ import android.os.Message; import android.preference.PreferenceManager.OnActivityResultListener; import android.util.Log; import android.view.ViewGroup; +import android.view.View; import android.view.Window; import android.view.WindowManager; @@ -246,6 +247,8 @@ public abstract class Cocos2dxActivity extends Activity { protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); + this.hideVirtualButton(); + onLoadNativeLibraries(); COCOS_ACTIVITY = this; @@ -280,6 +283,7 @@ public abstract class Cocos2dxActivity extends Activity { @Override protected void onResume() { Log.d(TAG, "onResume()"); + this.hideVirtualButton(); super.onResume(); resumeIfHasFocus(); } @@ -295,6 +299,7 @@ public abstract class Cocos2dxActivity extends Activity { private void resumeIfHasFocus() { if(isHasFocus) { + this.hideVirtualButton(); Cocos2dxHelper.onResume(); mGLSurfaceView.onResume(); } @@ -384,6 +389,20 @@ public abstract class Cocos2dxActivity extends Activity { return glSurfaceView; } + protected void hideVirtualButton() { + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + + getWindow().getDecorView().setSystemUiVisibility( + View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar + | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar + | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); + } + } + private static boolean isAndroidEmulator() { String model = Build.MODEL; Log.d(TAG, "model=" + model); diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java index 9bfd713f7e..bf43de4c6d 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java @@ -26,6 +26,7 @@ package org.cocos2dx.lib; import android.graphics.Bitmap; import android.graphics.Canvas; +import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.text.Layout; @@ -57,12 +58,74 @@ public final class Cocos2dxBitmap { private static native void nativeInitBitmapDC(final int width, final int height, final byte[] pixels); - public static boolean createTextBitmapShadowStroke(final String string, final String fontName, int fontSize, - int fontTintR, int fontTintG, int fontTintB, int fontTintA, - int alignment, int width, int height, - boolean shadow, float shadowDX, float shadowDY, float shadowBlur, float shadowOpacity, - boolean stroke, int strokeR, int strokeG, int strokeB, int strokeA, float strokeSize) + //http://egoco.de/post/19077604048/calculating-the-height-of-text-in-android + public static int getTextHeight(String text, int maxWidth, float textSize, Typeface typeface) { + TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG); + paint.setTextSize(textSize); + paint.setTypeface(typeface); + + int lineCount = 0; + + int index = 0; + int length = text.length(); + + while(index < length) { + index += paint.breakText(text, index, length, true, maxWidth, null); + lineCount++; + } + + float actualHeight = (Math.abs(paint.ascent()) + Math.abs(paint.descent())); + + return (int)Math.floor(lineCount * actualHeight); + } + + public static Typeface calculateShrinkTypeFace(String text, int width, int height, Layout.Alignment hAlignment, float textSize, TextPaint paint, boolean enableWrap) { + if (width == 0 || height == 0) { + return paint.getTypeface(); + } + float actualWidth = width + 1; + float actualHeight = height + 1; + float fontSize = textSize + 1; + + if (!enableWrap) { + while (actualWidth > width || actualHeight > height) { + fontSize = fontSize - 1; + + actualWidth = (int)Math.ceil( StaticLayout.getDesiredWidth(text, paint)); + actualHeight = getTextHeight(text, (int)actualWidth, fontSize, paint.getTypeface()); + + paint.setTextSize(fontSize); + if (fontSize <= 0) { + paint.setTextSize(textSize); + break; + } + } + } else { + while (actualHeight > height || actualWidth > width) { + fontSize = fontSize - 1; + + Layout layout = new StaticLayout(text, paint, (int) width, hAlignment,1.0f,0.0f,false); + actualWidth = layout.getWidth(); + actualHeight = layout.getLineTop(layout.getLineCount()); + + paint.setTextSize(fontSize); + + if (fontSize <= 0) { + paint.setTextSize(textSize); + break; + } + } + + } + return paint.getTypeface(); + } + + public static boolean createTextBitmapShadowStroke(final String string, final String fontName, int fontSize, + int fontTintR, int fontTintG, int fontTintB, int fontTintA, + int alignment, int width, int height, + boolean stroke, int strokeR, int strokeG, int strokeB, int strokeA, float strokeSize, boolean enableWrap, int overflow) { + Layout.Alignment hAlignment = Layout.Alignment.ALIGN_NORMAL; int horizontalAlignment = alignment & 0x0F; switch (horizontalAlignment) { @@ -79,18 +142,35 @@ public final class Cocos2dxBitmap { } TextPaint paint = Cocos2dxBitmap.newPaint(fontName, fontSize); + if (stroke) { paint.setStyle(TextPaint.Style.STROKE); paint.setStrokeWidth(strokeSize); } int maxWidth = width; + if (maxWidth <= 0) { maxWidth = (int)Math.ceil( StaticLayout.getDesiredWidth(string, paint)); } - StaticLayout staticLayout = new StaticLayout(string, paint, maxWidth , hAlignment,1.0f,0.0f,false); - int layoutWidth = staticLayout.getWidth(); - int layoutHeight = staticLayout.getLineTop(staticLayout.getLineCount()); + + Layout layout = null; + int layoutWidth = 0; + int layoutHeight = 0; + + + if (overflow == 1 && !enableWrap){ + int widthBoundary = (int)Math.ceil( StaticLayout.getDesiredWidth(string, paint)); + layout = new StaticLayout(string, paint, widthBoundary , hAlignment,1.0f,0.0f,false); + }else { + if (overflow == 2) { + calculateShrinkTypeFace(string, width, height, hAlignment, fontSize, paint, enableWrap); + } + layout = new StaticLayout(string, paint, maxWidth , hAlignment,1.0f,0.0f,false); + } + + layoutWidth = layout.getWidth(); + layoutHeight = layout.getLineTop(layout.getLineCount()); int bitmapWidth = Math.max(layoutWidth, width); int bitmapHeight = layoutHeight; @@ -98,6 +178,12 @@ public final class Cocos2dxBitmap { bitmapHeight = height; } + if (overflow == 1 && !enableWrap) { + if (width > 0) { + bitmapWidth = width; + } + } + if (bitmapWidth == 0 || bitmapHeight == 0) { return false; } @@ -128,11 +214,11 @@ public final class Cocos2dxBitmap { if ( stroke ) { paint.setARGB(strokeA, strokeR, strokeG, strokeB); - staticLayout.draw(canvas); + layout.draw(canvas); } paint.setStyle(TextPaint.Style.FILL); paint.setARGB(fontTintA, fontTintR, fontTintG, fontTintB); - staticLayout.draw(canvas); + layout.draw(canvas); Cocos2dxBitmap.initNativeObject(bitmap); return true; diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxDownloader.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxDownloader.java new file mode 100644 index 0000000000..8e620e2632 --- /dev/null +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxDownloader.java @@ -0,0 +1,325 @@ +package org.cocos2dx.lib; + +import com.loopj.android.http.AsyncHttpClient; +import com.loopj.android.http.AsyncHttpResponseHandler; +import com.loopj.android.http.BinaryHttpResponseHandler; +import com.loopj.android.http.FileAsyncHttpResponseHandler; +import com.loopj.android.http.RequestHandle; + +import org.apache.http.Header; +import org.apache.http.message.BasicHeader; + +import java.io.File; +import java.util.*; + +class DataTaskHandler extends BinaryHttpResponseHandler { + int _id; + private Cocos2dxDownloader _downloader; + private long _lastBytesWritten; + + void LogD(String msg) { + android.util.Log.d("Cocos2dxDownloader", msg); + } + + public DataTaskHandler(Cocos2dxDownloader downloader, int id) { + super(new String[]{".*"}); + _downloader = downloader; + _id = id; + _lastBytesWritten = 0; + } + + @Override + public void onProgress(long bytesWritten, long totalSize) { + //LogD("onProgress(bytesWritten:" + bytesWritten + " totalSize:" + totalSize); + long dlBytes = bytesWritten - _lastBytesWritten; + long dlNow = bytesWritten; + long dlTotal = totalSize; + _downloader.onProgress(_id, dlBytes, dlNow, dlTotal); + _lastBytesWritten = bytesWritten; + } + + @Override + public void onStart() { + _downloader.onStart(_id); + } + + @Override + public void onFailure(int i, Header[] headers, byte[] errorResponse, Throwable throwable) { + LogD("onFailure(i:" + i + " headers:" + headers + " throwable:" + throwable); + String errStr = ""; + if (null != throwable) { + errStr = throwable.toString(); + } + _downloader.onFinish(_id, i, errStr, null); + } + + @Override + public void onSuccess(int i, Header[] headers, byte[] binaryData) { + LogD("onSuccess(i:" + i + " headers:" + headers); + _downloader.onFinish(_id, 0, null, binaryData); + } +} + +class FileTaskHandler extends FileAsyncHttpResponseHandler { + int _id; + File _finalFile; + + private long _initFileLen; + private long _lastBytesWritten; + private Cocos2dxDownloader _downloader; + + void LogD(String msg) { + android.util.Log.d("Cocos2dxDownloader", msg); + } + + public FileTaskHandler(Cocos2dxDownloader downloader, int id, File temp, File finalFile) { + super(temp, true); + _finalFile = finalFile; + _downloader = downloader; + _id = id; + _initFileLen = getTargetFile().length(); + _lastBytesWritten = 0; + } + + @Override + public void onProgress(long bytesWritten, long totalSize) { + //LogD("onProgress(bytesWritten:" + bytesWritten + " totalSize:" + totalSize); + long dlBytes = bytesWritten - _lastBytesWritten; + long dlNow = bytesWritten + _initFileLen; + long dlTotal = totalSize + _initFileLen; + _downloader.onProgress(_id, dlBytes, dlNow, dlTotal); + _lastBytesWritten = bytesWritten; + } + + @Override + public void onStart() { + _downloader.onStart(_id); + } + + @Override + public void onFinish() { + // onFinish called after onSuccess/onFailure + _downloader.runNextTaskIfExists(); + } + + @Override + public void onFailure(int i, Header[] headers, Throwable throwable, File file) { + LogD("onFailure(i:" + i + " headers:" + headers + " throwable:" + throwable + " file:" + file); + String errStr = ""; + if (null != throwable) { + errStr = throwable.toString(); + } + _downloader.onFinish(_id, i, errStr, null); + } + + @Override + public void onSuccess(int i, Header[] headers, File file) { + LogD("onSuccess(i:" + i + " headers:" + headers + " file:" + file); + String errStr = null; + do { + // rename temp file to final file + // if final file exist, remove it + if (_finalFile.exists()) { + if (_finalFile.isDirectory()) { + errStr = "Dest file is directory:" + _finalFile.getAbsolutePath(); + break; + } + if (false == _finalFile.delete()) { + errStr = "Can't remove old file:" + _finalFile.getAbsolutePath(); + break; + } + } + + File tempFile = getTargetFile(); + tempFile.renameTo(_finalFile); + } while (false); + _downloader.onFinish(_id, 0, errStr, null); + } +} + +class DownloadTask { + + DownloadTask() { + handle = null; + handler = null; + resetStatus(); + } + + void resetStatus() { + bytesReceived = 0; + totalBytesReceived = 0; + totalBytesExpected = 0; + data = null; + } + + RequestHandle handle; + AsyncHttpResponseHandler handler; + + // progress + long bytesReceived; + long totalBytesReceived; + long totalBytesExpected; + byte[] data; + +} + +public class Cocos2dxDownloader { + private int _id; + private AsyncHttpClient _httpClient = new AsyncHttpClient(); + private String _tempFileNameSufix; + private int _countOfMaxProcessingTasks; + private HashMap _taskMap = new HashMap(); + private Queue _taskQueue = new LinkedList(); + private int _runningTaskCount = 0; + + void onProgress(final int id, final long downloadBytes, final long downloadNow, final long downloadTotal) { + DownloadTask task = (DownloadTask)_taskMap.get(id); + if (null != task) { + task.bytesReceived = downloadBytes; + task.totalBytesReceived = downloadNow; + task.totalBytesExpected = downloadTotal; + } + Cocos2dxHelper.runOnGLThread(new Runnable() { + @Override + public void run() { + nativeOnProgress(_id, id, downloadBytes, downloadNow, downloadTotal); + } + }); + } + + public void onStart(int id) { + DownloadTask task = (DownloadTask)_taskMap.get(id); + if (null != task) { + task.resetStatus(); + } + } + + public void onFinish(final int id, final int errCode, final String errStr, final byte[] data) { + DownloadTask task = (DownloadTask)_taskMap.get(id); + if (null == task) return; + _taskMap.remove(id); + Cocos2dxHelper.runOnGLThread(new Runnable() { + @Override + public void run() { + nativeOnFinish(_id, id, errCode, errStr, data); + } + }); + } + + public static Cocos2dxDownloader createDownloader(int id, int timeoutInSeconds, String tempFileNameSufix, int countOfMaxProcessingTasks) { + Cocos2dxDownloader downloader = new Cocos2dxDownloader(); + downloader._id = id; + + downloader._httpClient.setEnableRedirects(true); + if (timeoutInSeconds > 0) { + downloader._httpClient.setTimeout(timeoutInSeconds * 1000); + } + // downloader._httpClient.setMaxRetriesAndTimeout(3, timeoutInSeconds * 1000); + downloader._httpClient.allowRetryExceptionClass(javax.net.ssl.SSLException.class); + + downloader._tempFileNameSufix = tempFileNameSufix; + downloader._countOfMaxProcessingTasks = countOfMaxProcessingTasks; + return downloader; + } + + public static void createTask(final Cocos2dxDownloader downloader, int id_, String url_, String path_) { + final int id = id_; + final String url = url_; + final String path = path_; + + Runnable taskRunnable = new Runnable() { + @Override + public void run() { + DownloadTask task = new DownloadTask(); + if (0 == path.length()) { + // data task + task.handler = new DataTaskHandler(downloader, id); + task.handle = downloader._httpClient.get(Cocos2dxHelper.getActivity(), url, task.handler); + } + + do { + if (0 == path.length()) break; + // file task + File tempFile = new File(path + downloader._tempFileNameSufix); + if (tempFile.isDirectory()) break; + + File parent = tempFile.getParentFile(); + if (!parent.isDirectory() && !parent.mkdirs()) break; + + File finalFile = new File(path); + if (tempFile.isDirectory()) break; + + task.handler = new FileTaskHandler(downloader, id, tempFile, finalFile); + Header[] headers = null; + long fileLen = tempFile.length(); + if (fileLen > 0) { + // continue download + List
list = new ArrayList
(); + list.add(new BasicHeader("Range", "bytes=" + fileLen + "-")); + headers = list.toArray(new Header[list.size()]); + } + task.handle = downloader._httpClient.get(Cocos2dxHelper.getActivity(), url, headers, null, task.handler); + //task.handle = downloader._httpClient.get(url, task.handler); + } while (false); + + if (null == task.handle) { + final String errStr = "Can't create DownloadTask for " + url; + Cocos2dxHelper.runOnGLThread(new Runnable() { + @Override + public void run() { + downloader.nativeOnFinish(downloader._id, id, 0, errStr, null); + } + }); + } else { + downloader._taskMap.put(id, task); + } + } + }; + downloader.enqueueTask(taskRunnable); + } + + public static void cancelAllRequests(final Cocos2dxDownloader downloader) { + Cocos2dxHelper.getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + + //downloader._httpClient.cancelAllRequests(true); + Iterator iter = downloader._taskMap.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = (Map.Entry) iter.next(); + //Object key = entry.getKey(); + DownloadTask task = (DownloadTask) entry.getValue(); + if (null != task.handle) { + task.handle.cancel(true); + } + } + } + }); + } + + + public void enqueueTask(Runnable taskRunnable) { + synchronized (_taskQueue) { + if (_runningTaskCount < _countOfMaxProcessingTasks) { + Cocos2dxHelper.getActivity().runOnUiThread(taskRunnable); + _runningTaskCount++; + } else { + _taskQueue.add(taskRunnable); + } + } + } + + public void runNextTaskIfExists() { + synchronized (_taskQueue) { + Runnable taskRunnable = Cocos2dxDownloader.this._taskQueue.poll(); + if (taskRunnable != null) { + Cocos2dxHelper.getActivity().runOnUiThread(taskRunnable); + } else { + _runningTaskCount--; + } + } + } + + native void nativeOnProgress(int id, int taskId, long dl, long dlnow, long dltotal); + native void nativeOnFinish(int id, int taskId, int errCode, String errStr, final byte[] data); +} diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBox.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBox.java index 7a5d23ad76..53189dee44 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBox.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBox.java @@ -99,6 +99,11 @@ public class Cocos2dxEditBox extends EditText { */ private final int kEditBoxInputFlagInitialCapsAllCharacters = 4; + /** + * Lowercase all characters automatically. + */ + private final int kEditBoxInputFlagLowercaseAllCharacters = 5; + private final int kKeyboardReturnTypeDefault = 0; private final int kKeyboardReturnTypeDone = 1; private final int kKeyboardReturnTypeSend = 2; @@ -239,6 +244,9 @@ public class Cocos2dxEditBox extends EditText { case kEditBoxInputFlagInitialCapsAllCharacters: this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS; break; + case kEditBoxInputFlagLowercaseAllCharacters: + this.mInputFlagConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL; + break; default: break; } diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxHelper.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxHelper.java index a49cb1d7e6..2e83a0cd6e 100644 --- a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxHelper.java +++ b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxHelper.java @@ -28,6 +28,8 @@ import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.graphics.Typeface; +import android.os.Looper; +import android.renderscript.Type; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; @@ -94,7 +96,7 @@ public class Cocos2dxEditBoxHelper { final Cocos2dxEditBox editBox = new Cocos2dxEditBox(Cocos2dxActivity.COCOS_ACTIVITY); editBox.setFocusable(true); editBox.setFocusableInTouchMode(true); - editBox.setInputFlag(4); //kEditBoxInputFlagInitialCapsAllCharacters + editBox.setInputFlag(5); //kEditBoxInputFlagLowercaseAllCharacters editBox.setInputMode(6); //kEditBoxInputModeSingleLine editBox.setReturnType(0); //kKeyboardReturnTypeDefault editBox.setHintTextColor(Color.GRAY); @@ -148,6 +150,7 @@ public class Cocos2dxEditBoxHelper { public void afterTextChanged(Editable s) { } + }); @@ -187,8 +190,7 @@ public class Cocos2dxEditBoxHelper { (keyCode == KeyEvent.KEYCODE_ENTER)) { //if editbox doesn't support multiline, just hide the keyboard if ((editBox.getInputType() & InputType.TYPE_TEXT_FLAG_MULTI_LINE) != InputType.TYPE_TEXT_FLAG_MULTI_LINE) { - Cocos2dxEditBoxHelper.closeKeyboard(index); - Cocos2dxActivity.COCOS_ACTIVITY.getGLSurfaceView().requestFocus(); + Cocos2dxEditBoxHelper.closeKeyboardOnUiThread(index); return true; } } @@ -201,8 +203,7 @@ public class Cocos2dxEditBoxHelper { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { - Cocos2dxEditBoxHelper.closeKeyboard(index); - Cocos2dxActivity.COCOS_ACTIVITY.getGLSurfaceView().requestFocus(); + Cocos2dxEditBoxHelper.closeKeyboardOnUiThread(index); } return false; } @@ -235,6 +236,14 @@ public class Cocos2dxEditBoxHelper { if (editBox != null) { Typeface tf; if (!fontName.isEmpty()) { + if (fontName.endsWith(".ttf")) { + try { + tf = Cocos2dxTypefaces.get(Cocos2dxActivity.COCOS_ACTIVITY.getContext(), fontName); + } catch (final Exception e) { + Log.e("Cocos2dxEditBoxHelper", "error to create ttf type face: " + fontName); + tf = Typeface.create(fontName, Typeface.NORMAL); + } + } tf = Typeface.create(fontName, Typeface.NORMAL); }else{ tf = Typeface.DEFAULT; @@ -306,13 +315,6 @@ public class Cocos2dxEditBoxHelper { Cocos2dxEditBox editBox = sEditBoxArray.get(index); if (editBox != null) { editBox.setVisibility(visible ? View.VISIBLE : View.GONE); - if (visible) { - editBox.requestFocus(); - Cocos2dxEditBoxHelper.openKeyboard(index); - }else{ - Cocos2dxActivity.COCOS_ACTIVITY.getGLSurfaceView().requestFocus(); - Cocos2dxEditBoxHelper.closeKeyboard(index); - } } } }); @@ -380,21 +382,51 @@ public class Cocos2dxEditBoxHelper { }); } - public static void openKeyboard(int index) { - final InputMethodManager imm = (InputMethodManager) Cocos2dxActivity.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + public static void openKeyboard(final int index) { + Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + @Override + public void run() { + openKeyboardOnUiThread(index); + } + }); + } + + public static void closeKeyboard(final int index) { + Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() { + @Override + public void run() { + closeKeyboardOnUiThread(index); + } + }); + } + + private static void openKeyboardOnUiThread(int index) { + if (Looper.myLooper() != Looper.getMainLooper()) { + Log.e(TAG, "openKeyboardOnUiThread doesn't run on UI thread!"); + return; + } + + final InputMethodManager imm = (InputMethodManager) Cocos2dxActivity.COCOS_ACTIVITY.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); Cocos2dxEditBox editBox = sEditBoxArray.get(index); if (null != editBox) { + editBox.requestFocus(); imm.showSoftInput(editBox, 0); Cocos2dxActivity.COCOS_ACTIVITY.getGLSurfaceView().setSoftKeyboardShown(true); } } - public static void closeKeyboard(int index) { - final InputMethodManager imm = (InputMethodManager) Cocos2dxActivity.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + private static void closeKeyboardOnUiThread(int index) { + if (Looper.myLooper() != Looper.getMainLooper()) { + Log.e(TAG, "closeKeyboardOnUiThread doesn't run on UI thread!"); + return; + } + + final InputMethodManager imm = (InputMethodManager) Cocos2dxActivity.COCOS_ACTIVITY.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); Cocos2dxEditBox editBox = sEditBoxArray.get(index); if (null != editBox) { imm.hideSoftInputFromWindow(editBox.getWindowToken(), 0); Cocos2dxActivity.COCOS_ACTIVITY.getGLSurfaceView().setSoftKeyboardShown(false); + Cocos2dxActivity.COCOS_ACTIVITY.getGLSurfaceView().requestFocus(); } } } diff --git a/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxJavascriptJavaBridge.java b/native/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxJavascriptJavaBridge.java new file mode 100644 index 0000000000..9c7cf96359 --- /dev/null +++ b/native/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/native/cocos/platform/apple/CCDevice-apple.h b/native/cocos/platform/apple/CCDevice-apple.h new file mode 100644 index 0000000000..9ab2b957c9 --- /dev/null +++ b/native/cocos/platform/apple/CCDevice-apple.h @@ -0,0 +1,37 @@ +/**************************************************************************** + Copyright (c) 2010-2012 cocos2d-x.org + Copyright (c) 2013-2016 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 CCDevice_apple_hpp +#define CCDevice_apple_hpp + +#include "platform/CCDevice.h" + +namespace FontUtils { + NSMutableParagraphStyle* _calculateParagraphStyle(bool enableWrap, int overflow); + NSTextAlignment _calculateTextAlignment(cocos2d::Device::TextAlign align); + CGFloat _calculateTextDrawStartWidth(cocos2d::Device::TextAlign align, CGSize realDimensions, CGSize dimensions); +} + +#endif /* CCDevice_apple_hpp */ diff --git a/native/cocos/platform/apple/CCDevice-apple.mm b/native/cocos/platform/apple/CCDevice-apple.mm new file mode 100644 index 0000000000..86aea30979 --- /dev/null +++ b/native/cocos/platform/apple/CCDevice-apple.mm @@ -0,0 +1,62 @@ +/**************************************************************************** + Copyright (c) 2010-2012 cocos2d-x.org + Copyright (c) 2013-2016 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 "CCDevice-apple.h" + +namespace FontUtils { + NSMutableParagraphStyle* _calculateParagraphStyle(bool enableWrap, int overflow) + { + NSMutableParagraphStyle* paragraphStyle = [[[NSMutableParagraphStyle alloc] init] autorelease]; + paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping; + return paragraphStyle; + } + + NSTextAlignment _calculateTextAlignment(cocos2d::Device::TextAlign align) + { + unsigned uHoriFlag = (int)align & 0x0f; + NSTextAlignment nsAlign = (2 == uHoriFlag) ? NSTextAlignmentRight + : (3 == uHoriFlag) ? NSTextAlignmentCenter + : NSTextAlignmentLeft; + + return nsAlign; + } + + + + CGFloat _calculateTextDrawStartWidth(cocos2d::Device::TextAlign align, CGSize realDimensions, CGSize dimensions) + { + CGFloat xPadding = 0; + unsigned uHoriFlag = (int)align & 0x0f; + switch (uHoriFlag) { + //center + case 3: xPadding = (dimensions.width - realDimensions.width) / 2.0f; break; + //right + case 2: xPadding = dimensions.width - realDimensions.width; break; + default: break; + } + return xPadding; + } + +} diff --git a/native/cocos/platform/desktop/CCGLViewImpl-desktop.cpp b/native/cocos/platform/desktop/CCGLViewImpl-desktop.cpp index 0e1cbedeec..2f91976cff 100644 --- a/native/cocos/platform/desktop/CCGLViewImpl-desktop.cpp +++ b/native/cocos/platform/desktop/CCGLViewImpl-desktop.cpp @@ -33,6 +33,7 @@ THE SOFTWARE. #include "base/CCEventDispatcher.h" #include "base/CCEventKeyboard.h" #include "base/CCEventMouse.h" +#include "base/CCEventCustom.h" #include "base/CCIMEDispatcher.h" #include "base/ccUtils.h" #include "base/ccUTF8.h" @@ -776,11 +777,21 @@ void GLViewImpl::onGLFWframebuffersize(GLFWwindow* window, int w, int h) void GLViewImpl::onGLFWWindowSizeFunCallback(GLFWwindow *window, int width, int height) { - int frameWidth = width / _frameZoomFactor; - int frameHeight = height / _frameZoomFactor; - setFrameSize(frameWidth, frameHeight); - updateDesignResolutionSize(); - Director::DirectorInstance->setViewport(); + if (width && height && _resolutionPolicy != ResolutionPolicy::UNKNOWN) + { + Size baseDesignSize = _designResolutionSize; + ResolutionPolicy baseResolutionPolicy = _resolutionPolicy; + + int frameWidth = width / _frameZoomFactor; + int frameHeight = height / _frameZoomFactor; + setFrameSize(frameWidth, frameHeight); + setDesignResolutionSize(baseDesignSize.width, baseDesignSize.height, baseResolutionPolicy); + Director::getInstance()->setViewport(); + + EventCustom event("window-resize"); + auto dispatcher = Director::DirectorInstance->getEventDispatcher(); + dispatcher->dispatchEvent(&event); + } } void GLViewImpl::onGLFWWindowIconifyCallback(GLFWwindow* window, int iconified) diff --git a/native/cocos/platform/ios/CCDevice-ios.mm b/native/cocos/platform/ios/CCDevice-ios.mm index 6b8888407b..8fcc76512c 100644 --- a/native/cocos/platform/ios/CCDevice-ios.mm +++ b/native/cocos/platform/ios/CCDevice-ios.mm @@ -29,6 +29,7 @@ #include "CCDevice.h" #include "base/ccTypes.h" +#include "platform/apple/CCDevice-apple.h" #include "base/CCEventDispatcher.h" #include "base/CCEventAcceleration.h" #include "base/CCDirector.h" @@ -37,10 +38,120 @@ // Accelerometer #import #import - +#import // Vibrate #import +static NSAttributedString* __attributedStringWithFontSize(NSMutableAttributedString* attributedString, CGFloat fontSize) +{ + { + [attributedString beginEditing]; + + [attributedString enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, attributedString.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) { + + UIFont* font = value; + font = [font fontWithSize:fontSize]; + + [attributedString removeAttribute:NSFontAttributeName range:range]; + [attributedString addAttribute:NSFontAttributeName value:font range:range]; + }]; + + [attributedString endEditing]; + } + + return [[attributedString copy] autorelease]; +} + +static CGFloat _calculateTextDrawStartHeight(cocos2d::Device::TextAlign align, CGSize realDimensions, CGSize dimensions) +{ + float startH = 0; + // vertical alignment + unsigned int vAlignment = ((int)align >> 4) & 0x0F; + switch (vAlignment) { + //bottom + case 2:startH = dimensions.height - realDimensions.height;break; + //top + case 1:startH = 0;break; + //center + case 3: startH = (dimensions.height - realDimensions.height) / 2;break; + default: + break; + } + return startH; +} + +static CGSize _calculateShrinkedSizeForString(NSAttributedString **str, id font, CGSize constrainSize, bool enableWrap, int& newFontSize) +{ + CGRect actualSize = CGRectMake(0, 0, constrainSize.width + 1, constrainSize.height + 1); + int fontSize = [font pointSize]; + fontSize = fontSize + 1; + + if (!enableWrap) { + while (actualSize.size.width > constrainSize.width || + actualSize.size.height > constrainSize.height) { + fontSize = fontSize - 1; + + NSMutableAttributedString *mutableString = [[*str mutableCopy] autorelease]; + *str = __attributedStringWithFontSize(mutableString, fontSize); + + CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)*str); + CGSize targetSize = CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX); + CGSize fitSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, [(*str) length]), NULL, targetSize, NULL); + CFRelease(framesetter); + if (fitSize.width == 0 || fitSize.height == 0) { + continue; + } + + actualSize.size = fitSize; + + if (constrainSize.width <= 0) { + constrainSize.width = fitSize.width; + } + if (constrainSize.height <= 0) { + constrainSize.height = fitSize.height; + } + if (fontSize <= 0) { + break; + } + } + + } + else { + while (actualSize.size.height > constrainSize.height || + actualSize.size.width > constrainSize.width) { + fontSize = fontSize - 1; + + NSMutableAttributedString *mutableString = [[*str mutableCopy] autorelease]; + *str = __attributedStringWithFontSize(mutableString, fontSize); + + CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)*str); + CGSize targetSize = CGSizeMake(constrainSize.width, CGFLOAT_MAX); + CGSize fitSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, [(*str) length]), NULL, targetSize, NULL); + CFRelease(framesetter); + if (fitSize.width == 0 || fitSize.height == 0) { + continue; + } + + actualSize.size = fitSize; + + if (constrainSize.height <= 0) { + constrainSize.height = fitSize.height; + } + if (constrainSize.width <= 0) { + constrainSize.width = fitSize.width; + } + if (fontSize <= 0) { + break; + } + } + + } + + newFontSize = fontSize; + + return CGSizeMake(actualSize.size.width, actualSize.size.height); +} + #define SENSOR_DELAY_GAME 0.02 @interface CCAccelerometerDispatcher : NSObject @@ -209,17 +320,27 @@ typedef struct } tImageInfo; -static CGSize _calculateStringSize(NSString *str, id font, CGSize *constrainSize) +static CGSize _calculateStringSize(NSAttributedString *str, id font, CGSize *constrainSize, bool enableWrap, int overflow) { CGSize textRect = CGSizeZero; textRect.width = constrainSize->width > 0 ? constrainSize->width - : 0x7fffffff; + : CGFLOAT_MAX; textRect.height = constrainSize->height > 0 ? constrainSize->height - : 0x7fffffff; + : CGFLOAT_MAX; + + if (overflow == 1) { + if(!enableWrap) { + textRect.width = CGFLOAT_MAX; + textRect.height = CGFLOAT_MAX; + } else { + textRect.height = CGFLOAT_MAX; + } + } CGSize dim; - NSDictionary *attibutes = @{NSFontAttributeName:font}; - dim = [str boundingRectWithSize:textRect options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin) attributes:attibutes context:nil].size; + dim = [str boundingRectWithSize:CGSizeMake(textRect.width, textRect.height) + options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) + context:nil].size; dim.width = ceilf(dim.width); dim.height = ceilf(dim.height); @@ -227,97 +348,102 @@ static CGSize _calculateStringSize(NSString *str, id font, CGSize *constrainSize return dim; } -// refer Image::ETextAlign -#define ALIGN_TOP 1 -#define ALIGN_CENTER 3 -#define ALIGN_BOTTOM 2 - -static bool _initWithString(const char * text, cocos2d::Device::TextAlign align, const char * fontName, int size, tImageInfo* info) +static id _createSystemFont( const char * fontName, int size) { + NSString * fntName = [NSString stringWithUTF8String:fontName]; + // On iOS custom fonts must be listed beforehand in the App info.plist (in order to be usable) and referenced only the by the font family name itself when + // calling [UIFont fontWithName]. Therefore even if the developer adds 'SomeFont.ttf' or 'fonts/SomeFont.ttf' to the App .plist, the font must + // be referenced as 'SomeFont' when calling [UIFont fontWithName]. Hence we strip out the folder path components and the extension here in order to get just + // the font family name itself. This stripping step is required especially for references to user fonts stored in CCB files; CCB files appear to store + // the '.ttf' extensions when referring to custom fonts. + fntName = [[fntName lastPathComponent] stringByDeletingPathExtension]; + + // create the font + id font = [UIFont fontWithName:fntName size:size]; + + if (!font) + { + font = [UIFont systemFontOfSize:size]; + } + return font; +} + +static bool _initWithString(const char * text, cocos2d::Device::TextAlign align, const char * fontName, int size, tImageInfo* info, bool enableWrap, int overflow) +{ + bool bRet = false; do { CC_BREAK_IF(! text || ! info); - NSString * str = [NSString stringWithUTF8String:text]; - NSString * fntName = [NSString stringWithUTF8String:fontName]; - - CGSize dim, constrainSize; - - constrainSize.width = info->width; - constrainSize.height = info->height; - - // On iOS custom fonts must be listed beforehand in the App info.plist (in order to be usable) and referenced only the by the font family name itself when - // calling [UIFont fontWithName]. Therefore even if the developer adds 'SomeFont.ttf' or 'fonts/SomeFont.ttf' to the App .plist, the font must - // be referenced as 'SomeFont' when calling [UIFont fontWithName]. Hence we strip out the folder path components and the extension here in order to get just - // the font family name itself. This stripping step is required especially for references to user fonts stored in CCB files; CCB files appear to store - // the '.ttf' extensions when referring to custom fonts. - fntName = [[fntName lastPathComponent] stringByDeletingPathExtension]; - - // create the font - UIFont* font = [UIFont fontWithName:fntName size:size]; - if(font == nil) - { - font = [UIFont systemFontOfSize:size]; - } + id font = _createSystemFont(fontName, size); + CC_BREAK_IF(! font); + + NSString * str = [NSString stringWithUTF8String:text]; + CGSize dimensions; + dimensions.width = info->width; + dimensions.height = info->height; - dim = _calculateStringSize(str, font, &constrainSize); + NSTextAlignment nsAlign = FontUtils::_calculateTextAlignment(align); + NSMutableParagraphStyle* paragraphStyle = FontUtils::_calculateParagraphStyle(enableWrap, overflow); + paragraphStyle.alignment = nsAlign; + + // measure text size with specified font and determine the rectangle to draw text in + + UIColor *foregroundColor = [UIColor colorWithRed:info->tintColorR + green:info->tintColorG + blue:info->tintColorB + alpha:info->tintColorA]; + + //adjust text rect acoording to overflow + NSMutableDictionary* tokenAttributesDict = [NSMutableDictionary dictionaryWithObjectsAndKeys: + foregroundColor,NSForegroundColorAttributeName, + font, NSFontAttributeName, + paragraphStyle, NSParagraphStyleAttributeName, nil]; + + NSAttributedString *stringWithAttributes =[[[NSAttributedString alloc] initWithString:str + attributes:tokenAttributesDict] autorelease]; + + int shrinkFontSize = size; + CGSize realDimensions; + if (overflow == 2) { + realDimensions = _calculateShrinkedSizeForString(&stringWithAttributes, font, dimensions, enableWrap, shrinkFontSize); + } else { + realDimensions = _calculateStringSize(stringWithAttributes, font, &dimensions, enableWrap, overflow); + } + + + CC_BREAK_IF(realDimensions.width <= 0 || realDimensions.height <= 0); + if (dimensions.width <= 0) { + dimensions.width = realDimensions.width; + } + if (dimensions.height <= 0) { + dimensions.height = realDimensions.height; + } // compute start point - int startH = 0; - if (constrainSize.height > dim.height) - { - // vertical alignment - unsigned int vAlignment = ((int)align >> 4) & 0x0F; - if (vAlignment == ALIGN_TOP) - { - startH = 0; - } - else if (vAlignment == ALIGN_CENTER) - { - startH = (constrainSize.height - dim.height) / 2; - } - else - { - startH = constrainSize.height - dim.height; - } - } + CGFloat yPadding = _calculateTextDrawStartHeight(align, realDimensions, dimensions); + CGFloat xPadding = FontUtils::_calculateTextDrawStartWidth(align, realDimensions, dimensions); + + NSInteger POTWide = dimensions.width; + NSInteger POTHigh = dimensions.height; + + CGRect textRect = CGRectMake(xPadding, yPadding, + realDimensions.width, realDimensions.height); - // adjust text rect - if (constrainSize.width > 0 && constrainSize.width > dim.width) - { - dim.width = constrainSize.width; - } - if (constrainSize.height > 0 && constrainSize.height > dim.height) - { - dim.height = constrainSize.height; - } - // compute the padding needed by shadow and stroke - float shadowStrokePaddingX = 0.0f; - float shadowStrokePaddingY = 0.0f; - - if ( info->hasStroke ) - { - shadowStrokePaddingX = ceilf(info->strokeSize); - shadowStrokePaddingY = ceilf(info->strokeSize); - } - - // add the padding (this could be 0 if no shadow and no stroke) - dim.width += shadowStrokePaddingX*2; - dim.height += shadowStrokePaddingY*2; - - unsigned char* data = (unsigned char*)malloc(sizeof(unsigned char) * (int)(dim.width * dim.height * 4)); - memset(data, 0, (int)(dim.width * dim.height * 4)); + NSUInteger textureSize = POTWide * POTHigh * 4; + unsigned char* data = (unsigned char*)malloc(sizeof(unsigned char) * textureSize); + memset(data, 0, textureSize); // draw text CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(data, - dim.width, - dim.height, + POTWide, + POTHigh, 8, - (int)(dim.width) * 4, + POTWide * 4, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); if (!context) @@ -328,74 +454,60 @@ static bool _initWithString(const char * text, cocos2d::Device::TextAlign align, } // text color - CGContextSetRGBFillColor(context, info->tintColorR, info->tintColorG, info->tintColorB, info->tintColorA); - // move Y rendering to the top of the image - CGContextTranslateCTM(context, 0.0f, (dim.height - shadowStrokePaddingY) ); - CGContextScaleCTM(context, 1.0f, -1.0f); //NOTE: NSString draws in UIKit referential i.e. renders upside-down compared to CGBitmapContext referential + CGContextSetRGBFillColor(context, + info->tintColorR, + info->tintColorG, + info->tintColorB, + info->tintColorA); + // move Y rendering to the top of the image + CGContextTranslateCTM(context, 0.0f, POTHigh); + + //NOTE: NSString draws in UIKit referential i.e. renders upside-down compared to CGBitmapContext referential + CGContextScaleCTM(context, 1.0f, -1.0f); // store the current context UIGraphicsPushContext(context); - // measure text size with specified font and determine the rectangle to draw text in - unsigned uHoriFlag = (int)align & 0x0f; - NSTextAlignment nsAlign = (2 == uHoriFlag) ? NSTextAlignmentRight - : (3 == uHoriFlag) ? NSTextAlignmentCenter - : NSTextAlignmentLeft; - - CGColorSpaceRelease(colorSpace); - // compute the rect used for rendering the text - // based on wether shadows or stroke are enabled - - float textOriginX = 0; - float textOrigingY = startH; - - float textWidth = dim.width; - float textHeight = dim.height; - - CGRect rect = CGRectMake(textOriginX, textOrigingY, textWidth, textHeight); - CGContextSetShouldSubpixelQuantizeFonts(context, false); - CGContextBeginTransparencyLayerWithRect(context, rect, NULL); + CGContextBeginTransparencyLayerWithRect(context, textRect, NULL); - NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; - paragraphStyle.alignment = nsAlign; - paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping; if ( info->hasStroke ) { CGContextSetTextDrawingMode(context, kCGTextStroke); + UIColor *strokeColor = [UIColor colorWithRed:info->strokeColorR + green:info->strokeColorG + blue:info->strokeColorB + alpha:info->strokeColorA]; + + + NSMutableDictionary* tokenAttributesDict2 = [NSMutableDictionary dictionaryWithObjectsAndKeys: + foregroundColor,NSForegroundColorAttributeName, + font, NSFontAttributeName, + paragraphStyle, NSParagraphStyleAttributeName, nil]; + [tokenAttributesDict2 setObject:[NSNumber numberWithFloat: info->strokeSize / shrinkFontSize * 100] + forKey:NSStrokeWidthAttributeName]; + [tokenAttributesDict2 setObject:strokeColor forKey:NSStrokeColorAttributeName]; + + NSAttributedString *strokeString =[[[NSAttributedString alloc] initWithString:str + attributes:tokenAttributesDict2] autorelease]; + + if(overflow == 2){ + _calculateShrinkedSizeForString(&strokeString, font, dimensions, enableWrap, shrinkFontSize); + } + + + [strokeString drawInRect:textRect]; - [str drawInRect:rect withAttributes:@{ - NSFontAttributeName: font, - NSStrokeWidthAttributeName: [NSNumber numberWithFloat: info->strokeSize / size * 100 ], - NSForegroundColorAttributeName:[UIColor colorWithRed:info->tintColorR - green:info->tintColorG - blue:info->tintColorB - alpha:info->tintColorA], - NSParagraphStyleAttributeName:paragraphStyle, - NSStrokeColorAttributeName: [UIColor colorWithRed:info->strokeColorR - green:info->strokeColorG - blue:info->strokeColorB - alpha:info->strokeColorA] - } - ]; } CGContextSetTextDrawingMode(context, kCGTextFill); + // actually draw the text in the context - [str drawInRect:rect withAttributes:@{ - NSFontAttributeName: font, - NSForegroundColorAttributeName:[UIColor colorWithRed:info->tintColorR - green:info->tintColorG - blue:info->tintColorB - alpha:info->tintColorA], - NSParagraphStyleAttributeName:paragraphStyle - } - ]; - [paragraphStyle release]; + [stringWithAttributes drawInRect:textRect]; CGContextEndTransparencyLayer(context); @@ -404,12 +516,12 @@ static bool _initWithString(const char * text, cocos2d::Device::TextAlign align, // release the context CGContextRelease(context); - + // output params info->data = data; info->isPremultipliedAlpha = true; - info->width = dim.width; - info->height = dim.height; + info->width = static_cast(POTWide); + info->height = static_cast(POTHigh); bRet = true; } while (0); @@ -442,7 +554,7 @@ Data Device::getTextureDataForText(const std::string& text, const FontDefinition info.tintColorB = textDefinition._fontFillColor.b / 255.0f; info.tintColorA = textDefinition._fontAlpha / 255.0f; - if (! _initWithString(text.c_str(), align, textDefinition._fontName.c_str(), textDefinition._fontSize, &info)) + if (! _initWithString(text.c_str(), align, textDefinition._fontName.c_str(), textDefinition._fontSize, &info, textDefinition._enableWrap, textDefinition._overflow)) { break; } diff --git a/native/cocos/platform/mac/CCDevice-mac.mm b/native/cocos/platform/mac/CCDevice-mac.mm index 7e3387644a..6ac18241eb 100644 --- a/native/cocos/platform/mac/CCDevice-mac.mm +++ b/native/cocos/platform/mac/CCDevice-mac.mm @@ -31,16 +31,37 @@ THE SOFTWARE. #include #include #include "base/ccTypes.h" +#include "platform/apple/CCDevice-apple.h" NS_CC_BEGIN +static NSAttributedString* __attributedStringWithFontSize(NSMutableAttributedString* attributedString, CGFloat fontSize) +{ + { + [attributedString beginEditing]; + + [attributedString enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, attributedString.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) { + + NSFont* font = value; + font = [[NSFontManager sharedFontManager] convertFont:font toSize:fontSize]; + + [attributedString removeAttribute:NSFontAttributeName range:range]; + [attributedString addAttribute:NSFontAttributeName value:font range:range]; + }]; + + [attributedString endEditing]; + } + + return [[attributedString copy] autorelease]; +} + int Device::getDPI() { NSScreen *screen = [NSScreen mainScreen]; NSDictionary *description = [screen deviceDescription]; NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue]; CGSize displayPhysicalSize = CGDisplayScreenSize([[description objectForKey:@"NSScreenNumber"] unsignedIntValue]); - + return ((displayPixelSize.width / displayPhysicalSize.width) * 25.4f); } @@ -63,79 +84,176 @@ typedef struct unsigned char* data; } tImageInfo; - -static CGSize _calculateStringSize(NSString *str, id font, CGSize *constrainSize) +static NSSize _calculateStringSize(NSAttributedString *str, id font, CGSize *constrainSize, bool enableWrap, int overflow) { - CGSize textRect = CGSizeZero; + NSSize textRect = NSZeroSize; textRect.width = constrainSize->width > 0 ? constrainSize->width - : 0x7fffffff; + : CGFLOAT_MAX; textRect.height = constrainSize->height > 0 ? constrainSize->height - : 0x7fffffff; - - CGSize dim; - NSDictionary *attibutes = @{NSFontAttributeName:font}; - dim = [str boundingRectWithSize:textRect options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin) attributes:attibutes context:nil].size; - + : CGFLOAT_MAX; + + if (overflow == 1) { + if (!enableWrap) { + textRect.width = CGFLOAT_MAX; + textRect.height = CGFLOAT_MAX; + } else { + textRect.height = CGFLOAT_MAX; + } + } + + NSSize dim; +#ifdef __MAC_10_11 + #if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_11 + dim = [str boundingRectWithSize:textRect options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin) context:nil].size; + #else + dim = [str boundingRectWithSize:textRect options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin)].size; + #endif +#else + dim = [str boundingRectWithSize:textRect options:(NSStringDrawingOptions)(NSStringDrawingUsesLineFragmentOrigin)].size; +#endif + + dim.width = ceilf(dim.width); dim.height = ceilf(dim.height); return dim; } -static bool _initWithString(const char * text, Device::TextAlign align, const char * fontName, int size, tImageInfo* info, const Color3B* fontColor, int fontAlpha) +static NSSize _calculateRealSizeForString(NSAttributedString **str, id font, NSSize constrainSize, bool enableWrap) { - bool ret = false; + CGRect actualSize = CGRectMake(0, 0, constrainSize.width + 1, constrainSize.height + 1); + int fontSize = [font pointSize]; + fontSize = fontSize + 1; - CCASSERT(text, "Invalid text"); - CCASSERT(info, "Invalid info"); + if (!enableWrap) { + while (actualSize.size.width > constrainSize.width || + actualSize.size.height > constrainSize.height) { + fontSize = fontSize - 1; + + NSMutableAttributedString *mutableString = [[*str mutableCopy] autorelease]; + *str = __attributedStringWithFontSize(mutableString, fontSize); - do { - NSString * string = [NSString stringWithUTF8String:text]; - NSString * fntName = [NSString stringWithUTF8String:fontName]; - fntName = [[fntName lastPathComponent] stringByDeletingPathExtension]; + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( CGFLOAT_MAX, CGFLOAT_MAX) + options:NSStringDrawingUsesLineFragmentOrigin + context:nil].size; + + if(fitSize.width == 0 || fitSize.height == 0) continue; + actualSize.size = fitSize; - // font - NSFont *font = [[NSFontManager sharedFontManager] - fontWithFamily:fntName - traits:NSUnboldFontMask | NSUnitalicFontMask - weight:0 - size:size]; - if (font == nil) { - font = [[NSFontManager sharedFontManager] - fontWithFamily:@"Arial" + if (constrainSize.width <= 0) { + constrainSize.width = fitSize.width; + } + if (constrainSize.height <= 0){ + constrainSize.height = fitSize.height; + } + if(fontSize <= 0){ + break; + } + } + + } + else { + while (actualSize.size.height > constrainSize.height + ||actualSize.size.width > constrainSize.width) { + fontSize = fontSize - 1; + + NSMutableAttributedString *mutableString = [[*str mutableCopy] autorelease]; + *str = __attributedStringWithFontSize(mutableString, fontSize); + + CGSize fitSize = [*str boundingRectWithSize:CGSizeMake( constrainSize.width, CGFLOAT_MAX) + options:NSStringDrawingUsesLineFragmentOrigin + context:nil].size; + + if(fitSize.width == 0 || fitSize.height == 0) continue; + actualSize.size = fitSize; + + if (constrainSize.width <= 0) { + constrainSize.width = fitSize.width; + } + if (constrainSize.height <= 0){ + constrainSize.height = fitSize.height; + } + if(fontSize <= 0){ + break; + } + } + + } + return CGSizeMake(actualSize.size.width, actualSize.size.height); +} + +static NSFont* _createSystemFont(const char* fontName, int size) +{ + NSString * fntName = [NSString stringWithUTF8String:fontName]; + fntName = [[fntName lastPathComponent] stringByDeletingPathExtension]; + + // font + NSFont *font = [[NSFontManager sharedFontManager] + fontWithFamily:fntName traits:NSUnboldFontMask | NSUnitalicFontMask weight:0 size:size]; - } - CC_BREAK_IF(!font); + + if (font == nil) { + font = [[NSFontManager sharedFontManager] + fontWithFamily:@"Arial" + traits:NSUnboldFontMask | NSUnitalicFontMask + weight:0 + size:size]; + } + return font; +} + +static CGFloat _calculateTextDrawStartHeight(cocos2d::Device::TextAlign align, CGSize realDimensions, CGSize dimensions) +{ + float startH = 0; + // vertical alignment + unsigned int vAlignment = ((int)align >> 4) & 0x0F; + switch (vAlignment) { + //bottom + case 1:startH = dimensions.height - realDimensions.height;break; + //top + case 2:startH = 0;break; + //center + case 3: startH = (dimensions.height - realDimensions.height) / 2;break; + default: + break; + } + return startH; +} + + +static bool _initWithString(const char * text, Device::TextAlign align, const char * fontName, int size, tImageInfo* info, const Color3B* fontColor, int fontAlpha, bool enableWrap, int overflow) +{ + bool ret = false; + + CCASSERT(text, "Invalid text"); + CCASSERT(info, "Invalid info"); + + do { + NSString * string = [NSString stringWithUTF8String:text]; + + id font = _createSystemFont(fontName, size); + CC_BREAK_IF(!font); + // color NSColor* foregroundColor; if (fontColor) { - foregroundColor = [NSColor colorWithDeviceRed:fontColor->r/255.0 green:fontColor->g/255.0 blue:fontColor->b/255.0 alpha:fontAlpha/255.0]; + foregroundColor = [NSColor colorWithDeviceRed:fontColor->r/255.0 + green:fontColor->g/255.0 + blue:fontColor->b/255.0 + alpha:fontAlpha/255.0]; } else { foregroundColor = [NSColor whiteColor]; } - + // alignment - unsigned horiFlag = (int)align & 0x0f; - NSTextAlignment textAlign = NSLeftTextAlignment; - switch (horiFlag) { - case 2: - textAlign = NSRightTextAlignment; - break; - case 3: - textAlign = NSCenterTextAlignment; - break; - default: - break; - } - - NSMutableParagraphStyle *paragraphStyle = [[[NSMutableParagraphStyle alloc] init] autorelease]; - [paragraphStyle setParagraphStyle:[NSParagraphStyle defaultParagraphStyle]]; - [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping]; + NSTextAlignment textAlign = FontUtils::_calculateTextAlignment(align); + + NSMutableParagraphStyle *paragraphStyle = FontUtils::_calculateParagraphStyle(enableWrap, overflow); [paragraphStyle setAlignment:textAlign]; - + // attribute NSDictionary* tokenAttributesDict = [NSDictionary dictionaryWithObjectsAndKeys: foregroundColor,NSForegroundColorAttributeName, @@ -143,45 +261,43 @@ static bool _initWithString(const char * text, Device::TextAlign align, const ch paragraphStyle, NSParagraphStyleAttributeName, nil]; NSAttributedString *stringWithAttributes =[[[NSAttributedString alloc] initWithString:string attributes:tokenAttributesDict] autorelease]; - + CGSize dimensions = CGSizeMake(info->width, info->height); - CGSize realDimensions = _calculateStringSize(string, font, &dimensions); + + NSSize realDimensions; + + if (overflow == 2) { + realDimensions = _calculateRealSizeForString(&stringWithAttributes, font, dimensions, enableWrap); + } else { + realDimensions = _calculateStringSize(stringWithAttributes, font, &dimensions, enableWrap, overflow); + } + + // Mac crashes if the width or height is 0 CC_BREAK_IF(realDimensions.width <= 0 || realDimensions.height <= 0); - + + if(dimensions.width <= 0.f) { dimensions.width = realDimensions.width; } if (dimensions.height <= 0.f) { dimensions.height = realDimensions.height; } - + + //Alignment - CGFloat xPadding = 0; - switch (textAlign) { - case NSLeftTextAlignment: xPadding = 0; break; - case NSCenterTextAlignment: xPadding = (dimensions.width - realDimensions.width) / 2.0f; break; - case NSRightTextAlignment: xPadding = dimensions.width - realDimensions.width; break; - default: break; - } - - CGFloat yPadding = 0.f; - unsigned vertFlag = ((int)align >> 4) & 0x0f; - switch (vertFlag) { - // align to top - case 1: yPadding = dimensions.height - realDimensions.height; break; - // align to bottom - case 2: yPadding = 0.f; break; - // align to center - case 3: yPadding = (dimensions.height - realDimensions.height) / 2.0f; break; - default: break; - } - + CGFloat xPadding = FontUtils::_calculateTextDrawStartWidth(align, realDimensions, dimensions); + + CGFloat yPadding = _calculateTextDrawStartHeight(align, realDimensions, dimensions); + NSInteger POTWide = dimensions.width; NSInteger POTHigh = dimensions.height; - NSRect textRect = NSMakeRect(xPadding, POTHigh - dimensions.height + yPadding, realDimensions.width, realDimensions.height); + NSRect textRect = NSMakeRect(xPadding, POTHigh - dimensions.height + yPadding, + realDimensions.width, realDimensions.height); + + [[NSGraphicsContext currentContext] setShouldAntialias:NO]; - + NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize(POTWide, POTHigh)]; [image lockFocus]; // patch for mac retina display and lableTTF @@ -189,9 +305,9 @@ static bool _initWithString(const char * text, Device::TextAlign align, const ch [stringWithAttributes drawInRect:textRect]; NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect (0.0f, 0.0f, POTWide, POTHigh)]; [image unlockFocus]; - + auto data = (unsigned char*) [bitmap bitmapData]; //Use the same buffer to improve the performance. - + NSUInteger textureSize = POTWide * POTHigh * 4; auto dataNew = (unsigned char*)malloc(sizeof(unsigned char) * textureSize); if (dataNew) { @@ -218,7 +334,9 @@ Data Device::getTextureDataForText(const std::string& text, const FontDefinition info.width = textDefinition._dimensions.width; info.height = textDefinition._dimensions.height; - if (! _initWithString(text.c_str(), align, textDefinition._fontName.c_str(), textDefinition._fontSize, &info, &textDefinition._fontFillColor, textDefinition._fontAlpha)) + if (! _initWithString(text.c_str(), align, textDefinition._fontName.c_str(), + textDefinition._fontSize, &info, &textDefinition._fontFillColor, + textDefinition._fontAlpha, textDefinition._enableWrap, textDefinition._overflow)) { break; } diff --git a/native/cocos/renderer/CCTexture2D.cpp b/native/cocos/renderer/CCTexture2D.cpp index edc3420db3..e36f6244c7 100644 --- a/native/cocos/renderer/CCTexture2D.cpp +++ b/native/cocos/renderer/CCTexture2D.cpp @@ -1054,7 +1054,7 @@ Texture2D::PixelFormat Texture2D::convertDataToFormat(const unsigned char* data, } // implementation Texture2D (Text) -bool Texture2D::initWithString(const std::string& text, const std::string& fontName, float fontSize, const Size& dimensions/* = Size(0, 0)*/, TextHAlignment hAlignment/* = TextHAlignment::CENTER */, TextVAlignment vAlignment/* = TextVAlignment::TOP */) +bool Texture2D::initWithString(const std::string& text, const std::string& fontName, float fontSize, const Size& dimensions/* = Size(0, 0)*/, TextHAlignment hAlignment/* = TextHAlignment::CENTER */, TextVAlignment vAlignment/* = TextVAlignment::TOP */, bool enableWrap /* = false */, int overflow /* = 0 */) { FontDefinition tempDef; @@ -1068,6 +1068,8 @@ bool Texture2D::initWithString(const std::string& text, const std::string& fontN tempDef._alignment = hAlignment; tempDef._vertAlignment = vAlignment; tempDef._fontFillColor = Color3B::WHITE; + tempDef._enableWrap = enableWrap; + tempDef._overflow = overflow; return initWithString(text, tempDef); } diff --git a/native/cocos/renderer/CCTexture2D.h b/native/cocos/renderer/CCTexture2D.h index 1cf5d2e38a..16742d1009 100644 --- a/native/cocos/renderer/CCTexture2D.h +++ b/native/cocos/renderer/CCTexture2D.h @@ -276,7 +276,7 @@ public: @param hAlignment The font horizontal text alignment type. @param vAlignment The font vertical text alignment type. */ - bool initWithString(const std::string& text, const std::string &fontName, float fontSize, const Size& dimensions = Size(0, 0), TextHAlignment hAlignment = TextHAlignment::CENTER, TextVAlignment vAlignment = TextVAlignment::TOP); + bool initWithString(const std::string& text, const std::string &fontName, float fontSize, const Size& dimensions = Size(0, 0), TextHAlignment hAlignment = TextHAlignment::CENTER, TextVAlignment vAlignment = TextVAlignment::TOP, bool enableWrap = true, int overflow = 0); /** Initializes a texture from a string using a text definition. diff --git a/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js b/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js index 3316167355..4bdd000fca 100644 --- a/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js +++ b/native/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js @@ -130,6 +130,8 @@ getName : function ( * @param {size_object} size * @param {cc.TextHAlignment} texthalignment * @param {cc.TextVAlignment} textvalignment +* @param {bool} bool +* @param {int} int * @return {bool|bool} */ initWithString : function( @@ -138,7 +140,9 @@ str, float, size, texthalignment, -textvalignment +textvalignment, +bool, +int ) { return false; diff --git a/native/cocos/scripting/js-bindings/auto/api/jsb_creator_auto_api.js b/native/cocos/scripting/js-bindings/auto/api/jsb_creator_auto_api.js index d4b8666176..0e155eb763 100644 --- a/native/cocos/scripting/js-bindings/auto/api/jsb_creator_auto_api.js +++ b/native/cocos/scripting/js-bindings/auto/api/jsb_creator_auto_api.js @@ -330,3 +330,399 @@ Scale9SpriteV2 : function ( }, }; + +/** + * @class GraphicsNode + */ +cc.GraphicsNode = { + +/** + * @method quadraticCurveTo + * @param {float} arg0 + * @param {float} arg1 + * @param {float} arg2 + * @param {float} arg3 + */ +quadraticCurveTo : function ( +float, +float, +float, +float +) +{ +}, + +/** + * @method moveTo + * @param {float} arg0 + * @param {float} arg1 + */ +moveTo : function ( +float, +float +) +{ +}, + +/** + * @method lineTo + * @param {float} arg0 + * @param {float} arg1 + */ +lineTo : function ( +float, +float +) +{ +}, + +/** + * @method roundedRect + * @param {float} arg0 + * @param {float} arg1 + * @param {float} arg2 + * @param {float} arg3 + * @param {float} arg4 + */ +roundedRect : function ( +float, +float, +float, +float, +float +) +{ +}, + +/** + * @method stroke + */ +stroke : function ( +) +{ +}, + +/** + * @method arc + * @param {float} arg0 + * @param {float} arg1 + * @param {float} arg2 + * @param {float} arg3 + * @param {float} arg4 + * @param {int} arg5 + */ +arc : function ( +float, +float, +float, +float, +float, +int +) +{ +}, + +/** + * @method setLineJoin + * @param {creator::LineJoin} arg0 + */ +setLineJoin : function ( +linejoin +) +{ +}, + +/** + * @method close + */ +close : function ( +) +{ +}, + +/** + * @method ellipse + * @param {float} arg0 + * @param {float} arg1 + * @param {float} arg2 + * @param {float} arg3 + */ +ellipse : function ( +float, +float, +float, +float +) +{ +}, + +/** + * @method fill + */ +fill : function ( +) +{ +}, + +/** + * @method getStrokeColor + * @return {color4f_object} + */ +getStrokeColor : function ( +) +{ + return cc.Color4F; +}, + +/** + * @method setLineCap + * @param {creator::LineCap} arg0 + */ +setLineCap : function ( +linecap +) +{ +}, + +/** + * @method circle + * @param {float} arg0 + * @param {float} arg1 + * @param {float} arg2 + */ +circle : function ( +float, +float, +float +) +{ +}, + +/** + * @method bezierCurveTo + * @param {float} arg0 + * @param {float} arg1 + * @param {float} arg2 + * @param {float} arg3 + * @param {float} arg4 + * @param {float} arg5 + */ +bezierCurveTo : function ( +float, +float, +float, +float, +float, +float +) +{ +}, + +/** + * @method arcTo + * @param {float} arg0 + * @param {float} arg1 + * @param {float} arg2 + * @param {float} arg3 + * @param {float} arg4 + */ +arcTo : function ( +float, +float, +float, +float, +float +) +{ +}, + +/** + * @method fillRect + * @param {float} arg0 + * @param {float} arg1 + * @param {float} arg2 + * @param {float} arg3 + */ +fillRect : function ( +float, +float, +float, +float +) +{ +}, + +/** + * @method onDraw + * @param {mat4_object} arg0 + * @param {unsigned int} arg1 + */ +onDraw : function ( +mat4, +int +) +{ +}, + +/** + * @method setFillColor + * @param {color4f_object} arg0 + */ +setFillColor : function ( +color4f +) +{ +}, + +/** + * @method getFillColor + * @return {color4f_object} + */ +getFillColor : function ( +) +{ + return cc.Color4F; +}, + +/** + * @method getStrokeWidth + * @return {float} + */ +getStrokeWidth : function ( +) +{ + return 0; +}, + +/** + * @method beginPath + */ +beginPath : function ( +) +{ +}, + +/** + * @method setDeviceRatio + * @param {float} arg0 + */ +setDeviceRatio : function ( +float +) +{ +}, + +/** + * @method rect + * @param {float} arg0 + * @param {float} arg1 + * @param {float} arg2 + * @param {float} arg3 + */ +rect : function ( +float, +float, +float, +float +) +{ +}, + +/** + * @method getMiterLimit + * @return {float} + */ +getMiterLimit : function ( +) +{ + return 0; +}, + +/** + * @method getLineJoin + * @return {creator::LineJoin} + */ +getLineJoin : function ( +) +{ + return creator::LineJoin; +}, + +/** + * @method setStrokeWidth + * @param {float} arg0 + */ +setStrokeWidth : function ( +float +) +{ +}, + +/** + * @method getLineCap + * @return {creator::LineCap} + */ +getLineCap : function ( +) +{ + return creator::LineCap; +}, + +/** + * @method setMiterLimit + * @param {float} arg0 + */ +setMiterLimit : function ( +float +) +{ +}, + +/** + * @method clear + */ +clear : function ( +) +{ +}, + +/** + * @method getDeviceRatio + * @return {float} + */ +getDeviceRatio : function ( +) +{ + return 0; +}, + +/** + * @method setStrokeColor + * @param {color4f_object} arg0 + */ +setStrokeColor : function ( +color4f +) +{ +}, + +/** + * @method create + * @return {creator::GraphicsNode} + */ +create : function ( +) +{ + return creator::GraphicsNode; +}, + +/** + * @method GraphicsNode + * @constructor + */ +GraphicsNode : function ( +) +{ +}, + +}; diff --git a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp index 7d40d6b760..62d9ba79aa 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp @@ -463,6 +463,82 @@ bool js_cocos2dx_Texture2D_initWithString(JSContext *cx, uint32_t argc, jsval *v } } while(0); + do { + bool ok = true; + if (argc == 7) { + std::string arg0; + ok &= jsval_to_std_string(cx, args.get(0), &arg0); + if (!ok) { break; } + std::string arg1; + ok = true; + ok &= jsval_to_std_string(cx, args.get(1), &arg1); + if (!ok) { break; } + double arg2 = 0; + ok = true; + ok &= JS::ToNumber( cx, args.get(2), &arg2) && !isnan(arg2); + if (!ok) { break; } + cocos2d::Size arg3; + ok = true; + ok &= jsval_to_ccsize(cx, args.get(3), &arg3); + if (!ok) { break; } + cocos2d::TextHAlignment arg4; + ok = true; + ok &= jsval_to_int32(cx, args.get(4), (int32_t *)&arg4); + if (!ok) { break; } + cocos2d::TextVAlignment arg5; + ok = true; + ok &= jsval_to_int32(cx, args.get(5), (int32_t *)&arg5); + if (!ok) { break; } + bool arg6; + arg6 = JS::ToBoolean(args.get(6)); + bool ret = cobj->initWithString(arg0, arg1, arg2, arg3, arg4, arg5, arg6); + jsval jsret = JSVAL_NULL; + jsret = BOOLEAN_TO_JSVAL(ret); + args.rval().set(jsret); + return true; + } + } while(0); + + do { + bool ok = true; + if (argc == 8) { + std::string arg0; + ok &= jsval_to_std_string(cx, args.get(0), &arg0); + if (!ok) { break; } + std::string arg1; + ok = true; + ok &= jsval_to_std_string(cx, args.get(1), &arg1); + if (!ok) { break; } + double arg2 = 0; + ok = true; + ok &= JS::ToNumber( cx, args.get(2), &arg2) && !isnan(arg2); + if (!ok) { break; } + cocos2d::Size arg3; + ok = true; + ok &= jsval_to_ccsize(cx, args.get(3), &arg3); + if (!ok) { break; } + cocos2d::TextHAlignment arg4; + ok = true; + ok &= jsval_to_int32(cx, args.get(4), (int32_t *)&arg4); + if (!ok) { break; } + cocos2d::TextVAlignment arg5; + ok = true; + ok &= jsval_to_int32(cx, args.get(5), (int32_t *)&arg5); + if (!ok) { break; } + bool arg6; + arg6 = JS::ToBoolean(args.get(6)); + int arg7 = 0; + ok = true; + ok &= jsval_to_int32(cx, args.get(7), (int32_t *)&arg7); + if (!ok) { break; } + bool ret = cobj->initWithString(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7); + jsval jsret = JSVAL_NULL; + jsret = BOOLEAN_TO_JSVAL(ret); + args.rval().set(jsret); + return true; + } + } while(0); + JS_ReportError(cx, "js_cocos2dx_Texture2D_initWithString : wrong number of arguments"); return false; } diff --git a/native/cocos/scripting/js-bindings/auto/jsb_creator_auto.cpp b/native/cocos/scripting/js-bindings/auto/jsb_creator_auto.cpp index b05410bbc4..bf97847f42 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_creator_auto.cpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_creator_auto.cpp @@ -1,6 +1,7 @@ #include "jsb_creator_auto.hpp" #include "cocos2d_specifics.hpp" #include "creator/CCScale9Sprite.h" +#include "creator/CCGraphicsNode.h" template static bool dummy_constructor(JSContext *cx, uint32_t argc, jsval *vp) { @@ -901,11 +902,827 @@ void js_register_creator_Scale9SpriteV2(JSContext *cx, JS::HandleObject global) jsb_register_class(cx, jsb_creator_Scale9SpriteV2_class, proto, parent_proto); anonEvaluate(cx, global, "(function () { cc.Scale9SpriteV2.extend = cc.Class.extend; })()"); } +JSClass *jsb_creator_GraphicsNode_class; +JSObject *jsb_creator_GraphicsNode_prototype; + +bool js_creator_GraphicsNode_quadraticCurveTo(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_quadraticCurveTo : Invalid Native Object"); + if (argc == 4) { + double arg0 = 0; + double arg1 = 0; + double arg2 = 0; + double arg3 = 0; + ok &= JS::ToNumber( cx, args.get(0), &arg0) && !isnan(arg0); + ok &= JS::ToNumber( cx, args.get(1), &arg1) && !isnan(arg1); + ok &= JS::ToNumber( cx, args.get(2), &arg2) && !isnan(arg2); + ok &= JS::ToNumber( cx, args.get(3), &arg3) && !isnan(arg3); + JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_quadraticCurveTo : Error processing arguments"); + cobj->quadraticCurveTo(arg0, arg1, arg2, arg3); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_quadraticCurveTo : wrong number of arguments: %d, was expecting %d", argc, 4); + return false; +} +bool js_creator_GraphicsNode_moveTo(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_moveTo : Invalid Native Object"); + if (argc == 2) { + double arg0 = 0; + double arg1 = 0; + ok &= JS::ToNumber( cx, args.get(0), &arg0) && !isnan(arg0); + ok &= JS::ToNumber( cx, args.get(1), &arg1) && !isnan(arg1); + JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_moveTo : Error processing arguments"); + cobj->moveTo(arg0, arg1); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_moveTo : wrong number of arguments: %d, was expecting %d", argc, 2); + return false; +} +bool js_creator_GraphicsNode_lineTo(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_lineTo : Invalid Native Object"); + if (argc == 2) { + double arg0 = 0; + double arg1 = 0; + ok &= JS::ToNumber( cx, args.get(0), &arg0) && !isnan(arg0); + ok &= JS::ToNumber( cx, args.get(1), &arg1) && !isnan(arg1); + JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_lineTo : Error processing arguments"); + cobj->lineTo(arg0, arg1); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_lineTo : wrong number of arguments: %d, was expecting %d", argc, 2); + return false; +} +bool js_creator_GraphicsNode_roundedRect(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_roundedRect : Invalid Native Object"); + if (argc == 5) { + double arg0 = 0; + double arg1 = 0; + double arg2 = 0; + double arg3 = 0; + double arg4 = 0; + ok &= JS::ToNumber( cx, args.get(0), &arg0) && !isnan(arg0); + ok &= JS::ToNumber( cx, args.get(1), &arg1) && !isnan(arg1); + ok &= JS::ToNumber( cx, args.get(2), &arg2) && !isnan(arg2); + ok &= JS::ToNumber( cx, args.get(3), &arg3) && !isnan(arg3); + ok &= JS::ToNumber( cx, args.get(4), &arg4) && !isnan(arg4); + JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_roundedRect : Error processing arguments"); + cobj->roundedRect(arg0, arg1, arg2, arg3, arg4); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_roundedRect : wrong number of arguments: %d, was expecting %d", argc, 5); + return false; +} +bool js_creator_GraphicsNode_stroke(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_stroke : Invalid Native Object"); + if (argc == 0) { + cobj->stroke(); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_stroke : wrong number of arguments: %d, was expecting %d", argc, 0); + return false; +} +bool js_creator_GraphicsNode_arc(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_arc : Invalid Native Object"); + if (argc == 6) { + double arg0 = 0; + double arg1 = 0; + double arg2 = 0; + double arg3 = 0; + double arg4 = 0; + int arg5 = 0; + ok &= JS::ToNumber( cx, args.get(0), &arg0) && !isnan(arg0); + ok &= JS::ToNumber( cx, args.get(1), &arg1) && !isnan(arg1); + ok &= JS::ToNumber( cx, args.get(2), &arg2) && !isnan(arg2); + ok &= JS::ToNumber( cx, args.get(3), &arg3) && !isnan(arg3); + ok &= JS::ToNumber( cx, args.get(4), &arg4) && !isnan(arg4); + ok &= jsval_to_int32(cx, args.get(5), (int32_t *)&arg5); + JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_arc : Error processing arguments"); + cobj->arc(arg0, arg1, arg2, arg3, arg4, arg5); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_arc : wrong number of arguments: %d, was expecting %d", argc, 6); + return false; +} +bool js_creator_GraphicsNode_setLineJoin(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_setLineJoin : Invalid Native Object"); + if (argc == 1) { + creator::LineJoin arg0; + ok &= jsval_to_int32(cx, args.get(0), (int32_t *)&arg0); + JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_setLineJoin : Error processing arguments"); + cobj->setLineJoin(arg0); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_setLineJoin : wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} +bool js_creator_GraphicsNode_close(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_close : Invalid Native Object"); + if (argc == 0) { + cobj->close(); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_close : wrong number of arguments: %d, was expecting %d", argc, 0); + return false; +} +bool js_creator_GraphicsNode_ellipse(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_ellipse : Invalid Native Object"); + if (argc == 4) { + double arg0 = 0; + double arg1 = 0; + double arg2 = 0; + double arg3 = 0; + ok &= JS::ToNumber( cx, args.get(0), &arg0) && !isnan(arg0); + ok &= JS::ToNumber( cx, args.get(1), &arg1) && !isnan(arg1); + ok &= JS::ToNumber( cx, args.get(2), &arg2) && !isnan(arg2); + ok &= JS::ToNumber( cx, args.get(3), &arg3) && !isnan(arg3); + JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_ellipse : Error processing arguments"); + cobj->ellipse(arg0, arg1, arg2, arg3); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_ellipse : wrong number of arguments: %d, was expecting %d", argc, 4); + return false; +} +bool js_creator_GraphicsNode_fill(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_fill : Invalid Native Object"); + if (argc == 0) { + cobj->fill(); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_fill : wrong number of arguments: %d, was expecting %d", argc, 0); + return false; +} +bool js_creator_GraphicsNode_getStrokeColor(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_getStrokeColor : Invalid Native Object"); + if (argc == 0) { + cocos2d::Color4F ret = cobj->getStrokeColor(); + jsval jsret = JSVAL_NULL; + jsret = cccolor4f_to_jsval(cx, ret); + args.rval().set(jsret); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_getStrokeColor : wrong number of arguments: %d, was expecting %d", argc, 0); + return false; +} +bool js_creator_GraphicsNode_setLineCap(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_setLineCap : Invalid Native Object"); + if (argc == 1) { + creator::LineCap arg0; + ok &= jsval_to_int32(cx, args.get(0), (int32_t *)&arg0); + JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_setLineCap : Error processing arguments"); + cobj->setLineCap(arg0); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_setLineCap : wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} +bool js_creator_GraphicsNode_circle(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_circle : Invalid Native Object"); + if (argc == 3) { + double arg0 = 0; + double arg1 = 0; + double arg2 = 0; + ok &= JS::ToNumber( cx, args.get(0), &arg0) && !isnan(arg0); + ok &= JS::ToNumber( cx, args.get(1), &arg1) && !isnan(arg1); + ok &= JS::ToNumber( cx, args.get(2), &arg2) && !isnan(arg2); + JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_circle : Error processing arguments"); + cobj->circle(arg0, arg1, arg2); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_circle : wrong number of arguments: %d, was expecting %d", argc, 3); + return false; +} +bool js_creator_GraphicsNode_bezierCurveTo(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_bezierCurveTo : Invalid Native Object"); + if (argc == 6) { + double arg0 = 0; + double arg1 = 0; + double arg2 = 0; + double arg3 = 0; + double arg4 = 0; + double arg5 = 0; + ok &= JS::ToNumber( cx, args.get(0), &arg0) && !isnan(arg0); + ok &= JS::ToNumber( cx, args.get(1), &arg1) && !isnan(arg1); + ok &= JS::ToNumber( cx, args.get(2), &arg2) && !isnan(arg2); + ok &= JS::ToNumber( cx, args.get(3), &arg3) && !isnan(arg3); + ok &= JS::ToNumber( cx, args.get(4), &arg4) && !isnan(arg4); + ok &= JS::ToNumber( cx, args.get(5), &arg5) && !isnan(arg5); + JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_bezierCurveTo : Error processing arguments"); + cobj->bezierCurveTo(arg0, arg1, arg2, arg3, arg4, arg5); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_bezierCurveTo : wrong number of arguments: %d, was expecting %d", argc, 6); + return false; +} +bool js_creator_GraphicsNode_arcTo(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_arcTo : Invalid Native Object"); + if (argc == 5) { + double arg0 = 0; + double arg1 = 0; + double arg2 = 0; + double arg3 = 0; + double arg4 = 0; + ok &= JS::ToNumber( cx, args.get(0), &arg0) && !isnan(arg0); + ok &= JS::ToNumber( cx, args.get(1), &arg1) && !isnan(arg1); + ok &= JS::ToNumber( cx, args.get(2), &arg2) && !isnan(arg2); + ok &= JS::ToNumber( cx, args.get(3), &arg3) && !isnan(arg3); + ok &= JS::ToNumber( cx, args.get(4), &arg4) && !isnan(arg4); + JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_arcTo : Error processing arguments"); + cobj->arcTo(arg0, arg1, arg2, arg3, arg4); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_arcTo : wrong number of arguments: %d, was expecting %d", argc, 5); + return false; +} +bool js_creator_GraphicsNode_fillRect(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_fillRect : Invalid Native Object"); + if (argc == 4) { + double arg0 = 0; + double arg1 = 0; + double arg2 = 0; + double arg3 = 0; + ok &= JS::ToNumber( cx, args.get(0), &arg0) && !isnan(arg0); + ok &= JS::ToNumber( cx, args.get(1), &arg1) && !isnan(arg1); + ok &= JS::ToNumber( cx, args.get(2), &arg2) && !isnan(arg2); + ok &= JS::ToNumber( cx, args.get(3), &arg3) && !isnan(arg3); + JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_fillRect : Error processing arguments"); + cobj->fillRect(arg0, arg1, arg2, arg3); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_fillRect : wrong number of arguments: %d, was expecting %d", argc, 4); + return false; +} +bool js_creator_GraphicsNode_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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_onDraw : Invalid Native Object"); + if (argc == 2) { + cocos2d::Mat4 arg0; + unsigned int arg1 = 0; + ok &= jsval_to_matrix(cx, args.get(0), &arg0); + ok &= jsval_to_uint32(cx, args.get(1), &arg1); + JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_onDraw : Error processing arguments"); + cobj->onDraw(arg0, arg1); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_onDraw : wrong number of arguments: %d, was expecting %d", argc, 2); + return false; +} +bool js_creator_GraphicsNode_setFillColor(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_setFillColor : Invalid Native Object"); + if (argc == 1) { + cocos2d::Color4F arg0; + ok &= jsval_to_cccolor4f(cx, args.get(0), &arg0); + JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_setFillColor : Error processing arguments"); + cobj->setFillColor(arg0); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_setFillColor : wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} +bool js_creator_GraphicsNode_getFillColor(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_getFillColor : Invalid Native Object"); + if (argc == 0) { + cocos2d::Color4F ret = cobj->getFillColor(); + jsval jsret = JSVAL_NULL; + jsret = cccolor4f_to_jsval(cx, ret); + args.rval().set(jsret); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_getFillColor : wrong number of arguments: %d, was expecting %d", argc, 0); + return false; +} +bool js_creator_GraphicsNode_getLineWidth(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_getLineWidth : Invalid Native Object"); + if (argc == 0) { + double ret = cobj->getLineWidth(); + jsval jsret = JSVAL_NULL; + jsret = DOUBLE_TO_JSVAL(ret); + args.rval().set(jsret); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_getLineWidth : wrong number of arguments: %d, was expecting %d", argc, 0); + return false; +} +bool js_creator_GraphicsNode_beginPath(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_beginPath : Invalid Native Object"); + if (argc == 0) { + cobj->beginPath(); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_beginPath : wrong number of arguments: %d, was expecting %d", argc, 0); + return false; +} +bool js_creator_GraphicsNode_setDeviceRatio(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_setDeviceRatio : Invalid Native Object"); + if (argc == 1) { + double arg0 = 0; + ok &= JS::ToNumber( cx, args.get(0), &arg0) && !isnan(arg0); + JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_setDeviceRatio : Error processing arguments"); + cobj->setDeviceRatio(arg0); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_setDeviceRatio : wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} +bool js_creator_GraphicsNode_rect(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_rect : Invalid Native Object"); + if (argc == 4) { + double arg0 = 0; + double arg1 = 0; + double arg2 = 0; + double arg3 = 0; + ok &= JS::ToNumber( cx, args.get(0), &arg0) && !isnan(arg0); + ok &= JS::ToNumber( cx, args.get(1), &arg1) && !isnan(arg1); + ok &= JS::ToNumber( cx, args.get(2), &arg2) && !isnan(arg2); + ok &= JS::ToNumber( cx, args.get(3), &arg3) && !isnan(arg3); + JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_rect : Error processing arguments"); + cobj->rect(arg0, arg1, arg2, arg3); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_rect : wrong number of arguments: %d, was expecting %d", argc, 4); + return false; +} +bool js_creator_GraphicsNode_getMiterLimit(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_getMiterLimit : Invalid Native Object"); + if (argc == 0) { + double ret = cobj->getMiterLimit(); + jsval jsret = JSVAL_NULL; + jsret = DOUBLE_TO_JSVAL(ret); + args.rval().set(jsret); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_getMiterLimit : wrong number of arguments: %d, was expecting %d", argc, 0); + return false; +} +bool js_creator_GraphicsNode_getLineJoin(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_getLineJoin : Invalid Native Object"); + if (argc == 0) { + int ret = (int)cobj->getLineJoin(); + jsval jsret = JSVAL_NULL; + jsret = int32_to_jsval(cx, ret); + args.rval().set(jsret); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_getLineJoin : wrong number of arguments: %d, was expecting %d", argc, 0); + return false; +} +bool js_creator_GraphicsNode_setLineWidth(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_setLineWidth : Invalid Native Object"); + if (argc == 1) { + double arg0 = 0; + ok &= JS::ToNumber( cx, args.get(0), &arg0) && !isnan(arg0); + JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_setLineWidth : Error processing arguments"); + cobj->setLineWidth(arg0); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_setLineWidth : wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} +bool js_creator_GraphicsNode_getLineCap(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_getLineCap : Invalid Native Object"); + if (argc == 0) { + int ret = (int)cobj->getLineCap(); + jsval jsret = JSVAL_NULL; + jsret = int32_to_jsval(cx, ret); + args.rval().set(jsret); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_getLineCap : wrong number of arguments: %d, was expecting %d", argc, 0); + return false; +} +bool js_creator_GraphicsNode_setMiterLimit(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_setMiterLimit : Invalid Native Object"); + if (argc == 1) { + double arg0 = 0; + ok &= JS::ToNumber( cx, args.get(0), &arg0) && !isnan(arg0); + JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_setMiterLimit : Error processing arguments"); + cobj->setMiterLimit(arg0); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_setMiterLimit : wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} +bool js_creator_GraphicsNode_clear(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_clear : Invalid Native Object"); + if (argc == 0) { + cobj->clear(); + args.rval().setUndefined(); + return true; + } + if (argc == 1) { + bool arg0; + arg0 = JS::ToBoolean(args.get(0)); + JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_clear : Error processing arguments"); + cobj->clear(arg0); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_clear : wrong number of arguments: %d, was expecting %d", argc, 0); + return false; +} +bool js_creator_GraphicsNode_getDeviceRatio(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_getDeviceRatio : Invalid Native Object"); + if (argc == 0) { + double ret = cobj->getDeviceRatio(); + jsval jsret = JSVAL_NULL; + jsret = DOUBLE_TO_JSVAL(ret); + args.rval().set(jsret); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_getDeviceRatio : wrong number of arguments: %d, was expecting %d", argc, 0); + return false; +} +bool js_creator_GraphicsNode_setStrokeColor(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); + creator::GraphicsNode* cobj = (creator::GraphicsNode *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_creator_GraphicsNode_setStrokeColor : Invalid Native Object"); + if (argc == 1) { + cocos2d::Color4F arg0; + ok &= jsval_to_cccolor4f(cx, args.get(0), &arg0); + JSB_PRECONDITION2(ok, cx, false, "js_creator_GraphicsNode_setStrokeColor : Error processing arguments"); + cobj->setStrokeColor(arg0); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_creator_GraphicsNode_setStrokeColor : wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} +bool js_creator_GraphicsNode_create(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + if (argc == 0) { + creator::GraphicsNode* ret = creator::GraphicsNode::create(); + jsval jsret = JSVAL_NULL; + do { + if (ret) { + js_proxy_t *jsProxy = js_get_or_create_proxy(cx, (creator::GraphicsNode*)ret); + jsret = OBJECT_TO_JSVAL(jsProxy->obj); + } else { + jsret = JSVAL_NULL; + } + } while (0); + args.rval().set(jsret); + return true; + } + JS_ReportError(cx, "js_creator_GraphicsNode_create : wrong number of arguments"); + return false; +} +bool js_creator_GraphicsNode_constructor(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + creator::GraphicsNode* cobj = new (std::nothrow) creator::GraphicsNode(); + 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."); + JS::RootedObject proto(cx, typeClass->proto.ref()); + JS::RootedObject parent(cx, typeClass->parentProto.ref()); + 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); + if (JS_HasProperty(cx, obj, "_ctor", &ok) && ok) + ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(obj), "_ctor", args); + return true; +}static bool js_creator_GraphicsNode_ctor(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + creator::GraphicsNode *nobj = new (std::nothrow) creator::GraphicsNode(); + js_proxy_t* p = jsb_new_proxy(nobj, obj); + bool isFound = false; + if (JS_HasProperty(cx, obj, "_ctor", &isFound) && isFound) + ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(obj), "_ctor", args); + args.rval().setUndefined(); + return true; +} + +extern JSObject *jsb_cocos2d_Node_prototype; + +void js_creator_GraphicsNode_finalize(JSFreeOp *fop, JSObject *obj) { + CCLOGINFO("jsbindings: finalizing JS object %p (GraphicsNode)", obj); + JSContext *cx = ScriptingCore::getInstance()->getGlobalContext(); + JS::RootedObject jsobj(cx, obj); + auto proxy = jsb_get_js_proxy(jsobj); + if (proxy) { + creator::GraphicsNode *nobj = static_cast(proxy->ptr); + + if (nobj) { + jsb_remove_proxy(proxy); + nobj->release(); + } + else jsb_remove_proxy(proxy); + } +} + +void js_register_creator_GraphicsNode(JSContext *cx, JS::HandleObject global) { + jsb_creator_GraphicsNode_class = (JSClass *)calloc(1, sizeof(JSClass)); + jsb_creator_GraphicsNode_class->name = "GraphicsNode"; + jsb_creator_GraphicsNode_class->addProperty = JS_PropertyStub; + jsb_creator_GraphicsNode_class->delProperty = JS_DeletePropertyStub; + jsb_creator_GraphicsNode_class->getProperty = JS_PropertyStub; + jsb_creator_GraphicsNode_class->setProperty = JS_StrictPropertyStub; + jsb_creator_GraphicsNode_class->enumerate = JS_EnumerateStub; + jsb_creator_GraphicsNode_class->resolve = JS_ResolveStub; + jsb_creator_GraphicsNode_class->convert = JS_ConvertStub; + jsb_creator_GraphicsNode_class->finalize = js_creator_GraphicsNode_finalize; + jsb_creator_GraphicsNode_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("quadraticCurveTo", js_creator_GraphicsNode_quadraticCurveTo, 4, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("moveTo", js_creator_GraphicsNode_moveTo, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("lineTo", js_creator_GraphicsNode_lineTo, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("roundedRect", js_creator_GraphicsNode_roundedRect, 5, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("stroke", js_creator_GraphicsNode_stroke, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("arc", js_creator_GraphicsNode_arc, 6, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("setLineJoin", js_creator_GraphicsNode_setLineJoin, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("close", js_creator_GraphicsNode_close, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("ellipse", js_creator_GraphicsNode_ellipse, 4, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("fill", js_creator_GraphicsNode_fill, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("getStrokeColor", js_creator_GraphicsNode_getStrokeColor, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("setLineCap", js_creator_GraphicsNode_setLineCap, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("circle", js_creator_GraphicsNode_circle, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("bezierCurveTo", js_creator_GraphicsNode_bezierCurveTo, 6, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("arcTo", js_creator_GraphicsNode_arcTo, 5, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("fillRect", js_creator_GraphicsNode_fillRect, 4, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("onDraw", js_creator_GraphicsNode_onDraw, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("setFillColor", js_creator_GraphicsNode_setFillColor, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("getFillColor", js_creator_GraphicsNode_getFillColor, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("getLineWidth", js_creator_GraphicsNode_getLineWidth, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("beginPath", js_creator_GraphicsNode_beginPath, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("setDeviceRatio", js_creator_GraphicsNode_setDeviceRatio, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("rect", js_creator_GraphicsNode_rect, 4, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("getMiterLimit", js_creator_GraphicsNode_getMiterLimit, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("getLineJoin", js_creator_GraphicsNode_getLineJoin, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("setLineWidth", js_creator_GraphicsNode_setLineWidth, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("getLineCap", js_creator_GraphicsNode_getLineCap, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("setMiterLimit", js_creator_GraphicsNode_setMiterLimit, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("clear", js_creator_GraphicsNode_clear, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("getDeviceRatio", js_creator_GraphicsNode_getDeviceRatio, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("setStrokeColor", js_creator_GraphicsNode_setStrokeColor, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("ctor", js_creator_GraphicsNode_ctor, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FS_END + }; + + static JSFunctionSpec st_funcs[] = { + JS_FN("create", js_creator_GraphicsNode_create, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FS_END + }; + + JS::RootedObject parent_proto(cx, jsb_cocos2d_Node_prototype); + jsb_creator_GraphicsNode_prototype = JS_InitClass( + cx, global, + parent_proto, + jsb_creator_GraphicsNode_class, + js_creator_GraphicsNode_constructor, 0, // constructor + properties, + funcs, + NULL, // no static properties + st_funcs); + + // add the proto and JSClass to the type->js info hash table + JS::RootedObject proto(cx, jsb_creator_GraphicsNode_prototype); + jsb_register_class(cx, jsb_creator_GraphicsNode_class, proto, parent_proto); + anonEvaluate(cx, global, "(function () { cc.GraphicsNode.extend = cc.Class.extend; })()"); +} void register_all_creator(JSContext* cx, JS::HandleObject obj) { // Get the ns JS::RootedObject ns(cx); get_or_create_js_obj(cx, obj, "cc", &ns); + js_register_creator_GraphicsNode(cx, ns); js_register_creator_Scale9SpriteV2(cx, ns); } diff --git a/native/cocos/scripting/js-bindings/auto/jsb_creator_auto.hpp b/native/cocos/scripting/js-bindings/auto/jsb_creator_auto.hpp index 70e96b2c64..0e7fd011da 100644 --- a/native/cocos/scripting/js-bindings/auto/jsb_creator_auto.hpp +++ b/native/cocos/scripting/js-bindings/auto/jsb_creator_auto.hpp @@ -44,4 +44,45 @@ bool js_creator_Scale9SpriteV2_setInsetRight(JSContext *cx, uint32_t argc, jsval bool js_creator_Scale9SpriteV2_enableTrimmedContentSize(JSContext *cx, uint32_t argc, jsval *vp); bool js_creator_Scale9SpriteV2_Scale9SpriteV2(JSContext *cx, uint32_t argc, jsval *vp); +extern JSClass *jsb_creator_GraphicsNode_class; +extern JSObject *jsb_creator_GraphicsNode_prototype; + +bool js_creator_GraphicsNode_constructor(JSContext *cx, uint32_t argc, jsval *vp); +void js_creator_GraphicsNode_finalize(JSContext *cx, JSObject *obj); +void js_register_creator_GraphicsNode(JSContext *cx, JS::HandleObject global); +void register_all_creator(JSContext* cx, JS::HandleObject obj); +bool js_creator_GraphicsNode_quadraticCurveTo(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_moveTo(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_lineTo(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_roundedRect(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_stroke(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_arc(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_setLineJoin(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_close(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_ellipse(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_fill(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_getStrokeColor(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_setLineCap(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_circle(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_bezierCurveTo(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_arcTo(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_fillRect(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_onDraw(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_setFillColor(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_getFillColor(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_getLineWidth(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_beginPath(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_setDeviceRatio(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_rect(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_getMiterLimit(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_getLineJoin(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_setLineWidth(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_getLineCap(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_setMiterLimit(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_clear(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_getDeviceRatio(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_setStrokeColor(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_create(JSContext *cx, uint32_t argc, jsval *vp); +bool js_creator_GraphicsNode_GraphicsNode(JSContext *cx, uint32_t argc, jsval *vp); + #endif // __creator_h__ diff --git a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp index 2afa4ee167..1cd3f76561 100644 --- a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp +++ b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp @@ -380,6 +380,22 @@ bool JSB_core_restartVM(JSContext *cx, uint32_t argc, jsval *vp) return true; }; +bool JSB_closeWindow(JSContext *cx, uint32_t argc, jsval *vp) +{ + EventListenerCustom* _event = Director::getInstance()->getEventDispatcher()->addCustomEventListener(Director::EVENT_AFTER_DRAW, [&](EventCustom *event) { + Director::getInstance()->getEventDispatcher()->removeEventListener(_event); + _event->release(); + + ScriptingCore::getInstance()->cleanup(); + }); + _event->retain(); + Director::getInstance()->end(); +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) + exit(0); +#endif + return true; +}; + void registerDefaultClasses(JSContext* cx, JS::HandleObject global) { // first, try to get the ns JS::RootedValue nsval(cx); @@ -425,6 +441,7 @@ void registerDefaultClasses(JSContext* cx, JS::HandleObject global) { JS_DefineFunction(cx, global, "__restartVM", JSB_core_restartVM, 0, JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE ); JS_DefineFunction(cx, global, "__cleanScript", JSB_cleanScript, 1, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, global, "__isObjectValid", ScriptingCore::isObjectValid, 1, JSPROP_READONLY | JSPROP_PERMANENT); + JS_DefineFunction(cx, global, "close", JSB_closeWindow, 0, JSPROP_READONLY | JSPROP_PERMANENT); } static void sc_finalize(JSFreeOp *freeOp, JSObject *obj) { @@ -604,6 +621,7 @@ void ScriptingCore::createGlobalContext() { sc_register_sth callback = *it; callback(_cx, _global.ref()); } + _needCleanup = true; } static std::string RemoveFileExt(const std::string& filePath) { @@ -843,6 +861,10 @@ void ScriptingCore::recordJSRelease(cocos2d::Ref *object) void ScriptingCore::cleanup() { + if (!_needCleanup) { + return; + } + if(_runLoop) { delete _runLoop; @@ -888,6 +910,8 @@ void ScriptingCore::cleanup() _js_global_type_map.clear(); cleanAllScript(); registrationList.clear(); + + _needCleanup = false; } void ScriptingCore::reportError(JSContext *cx, const char *message, JSErrorReport *report) diff --git a/native/cocos/scripting/js-bindings/manual/ScriptingCore.h b/native/cocos/scripting/js-bindings/manual/ScriptingCore.h index 3bf7a21dd8..2b8e9f2635 100644 --- a/native/cocos/scripting/js-bindings/manual/ScriptingCore.h +++ b/native/cocos/scripting/js-bindings/manual/ScriptingCore.h @@ -83,6 +83,7 @@ private: mozilla::Maybe _global; mozilla::Maybe _debugGlobal; SimpleRunLoop* _runLoop; + bool _needCleanup; bool _callFromScript; std::unordered_map _jsRetainRefMap; diff --git a/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp b/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp index c954efc590..74cae85bf3 100644 --- a/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp +++ b/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp @@ -2097,6 +2097,37 @@ bool js_cocos2dx_CCScheduler_isTargetPaused(JSContext *cx, uint32_t argc, jsval return false; } +bool js_cocos2dx_CCScheduler_isScheduled(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::Scheduler* cobj = (cocos2d::Scheduler *)(proxy ? proxy->ptr : nullptr); + TEST_NATIVE_OBJECT(cx, cobj); + + if (argc == 2) { + bool isScheduled = false; + JS::RootedObject tmpObj(cx, args.get(1).toObjectOrNull()); + + auto arr = JSScheduleWrapper::getTargetForJSObject(tmpObj); + if(! arr) { + args.rval().set(BOOLEAN_TO_JSVAL(isScheduled)); + return true; + }; + for (ssize_t i = 0; i < arr->size(); ++i) { + Ref *wrapper = arr->at(i); + if (wrapper) { + isScheduled = cobj->isScheduled(schedule_selector(JSScheduleWrapper::scheduleFunc), wrapper); + break; + } + } + args.rval().set(BOOLEAN_TO_JSVAL(isScheduled)); + return true; + } + JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} + bool js_forceGC(JSContext *cx, uint32_t argc, jsval *vp) { JSRuntime *rt = JS_GetRuntime(cx); JS_GC(rt); @@ -5039,6 +5070,7 @@ void register_cocos2dx_js_core(JSContext* cx, JS::HandleObject global) JS_DefineFunction(cx, tmpObj, "unscheduleAllCallbacks", js_cocos2dx_CCScheduler_unscheduleAll, 1, JSPROP_ENUMERATE | JSPROP_PERMANENT); JS_DefineFunction(cx, tmpObj, "unscheduleAllCallbacksWithMinPriority", js_cocos2dx_CCScheduler_unscheduleAllCallbacksWithMinPriority, 1, JSPROP_ENUMERATE | JSPROP_PERMANENT); JS_DefineFunction(cx, tmpObj, "isTargetPaused", js_cocos2dx_CCScheduler_isTargetPaused, 1, JSPROP_ENUMERATE | JSPROP_PERMANENT); + JS_DefineFunction(cx, tmpObj, "isScheduled", js_cocos2dx_CCScheduler_isScheduled, 2, JSPROP_ENUMERATE | JSPROP_PERMANENT); tmpObj.set(jsb_cocos2d_ActionManager_prototype); JS_DefineFunction(cx, tmpObj, "retain", js_cocos2dx_retain, 0, JSPROP_ENUMERATE | JSPROP_PERMANENT); diff --git a/native/cocos/scripting/js-bindings/manual/js_manual_conversions.cpp b/native/cocos/scripting/js-bindings/manual/js_manual_conversions.cpp index 980f2476c0..8b96e6c474 100644 --- a/native/cocos/scripting/js-bindings/manual/js_manual_conversions.cpp +++ b/native/cocos/scripting/js-bindings/manual/js_manual_conversions.cpp @@ -541,7 +541,7 @@ bool jsval_to_long_long(JSContext *cx, JS::HandleValue vp, long long* r) } bool jsval_to_std_string(JSContext *cx, JS::HandleValue v, std::string* ret) { - if(v.isString() || v.isNumber()) + if(v.isString() || v.isNumber() || v.isBoolean()) { JSString *tmp = JS::ToString(cx, v); JSB_PRECONDITION3(tmp, cx, false, "Error processing arguments"); diff --git a/native/cocos/scripting/js-bindings/manual/js_module_register.cpp b/native/cocos/scripting/js-bindings/manual/js_module_register.cpp index 9d1b96c310..6dd965a082 100755 --- a/native/cocos/scripting/js-bindings/manual/js_module_register.cpp +++ b/native/cocos/scripting/js-bindings/manual/js_module_register.cpp @@ -34,6 +34,10 @@ #include "platform/ios/JavaScriptObjCBridge.h" #endif +#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) +#include "platform/android/CCJavascriptJavaBridge.h" +#endif + USING_NS_CC; int js_module_register() { @@ -94,7 +98,9 @@ int js_module_register() sc->addRegisterCallback(register_all_cocos2dx_audioengine); #endif -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) +#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 return 1; diff --git a/native/cocos/scripting/js-bindings/manual/platform/android/CCJavascriptJavaBridge.cpp b/native/cocos/scripting/js-bindings/manual/platform/android/CCJavascriptJavaBridge.cpp new file mode 100644 index 0000000000..24728661d6 --- /dev/null +++ b/native/cocos/scripting/js-bindings/manual/platform/android/CCJavascriptJavaBridge.cpp @@ -0,0 +1,438 @@ +/* + * 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. + */ + +#include +#include "scripting/js-bindings/manual/platform/android/CCJavascriptJavaBridge.h" + +#include "platform/android/jni/JniHelper.h" +#include "scripting/js-bindings/manual/spidermonkey_specifics.h" +#include "scripting/js-bindings/manual/ScriptingCore.h" +#include "scripting/js-bindings/manual/js_manual_conversions.h" +#include "base/ccUTF8.h" + +#define LOG_TAG "CCJavascriptJavaBridge" +#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) + +#ifdef __cplusplus +extern "C" { +#endif + +JNIEXPORT jint JNICALL Java_org_cocos2dx_lib_Cocos2dxJavascriptJavaBridge_evalString + (JNIEnv *env, jclass cls, jstring value) +{ + bool strFlag = false; + std::string strValue = cocos2d::JniHelper::getStringUTFCharsJNI(env, value, &strFlag); + if (!strFlag) + { + CCLOG("Cocos2dxJavascriptJavaBridge_evalString error, invalid string code"); + return 0; + } + ScriptingCore::getInstance()->evalString(strValue.c_str(), nullptr); + return 1; +} + +#ifdef __cplusplus +} +#endif + +JavascriptJavaBridge::CallInfo::~CallInfo(void) +{ + if (m_returnType == TypeString && m_ret.stringValue) + { + delete m_ret.stringValue; + } +} + +bool JavascriptJavaBridge::CallInfo::execute(void) +{ + switch (m_returnType) + { + case TypeVoid: + m_env->CallStaticVoidMethod(m_classID, m_methodID); + break; + + case TypeInteger: + m_ret.intValue = m_env->CallStaticIntMethod(m_classID, m_methodID); + break; + + case TypeFloat: + m_ret.floatValue = m_env->CallStaticFloatMethod(m_classID, m_methodID); + break; + + case TypeBoolean: + m_ret.boolValue = m_env->CallStaticBooleanMethod(m_classID, m_methodID); + break; + + case TypeString: + m_retjstring = (jstring)m_env->CallStaticObjectMethod(m_classID, m_methodID); + std::string strValue = cocos2d::JniHelper::getStringUTFCharsJNI(m_env, m_retjstring); + + m_ret.stringValue = new string(strValue); + break; + } + + if (m_env->ExceptionCheck() == JNI_TRUE) + { + m_env->ExceptionDescribe(); + m_env->ExceptionClear(); + m_error = JSJ_ERR_EXCEPTION_OCCURRED; + return false; + } + + return true; +} + + +bool JavascriptJavaBridge::CallInfo::executeWithArgs(jvalue *args) +{ + switch (m_returnType) + { + case TypeVoid: + m_env->CallStaticVoidMethodA(m_classID, m_methodID, args); + break; + + case TypeInteger: + m_ret.intValue = m_env->CallStaticIntMethodA(m_classID, m_methodID, args); + break; + + case TypeFloat: + m_ret.floatValue = m_env->CallStaticFloatMethodA(m_classID, m_methodID, args); + break; + + case TypeBoolean: + m_ret.boolValue = m_env->CallStaticBooleanMethodA(m_classID, m_methodID, args); + break; + + case TypeString: + m_retjstring = (jstring)m_env->CallStaticObjectMethodA(m_classID, m_methodID, args); + std::string strValue = cocos2d::JniHelper::getStringUTFCharsJNI(m_env, m_retjstring); + m_ret.stringValue = new string(strValue); + break; + } + + if (m_env->ExceptionCheck() == JNI_TRUE) + { + m_env->ExceptionDescribe(); + m_env->ExceptionClear(); + m_error = JSJ_ERR_EXCEPTION_OCCURRED; + return false; + } + + return true; +} + +bool JavascriptJavaBridge::CallInfo::validateMethodSig() +{ + size_t len = m_methodSig.length(); + if (len < 3 || m_methodSig[0] != '(') // min sig is "()V" + { + m_error = JSJ_ERR_INVALID_SIGNATURES; + return false; + } + + size_t pos = 1; + while (pos < len && m_methodSig[pos] != ')') + { + JavascriptJavaBridge::ValueType type = checkType(m_methodSig, &pos); + if (type == TypeInvalid) return false; + + m_argumentsCount++; + m_argumentsType.push_back(type); + pos++; + } + + if (pos >= len || m_methodSig[pos] != ')') + { + m_error = JSJ_ERR_INVALID_SIGNATURES; + return false; + } + + pos++; + m_returnType = checkType(m_methodSig, &pos); + return true; +} + +JavascriptJavaBridge::ValueType JavascriptJavaBridge::CallInfo::checkType(const string& sig, size_t *pos) +{ + switch (sig[*pos]) + { + case 'I': + return TypeInteger; + case 'F': + return TypeFloat; + case 'Z': + return TypeBoolean; + case 'V': + return TypeVoid; + case 'L': + size_t pos2 = sig.find_first_of(';', *pos + 1); + if (pos2 == string::npos) + { + m_error = JSJ_ERR_INVALID_SIGNATURES; + return TypeInvalid; + } + + const string t = sig.substr(*pos, pos2 - *pos + 1); + if (t.compare("Ljava/lang/String;") == 0) + { + *pos = pos2; + return TypeString; + } + else if (t.compare("Ljava/util/Vector;") == 0) + { + *pos = pos2; + return TypeVector; + } + else + { + m_error = JSJ_ERR_TYPE_NOT_SUPPORT; + return TypeInvalid; + } + } + + m_error = JSJ_ERR_TYPE_NOT_SUPPORT; + return TypeInvalid; +} + + +bool JavascriptJavaBridge::CallInfo::getMethodInfo(void) +{ + m_methodID = 0; + m_env = 0; + + JavaVM* jvm = cocos2d::JniHelper::getJavaVM(); + jint ret = jvm->GetEnv((void**)&m_env, JNI_VERSION_1_4); + switch (ret) { + case JNI_OK: + break; + + case JNI_EDETACHED : + if (jvm->AttachCurrentThread(&m_env, NULL) < 0) + { + LOGD("%s", "Failed to get the environment using AttachCurrentThread()"); + m_error = JSJ_ERR_VM_THREAD_DETACHED; + return false; + } + break; + + case JNI_EVERSION : + default : + LOGD("%s", "Failed to get the environment using GetEnv()"); + m_error = JSJ_ERR_VM_FAILURE; + return false; + } + jstring _jstrClassName = m_env->NewStringUTF(m_className.c_str()); + m_classID = (jclass) m_env->CallObjectMethod(cocos2d::JniHelper::classloader, + cocos2d::JniHelper::loadclassMethod_methodID, + _jstrClassName); + + if (NULL == m_classID) { + LOGD("Classloader failed to find class of %s", m_className.c_str()); + } + + m_env->DeleteLocalRef(_jstrClassName); + m_methodID = m_env->GetStaticMethodID(m_classID, m_methodName.c_str(), m_methodSig.c_str()); + if (!m_methodID) + { + m_env->ExceptionClear(); + LOGD("Failed to find method id of %s.%s %s", + m_className.c_str(), + m_methodName.c_str(), + m_methodSig.c_str()); + m_error = JSJ_ERR_METHOD_NOT_FOUND; + return false; + } + + return true; +} + +JS::Value JavascriptJavaBridge::convertReturnValue(JSContext *cx, ReturnValue retValue, ValueType type) +{ + JS::Value ret = JSVAL_NULL; + + switch (type) + { + case TypeInteger: + return INT_TO_JSVAL(retValue.intValue); + case TypeFloat: + return DOUBLE_TO_JSVAL((double)retValue.floatValue); + case TypeBoolean: + return BOOLEAN_TO_JSVAL(retValue.boolValue); + case TypeString: + return c_string_to_jsval(cx, retValue.stringValue->c_str(),retValue.stringValue->size()); + } + + return ret; +} + +/** + * @brief Initialize Object and needed properties. + * + */ +JS_BINDED_CLASS_GLUE_IMPL(JavascriptJavaBridge); + +/** + * @brief Implementation for the Javascript Constructor + * + */ +JS_BINDED_CONSTRUCTOR_IMPL(JavascriptJavaBridge) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + JavascriptJavaBridge* jsj = new JavascriptJavaBridge(); + + js_proxy_t *p; + jsval out; + + JS::RootedObject proto(cx, JavascriptJavaBridge::js_proto); + JS::RootedObject parentProto(cx, JavascriptJavaBridge::js_parent); + JS::RootedObject obj(cx, JS_NewObject(cx, &JavascriptJavaBridge::js_class, proto, parentProto)); + + if (obj) { + JS_SetPrivate(obj, jsj); + out = OBJECT_TO_JSVAL(obj); + } + + args.rval().set(out); + p = jsb_new_proxy(jsj, obj); + + JS::AddNamedObjectRoot(cx, &p->obj, "JavascriptJavaBridge"); + return true; +} + +/** + * @brief destructor for Javascript + * + */ +static void basic_object_finalize(JSFreeOp *freeOp, JSObject *obj) +{ + CCLOG("jsbindings: finalizing JS object %p (JavascriptJavaBridge)", obj); + JavascriptJavaBridge* native = (JavascriptJavaBridge*)JS_GetPrivate(obj); + if(native) + { + delete native; + } +} + +/** + * @brief implementation for call java static method + */ +JS_BINDED_FUNC_IMPL(JavascriptJavaBridge, callStaticMethod) +{ + JS::CallArgs argv = JS::CallArgsFromVp(argc, vp); + if (argc == 3) { + JSStringWrapper arg0(argv[0]); + JSStringWrapper arg1(argv[1]); + JSStringWrapper arg2(argv[2]); + + CallInfo call(arg0.get(), arg1.get(), arg2.get()); + if(call.isValid()){ + bool success = call.execute(); + int errorCode = call.getErrorCode(); + if(errorCode < 0) + JS_ReportError(cx, "js_cocos2dx_JSJavaBridge : call result code: %d", errorCode); + argv.rval().set(convertReturnValue(cx, call.getReturnValue(), call.getReturnValueType())); + return success; + } + } + else if(argc > 3){ + JSStringWrapper arg0(argv[0]); + JSStringWrapper arg1(argv[1]); + JSStringWrapper arg2(argv[2]); + + CallInfo call(arg0.get(), arg1.get(), arg2.get()); + if(call.isValid() && call.getArgumentsCount() == (argc - 3)){ + int count = argc - 3; + jvalue *args = new jvalue[count]; + for (int i = 0; i < count; ++i){ + int index = i + 3; + switch (call.argumentTypeAtIndex(i)) + { + case TypeInteger: + double interger; + JS::ToNumber(cx, argv.get(index), &interger); + args[i].i = (int)interger; + break; + + case TypeFloat: + double floatNumber; + JS::ToNumber(cx, argv.get(index), &floatNumber); + args[i].f = (float)floatNumber; + break; + + case TypeBoolean: + args[i].z = JS::ToBoolean(argv.get(index)) ? JNI_TRUE : JNI_FALSE; + break; + + case TypeString: + default: + JSStringWrapper arg(argv.get(index)); + args[i].l = call.getEnv()->NewStringUTF(arg.get()); + break; + } + } + bool success = call.executeWithArgs(args); + if (args) delete []args; + int errorCode = call.getErrorCode(); + if(errorCode < 0) + JS_ReportError(cx, "js_cocos2dx_JSJavaBridge : call result code: %d", errorCode); + argv.rval().set(convertReturnValue(cx, call.getReturnValue(), call.getReturnValueType())); + return success; + } + + }else{ + JS_ReportError(cx, "js_cocos2dx_JSJavaBridge : wrong number of arguments: %d, was expecting more than 3", argc); + } + + return false; +} + +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; +} + +/** + * @brief register JavascriptJavaBridge to be usable in js + * + */ +void JavascriptJavaBridge::_js_register(JSContext *cx, JS::HandleObject global) +{ + JSClass jsclass = { + "JavascriptJavaBridge", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub,basic_object_finalize + }; + + JavascriptJavaBridge::js_class = jsclass; + static JSPropertySpec props[] = { + JS_PSG("__nativeObj", js_is_native_obj, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_PS_END + }; + + static JSFunctionSpec funcs[] = { + JS_BINDED_FUNC_FOR_DEF(JavascriptJavaBridge, callStaticMethod), + JS_FS_END + }; + + JavascriptJavaBridge::js_parent = NULL; + JavascriptJavaBridge::js_proto = JS_InitClass(cx, global, JS::NullPtr(), &JavascriptJavaBridge::js_class , JavascriptJavaBridge::_js_constructor, 0, props, funcs, NULL, NULL); +} diff --git a/native/cocos/scripting/js-bindings/manual/platform/android/CCJavascriptJavaBridge.h b/native/cocos/scripting/js-bindings/manual/platform/android/CCJavascriptJavaBridge.h new file mode 100644 index 0000000000..6cc0c47e7e --- /dev/null +++ b/native/cocos/scripting/js-bindings/manual/platform/android/CCJavascriptJavaBridge.h @@ -0,0 +1,155 @@ +/* + * 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. + */ + +#ifndef __CC_JAVASCRIPT_JAVA_BRIDGE__ +#define __CC_JAVASCRIPT_JAVA_BRIDGE__ + +#include +#include +#include +#include "jsapi.h" +#include "jsfriendapi.h" +#include "scripting/js-bindings/manual/js_bindings_config.h" +#include "scripting/js-bindings/manual/jsb_helper.h" + +using namespace std; + +#define JSJ_ERR_OK (0) +#define JSJ_ERR_TYPE_NOT_SUPPORT (-1) +#define JSJ_ERR_INVALID_SIGNATURES (-2) +#define JSJ_ERR_METHOD_NOT_FOUND (-3) +#define JSJ_ERR_EXCEPTION_OCCURRED (-4) +#define JSJ_ERR_VM_THREAD_DETACHED (-5) +#define JSJ_ERR_VM_FAILURE (-6) + +class JavascriptJavaBridge +{ + +private: + typedef enum : char + { + TypeInvalid = -1, + TypeVoid = 0, + TypeInteger = 1, + TypeFloat = 2, + TypeBoolean = 3, + TypeString = 4, + TypeVector = 5, + TypeFunction= 6, + } ValueType; + + typedef vector ValueTypes; + + typedef union + { + int intValue; + float floatValue; + int boolValue; + string *stringValue; + } ReturnValue; + + class CallInfo + { + public: + CallInfo(const char *className, const char *methodName, const char *methodSig) + : m_valid(false) + , m_error(JSJ_ERR_OK) + , m_className(className) + , m_methodName(methodName) + , m_methodSig(methodSig) + , m_returnType(TypeVoid) + , m_argumentsCount(0) + , m_retjstring(NULL) + , m_env(NULL) + , m_classID(NULL) + , m_methodID(NULL) + { + memset(&m_ret, 0, sizeof(m_ret)); + m_valid = validateMethodSig() && getMethodInfo(); + } + ~CallInfo(void); + + bool isValid(void) { + return m_valid; + } + + int getErrorCode(void) { + return m_error; + } + + JNIEnv *getEnv(void) { + return m_env; + } + + int argumentTypeAtIndex(size_t index) { + return m_argumentsType.at(index); + } + + int getArgumentsCount(){ + return m_argumentsCount; + } + + ValueType getReturnValueType(){ + return m_returnType; + } + + ReturnValue getReturnValue(){ + return m_ret; + } + + bool execute(void); + bool executeWithArgs(jvalue *args); + + + private: + bool m_valid; + int m_error; + + string m_className; + string m_methodName; + string m_methodSig; + int m_argumentsCount; + ValueTypes m_argumentsType; + ValueType m_returnType; + + ReturnValue m_ret; + jstring m_retjstring; + + JNIEnv *m_env; + jclass m_classID; + jmethodID m_methodID; + + bool validateMethodSig(void); + bool getMethodInfo(void); + ValueType checkType(const string& sig, size_t *pos); + }; + + JS::Value convertReturnValue(JSContext *cx, ReturnValue retValue, ValueType type); +public: + + JS_BINDED_CLASS_GLUE(JavascriptJavaBridge); + JS_BINDED_CONSTRUCTOR(JavascriptJavaBridge); + JS_BINDED_FUNC(JavascriptJavaBridge, callStaticMethod); + +}; + +#endif \ No newline at end of file diff --git a/native/cocos/scripting/js-bindings/proj.android/Android.mk b/native/cocos/scripting/js-bindings/proj.android/Android.mk index 110a8f69f1..8b4e2e67d3 100644 --- a/native/cocos/scripting/js-bindings/proj.android/Android.mk +++ b/native/cocos/scripting/js-bindings/proj.android/Android.mk @@ -46,7 +46,8 @@ LOCAL_SRC_FILES := ../auto/jsb_cocos2dx_extension_auto.cpp \ ../manual/chipmunk/js_bindings_chipmunk_auto_classes.cpp \ ../manual/chipmunk/js_bindings_chipmunk_functions.cpp \ ../manual/chipmunk/js_bindings_chipmunk_manual.cpp \ - ../manual/chipmunk/js_bindings_chipmunk_registration.cpp + ../manual/chipmunk/js_bindings_chipmunk_registration.cpp \ + ../manual/platform/android/CCJavascriptJavaBridge.cpp LOCAL_CFLAGS := -DCOCOS2D_JAVASCRIPT @@ -55,6 +56,7 @@ LOCAL_EXPORT_CFLAGS := -DCOCOS2D_JAVASCRIPT LOCAL_C_INCLUDES := $(LOCAL_PATH)/../manual \ $(LOCAL_PATH)/../manual/cocostudio \ $(LOCAL_PATH)/../manual/spine \ + $(LOCAL_PATH)/../manual/platform/android \ $(LOCAL_PATH)/../auto \ $(LOCAL_PATH)/../../../2d \ $(LOCAL_PATH)/../../../base \ diff --git a/native/cocos/scripting/js-bindings/script/jsb_boot.js b/native/cocos/scripting/js-bindings/script/jsb_boot.js index 4a96b85e87..39bcddfec2 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_boot.js +++ b/native/cocos/scripting/js-bindings/script/jsb_boot.js @@ -788,6 +788,11 @@ cc.view.getTargetDensityDPI = function() {return cc.DENSITYDPI_DEVICE;}; cc.eventManager = cc.director.getEventDispatcher(); +cc.eventManager.addCustomListener('window-resize', function () { + cc.winSize = cc.director.getWinSize(); + cc.visibleRect.init(); +}); + cc.audioEngine = cc.AudioEngine.getInstance(); cc.audioEngine.end = function(){ this.stopMusic(); @@ -1506,6 +1511,13 @@ cc.game = { __restartVM(); }, + /** + * End game, it will close the game window + */ + end: function () { + close(); + }, + /** * Run game. */ diff --git a/native/cocos/scripting/js-bindings/script/jsb_create_apis.js b/native/cocos/scripting/js-bindings/script/jsb_create_apis.js index d4e496bdde..7f08f1b2d4 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_create_apis.js +++ b/native/cocos/scripting/js-bindings/script/jsb_create_apis.js @@ -428,8 +428,8 @@ cc.Speed.prototype._ctor = function(action, speed) { cc.Follow.prototype._ctor = function (followedNode, rect) { if(followedNode) - rect ? ret.initWithTarget(followedNode, rect) - : ret.initWithTarget(followedNode); + rect ? this.initWithTarget(followedNode, rect) + : this.initWithTarget(followedNode); }; cc.OrbitCamera.prototype._ctor = function (t, radius, deltaRadius, angleZ, deltaAngleZ, angleX, deltaAngleX) { diff --git a/native/cocos/ui/UIEditBox/Mac/CCUIEditBoxMac.mm b/native/cocos/ui/UIEditBox/Mac/CCUIEditBoxMac.mm index 018ec66557..833a1817ab 100644 --- a/native/cocos/ui/UIEditBox/Mac/CCUIEditBoxMac.mm +++ b/native/cocos/ui/UIEditBox/Mac/CCUIEditBoxMac.mm @@ -44,7 +44,7 @@ self.frameRect = frameRect; self.editBox = editBox; - self.dataInputMode = cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_ALL_CHARACTERS; + self.dataInputMode = cocos2d::ui::EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS; self.keyboardReturnType = cocos2d::ui::EditBox::KeyboardReturnType::DEFAULT; [self createMultiLineTextField]; @@ -243,6 +243,9 @@ case cocos2d::ui::EditBox::InputFlag::SENSITIVE: CCLOG("SENSITIVE not implemented"); break; + case cocos2d::ui::EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS: + CCLOG("LOWERCASE_ALL_CHARACTERS not implemented"); + break; default: break; } diff --git a/native/cocos/ui/UIEditBox/UIEditBox.cpp b/native/cocos/ui/UIEditBox/UIEditBox.cpp index 0d803a8f32..02c8073644 100644 --- a/native/cocos/ui/UIEditBox/UIEditBox.cpp +++ b/native/cocos/ui/UIEditBox/UIEditBox.cpp @@ -36,7 +36,7 @@ EditBox::EditBox() : _editBoxImpl(nullptr) , _delegate(nullptr) , _editBoxInputMode(EditBox::InputMode::SINGLE_LINE) -, _editBoxInputFlag(EditBox::InputFlag::INITIAL_CAPS_ALL_CHARACTERS) +, _editBoxInputFlag(EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS) , _keyboardReturnType(KeyboardReturnType::DEFAULT) , _backgroundSprite(nullptr) , _fontSize(-1) diff --git a/native/cocos/ui/UIEditBox/UIEditBox.h b/native/cocos/ui/UIEditBox/UIEditBox.h index 3c2d10489f..952745158f 100644 --- a/native/cocos/ui/UIEditBox/UIEditBox.h +++ b/native/cocos/ui/UIEditBox/UIEditBox.h @@ -184,7 +184,12 @@ namespace ui { /** * Capitalize all characters automatically. */ - INITIAL_CAPS_ALL_CHARACTERS, + INITIAL_CAPS_ALL_CHARACTERS, + + /** + * Lowercase all characters automatically. + */ + LOWERCASE_ALL_CHARACTERS }; /** diff --git a/native/cocos/ui/UIEditBox/UIEditBoxImpl-android.cpp b/native/cocos/ui/UIEditBox/UIEditBoxImpl-android.cpp index 91c65cb713..0ef7a60717 100644 --- a/native/cocos/ui/UIEditBox/UIEditBoxImpl-android.cpp +++ b/native/cocos/ui/UIEditBox/UIEditBoxImpl-android.cpp @@ -36,6 +36,7 @@ #include "math/Vec2.h" #include "ui/UIHelper.h" #include "base/CCDirector.h" +#include "platform/CCFileUtils.h" NS_CC_BEGIN @@ -112,8 +113,18 @@ void EditBoxImplAndroid::setNativeFont(const char* pFontName, int fontSize) { auto director = cocos2d::Director::getInstance(); auto glView = director->getOpenGLView(); + auto isFontFileExists = cocos2d::FileUtils::getInstance()->isFileExist(pFontName); + std::string realFontPath = pFontName; + if (isFontFileExists) + { + realFontPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(pFontName); + if (realFontPath.find("assets/") == 0) + { + realFontPath = realFontPath.substr(strlen("assets/")); + } + } JniHelper::callStaticVoidMethod(editBoxClassName, "setFont", - _editBoxIndex, pFontName, + _editBoxIndex, realFontPath, (float)fontSize * glView->getScaleX()); } @@ -174,11 +185,8 @@ void EditBoxImplAndroid::setNativePlaceHolder(const char* pText) } void EditBoxImplAndroid::setNativeVisible(bool visible) -{ - if (!visible) - { - nativeCloseKeyboard(); - } +{ // don't need to be implemented on android platform. + JniHelper::callStaticVoidMethod(editBoxClassName, "setVisible", _editBoxIndex, visible); } void EditBoxImplAndroid::updateNativeFrame(const Rect& rect) @@ -191,7 +199,7 @@ void EditBoxImplAndroid::updateNativeFrame(const Rect& rect) void EditBoxImplAndroid::nativeOpenKeyboard() { //it will also open up the soft keyboard - JniHelper::callStaticVoidMethod(editBoxClassName, "setVisible", _editBoxIndex, true); + JniHelper::callStaticVoidMethod(editBoxClassName, "openKeyboard", _editBoxIndex); } @@ -229,7 +237,7 @@ void editBoxEditingDidEnd(int index, const std::string& text) const char* EditBoxImplAndroid::getNativeDefaultFontName() { - return ""; + return "sans-serif"; } } //end of ui namespace diff --git a/native/cocos/ui/UIEditBox/UIEditBoxImpl-common.cpp b/native/cocos/ui/UIEditBox/UIEditBoxImpl-common.cpp index 92e80d76f4..59df9e1ba0 100644 --- a/native/cocos/ui/UIEditBox/UIEditBoxImpl-common.cpp +++ b/native/cocos/ui/UIEditBox/UIEditBoxImpl-common.cpp @@ -225,11 +225,6 @@ void EditBoxImplCommon::setPlaceHolder(const char* pText) if (pText != NULL) { _placeHolder = pText; - if (_placeHolder.length() > 0 && _text.length() == 0) - { - _labelPlaceHolder->setVisible(true); - } - _labelPlaceHolder->setString(_placeHolder); this->setNativePlaceHolder(pText); } @@ -238,7 +233,16 @@ void EditBoxImplCommon::setPlaceHolder(const char* pText) void EditBoxImplCommon::setVisible(bool visible) { - this->setNativeVisible(visible); + if (visible) + { + refreshInactiveText(); + } + else + { + this->setNativeVisible(visible); + _label->setVisible(visible); + _labelPlaceHolder->setVisible(visible); + } } void EditBoxImplCommon::setContentSize(const Size& size) @@ -269,7 +273,7 @@ void EditBoxImplCommon::openKeyboard() { _label->setVisible(false); _labelPlaceHolder->setVisible(false); - + this->setNativeVisible(true); this->nativeOpenKeyboard(); } @@ -281,18 +285,7 @@ void EditBoxImplCommon::closeKeyboard() void EditBoxImplCommon::onEndEditing(const std::string& text) { this->setNativeVisible(false); - - if(text.empty()) - { - _label->setVisible(false); - _labelPlaceHolder->setVisible(true); - } - else - { - _label->setVisible(true); - _labelPlaceHolder->setVisible(false); - setInactiveText(text.c_str()); - } + refreshInactiveText(); } void EditBoxImplCommon::editBoxEditingDidBegin() @@ -317,9 +310,7 @@ void EditBoxImplCommon::editBoxEditingDidBegin() void EditBoxImplCommon::editBoxEditingDidEnd(const std::string& text) { - // LOGD("textFieldShouldEndEditing..."); _text = text; - this->refreshInactiveText(); cocos2d::ui::EditBoxDelegate *pDelegate = _editBox->getDelegate(); if (pDelegate != nullptr) diff --git a/native/cocos/ui/UIEditBox/UIEditBoxImpl-ios.mm b/native/cocos/ui/UIEditBox/UIEditBoxImpl-ios.mm index b54ecfaeb2..79691f3296 100644 --- a/native/cocos/ui/UIEditBox/UIEditBoxImpl-ios.mm +++ b/native/cocos/ui/UIEditBox/UIEditBoxImpl-ios.mm @@ -226,6 +226,9 @@ UIFont* EditBoxImplIOS::constructFont(const char *fontName, int fontSize) if (strlen(fontName) > 0) { textFont = [UIFont fontWithName:fntName size:fontSize]; + if(textFont == nil) { + textFont = [UIFont systemFontOfSize:fontSize]; + } } else { diff --git a/native/cocos/ui/UIEditBox/UIEditBoxImpl-mac.mm b/native/cocos/ui/UIEditBox/UIEditBoxImpl-mac.mm index c3413a1f43..e5216e235d 100644 --- a/native/cocos/ui/UIEditBox/UIEditBoxImpl-mac.mm +++ b/native/cocos/ui/UIEditBox/UIEditBoxImpl-mac.mm @@ -97,6 +97,9 @@ NSFont* EditBoxImplMac::constructFont(const char *fontName, int fontSize) else { textFont = [NSFont fontWithName:fntName size:fontSize]; + if (textFont == nil) { + textFont = [NSFont systemFontOfSize:fontSize]; + } } return textFont; diff --git a/native/cocos/ui/UIEditBox/iOS/CCUIEditBoxIOS.mm b/native/cocos/ui/UIEditBox/iOS/CCUIEditBoxIOS.mm index 794e869dbf..ad5cbccad1 100644 --- a/native/cocos/ui/UIEditBox/iOS/CCUIEditBoxIOS.mm +++ b/native/cocos/ui/UIEditBox/iOS/CCUIEditBoxIOS.mm @@ -57,7 +57,7 @@ _editState = NO; self.frameRect = frameRect; self.editBox = editBox; - self.dataInputMode = cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_ALL_CHARACTERS; + self.dataInputMode = cocos2d::ui::EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS; self.keyboardReturnType = cocos2d::ui::EditBox::KeyboardReturnType::DEFAULT; [self createMultiLineTextField]; @@ -204,8 +204,13 @@ case cocos2d::ui::EditBox::InputFlag::SENSITIVE: self.textInput.autocorrectionType = UITextAutocorrectionTypeNo; + self.textInput.autocapitalizationType = UITextAutocapitalizationTypeNone; break; - + + case cocos2d::ui::EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS: + self.textInput.autocapitalizationType = UITextAutocapitalizationTypeNone; + break; + default: break; } diff --git a/native/external/config.json b/native/external/config.json index 3573ba3a43..8ff8c73d25 100644 --- a/native/external/config.json +++ b/native/external/config.json @@ -2,5 +2,5 @@ "version":"v3-deps-4", "zip_file_size":"51525671", "repo_name":"cocos2d-x-lite-external", - "repo_parent":"https://github.com/WenhaiLin/" + "repo_parent":"https://github.com/cocos-creator/" } diff --git a/native/gulpfile.js b/native/gulpfile.js index 7d51a88e98..66cf07735d 100644 --- a/native/gulpfile.js +++ b/native/gulpfile.js @@ -7,7 +7,7 @@ var Ftp = require('ftp'); var ExecSync = require('child_process').execSync; var spawn = require('child_process').spawn; var Path = require('path'); -var fs = require('fs'); +var fs = require('fs-extra'); gulp.task('make-cocos2d-x', gulpSequence('gen-cocos2d-x', 'upload-cocos2d-x')); gulp.task('make-prebuilt', gulpSequence('gen-libs', 'collect-prebuilt-mk', 'archive-prebuilt-mk', 'archive-prebuilt', 'upload-prebuilt', 'upload-prebuilt-mk')); @@ -66,7 +66,11 @@ function upload2Ftp(localPath, ftpPath, config, cb) { } function uploadZipFile (zipFileName, path, cb) { - var remotePath = Path.join('TestBuilds','Fireball', 'cocos2d-x', zipFileName); + var branch = getCurrentBranch(); + if (branch === 'develop') { + branch = 'dev'; + } + var remotePath = Path.join('TestBuilds','Fireball', 'cocos2d-x', branch, zipFileName); var zipFilePath = Path.join(path, zipFileName); upload2Ftp(zipFilePath, remotePath, { host: '192.168.52.109', @@ -80,6 +84,13 @@ function uploadZipFile (zipFileName, path, cb) { }); } +function getCurrentBranch() { + var spawnSync = require('child_process').spawnSync; + var output = spawnSync('git', ['symbolic-ref', '--short', '-q', 'HEAD']); + // console.log(output); + return output.stdout.toString().trim(); +} + gulp.task('init', function(cb) { execSync('python download-deps.py', '.'); execSync('git submodule update --init', '.'); @@ -152,32 +163,40 @@ gulp.task('collect-prebuilt-mk', function () { '**/prebuilt-mk/Android.mk', ], { base: './', - ignore: 'prebuilt_mk/**/*' + ignore: './prebuilt_mk/**/*' }).pipe(gulp.dest('prebuilt_mk')); }); -gulp.task('update-simulator-config', ['update-simulator-script'], function () { - var destPath = process.platform === 'win32' ? './simulator/win32' : './simulator/mac/Simulator.app/Contents/Resources'; - return gulp.src('./tools/simulator/config.json') - .pipe(gulp.dest(destPath)); +gulp.task('update-simulator-config', ['update-simulator-script'], function (cb) { + var destPath = process.platform === 'win32' ? './simulator/win32/config.json' : './simulator/mac/Simulator.app/Contents/Resources/config.json'; + fs.copy('./tools/simulator/config.json', destPath, cb); }); -gulp.task('update-simulator-script', function () { - var destPath = process.platform === 'win32' ? './simulator/win32' : './simulator/mac/Simulator.app/Contents/Resources'; - var updateScript = function () { - // scripts - return gulp.src(['./cocos/scripting/js-bindings/script/**/*', '!**/.DS_Store'], { - base: './cocos/scripting/js-bindings' - }).pipe(gulp.dest(destPath)); +gulp.task('update-simulator-script', function (cb) { + var simulatorPath = process.platform === 'win32' ? './simulator/win32' : './simulator/mac/Simulator.app/Contents/Resources'; + var destPath = simulatorPath + '/script'; + var updateScript = function (callback) { + fs.copy('./cocos/scripting/js-bindings/script', destPath, { + clobber: true, + filter: function(name) { + if (name.startsWith('.DS_Store')) { + return false; + } else { + return true; + } + } + }, callback); }; - if (!fs.existsSync(destPath)) { - console.error(`Cant\'t find simulator dir [${destPath}]`); + if (!fs.existsSync(simulatorPath)) { + console.error(`Cant\'t find simulator dir [${simulatorPath}]`); } else { if (process.platform === 'win32') { - downloadSimulatorDLL(updateScript); + downloadSimulatorDLL(function () { + updateScript(cb); + }); } else { - updateScript(); + updateScript(cb); } } }); diff --git a/native/package.json b/native/package.json index 06c9a5f3ef..1cf6375aee 100644 --- a/native/package.json +++ b/native/package.json @@ -8,6 +8,7 @@ }, "devDependencies": { "download": "4.4.3", + "fs-extra": "0.30.0", "ftp": "0.3.10", "gulp": "3.9.1", "gulp-sequence": "0.4.5", diff --git a/native/templates/cocos2dx_files.json b/native/templates/cocos2dx_files.json index e3a6e1e12b..989295ed9e 100644 --- a/native/templates/cocos2dx_files.json +++ b/native/templates/cocos2dx_files.json @@ -432,6 +432,13 @@ "cocos/editor-support/creator/Android.mk", "cocos/editor-support/creator/CCScale9Sprite.cpp", "cocos/editor-support/creator/CCScale9Sprite.h", + "cocos/editor-support/creator/CCGraphicsNode.h", + "cocos/editor-support/creator/CCGraphicsNode.cpp", + "cocos/editor-support/creator/CCGraphicsNode.vert", + "cocos/editor-support/creator/CCGraphicsNode.frag", + "cocos/editor-support/creator/Triangulate.h", + "cocos/editor-support/creator/Triangulate.cpp", + "cocos/editor-support/creator/Android.mk", "cocos/editor-support/spine/Android.mk", "cocos/editor-support/spine/Animation.c", "cocos/editor-support/spine/Animation.h", @@ -600,17 +607,21 @@ "cocos/platform/android/java/.project", "cocos/platform/android/java/AndroidManifest.xml", "cocos/platform/android/java/build.xml", + "cocos/platform/android/java/libs/", + "cocos/platform/android/java/libs/android-async-http-1.4.8.jar", "cocos/platform/android/java/proguard-project.txt", "cocos/platform/android/java/project.properties", "cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxAccelerometer.java", "cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java", "cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxBitmap.java", + "cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxDownloader.java", "cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBox.java", "cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxEditBoxHelper.java", "cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxGLSurfaceView.java", "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/Cocos2dxMusic.java", "cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxRenderer.java", @@ -641,6 +652,8 @@ "cocos/platform/android/libcocos2dx/AndroidManifest.xml", "cocos/platform/android/libcocos2dx/build.gradle", "cocos/platform/android/libcocos2dx/proguard-rules.pro", + "cocos/platform/apple/CCDevice-apple.h", + "cocos/platform/apple/CCDevice-apple.mm", "cocos/platform/apple/CCFileUtils-apple.h", "cocos/platform/apple/CCFileUtils-apple.mm", "cocos/platform/apple/CCLock-apple.cpp", @@ -3099,6 +3112,8 @@ "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", diff --git a/native/templates/js-template-binary/cocos-project-template.json b/native/templates/js-template-binary/cocos-project-template.json index b6d721e378..c0ebb6e0c2 100755 --- a/native/templates/js-template-binary/cocos-project-template.json +++ b/native/templates/js-template-binary/cocos-project-template.json @@ -61,6 +61,13 @@ "include": [ "*.java" ] + }, + { + "from":"cocos/platform/android/java/libs", + "to":"frameworks/runtime-src/proj.android/libs", + "include": [ + "*.jar" + ] } ], "project_rename":{ diff --git a/native/templates/js-template-binary/frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java b/native/templates/js-template-binary/frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java index 5f065885bb..4ee7f3c3f7 100755 --- a/native/templates/js-template-binary/frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java +++ b/native/templates/js-template-binary/frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java @@ -34,6 +34,10 @@ import android.net.wifi.WifiManager; import android.os.Bundle; import android.view.WindowManager; +// For JS and JAVA reflection test, you can delete it if it's your own project +import android.app.AlertDialog; +import android.content.DialogInterface; +// ------------------------------------- // The name of .so is specified in AndroidMenifest.xml. NativityActivity will load it automatically for you. // You can use "System.loadLibrary()" to load other .so files. @@ -41,11 +45,13 @@ import android.view.WindowManager; public class AppActivity extends Cocos2dxActivity{ static String hostIPAdress = "0.0.0.0"; + private static AppActivity app = null; + @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); - + app = this; if(nativeIsDebug()){ getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } @@ -73,5 +79,18 @@ public class AppActivity extends Cocos2dxActivity{ } private static native boolean nativeIsDebug(); - + + // For JS and JAVA reflection test, you can delete it if it's your own project + public static void showAlertDialog(final String title,final String message) { + // Here be sure to use runOnUiThread + app.runOnUiThread(new Runnable() { + @Override + public void run() { + AlertDialog alertDialog = new AlertDialog.Builder(app).create(); + alertDialog.setTitle(title); + alertDialog.setMessage(message); + alertDialog.show(); + } + }); + } } diff --git a/native/templates/js-template-binary/frameworks/runtime-src/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj b/native/templates/js-template-binary/frameworks/runtime-src/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj index d4509a5936..8c818be610 100755 --- a/native/templates/js-template-binary/frameworks/runtime-src/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj +++ b/native/templates/js-template-binary/frameworks/runtime-src/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj @@ -13,6 +13,7 @@ 1AD7E0A918C9DBE3004817A6 /* main.js in Resources */ = {isa = PBXBuildFile; fileRef = 1A6BF21418C9DB5900FB0E1C /* main.js */; }; 1AE159EC18C9DF3600FCA372 /* project.json in Resources */ = {isa = PBXBuildFile; fileRef = 1A1A081B18C9DF05005C6854 /* project.json */; }; 1BFE40C9B3992EFC7694ECAD /* libsimulator iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = B369480BACF7CC3BFAF3B77A /* libsimulator iOS.a */; }; + 294D7D781D0D6667002CE7B7 /* CoreText.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 294D7D771D0D6667002CE7B7 /* CoreText.framework */; }; 3B67481F942374033A420049 /* libjscocos2d iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = DCAA4417880B45A57D3DBA4A /* libjscocos2d iOS.a */; }; 471C47CE8C319E15D42CFACA /* libsimulator Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1DBD455C8FDA2F3E10BCC26C /* libsimulator Mac.a */; }; 4EF7467CB50B6A7F2A970566 /* libcocos2d iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 403C4AA98CE6BA7FB917B960 /* libcocos2d iOS.a */; }; @@ -102,6 +103,7 @@ 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 = "/Applications/CocosCreator.app/Contents/Resources/cocos2d-x/cocos2dx/platform/third_party/ios/libraries/libcurl.a"; sourceTree = ""; }; 1DBD455C8FDA2F3E10BCC26C /* libsimulator Mac.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = "libsimulator Mac.a"; path = "/Applications/CocosCreator.app/Contents/Resources/cocos2d-x/prebuilt/mac/libsimulator Mac.a"; sourceTree = ""; }; + 294D7D771D0D6667002CE7B7 /* CoreText.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreText.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/CoreText.framework; sourceTree = DEVELOPER_DIR; }; 403C4AA98CE6BA7FB917B960 /* libcocos2d iOS.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = "libcocos2d iOS.a"; path = "/Applications/CocosCreator.app/Contents/Resources/cocos2d-x/prebuilt/ios/libcocos2d iOS.a"; 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 = ""; }; @@ -217,6 +219,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 294D7D781D0D6667002CE7B7 /* CoreText.framework in Frameworks */, ED545A901B68A25E00C3958E /* libiconv.dylib in Frameworks */, 9F20C9E61A5BD38A006FB50B /* Security.framework in Frameworks */, BA4E718719EB6E7900932425 /* MediaPlayer.framework in Frameworks */, @@ -380,6 +383,7 @@ A92275401517C094001B78AA /* Frameworks */ = { isa = PBXGroup; children = ( + 294D7D771D0D6667002CE7B7 /* CoreText.framework */, ED545A911B68A26600C3958E /* libiconv.dylib */, ED545A8F1B68A25E00C3958E /* libiconv.dylib */, 87D4C4441AB2187000F68C44 /* Security.framework */, diff --git a/native/templates/js-template-default/cocos-project-template.json b/native/templates/js-template-default/cocos-project-template.json index c2a11dc87c..5c06dcdb33 100755 --- a/native/templates/js-template-default/cocos-project-template.json +++ b/native/templates/js-template-default/cocos-project-template.json @@ -46,6 +46,7 @@ "frameworks/runtime-src/proj.android/build.xml", "frameworks/runtime-src/proj.android/res/values/strings.xml", "frameworks/runtime-src/proj.android-studio/settings.gradle", + "frameworks/runtime-src/proj.android-studio/app/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", diff --git a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml index 59cb2ffb84..447d63d2f3 100755 --- a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml +++ b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml @@ -10,9 +10,9 @@ android:icon="@mipmap/ic_launcher"> - - + + - - + + - + \ No newline at end of file diff --git a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/jni/Android.mk b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/jni/Android.mk index 26a744cd2c..d53d0b7fdb 100755 --- a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/jni/Android.mk +++ b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/jni/Android.mk @@ -6,10 +6,12 @@ LOCAL_MODULE := cocos2djs_shared LOCAL_MODULE_FILENAME := libcocos2djs +ifeq ($(USE_ARM_MODE),1) +LOCAL_ARM_MODE := arm +endif + LOCAL_SRC_FILES := hellojavascript/main.cpp \ - ../../../Classes/AppDelegate.cpp \ - ../../../Classes/CCScale9Sprite.cpp \ - ../../../Classes/jsb/jsb_creator_auto.cpp + ../../../Classes/AppDelegate.cpp LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../../Classes diff --git a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/project.properties b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/project.properties new file mode 100755 index 0000000000..510f51cd89 --- /dev/null +++ b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/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-16 + +android.library.reference.1=../../cocos2d-x/cocos/platform/android/java diff --git a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/src/org/cocos2dx/javascript/AppActivity.java b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/src/org/cocos2dx/javascript/AppActivity.java index 6b14791fad..030dd221a9 100755 --- a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/src/org/cocos2dx/javascript/AppActivity.java +++ b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/app/src/org/cocos2dx/javascript/AppActivity.java @@ -26,7 +26,21 @@ package org.cocos2dx.javascript; import org.cocos2dx.lib.Cocos2dxActivity; import org.cocos2dx.lib.Cocos2dxGLSurfaceView; +// For JS and JAVA reflection test, you can delete it if it's your own project +import android.os.Bundle; +import android.app.AlertDialog; +import android.content.DialogInterface; +// ------------------------------------- + public class AppActivity extends Cocos2dxActivity { + + private static AppActivity app = null; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + app = this; + } @Override public Cocos2dxGLSurfaceView onCreateView() { @@ -36,4 +50,18 @@ public class AppActivity extends Cocos2dxActivity { return glSurfaceView; } + + // For JS and JAVA reflection test, you can delete it if it's your own project + public static void showAlertDialog(final String title,final String message) { + // Here be sure to use runOnUiThread + app.runOnUiThread(new Runnable() { + @Override + public void run() { + AlertDialog alertDialog = new AlertDialog.Builder(app).create(); + alertDialog.setTitle(title); + alertDialog.setMessage(message); + alertDialog.show(); + } + }); + } } diff --git a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/build.gradle b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/build.gradle index 9405f3fd18..1b7886d148 100755 --- a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/build.gradle +++ b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/build.gradle @@ -5,7 +5,7 @@ buildscript { jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:1.2.3' + classpath 'com.android.tools.build:gradle:1.3.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files diff --git a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties index 0c71e760dc..e7faee01a4 100755 --- a/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties +++ b/native/templates/js-template-default/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip diff --git a/native/templates/js-template-default/frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java b/native/templates/js-template-default/frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java index 7bc1264c83..21931a86d7 100755 --- a/native/templates/js-template-default/frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java +++ b/native/templates/js-template-default/frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java @@ -29,7 +29,21 @@ package org.cocos2dx.javascript; import org.cocos2dx.lib.Cocos2dxActivity; import org.cocos2dx.lib.Cocos2dxGLSurfaceView; +// For JS and JAVA reflection test, you can delete it if it's your own project +import android.os.Bundle; +import android.app.AlertDialog; +import android.content.DialogInterface; +// ------------------------------------- + public class AppActivity extends Cocos2dxActivity { + + private static AppActivity app = null; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + app = this; + } @Override public Cocos2dxGLSurfaceView onCreateView() { @@ -39,4 +53,18 @@ public class AppActivity extends Cocos2dxActivity { return glSurfaceView; } + + // For JS and JAVA reflection test, you can delete it if it's your own project + public static void showAlertDialog(final String title,final String message) { + // Here be sure to use runOnUiThread + app.runOnUiThread(new Runnable() { + @Override + public void run() { + AlertDialog alertDialog = new AlertDialog.Builder(app).create(); + alertDialog.setTitle(title); + alertDialog.setMessage(message); + alertDialog.show(); + } + }); + } } diff --git a/native/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj b/native/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj index afe9612966..4818c5f85c 100755 --- a/native/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj +++ b/native/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj @@ -14,6 +14,7 @@ 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 */; }; + 294D7D7C1D0D667B002CE7B7 /* CoreText.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 294D7D7B1D0D667B002CE7B7 /* CoreText.framework */; }; 4D697BDA1CBD301C00A5AF29 /* libjs_static.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4D697BD91CBD301C00A5AF29 /* libjs_static.a */; }; 4D697BDE1CBD303100A5AF29 /* libjs_static.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4D697BDC1CBD303100A5AF29 /* libjs_static.a */; }; 502380DC17EBB88200990C9B /* libcurl.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 502380DB17EBB88200990C9B /* libcurl.dylib */; }; @@ -239,6 +240,7 @@ 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 = ""; }; + 294D7D7B1D0D667B002CE7B7 /* CoreText.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreText.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/CoreText.framework; sourceTree = DEVELOPER_DIR; }; 4D697BD91CBD301C00A5AF29 /* libjs_static.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libjs_static.a; path = "../../cocos2d-x/external/ios/libs/libjs_static.a"; sourceTree = ""; }; 4D697BDC1CBD303100A5AF29 /* libjs_static.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libjs_static.a; path = "../../cocos2d-x/external/mac/libs/libjs_static.a"; sourceTree = ""; }; 502380DB17EBB88200990C9B /* libcurl.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libcurl.dylib; path = usr/lib/libcurl.dylib; sourceTree = SDKROOT; }; @@ -327,6 +329,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 294D7D7C1D0D667B002CE7B7 /* CoreText.framework in Frameworks */, FA676C761C71AFA200E091E3 /* libiconv.dylib in Frameworks */, BA3A85EC1A724AE900924D24 /* Security.framework in Frameworks */, BA4E718119EB6E3F00932425 /* MediaPlayer.framework in Frameworks */, @@ -436,6 +439,7 @@ A92275401517C094001B78AA /* Frameworks */ = { isa = PBXGroup; children = ( + 294D7D7B1D0D667B002CE7B7 /* CoreText.framework */, 4D697BDC1CBD303100A5AF29 /* libjs_static.a */, 4D697BD91CBD301C00A5AF29 /* libjs_static.a */, FA676C771C71AFAB00E091E3 /* libiconv.dylib */, diff --git a/native/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Info.plist b/native/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Info.plist index e2340c56e3..9aa4006886 100755 --- a/native/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Info.plist +++ b/native/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/ios/Info.plist @@ -92,5 +92,10 @@ UIInterfaceOrientationLandscapeRight UIInterfaceOrientationLandscapeLeft + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + diff --git a/native/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/mac/Info.plist b/native/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/mac/Info.plist index aa22263424..ada75113cd 100755 --- a/native/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/mac/Info.plist +++ b/native/templates/js-template-default/frameworks/runtime-src/proj.ios_mac/mac/Info.plist @@ -32,5 +32,10 @@ MainMenu NSPrincipalClass NSApplication + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + diff --git a/native/templates/js-template-link/cocos-project-template.json b/native/templates/js-template-link/cocos-project-template.json index 6b6b7fc694..952c81b917 100755 --- a/native/templates/js-template-link/cocos-project-template.json +++ b/native/templates/js-template-link/cocos-project-template.json @@ -26,6 +26,13 @@ "include": [ "*.java" ] + }, + { + "from":"cocos/platform/android/java/libs", + "to":"frameworks/runtime-src/proj.android/libs", + "include": [ + "*.jar" + ] } ], "project_rename":{ @@ -51,6 +58,7 @@ "frameworks/runtime-src/proj.android/build.xml", "frameworks/runtime-src/proj.android/res/values/strings.xml", "frameworks/runtime-src/proj.android-studio/settings.gradle", + "frameworks/runtime-src/proj.android-studio/app/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", diff --git a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml index 59cb2ffb84..447d63d2f3 100755 --- a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml +++ b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/AndroidManifest.xml @@ -10,9 +10,9 @@ android:icon="@mipmap/ic_launcher"> - - + + - - + + - + \ No newline at end of file diff --git a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/jni/Android.mk b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/jni/Android.mk index 26a744cd2c..d53d0b7fdb 100755 --- a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/jni/Android.mk +++ b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/jni/Android.mk @@ -6,10 +6,12 @@ LOCAL_MODULE := cocos2djs_shared LOCAL_MODULE_FILENAME := libcocos2djs +ifeq ($(USE_ARM_MODE),1) +LOCAL_ARM_MODE := arm +endif + LOCAL_SRC_FILES := hellojavascript/main.cpp \ - ../../../Classes/AppDelegate.cpp \ - ../../../Classes/CCScale9Sprite.cpp \ - ../../../Classes/jsb/jsb_creator_auto.cpp + ../../../Classes/AppDelegate.cpp LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../../Classes diff --git a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/project.properties b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/project.properties new file mode 100755 index 0000000000..895c9ce2eb --- /dev/null +++ b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/project.properties @@ -0,0 +1,11 @@ +# 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-16 diff --git a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/src/org/cocos2dx/javascript/AppActivity.java b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/src/org/cocos2dx/javascript/AppActivity.java index 6b14791fad..dc8ab2e42a 100755 --- a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/src/org/cocos2dx/javascript/AppActivity.java +++ b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/app/src/org/cocos2dx/javascript/AppActivity.java @@ -26,7 +26,21 @@ package org.cocos2dx.javascript; import org.cocos2dx.lib.Cocos2dxActivity; import org.cocos2dx.lib.Cocos2dxGLSurfaceView; +// For JS and JAVA reflection test, you can delete it if it's your own project +import android.os.Bundle; +import android.app.AlertDialog; +import android.content.DialogInterface; +// ------------------------------------- + public class AppActivity extends Cocos2dxActivity { + + private static AppActivity app = null; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + app = this; + } @Override public Cocos2dxGLSurfaceView onCreateView() { @@ -36,4 +50,18 @@ public class AppActivity extends Cocos2dxActivity { return glSurfaceView; } + + // For JS and JAVA reflection test, you can delete it if it's your own project + public static void showAlertDialog(final String title,final String message) { + // Here be sure to use runOnUiThread + app.runOnUiThread(new Runnable() { + @Override + public void run() { + AlertDialog alertDialog = new AlertDialog.Builder(app).create(); + alertDialog.setTitle(title); + alertDialog.setMessage(message); + alertDialog.show(); + } + }); + } } diff --git a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/build-cfg.json b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/build-cfg.json index d427ea47b6..5a884a4368 100755 --- a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/build-cfg.json +++ b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/build-cfg.json @@ -1,8 +1,10 @@ { "ndk_module_path" :[ - "../../cocos2d-x", - "../../cocos2d-x/cocos", - "../../cocos2d-x/external" + "${COCOS_X_ROOT}", + "${COCOS_X_ROOT}/cocos", + "${COCOS_X_ROOT}/external", + "${COCOS_X_ROOT}/external/android/include", + "${COCOS_X_ROOT}/external/android/spidermonkey" ], "copy_resources": [ { @@ -18,12 +20,12 @@ "to": "" }, { - "from": "../../../project.json", - "to": "" + "from": "${COCOS_X_ROOT}/cocos/scripting/js-bindings/script", + "to": "script" }, { - "from": "../../cocos2d-x/cocos/scripting/js-bindings/script", - "to": "script" + "from": "../../../project.json", + "to": "" } ] } diff --git a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/build.gradle b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/build.gradle index 9405f3fd18..1b7886d148 100755 --- a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/build.gradle +++ b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/build.gradle @@ -5,7 +5,7 @@ buildscript { jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:1.2.3' + classpath 'com.android.tools.build:gradle:1.3.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files diff --git a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties index 0c71e760dc..e7faee01a4 100755 --- a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties +++ b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip diff --git a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/settings.gradle b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/settings.gradle index 133ec2d702..52bd19dfee 100755 --- a/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/settings.gradle +++ b/native/templates/js-template-link/frameworks/runtime-src/proj.android-studio/settings.gradle @@ -1,4 +1,4 @@ include ':libcocos2dx' -project(':libcocos2dx').projectDir = new File(settingsDir, '../../cocos2d-x/cocos/platform/android/libcocos2dx') +project(':libcocos2dx').projectDir = new File('${COCOS_X_ROOT}/cocos/platform/android/libcocos2dx') include ':HelloJavascript' project(':HelloJavascript').projectDir = new File(settingsDir, 'app') diff --git a/native/templates/js-template-link/frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java b/native/templates/js-template-link/frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java index 7bc1264c83..21931a86d7 100755 --- a/native/templates/js-template-link/frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java +++ b/native/templates/js-template-link/frameworks/runtime-src/proj.android/src/org/cocos2dx/javascript/AppActivity.java @@ -29,7 +29,21 @@ package org.cocos2dx.javascript; import org.cocos2dx.lib.Cocos2dxActivity; import org.cocos2dx.lib.Cocos2dxGLSurfaceView; +// For JS and JAVA reflection test, you can delete it if it's your own project +import android.os.Bundle; +import android.app.AlertDialog; +import android.content.DialogInterface; +// ------------------------------------- + public class AppActivity extends Cocos2dxActivity { + + private static AppActivity app = null; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + app = this; + } @Override public Cocos2dxGLSurfaceView onCreateView() { @@ -39,4 +53,18 @@ public class AppActivity extends Cocos2dxActivity { return glSurfaceView; } + + // For JS and JAVA reflection test, you can delete it if it's your own project + public static void showAlertDialog(final String title,final String message) { + // Here be sure to use runOnUiThread + app.runOnUiThread(new Runnable() { + @Override + public void run() { + AlertDialog alertDialog = new AlertDialog.Builder(app).create(); + alertDialog.setTitle(title); + alertDialog.setMessage(message); + alertDialog.show(); + } + }); + } } diff --git a/native/templates/js-template-link/frameworks/runtime-src/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj b/native/templates/js-template-link/frameworks/runtime-src/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj index d733c93f0c..d601df8130 100755 --- a/native/templates/js-template-link/frameworks/runtime-src/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj +++ b/native/templates/js-template-link/frameworks/runtime-src/proj.ios_mac/HelloJavascript.xcodeproj/project.pbxproj @@ -12,6 +12,7 @@ 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 */; }; + 294D7D801D0D668F002CE7B7 /* CoreText.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 294D7D7F1D0D668F002CE7B7 /* CoreText.framework */; }; 4D697BDA1CBD301C00A5AF29 /* libjs_static.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4D697BD91CBD301C00A5AF29 /* libjs_static.a */; }; 4D697BDE1CBD303100A5AF29 /* libjs_static.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4D697BDC1CBD303100A5AF29 /* libjs_static.a */; }; 4DD5E6AB1CDAF6430046171E /* libcocos2d Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4DD0DB561CDAF5F40099AD86 /* libcocos2d Mac.a */; }; @@ -141,6 +142,7 @@ 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 = "/Applications/CocosCreator.app/Contents/Resources/cocos2d-x/build/cocos2d_libs.xcodeproj"; sourceTree = ""; }; + 294D7D7F1D0D668F002CE7B7 /* CoreText.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreText.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/CoreText.framework; sourceTree = DEVELOPER_DIR; }; 4D697BD91CBD301C00A5AF29 /* libjs_static.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libjs_static.a; path = "/Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/ios/libs/libjs_static.a"; sourceTree = ""; }; 4D697BDC1CBD303100A5AF29 /* libjs_static.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libjs_static.a; path = "/Applications/CocosCreator.app/Contents/Resources/cocos2d-x/external/mac/libs/libjs_static.a"; sourceTree = ""; }; 502380DB17EBB88200990C9B /* libcurl.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libcurl.dylib; path = usr/lib/libcurl.dylib; sourceTree = SDKROOT; }; @@ -229,6 +231,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 294D7D801D0D668F002CE7B7 /* CoreText.framework in Frameworks */, 4DD5E6B21CDAF6600046171E /* libjscocos2d iOS.a in Frameworks */, 4DD5E6B11CDAF65C0046171E /* libcocos2d iOS.a in Frameworks */, FA676C761C71AFA200E091E3 /* libiconv.dylib in Frameworks */, @@ -339,6 +342,7 @@ A92275401517C094001B78AA /* Frameworks */ = { isa = PBXGroup; children = ( + 294D7D7F1D0D668F002CE7B7 /* CoreText.framework */, 4D697BDC1CBD303100A5AF29 /* libjs_static.a */, 4D697BD91CBD301C00A5AF29 /* libjs_static.a */, FA676C771C71AFAB00E091E3 /* libiconv.dylib */, diff --git a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/Info.plist b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/Info.plist index 70c8595a30..8cf49c5928 100755 --- a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/Info.plist +++ b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/Info.plist @@ -56,5 +56,10 @@ MainMenu NSPrincipalClass NSApplication + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + diff --git a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.mm b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.mm index 38c279be40..87e414fa65 100755 --- a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.mm +++ b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.mm @@ -383,7 +383,7 @@ static void glfwDropFunc(GLFWwindow *window, int count, const char **files) const cocos2d::Rect frameRect = cocos2d::Rect(0, 0, frameSize.width, frameSize.height); std::stringstream title; title << "Cocos Simulator (" << _project.getFrameScale() * 100 << "%)"; - GLViewImpl *eglView = GLViewImpl::createWithRect(title.str(), frameRect, frameScale); + GLViewImpl *eglView = GLViewImpl::createWithRect(title.str(), frameRect, frameScale, true); auto director = Director::getInstance(); director->setOpenGLView(eglView); diff --git a/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorWin.cpp b/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorWin.cpp index adc0d77bd6..5794158f49 100755 --- a/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorWin.cpp +++ b/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorWin.cpp @@ -380,7 +380,7 @@ int SimulatorWin::run() std::stringstream title; title << "Cocos Simulator (" << _project.getFrameScale() * 100 << "%)"; initGLContextAttrs(); - auto glview = GLViewImpl::createWithRect(title.str(), frameRect, frameScale); + auto glview = GLViewImpl::createWithRect(title.str(), frameRect, frameScale, true); _hwnd = glview->getWin32Window(); player::PlayerWin::createWithHwnd(_hwnd); DragAcceptFiles(_hwnd, TRUE); diff --git a/native/tools/simulator/libsimulator/lib/platform/win32/SimulatorWin.cpp b/native/tools/simulator/libsimulator/lib/platform/win32/SimulatorWin.cpp index 0734e58527..3a7adbd02d 100755 --- a/native/tools/simulator/libsimulator/lib/platform/win32/SimulatorWin.cpp +++ b/native/tools/simulator/libsimulator/lib/platform/win32/SimulatorWin.cpp @@ -323,7 +323,7 @@ int SimulatorWin::run() std::stringstream title; title << "Cocos Simulator - " << ConfigParser::getInstance()->getInitViewName(); initGLContextAttrs(); - auto glview = GLViewImpl::createWithRect(title.str(), frameRect, frameScale); + auto glview = GLViewImpl::createWithRect(title.str(), frameRect, frameScale, true); _hwnd = glview->getWin32Window(); DragAcceptFiles(_hwnd, TRUE); //SendMessage(_hwnd, WM_SETICON, ICON_BIG, (LPARAM)icon); diff --git a/native/tools/tojs/creator.ini b/native/tools/tojs/creator.ini index 74f6596ab5..d57a7a029e 100755 --- a/native/tools/tojs/creator.ini +++ b/native/tools/tojs/creator.ini @@ -26,15 +26,15 @@ cxxgenerator_headers = extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s # what headers to parse -headers = %(creatordir)s/CCScale9Sprite.h +headers = %(creatordir)s/CCScale9Sprite.h %(creatordir)s/CCGraphicsNode.h -replace_headers = CCScale9Sprite.h::creator/CCScale9Sprite.h +replace_headers = CCScale9Sprite.h::creator/CCScale9Sprite.h,CCGraphicsNode.h::creator/CCGraphicsNode.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 = Scale9SpriteV2 +classes = Scale9SpriteV2 GraphicsNode -classes_need_extend = Scale9SpriteV2 +classes_need_extend = Scale9SpriteV2 GraphicsNode # 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