Merge branch 'develop' of github.com:nantas/cocos2d-x-lite into develop

This commit is contained in:
Nan Wang
2016-07-05 14:40:20 +08:00
92 changed files with 5427 additions and 384 deletions
-1
View File
@@ -51,7 +51,6 @@ BundleArtifacts
.vs/
# Ignore files build by ndk and eclipse
libs/
bin/
obj/
gen/
+1 -1
View File
@@ -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=
@@ -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 = "<group>"; };
29394CEE19B01DBA00D2DE1A /* UIWebViewImpl-ios.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIWebViewImpl-ios.h"; sourceTree = "<group>"; };
29394CEF19B01DBA00D2DE1A /* UIWebViewImpl-ios.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = "UIWebViewImpl-ios.mm"; sourceTree = "<group>"; };
294D7D981D0E93A2002CE7B7 /* CCDevice-apple.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "CCDevice-apple.h"; sourceTree = "<group>"; };
294D7D991D0E93A2002CE7B7 /* CCDevice-apple.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = "CCDevice-apple.mm"; sourceTree = "<group>"; };
2958244919873D8E00F9746D /* UIScale9Sprite.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = UIScale9Sprite.cpp; sourceTree = "<group>"; };
2958244A19873D8E00F9746D /* UIScale9Sprite.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UIScale9Sprite.h; sourceTree = "<group>"; };
2980F0171BA9A5550059E678 /* CCUIEditBoxIOS.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCUIEditBoxIOS.h; sourceTree = "<group>"; };
@@ -1834,6 +1848,10 @@
46A168631807AF4E005B8026 /* CCTableView.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CCTableView.h; sourceTree = "<group>"; };
46A168641807AF4E005B8026 /* CCTableViewCell.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = CCTableViewCell.cpp; sourceTree = "<group>"; };
46A168651807AF4E005B8026 /* CCTableViewCell.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CCTableViewCell.h; sourceTree = "<group>"; };
4D2E69031CC543B40032DD5C /* CCGraphicsNode.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCGraphicsNode.cpp; path = creator/CCGraphicsNode.cpp; sourceTree = "<group>"; };
4D2E69041CC543B40032DD5C /* CCGraphicsNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCGraphicsNode.h; path = creator/CCGraphicsNode.h; sourceTree = "<group>"; };
4D2E69051CC543B40032DD5C /* Triangulate.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = Triangulate.cpp; path = creator/Triangulate.cpp; sourceTree = "<group>"; };
4D2E69061CC543B40032DD5C /* Triangulate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Triangulate.h; path = creator/Triangulate.h; sourceTree = "<group>"; };
4D76BE381A4AAF0A00102962 /* CCActionTimelineNode.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCActionTimelineNode.cpp; sourceTree = "<group>"; };
4D76BE391A4AAF0A00102962 /* CCActionTimelineNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCActionTimelineNode.h; sourceTree = "<group>"; };
4DFA4C151CBCE34100E3B736 /* CCScale9Sprite.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCScale9Sprite.cpp; path = creator/CCScale9Sprite.cpp; sourceTree = "<group>"; };
@@ -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 */,
+19 -4
View File
@@ -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("<Action | Tag = %d", _tag);
@@ -271,6 +281,12 @@ void Follow::step(float dt)
{
CC_UNUSED_PARAM(dt);
Vec2 targetWorldPos = _target->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
+4
View File
@@ -183,6 +183,10 @@ protected:
#endif
private:
CC_DISALLOW_COPY_AND_ASSIGN(Action);
protected:
void sendUpdateEventToScript(float dt, Action *actionObject);
};
/** @class FiniteTimeAction
+7 -10
View File
@@ -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);
+2
View File
@@ -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();
+21 -4
View File
@@ -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::function<int(const std::u16string&, int, int)
bool Label::multilineTextWrapByWord()
{
return multilineTextWrap(std::bind(getFirstWordLen, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
return multilineTextWrap(std::bind(CC_CALLBACK_3(Label::getFirstWordLen, this), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
}
bool Label::multilineTextWrapByChar()
{
return multilineTextWrap(std::bind(getFirstCharLen, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
return multilineTextWrap(std::bind(CC_CALLBACK_3(Label::getFirstCharLen, this) , std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
}
bool Label::isVerticalClamp()
+45
View File
@@ -436,6 +436,12 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts)
}
CCASSERT( compression == "" || compression == "gzip" || compression == "zlib", "TMX: unsupported compression method" );
}
else if (encoding == "csv")
{
int layerAttribs = tmxMapInfo->getLayerAttribs();
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<string> 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<uint32_t*>(buffer);
for(auto gidToken : gidTokens) {
auto tileGid = (uint32_t)strtol(gidToken.c_str(), nullptr, 10);
*bufferPtr = tileGid;
bufferPtr++;
}
layer->_tiles = reinterpret_cast<uint32_t*>(buffer);
tmxMapInfo->setCurrentString("");
}
else if (tmxMapInfo->getLayerAttribs() & TMXLayerAttribNone)
{
_xmlTileIndex = 0;
+1
View File
@@ -62,6 +62,7 @@ enum {
TMXLayerAttribBase64 = 1 << 1,
TMXLayerAttribGzip = 1 << 2,
TMXLayerAttribZlib = 1 << 3,
TMXLayerAttribCSV = 1 << 4,
};
enum {
+6 -1
View File
@@ -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;
};
/**
@@ -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)/..
File diff suppressed because it is too large Load Diff
+23
View File
@@ -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);
}
);
@@ -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<Path*> _paths;
Path* _curPath;
// verts
int _nVerts;
int _vertsOffset;
VecVertex* _verts;
// indices
int _nIndices;
int _indicesOffset;
GLushort* _indices;
};
}
#endif /* defined(__CREATOR_CCGRAPHICSNODE_H__) */
+18
View File
@@ -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;
}
);
@@ -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;
@@ -0,0 +1,139 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#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<n; p=q++) {
A+= contour[p].x*contour[q].y - contour[q].x*contour[p].y;
}
return A*0.5f;
}
/*
InsideTriangle decides if a point P is Inside of the triangle
defined by A, B, C.
*/
bool Triangulate::insideTriangle(float Ax, float Ay,
float Bx, float By,
float Cx, float Cy,
float Px, float Py)
{
float ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy;
float cCROSSap, bCROSScp, aCROSSbp;
ax = Cx - Bx; ay = Cy - By;
bx = Ax - Cx; by = Ay - Cy;
cx = Bx - Ax; cy = By - Ay;
apx= Px - Ax; apy= Py - Ay;
bpx= Px - Bx; bpy= Py - By;
cpx= Px - Cx; cpy= Py - Cy;
aCROSSbp = ax*bpy - ay*bpx;
cCROSSap = cx*apy - cy*apx;
bCROSScp = bx*cpy - by*cpx;
return ((aCROSSbp >= 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<int> &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; v<n; v++) V[v] = v;
else
for(int v=0; v<n; v++) V[v] = (n-1)-v;
int nv = n;
/* remove nv-2 Vertices, creating 1 triangle every time */
int count = 2*nv; /* error detection */
for(int m=0, v=nv-1; nv>2; )
{
/* 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, <u,v,w> */
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<nv;s++,t++) V[s] = V[t]; nv--;
/* resest error detection counter */
count = 2*nv;
}
}
delete []V;
return true;
}
@@ -0,0 +1,69 @@
// COTD Entry submitted by John W. Ratcliff [jratcliff@verant.com]
// ** THIS IS A CODE SNIPPET WHICH WILL EFFICIEINTLY TRIANGULATE ANY
// ** POLYGON/CONTOUR (without holes) AS A STATIC CLASS. THIS SNIPPET
// ** IS COMPRISED OF 3 FILES, TRIANGULATE.H, THE HEADER FILE FOR THE
// ** TRIANGULATE BASE CLASS, TRIANGULATE.CPP, THE IMPLEMENTATION OF
// ** THE TRIANGULATE BASE CLASS, AND TEST.CPP, A SMALL TEST PROGRAM
// ** DEMONSTRATING THE USAGE OF THE TRIANGULATOR. THE TRIANGULATE
// ** BASE CLASS ALSO PROVIDES TWO USEFUL HELPER METHODS, ONE WHICH
// ** COMPUTES THE AREA OF A POLYGON, AND ANOTHER WHICH DOES AN EFFICENT
// ** POINT IN A TRIANGLE TEST.
// ** SUBMITTED BY JOHN W. RATCLIFF (jratcliff@verant.com) July 22, 2000
/**********************************************************************/
/************ HEADER FILE FOR TRIANGULATE.H ***************************/
/**********************************************************************/
#ifndef TRIANGULATE_H
#define TRIANGULATE_H
/*****************************************************************/
/** Static class to triangulate any contour/polygon efficiently **/
/** You should replace Vector2d with whatever your own Vector **/
/** class might be. Does not support polygons with holes. **/
/** Uses STL vectors to represent a dynamic array of vertices. **/
/** This code snippet was submitted to FlipCode.com by **/
/** John W. Ratcliff (jratcliff@verant.com) on July 22, 2000 **/
/** I did not write the original code/algorithm for this **/
/** this triangulator, in fact, I can't even remember where I **/
/** found it in the first place. However, I did rework it into **/
/** the following black-box static class so you can make easy **/
/** use of it in your own code. Simply replace Vector2d with **/
/** whatever your own Vector implementation might be. **/
/*****************************************************************/
#include <vector> // 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<int> &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
@@ -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;
}
@@ -12,4 +12,4 @@
android.library=true
# Project target.
target=android-10
target=android-19
@@ -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);
@@ -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;
@@ -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<Runnable> _taskQueue = new LinkedList<Runnable>();
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<Header> list = new ArrayList<Header>();
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);
}
@@ -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;
}
@@ -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();
}
}
}
@@ -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);
}
@@ -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 */
@@ -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;
}
}
@@ -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)
+246 -134
View File
@@ -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<CoreMotion/CoreMotion.h>
#import<CoreFoundation/CoreFoundation.h>
#import <CoreText/CoreText.h>
// Vibrate
#import <AudioToolbox/AudioToolbox.h>
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<UIAccelerometerDelegate>
@@ -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<int>(POTWide);
info->height = static_cast<int>(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;
}
+196 -78
View File
@@ -31,16 +31,37 @@ THE SOFTWARE.
#include <Cocoa/Cocoa.h>
#include <string>
#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;
}
+3 -1
View File
@@ -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);
}
+1 -1
View File
@@ -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.
@@ -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;
@@ -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 (
)
{
},
};
@@ -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;
}
@@ -1,6 +1,7 @@
#include "jsb_creator_auto.hpp"
#include "cocos2d_specifics.hpp"
#include "creator/CCScale9Sprite.h"
#include "creator/CCGraphicsNode.h"
template<class T>
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<creator::Scale9SpriteV2>(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<creator::GraphicsNode>(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<creator::GraphicsNode> 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<creator::GraphicsNode *>(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<creator::GraphicsNode>(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);
}
@@ -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__
@@ -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)
@@ -83,6 +83,7 @@ private:
mozilla::Maybe<JS::PersistentRootedObject> _global;
mozilla::Maybe<JS::PersistentRootedObject> _debugGlobal;
SimpleRunLoop* _runLoop;
bool _needCleanup;
bool _callFromScript;
std::unordered_map<cocos2d::Ref*, int> _jsRetainRefMap;
@@ -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);
@@ -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");
@@ -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;
@@ -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 <android/log.h>
#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);
}
@@ -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 <jni.h>
#include <string>
#include <vector>
#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<ValueType> 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
@@ -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 \
@@ -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.
*/
@@ -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) {
@@ -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;
}
+1 -1
View File
@@ -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)
+6 -1
View File
@@ -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
};
/**
@@ -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
@@ -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)
@@ -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
{
@@ -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;
@@ -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;
}
+1 -1
View File
@@ -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/"
}
+37 -18
View File
@@ -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);
}
}
});
+1
View File
@@ -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",
+15
View File
@@ -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",
@@ -61,6 +61,13 @@
"include": [
"*.java"
]
},
{
"from":"cocos/platform/android/java/libs",
"to":"frameworks/runtime-src/proj.android/libs",
"include": [
"*.jar"
]
}
],
"project_rename":{
@@ -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();
}
});
}
}
@@ -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 = "<group>"; };
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 = "<absolute>"; };
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 = "<absolute>"; };
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 = "<group>"; };
@@ -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 */,
@@ -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",
@@ -10,9 +10,9 @@
android:icon="@mipmap/ic_launcher">
<!-- Tell Cocos2dxActivity the name of our .so -->
<meta-data android:name="android.app.lib_name"
android:value="cocos2djs" />
<meta-data android:name="android.app.lib_name"
android:value="cocos2djs" />
<activity
android:name="org.cocos2dx.javascript.AppActivity"
android:screenOrientation="landscape"
@@ -33,7 +33,7 @@
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
</manifest>
@@ -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
@@ -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
@@ -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();
}
});
}
}
@@ -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
@@ -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
@@ -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();
}
});
}
}
@@ -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 = "<group>"; };
1AC6FB34180E9ACB004C840B /* cocos2d_libs.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = cocos2d_libs.xcodeproj; path = "../../cocos2d-x/build/cocos2d_libs.xcodeproj"; sourceTree = "<group>"; };
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 = "<group>"; };
4D697BDC1CBD303100A5AF29 /* libjs_static.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libjs_static.a; path = "../../cocos2d-x/external/mac/libs/libjs_static.a"; sourceTree = "<group>"; };
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 */,
@@ -92,5 +92,10 @@
<string>UIInterfaceOrientationLandscapeRight</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
</array>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
</dict>
</plist>
@@ -32,5 +32,10 @@
<string>MainMenu</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
</dict>
</plist>
@@ -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",
@@ -10,9 +10,9 @@
android:icon="@mipmap/ic_launcher">
<!-- Tell Cocos2dxActivity the name of our .so -->
<meta-data android:name="android.app.lib_name"
android:value="cocos2djs" />
<meta-data android:name="android.app.lib_name"
android:value="cocos2djs" />
<activity
android:name="org.cocos2dx.javascript.AppActivity"
android:screenOrientation="landscape"
@@ -33,7 +33,7 @@
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
</manifest>
@@ -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
@@ -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
@@ -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();
}
});
}
}
@@ -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": ""
}
]
}
@@ -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
@@ -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
@@ -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')
@@ -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();
}
});
}
}
@@ -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 = "<group>"; };
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 = "<absolute>"; };
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 = "<absolute>"; };
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 = "<absolute>"; };
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 */,
@@ -56,5 +56,10 @@
<string>MainMenu</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
</dict>
</plist>
@@ -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);
@@ -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);
@@ -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);
+4 -4
View File
@@ -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