初始化

This commit is contained in:
SmallMain
2022-06-25 00:23:03 +08:00
commit ef0589e8e5
2264 changed files with 617829 additions and 0 deletions

View File

@@ -0,0 +1,8 @@
.DS_Store
gen/
*.pyc
test/user.cfg
test/userconf.ini
test/simple_test_bindings/
.idea
.swp

View File

@@ -0,0 +1,37 @@
Core Developers:
Rolando Abarca (funkaster)
The original author of repo
Surith Thekkiam (folecr)
James Chen (dumganhar)
The main maintainer
samuele3hu
Added lua target support
Dhilan007
pandamicro
Developers:
rohankuruvillak
The maintainer of this repo
carlomorgantinizynga
new manual conversion for type ccFontDefinition
jdmunro
Fixed an issue where cocos2d-x specific functionality was not appropriately wrapped with an #ifdef in binding code generated for default class constructors.
led42
Fixed native objects were left allocated with no references by the finalise routine
colesbury
Generated conversion from JS functions to std::function
lihex
Better support for Windows
dplusic
Fixed incorrect regular expression for std::function return type

View File

@@ -0,0 +1,168 @@
# What's new
* Add a prebuilt libclang 5.0 in `libclang/`for mac, linux and windows.
* If you want use the prebuilt licbclang 5.0 work with Android NDK, then `only the NDK r16 (or higher version) can work corrently` with it.
# Requirements
* python2.7
* py-yaml
* cheetah (for target language templates)
* libclang binary files
# Usage
Usage: generator.py [options] {configfile}
Options:
-h, --help show this help message and exit
-s SECTION sets a specific section to be converted
-t TARGET specifies the target vm. Will search for TARGET.yaml
Basically, you specify a target vm (spidermonkey is the only current target vm) and the section from
the `.ini` file you want to generate code for.
### Download libclang binary files
* Go to website [http://releases.llvm.org/download.html#5.0.0](http://releases.llvm.org/download.html#5.0.0)
* Download `Pre-Built Binaries` according your platforms
* Unzip or install binaries. For example, unzip `clang+llvm-5.0.0-x86_64-apple-darwin.tar.xz` for macOS.
* Find libclang.dll (windows) or libclang.dylib (macOS)
* Copy the dynamic library to `bindings-generator/libclang` folder.
## Run the simple test with prebuilt libclang 5.0
Included in this repository is a simple test. Use this to confirm the generator is working and that your environment is set up correctly.
#### NOTE
* The test uses the prebuilt 5.0 libclang, so you should use `Android NDK r16` or higher version.
* The test uses <string> and <stdint.h> so you need a C++ implementation that provides these
* Currently, the test script is setup to use the Android NDK's llvm libc++
### Mac OS X
* The OSX 10.9 has a built-in python2.7 and if your os don't have python2.7 then use [Homebrew](http://brew.sh/) to install the python and use pip install the python dependencies.
<pre>
brew install python
</pre>
* Install python dependices by pip.
<pre>
sudo easy_install pip
sudo pip install PyYAML
sudo pip install Cheetah
</pre>
* Download [NDK r16](https://dl.google.com/android/repository/android-ndk-r16-darwin-x86_64.zip) from [google](https://developer.android.com/ndk/downloads/index.html)
* If you are using python installed from other way, copy user.cfg.sample and rename it as `user.cfg` then set the absolute path to python `PYTHON_BIN` in `user.cfg`
* Run follow command, it will generate a `userconf.ini`, and check the values in it if it occorus any error.
<pre>
export NDK_ROOT=/path/to/android-ndk-r16
./test.sh
</pre>
### Ubuntu Linux 12.04 64bit
* Install python
<pre>
sudo apt-get install python2.7
</pre>
* Install python dependices by pip.
<pre>
sudo apt-get install python-pip
sudo pip install PyYAML
sudo pip install Cheetah
</pre>
* Download [NDK r16](https://dl.google.com/android/repository/android-ndk-r16-linux-x86_64.zip) from [google](https://developer.android.com/ndk/downloads/index.html)
* If you are using python installed from other way, copy user.cfg.sample and rename it as `user.cfg` then set the absolute path to python `PYTHON_BIN` in `user.cfg`
* Run follow command, it will generate a `userconf.ini`, and check the values in it if it occorus any error.
<pre>
export NDK_ROOT=/path/to/android-ndk-r16
./test.sh
</pre>
### Windows 7 64bit
* Download python2.7.3 (`32bit`) from (http://www.python.org/ftp/python/2.7.3/python-2.7.3.msi).
* Add the installed path of python (e.g. C:\Python27) to windows environment variable named 'PATH'.
* Download pyyaml from http://pyyaml.org/download/pyyaml/PyYAML-3.10.win32-py2.7.exe and install it.
* Download [Cheetah-2.4.4.tar.gz](https://pypi.python.org/packages/cd/b0/c2d700252fc251e91c08639ff41a8a5203b627f4e0a2ae18a6b662ab32ea/Cheetah-2.4.4.tar.gz#md5=853917116e731afbc8c8a43c37e6ddba), extract and install it by `python setup.py`.
* Download [NDK r16](https://dl.google.com/android/repository/android-ndk-r16-windows-x86_64.zip) from [google](https://developer.android.com/ndk/downloads/index.html)
* Set the environment variables (`PYTHON_ROOT` and `NDK_ROOT`) or just them in `test.bat`.
* Run "test.bat". The generated codes will be under "simple_test_bindings".
### Expected output
Upon running the test you might see some warnings but should not see any errors.
The test will create a directory named simple_test_bindings that contains 3 files
* A .hpp header file for the bindings class
* A .cpp file implementing the bindings class
* A .js file that documents how to call (from JavaScript) the methods the C++ class exposes
# The `.ini` file
The `.ini` file is a simple text file specifying the settings for the code generator. Here's the
default one, used for cocos2d-x
[cocos2d-x]
prefix = cocos2dx
events = CCNode#onEnter CCNode#onExit
extra_arguments = -I../../cocos2dx/include -I../../cocos2dx/platform -I../../cocos2dx/platform/ios -I../../cocos2dx -I../../cocos2dx/kazmath/include -arch i386 -DTARGET_OS_IPHONE -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.1.sdk -x c++
headers = ../../cocos2dx/include/cocos2d.h
classes = CCSprite
functions = my_free_function
## Required sections
* prefix: the prefix for the project. Must be a valid identifier for the language of the target vm.
Most of the time, the name will be intermixed between the class name and the function name, since
all generated (probably) will be free functions, we do that in order to avoid name collition. The
script will generate ${prefix}.cpp and ${prefix}.hpp as a result.
* events: a list of identifiers in the form of ClassName#functionName that are events to be called
from the native world to the target vm.
* extra_arguments: extra arguments to pass to the clang interface. Basically you can think of this
as the arguments to pass to the "compiler", so add as many as you need here. If you're targetting
C++, make sure you add "-x c++" as the last argument to force C++ mode on a ".h" file. Otherwise,
name your header files as ".hpp".
* headers: list of headers to parse. Usually you add a single header that in turn `#include`s the
rest of the files.
* classes: the classes that will be parsed. Right not is just a string, but it will accept regular
expressions
* functions: space-separated list of free functions to be binded. Same as with classes, it will
support regular expressions.
* skip: a space-separated list of `Classes::functions` or just `functions` to not generate any code.
# The templates
The generator is using [Cheetah templates](http://www.cheetahtemplate.org/) to create a more
flexible generator. The way it was thought, is that for every target environment, you should provide
with a way to generate the same C/C++ functionality. Every template has access to the proper meta
information for the code or generator (function, classes, etc.)
Right now it's separated in the following set of templates:
* prelude.c/.h: The header of the generated files.
* ifunction.c/.h: The template for an instance function
* ifunction_overloaded.c: The template for the implementation of an overloaded function. An
overloaded function is exactly the same as a function, but it has an array of functions sharing
the same name. The current implementation for spidermonkey only works if the overloading is with
different number of arguments.
* sfunction.c/.h: The template for a static function
* sfunction_overloaded.c: The template for an overloaded static function
* register.c: Here you should add the constructor/finalizer, the registration function (if needed)
and the footer of the header file. This is the last chunk being generated
Templates are stored in the `templates/${target}` directory and follow the naming specified above.
One final part of the puzzle is the `${target}.yaml` file, that contains specific type conversion
snippets to be used by the templates. For instance, for spidermonkey, this is the place where we
specify the conversion routines for the native types (to and from int, float, string, etc.)
# Limitations
Currently the generator is leveraging clang in order to get information about the C/C++ code, so we
can only get as much information as clang give us. Known list of things that won't work:
* variable number of arguments. Solution: write a manual wrapper

View File

@@ -0,0 +1,24 @@
#===- __init__.py - Clang Python Bindings --------------------*- python -*--===#
#
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
#===------------------------------------------------------------------------===#
r"""
Clang Library Bindings
======================
This package provides access to the Clang compiler and libraries.
The available modules are:
cindex
Bindings for the Clang indexing library.
"""
__all__ = ['cindex']

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,34 @@
#===- enumerations.py - Python Enumerations ------------------*- python -*--===#
#
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
#===------------------------------------------------------------------------===#
"""
Clang Enumerations
==================
This module provides static definitions of enumerations that exist in libclang.
Enumerations are typically defined as a list of tuples. The exported values are
typically munged into other types or classes at module load time.
All enumerations are centrally defined in this file so they are all grouped
together and easier to audit. And, maybe even one day this file will be
automatically generated by scanning the libclang headers!
"""
# Maps to CXTokenKind. Note that libclang maintains a separate set of token
# enumerations from the C++ API.
TokenKinds = [
('PUNCTUATION', 0),
('KEYWORD', 1),
('IDENTIFIER', 2),
('LITERAL', 3),
('COMMENT', 4),
]
__all__ = ['TokenKinds']

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1 @@
libclang in LLVM 5.0.0

View File

@@ -0,0 +1,192 @@
definitions:
# the names of the functions - we use this to generate the code and to register the functions in
# the javascript class
ifunction: "js_${generator.prefix}_${class_name}_${func_name}"
sfunction: "js_${generator.prefix}_${class_name}_${func_name}"
constructor: "js_${generator.prefix}_${class_name}_constructor"
ctor: "js_${generator.prefix}_${class_name}_ctor"
public_field: "js_${generator.prefix}_${class_name}"
conversions:
# some times you want to use a special native type when converting from spidermonkey to native
# the most common case would be from JS-boolean to bool. Using "bool" will fail here since we
# pass the address to the conversion method, and a JSBool is defined as an integer in spidermonkey
native_types:
# float: "double"
short: "int16_t"
"unsigned char": "uint8_t"
"char": "int8_t"
ns_map:
"cocos2d::extension::": "cc."
"cocos2d::ui::": "ccui."
"cocos2d::": "cc."
"spine::": "sp."
"cocostudio::": "ccs."
"cocosbuilder::": "cc."
"CocosDenshion::": "cc."
to_native:
# jsval to int
int32_t: "ok &= seval_to_int32(${in_value}, (int32_t*)&${out_value})"
# int: "ok &= seval_to_int32(${in_value}, (int32_t*)&${out_value})"
int: "do { int32_t tmp = 0; ok &= seval_to_int32(${in_value}, &tmp); ${out_value} = (${arg_type})tmp; } while(false)"
"unsigned int": "ok &= seval_to_uint32(${in_value}, (uint32_t*)&${out_value})"
"unsigned char": "ok &= seval_to_uint8(${in_value}, (uint8_t*)&${out_value})"
short: "ok &= seval_to_int16(${in_value}, &${out_value})"
"unsigned short": "ok &= seval_to_uint16(${in_value}, &${out_value})"
char: "ok &= seval_to_int8(${in_value}, (int8_t*)&${out_value})"
bool: "ok &= seval_to_boolean(${in_value}, &${out_value})"
float: "ok &= seval_to_float(${in_value}, &${out_value})"
double: "ok &= seval_to_double(${in_value}, &${out_value})"
long: "ok &= seval_to_long(${in_value}, &${out_value})"
"unsigned long": "ok &= seval_to_ulong(${in_value}, &${out_value})"
"ssize_t": "ok &= seval_to_ssize(${in_value}, &${out_value})"
"size_t": "ok &= seval_to_size(${in_value}, &${out_value})"
# jsval has to be a TypedArray, a UInt32Array with 2 elements
"long long": "ok &= seval_to_longlong(${in_value}, &${out_value})"
"string": "ok &= seval_to_std_string(${in_value}, &${out_value})"
"char*": "std::string ${out_value}_tmp; ok &= seval_to_std_string(${in_value}, &${out_value}_tmp); ${out_value} = ${out_value}_tmp.c_str()"
"Point": "ok &= seval_to_Vec2(${in_value}, &${out_value})"
"Rect": "ok &= seval_to_Rect(${in_value}, &${out_value})"
"Size": "ok &= seval_to_Size(${in_value}, &${out_value})"
"Color4B": "ok &= seval_to_Color4B(${in_value}, &${out_value})"
"Color4F": "ok &= seval_to_Color4F(${in_value}, &${out_value})"
"Color3B": "ok &= seval_to_Color3B(${in_value}, &${out_value})"
"Color3F": "ok &= seval_to_Color3F(${in_value}, &${out_value})"
# "Array*": "ok &= seval_to_ccarray(${in_value}, &${out_value})"
# "Dictionary*": "ok &= seval_to_ccdictionary(${in_value}, &${out_value})"
"AffineTransform": "ok &= seval_to_AffineTransform(${in_value}, &${out_value})"
"FontDefinition": "ok &= seval_to_FontDefinition(${in_value}, &${out_value})"
"String*": "std::string ${out_value}_tmp; ok &= seval_to_std_string(${in_value}, &${out_value}_tmp); ${out_value} = cocos2d::String::create(${out_value}_tmp)"
"@Vector<.*>": "ok &= seval_to_Vector(${in_value}, &${out_value})"
"@Map<std::string.*>": "ok &= seval_to_Map_string_key(${in_value}, &${out_value})"
"@map<std::string.*,\\s*std::string.*>": "ok &= seval_to_std_map_string_string(${in_value}, &${out_value})"
"Value": "ok &= seval_to_ccvalue(${in_value}, &${out_value})"
"ValueMap": "ok &= seval_to_ccvaluemap(${in_value}, &${out_value})"
"ValueMapIntKey": "ok &= seval_to_ccvaluemapintkey(${in_value}, &${out_value})"
"ValueVector": "ok &= seval_to_ccvaluevector(${in_value}, &${out_value})"
"@vector<std::string.*>": "ok &= seval_to_std_vector_string(${in_value}, &${out_value})"
"@vector<int.*>": "ok &= seval_to_std_vector_int(${in_value}, &${out_value})"
"@vector<float.*>": "ok &= seval_to_std_vector_float(${in_value}, &${out_value})"
"@vector<.*Texture.*>": "ok &= seval_to_std_vector_Texture(${in_value}, &${out_value})"
"@vector<.*RenderTarget.*>": "ok &= seval_to_std_vector_RenderTarget(${in_value}, &${out_value})"
"vector<std::unordered_map<std::string, cocos2d::Value>>": "ok &= seval_to_EffectDefineTemplate(${in_value}, &${out_value})"
"unordered_map<std::string, cocos2d::renderer::Technique::Parameter>": "ok &= seval_to_EffectProperty(${in_value}, &${out_value})"
"Acceleration": "ok &= seval_to_Acceleration(${in_value}, &${out_value})"
"Parameter": "ok &= seval_to_TechniqueParameter(${in_value}, &${out_value})"
"vector<cocos2d::renderer::Technique::Parameter>": "ok &= seval_to_std_vector_TechniqueParameter(${in_value}, &${out_value})"
"vector<cocos2d::renderer::ProgramLib::Template>": "ok &= seval_to_std_vector_ProgramLib_Template(${in_value}, &${out_value})"
"Mat4": "ok &= seval_to_Mat4(${in_value}, &${out_value})"
"Vec2": "ok &= seval_to_Vec2(${in_value}, &${out_value})"
"Vec3": "ok &= seval_to_Vec3(${in_value}, &${out_value})"
"Vec2*": "std::vector<cocos2d::Vec2> tempData;ok &= seval_to_std_vector_Vec2(${in_value}, &tempData);${out_value}=tempData.data()"
"BlendFunc": "ok &= seval_to_blendfunc(${in_value}, &${out_value})"
"_ttfConfig": "ok &= seval_to_TTFConfig(${in_value}, &${out_value})"
"TTFConfig": "ok &= seval_to_TTFConfig(${in_value}, &${out_value})"
# "AnimationInfo": "ok &= seval_to_animationInfo(${in_value}, &${out_value})"
"Quaternion": "ok &= seval_to_Quaternion(${in_value}, &${out_value})"
# "Ray": "ok &= seval_to_ray(${in_value}, &${out_value})"
# "NavMeshAgentParam": "ok &= seval_to_NavMeshAgentParam(${in_value}, &${out_value})"
# "Physics3DRigidBodyDes*": "cocos2d::Physics3DRigidBodyDes tempObj;${out_value}=&tempObj;ok &= seval_to_physics3DRigidBodyDes(${in_value}, ${out_value})"
# "TerrainData": "ok &= seval_to_TerrainData(${in_value}, &${out_value})"
"TMXTileFlags_": "ok &= seval_to_uint32(${in_value}, (uint32_t *)&${out_value})"
"TMXTileFlags_*": "uint32_t tempData;${out_value}=(cocos2d::TMXTileFlags_*)&tempData;ok &= seval_to_uint32(${in_value}, (uint32_t *)&${out_value})"
"ResourceData": "ok &= seval_to_ResourceData(${in_value}, &${out_value})"
"ListenerID": "ok &= seval_to_std_string(${in_value}, &${out_value})"
"DownloaderHints": "ok &= seval_to_DownloaderHints(${in_value}, &${out_value})"
"Viewport": "ok &= seval_to_Viewport(${in_value}, &${out_value})"
"Data": "ok &= seval_to_Data(${in_value}, &${out_value})"
"b2Vec2": "ok &= seval_to_b2Vec2(${in_value}, &${out_value})"
"b2AABB": "ok &= seval_to_b2AABB(${in_value}, &${out_value})"
"Options": "ok &= seval_to_TextureOptions(${in_value}, &${out_value})"
"SubImageOption": "ok &= seval_to_TextureSubImageOption(${in_value}, &${out_value})"
"ImageOption": "ok &= seval_to_TextureImageOption(${in_value}, &${out_value})"
"String": "${out_value} = ${in_value}.toStringForce().c_str()"
"@Vector<spine::String.*>": "ok &= seval_to_spine_Vector_String(${in_value}, &${out_value})"
"@Vector<spine::((?!String).)*>": "ok &= seval_to_spine_Vector_T_ptr(${in_value}, &${out_value})"
"se_object_ptr": "${out_value} = ${in_value}.toObject()"
object: "ok &= seval_to_native_ptr(${in_value}, &${out_value})"
from_native:
# int to jsval
int32_t: "ok &= int32_to_seval(${in_value}, &${out_value})"
int: "ok &= int32_to_seval(${in_value}, &${out_value})"
enum: "ok &= int32_to_seval(${in_value}, &${out_value})"
"unsigned int": "ok &= uint32_to_seval(${in_value}, &${out_value})"
"unsigned short": "ok &= int16_to_seval(${in_value}, &${out_value})"
"unsigned char": "ok &= uint8_to_seval(${in_value}, &${out_value})"
"char": "ok &= int8_to_seval(${in_value}, &${out_value})"
"long long": "ok &= longlong_to_seval(${in_value}, &${out_value})"
"string": "ok &= std_string_to_seval(${in_value}, &${out_value})"
"string&": "ok &= std_string_to_seval(${in_value}, &${out_value})"
"char*": "ok &= std_string_to_seval(${in_value}, &${out_value})"
bool: "ok &= boolean_to_seval(${in_value}, &${out_value})"
float: "ok &= float_to_seval(${in_value}, &${out_value})"
double: "ok &= double_to_seval(${in_value}, &${out_value})"
long: "ok &= long_to_seval(${in_value}, &${out_value})"
"unsigned long": "ok &= ulong_to_seval(${in_value}, &${out_value})"
"ssize_t": "ok &= ssize_to_seval(${in_value}, &${out_value})"
"ssize_t": "ok &= size_to_seval(${in_value}, &${out_value})"
"Point": "ok &= Vec2_to_seval(${in_value}, &${out_value})"
"Rect": "ok &= Rect_to_seval(${in_value}, &${out_value})"
"Size": "ok &= Size_to_seval(${in_value}, &${out_value})"
"Color4B": "ok &= Color4B_to_seval(${in_value}, &${out_value})"
"Color4F": "ok &= Color4F_to_seval(${in_value}, &${out_value})"
"Color3B": "ok &= Color3B_to_seval(${in_value}, &${out_value})"
"Color3F": "ok &= Color3F_to_seval(${in_value}, &${out_value})"
# "Array*": "${out_value} = ccarray_to_seval(${in_value})"
# "Dictionary*": "${out_value} = ccdictionary_to_seval(${in_value})"
"AffineTransform": "ok &= AffineTransform_to_seval(${in_value}, &${out_value})"
"FontDefinition": "ok &= FontDefinition_to_seval(${in_value}, &${out_value})"
# "String*": "${out_value} = std_string_to_seval(${in_value}->getCString())"
"@Vector<.*>": "ok &= Vector_to_seval(${in_value}, &${out_value})"
"@Map<std::string.*>": "ok &= Map_string_key_to_seval(${in_value}, &${out_value})"
"@map<std::string.*,\\s*std::string.*>": "ok &= std_map_string_string_to_seval(${in_value}, &${out_value})"
"Value": "ok &= ccvalue_to_seval(${in_value}, &${out_value})"
"ValueMap": "ok &= ccvaluemap_to_seval(${in_value}, &${out_value})"
"ValueMapIntKey": "ok &= ccvaluemapintkey_to_seval(${in_value}, &${out_value})"
"ValueVector": "ok &= ccvaluevector_to_seval(${in_value}, &${out_value})"
"@vector<std::string.*>": "ok &= std_vector_string_to_seval(${in_value}, &${out_value})"
"@vector<int.*>": "ok &= std_vector_int_to_seval(${in_value}, &${out_value})"
"@vector<float.*>": "ok &= std_vector_float_to_seval(${in_value}, &${out_value})"
"@vector<.*Touch.*>": "ok &= std_vector_Touch_to_seval(${in_value}, &${out_value})"
"@vector<.*RenderTarget.*>": "ok &= std_vector_RenderTarget_to_seval(${in_value}, &${out_value})"
"Acceleration*": "ok &= Acceleration_to_seval(${in_value}, &${out_value})"
"Parameter": "ok &= TechniqueParameter_to_seval(${in_value}, &${out_value})"
"vector<cocos2d::renderer::Technique::Parameter>": "ok &= std_vector_TechniqueParameter_to_seval(${in_value}, &${out_value})"
"Mat4": "ok &= Mat4_to_seval(${in_value}, &${out_value})"
"Vec2": "ok &= Vec2_to_seval(${in_value}, &${out_value})"
"Vec3": "ok &= Vec3_to_seval(${in_value}, &${out_value})"
"Vec4": "ok &= Vec4_to_seval(${in_value}, &${out_value})"
"BlendFunc": "ok &= blendfunc_to_seval(${in_value}, &${out_value})"
"Quaternion": "ok &= Quaternion_to_seval(${in_value}, &${out_value})"
"spEventData*": "ok &= speventdata_to_seval(${in_value}, &${out_value})"
"spEvent*": "ok &= spevent_to_seval(${in_value}, &${out_value})"
"spBoneData*": "ok &= spbonedata_to_seval(${in_value}, &${out_value})"
"spBone*": "ok &= spbone_to_seval(${in_value}, &${out_value})"
"spSkeleton*": "ok &= spskeleton_to_seval(${in_value}, &${out_value})"
"spAttachment*": "ok &= spattachment_to_seval(${in_value}, &${out_value})"
"spSlotData*": "ok &= spslotdata_to_seval(${in_value}, &${out_value})"
"spSlot*": "ok &= spslot_to_seval(${in_value}, &${out_value})"
"spTimeline*": "ok &= sptimeline_to_seval(${in_value}, &${out_value})"
"spAnimationState*": "ok &= spanimationstate_to_seval(${in_value}, &${out_value})"
"spAnimation*": "ok &= spanimation_to_seval(${in_value}, &${out_value})"
"spTrackEntry*": "ok &= sptrackentry_to_seval(${in_value}, &${out_value})"
# "OffMeshLinkData": "${out_value} = offMeshLinkData_to_seval(${in_value})"
"TouchEventType": "ok &= int32_to_seval((int32_t)${in_value}, &${out_value})"
"EventType": "ok &= int32_to_seval((int32_t)${in_value}, &${out_value})"
"ManifestAsset": "ok &= ManifestAsset_to_seval(${in_value}, &${out_value})"
"@DownloadTask.*": "ok &= DownloadTask_to_seval(${in_value}, &${out_value})"
"@shared_ptr<.*DownloadTask.*": "ok &= DownloadTask_to_seval(*${in_value}, &${out_value})"
"Viewport": "ok &= Viewport_to_seval(${in_value}, &${out_value})"
"Data": "ok &= Data_to_seval(${in_value}, &${out_value})"
"b2Vec2": "ok &= b2Vec2_to_seval(${in_value}, &${out_value})"
"b2Manifold*": "ok &= b2Manifold_to_seval(${in_value}, &${out_value})"
"b2AABB": "ok &= b2AABB_to_seval(${in_value}, &${out_value})"
"VertexFormat": "ok &= VertexFormat_to_seval(${in_value}, &${out_value})"
"se_object_ptr": "${out_value}.setObject(${in_value})"
"String": "${out_value}.setString(${in_value}.buffer())"
"@(?:\\bBoneData\\b|\\bSkeleton\\b|\\bColor\\b|\\bEventData\\b|\\bIkConstraintData\\b|\\bPathConstraintData\\b|\\bTransformConstraintData\\b|\\bBone\\b|\\bSlotData\\b)+(?!\\*)+": "ok &= native_ptr_to_rooted_seval<${ntype.replace('const ', '').replace('&', '')}>((${ntype.replace('const ', '').replace('&', '')}*)&${in_value}, &${out_value})"
"@Vector<spine::((?!String).)*>": "ok &= spine_Vector_T_ptr_to_seval(${in_value}, &${out_value})"
"@Vector<.*(\\bshort\\b|\\bfloat\\b)+>": "ok &= spine_Vector_T_to_seval(${in_value}, &${out_value})"
"@Vector<spine::String.*>": "ok &= spine_Vector_String_to_seval(${in_value}, &${out_value})"
object: "ok &= native_ptr_to_seval<${ntype.replace('*', '').replace('const ', '')}>((${ntype.replace('const ', '')})${in_value}, &${out_value})"
rooted_object: "ok &= native_ptr_to_rooted_seval<${ntype.replace('*', '').replace('const ', '')}>((${ntype.replace('const ', '')})${in_value}, &${out_value})"

View File

@@ -0,0 +1,11 @@
#set generator = $current_class.generator
/**
* @class ${current_class.class_name}
*/
#if $generator.target_ns
${generator.target_ns}.${current_class.target_class_name} = {
#else
${current_class.target_class_name} = {
#end if

View File

@@ -0,0 +1,40 @@
/**
* @method ${func_name}
#if $is_constructor
* @constructor
#end if
#if $min_args > 0
#set $count = 0
#for $arg in $arguments
#set $argValue = "arg" + str(count)
* @param {$generator.js_typename_from_natve($arg.namespaced_class_name)} $argValue
#set $count = $count + 1
#end for
#end if
#if str($ret_type) != "void"
* @return {$generator.js_typename_from_natve($ret_type.namespaced_class_name)}
#end if
*/
${func_name} : function (
#if $min_args > 0
#set $length = len($arguments)
#set $index = 0
#for $arg in $arguments
#set $argname = $arg.name.replace("*", "").replace("const ", "")
#if $index < $length - 1
$generator.api_param_name_from_native(argname),
#else
$generator.api_param_name_from_native(argname)
#end if
#set $index = $index + 1
#end for
#end if
)
{
#if str($ret_type) != "void"
#set $is_enum = $ret_type.is_enum
#set $ret = $ret_type.namespaced_class_name.replace("*", "").replace("const ", "")
return $generator.js_ret_name_from_native($ret,$is_enum);
#end if
},

View File

@@ -0,0 +1,102 @@
/**
* @method ${func_name}
#if $is_constructor
* @constructor
#end if
#set $max_count = 0
#set $func_count = len($implementations)
#set $func_index = 0
#for func in $implementations
#if len($func.arguments) >= $max_count
#set $max_count = len($func.arguments)
#end if
#set $func_index = $func_index + 1
#end for
#if $max_count > 0
#set $arg_idx = 0
#while $arg_idx < $max_count
#set $tip = "@param {"
#set $sub_tip = ""
#set $is_sub_tip_set = False
#set $func_index = 0
#for func in $implementations
#set $loop_index = 0
#set $is_find = False
#for $arg in $func.arguments
#if $loop_index < len($func.arguments)
#if $loop_index == $arg_idx
#set $tip = $tip + $generator.js_typename_from_natve($arg.namespaced_class_name)
#set $is_find = True
#if $is_sub_tip_set == False
#set $is_sub_tip_set = True
#set $sub_tip = $generator.api_param_name_from_native($arg.name.replace("*", "").replace("const ", ""))
#end if
#end if
#set $loop_index = $loop_index + 1
#end if
#end for
#if $func_index < $func_count - 1
#if $is_find == True
#set $tip = $tip + "|"
#end if
#end if
#set $func_index = $func_index + 1
#end for
#if $tip.endswith('|')
#set $tip = $tip[:-1]
#end if
#set $tip = $tip + "} " + $sub_tip
* $tip
#set $arg_idx = $arg_idx + 1
#end while
#end if
#set $ret_tip = "{"
#set $func_index = 0
#set $have_ret = False
#for func in $implementations
#if str($func.ret_type) != "void"
#set $ret_tip = $ret_tip + $generator.js_typename_from_natve($func.ret_type.namespaced_class_name) + "|"
#set $have_ret = True
#end if
#set $func_index = $func_index + 1
#end for
#if $ret_tip.endswith('|')
#set $ret_tip = $ret_tip[:-1] + "}"
#end if
#if $have_ret
* @return $ret_tip
#end if
*/
#set $max_count = 0
#set $func_count = len($implementations)
#set $func_index = 0
#set $max_index = 0
#set $selected_func = 0
#for func in $implementations
#if len($func.arguments) >= $max_count
#set $max_count = len($func.arguments)
#set $max_index = $func_index
#set $selected_func = func
#end if
#set $func_index = $func_index + 1
#end for
${func_name} : function(
#set $arg_idx = 0
#for $arg in $selected_func.arguments
#set $argname = $arg.name.replace("*", "").replace("const ", "")
#if $arg_idx < $max_count - 1
$generator.api_param_name_from_native(argname),
#else
$generator.api_param_name_from_native(argname)
#end if
#set $arg_idx = $arg_idx + 1
#end for
)
{
#if str($selected_func.ret_type) != "void"
#set $is_enum = $selected_func.ret_type.is_enum
#set $ret = $selected_func.ret_type.namespaced_class_name.replace("*", "").replace("const ", "")
return $generator.js_ret_name_from_native($ret,$is_enum);
#end if
},

View File

@@ -0,0 +1,12 @@
#if $target_ns
#if $prefix
/**
* @module ${prefix}
*/
#else
/**
* @module ${target_ns}
*/
#end if
var ${target_ns} = ${target_ns} || {};
#end if

View File

@@ -0,0 +1,56 @@
## ===== constructor function implementation template
SE_DECLARE_FINALIZE_FUNC(js_${underlined_class_name}_finalize)
static bool ${signature_name}(se::State& s)
{
#if len($arguments) >= $min_args
#set arg_count = len($arguments)
#set arg_idx = $min_args
#set $count = 0
#if $arg_idx > 0
CC_UNUSED bool ok = true;
const auto& args = s.args();
#end if
#while $count < $arg_idx
#set $arg = $arguments[$count]
#set $arg_type = arg.to_string($generator)
#if $arg.is_numeric
$arg_type arg${count} = 0;
#elif $arg.is_pointer
$arg_type arg${count} = nullptr;
#else
$arg_type arg${count};
#end if
#set $count = $count + 1
#end while
#set $count = 0
#set arg_list = ""
#set arg_array = []
#while $count < $arg_idx
#set $arg = $arguments[$count]
#set $arg_type = arg.to_string($generator)
${arg.to_native({"generator": $generator,
"arg_type": $arg_type,
"in_value": "args[" + str(count) + "]",
"out_value": "arg" + str(count),
"class_name": $class_name,
"level": 2,
"is_static": False,
"ntype": str($arg)})};
#set $arg_array += ["arg"+str(count)]
#set $count = $count + 1
#end while
#if $arg_idx > 0
SE_PRECONDITION2(ok, false, "${signature_name} : Error processing arguments");
#end if
#set $arg_list = ", ".join($arg_array)
${namespaced_class_name}* cobj = new (std::nothrow) ${namespaced_class_name}($arg_list);
s.thisObject()->setPrivateData(cobj);
#if not $is_ref_class
se::NonRefNativePtrCreatedByCtorMap::emplace(cobj);
#end if
#end if
return true;
}
SE_BIND_CTOR(${signature_name}, __jsb_${underlined_class_name}_class, js_${underlined_class_name}_finalize)

View File

@@ -0,0 +1,63 @@
## ===== constructor function implementation template
SE_DECLARE_FINALIZE_FUNC(js_${underlined_class_name}_finalize)
static bool ${signature_name}(se::State& s)
{
CC_UNUSED bool ok = true;
const auto& args = s.args();
size_t argc = args.size();
#for func in $implementations
#if len($func.arguments) >= $func.min_args
#set arg_count = len($func.arguments)
#set arg_idx = $func.min_args
#while $arg_idx <= $arg_count
#set arg_list = ""
#set arg_array = []
do {
#if $func.min_args >= 0
if (argc == $arg_idx) {
#set $count = 0
#while $count < $arg_idx
#set $arg = $func.arguments[$count]
#set $arg_type = arg.to_string($generator)
#if $arg.is_numeric
${arg_type} arg${count} = 0;
#elif $arg.is_pointer
${arg_type} arg${count} = nullptr;
#else
${arg_type} arg${count};
#end if
${arg.to_native({"generator": $generator,
"arg_type": $arg_type,
"in_value": "args[" + str(count) + "]",
"out_value": "arg" + str(count),
"class_name": $class_name,
"level": 3,
"is_static": False,
"is_persistent": $is_persistent,
"ntype": str($arg)})};
#set $arg_array += ["arg"+str(count)]
#set $count = $count + 1
#if $arg_idx > 0
if (!ok) { ok = true; break; }
#end if
#end while
#end if
#set $arg_list = ", ".join($arg_array)
${namespaced_class_name}* cobj = new (std::nothrow) ${namespaced_class_name}($arg_list);
s.thisObject()->setPrivateData(cobj);
#if not $is_ref_class
se::NonRefNativePtrCreatedByCtorMap::emplace(cobj);
#end if
return true;
}
} while(false);
#set $arg_idx = $arg_idx + 1
#end while
#end if
#end for
SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc);
return false;
}
SE_BIND_CTOR(${signature_name}, __jsb_${underlined_class_name}_class, js_${underlined_class_name}_finalize)

View File

@@ -0,0 +1,55 @@
## ===== ctor function implementation template
static bool ${signature_name}(se::State& s)
{
#if len($arguments) >= $min_args
#set arg_count = len($arguments)
#set arg_idx = $min_args
#set $count = 0
#if $arg_idx > 0
CC_UNUSED bool ok = true;
const auto& args = s.args();
#end if
#while $count < $arg_idx
#set $arg = $arguments[$count]
#set $arg_type = arg.to_string($generator)
#if $arg.is_numeric
${arg.to_string($generator)} arg${count} = 0;
#elif $arg.is_pointer
${arg.to_string($generator)} arg${count} = nullptr;
#else
${arg.to_string($generator)} arg${count};
#end if
#set $count = $count + 1
#end while
#set $count = 0
#set arg_list = ""
#set arg_array = []
#while $count < $arg_idx
#set $arg = $arguments[$count]
#set $arg_type = arg.to_string($generator)
${arg.to_native({"generator": $generator,
"arg_type": $arg_type,
"in_value": "args[" + str(count) + "]",
"out_value": "arg" + str(count),
"class_name": $class_name,
"level": 2,
"is_static": False,
"is_persistent": $is_persistent,
"ntype": str($arg)})};
#set $arg_array += ["arg"+str(count)]
#set $count = $count + 1
#end while
#if $arg_idx > 0
SE_PRECONDITION2(ok, false, "${signature_name} : Error processing arguments");
#end if
#set $arg_list = ", ".join($arg_array)
${namespaced_class_name}* cobj = new (std::nothrow) ${namespaced_class_name}($arg_list);
s.thisObject()->setPrivateData(cobj);
#if not $is_ref_class
se::NonRefNativePtrCreatedByCtorMap::emplace(cobj);
#end if
#end if
return true;
}
SE_BIND_SUB_CLS_CTOR(${signature_name}, __jsb_${underlined_class_name}_class, js_${underlined_class_name}_finalize)

View File

@@ -0,0 +1,63 @@
## ===== constructor function implementation template
SE_DECLARE_FINALIZE_FUNC(js_${underlined_class_name}_finalize)
static bool ${signature_name}(se::State& s)
{
CC_UNUSED bool ok = true;
const auto& args = s.args();
size_t argc = args.size();
#for func in $implementations
#if len($func.arguments) >= $func.min_args
#set arg_count = len($func.arguments)
#set arg_idx = $func.min_args
#while $arg_idx <= $arg_count
#set arg_list = ""
#set arg_array = []
do {
#if $func.min_args >= 0
if (argc == $arg_idx) {
#set $count = 0
#while $count < $arg_idx
#set $arg = $func.arguments[$count]
#set $arg_type = arg.to_string($generator)
#if $arg.is_numeric
${arg_type} arg${count} = 0;
#elif $arg.is_pointer
${arg_type} arg${count} = nullptr;
#else
${arg_type} arg${count};
#end if
${arg.to_native({"generator": $generator,
"arg_type": $arg_type,
"in_value": "args[" + str(count) + "]",
"out_value": "arg" + str(count),
"class_name": $class_name,
"level": 3,
"is_static": False,
"is_persistent": $is_persistent,
"ntype": str($arg)})};
#set $arg_array += ["arg"+str(count)]
#set $count = $count + 1
#if $arg_idx > 0
if (!ok) { ok = true; break; }
#end if
#end while
#end if
#set $arg_list = ", ".join($arg_array)
${namespaced_class_name}* cobj = new (std::nothrow) ${namespaced_class_name}($arg_list);
s.thisObject()->setPrivateData(cobj);
#if not $is_ref_class
se::NonRefNativePtrCreatedByCtorMap::emplace(cobj);
#end if
return true;
}
} while(false);
#set $arg_idx = $arg_idx + 1
#end while
#end if
#end for
SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc);
return false;
}
SE_BIND_SUB_CLS_CTOR(${signature_name}, __jsb_${underlined_class_name}_class, js_${underlined_class_name}_finalize)

View File

@@ -0,0 +1 @@
SE_DECLARE_FUNC(js_${generator.prefix}_${class_name}_${func_name});

View File

@@ -0,0 +1,76 @@
## ===== instance function implementation template
static bool ${signature_name}(se::State& s)
{
${namespaced_class_name}* cobj = (${namespaced_class_name}*)s.nativeThisObject();
SE_PRECONDITION2(cobj, false, "${signature_name} : Invalid Native Object");
#if len($arguments) >= $min_args
const auto& args = s.args();
size_t argc = args.size();
#set arg_count = len($arguments)
#set arg_idx = $min_args
#if $arg_count > 0 or $ret_type.name != "void"
CC_UNUSED bool ok = true;
#end if
#while $arg_idx <= $arg_count
if (argc == ${arg_idx}) {
#set $count = 0
#while $count < $arg_idx
#set $arg = $arguments[$count]
#set $arg_type = $arg.to_string($generator)
#if $arg.is_numeric
$arg_type arg${count} = 0;
#elif $arg.is_pointer
$arg_type arg${count} = nullptr;
#else
$arg_type arg${count};
#end if
#set $count = $count + 1
#end while
#set $count = 0
#set arg_list = ""
#set arg_array = []
#while $count < $arg_idx
#set $arg = $arguments[$count]
#set $arg_type = $arg.to_string($generator)
${arg.to_native({"generator": $generator,
"arg_type": $arg_type,
"in_value": "args[" + str(count) + "]",
"out_value": "arg" + str(count),
"class_name": $class_name,
"level": 2,
"is_static": False,
"is_persistent": $is_persistent,
"ntype": str($arg)})};
#set $arg_array += ["arg"+str(count)]
#set $count = $count + 1
#end while
#if $arg_idx > 0
SE_PRECONDITION2(ok, false, "${signature_name} : Error processing arguments");
#end if
#set $arg_list = ", ".join($arg_array)
#if $ret_type.name != "void"
#if $ret_type.is_enum
$ret_type.enum_declare_type result = ($ret_type.enum_declare_type)cobj->${func_name}($arg_list);
#else
${ret_type.get_whole_name($generator)} result = cobj->${func_name}($arg_list);
#end if
${ret_type.from_native({"generator": $generator,
"in_value": "result",
"out_value": "s.rval()",
"class_name": $ret_type.get_class_name($generator),
"ntype": str($ret_type),
"level": 2})};
SE_PRECONDITION2(ok, false, "${signature_name} : Error processing arguments");
#else
cobj->${func_name}($arg_list);
#end if
return true;
}
#set $arg_idx = $arg_idx + 1
#end while
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, $arg_count);
#end if
return false;
}
SE_BIND_FUNC(${signature_name})

View File

@@ -0,0 +1,75 @@
## ===== instance function implementation template - for overloaded functions
static bool ${signature_name}(se::State& s)
{
CC_UNUSED bool ok = true;
${namespaced_class_name}* cobj = (${namespaced_class_name}*)s.nativeThisObject();
SE_PRECONDITION2( cobj, false, "${signature_name} : Invalid Native Object");
const auto& args = s.args();
size_t argc = args.size();
#for func in $implementations
#if len($func.arguments) >= $func.min_args
#set arg_count = len($func.arguments)
#set arg_idx = $func.min_args
#while $arg_idx <= $arg_count
#set arg_list = ""
#set arg_array = []
do {
#if $func.min_args >= 0
if (argc == $arg_idx) {
#set $count = 0
#while $count < $arg_idx
#set $arg = $func.arguments[$count]
#set $arg_type = $arg.to_string($generator)
#if $arg.is_numeric
${arg_type} arg${count} = 0;
#elif $arg.is_pointer
${arg_type} arg${count} = nullptr;
#else
${arg_type} arg${count};
#end if
${arg.to_native({"generator": $generator,
"arg_type": $arg_type,
"in_value": "args[" + str(count) + "]",
"out_value": "arg" + str(count),
"class_name": $class_name,
"level": 3,
"is_static": False,
"is_persistent": $is_persistent,
"ntype": str($arg)})};
#set $arg_array += ["arg"+str(count)]
#set $count = $count + 1
#if $arg_idx > 0 and arg_type != "bool"
if (!ok) { ok = true; break; }
#end if
#end while
#set $arg_list = ", ".join($arg_array)
#end if
#if str($func.ret_type) != "void"
#if $func.ret_type.is_enum
$ret_type.enum_declare_type result = ($ret_type.enum_declare_type)cobj->${func.func_name}($arg_list);
#else
${func.ret_type.get_whole_name($generator)} result = cobj->${func.func_name}($arg_list);
#end if
${func.ret_type.from_native({"generator": $generator,
"in_value": "result",
"out_value": "s.rval()",
"class_name": $func.ret_type.get_class_name($generator),
"ntype": str($func.ret_type),
"level": 2})};
SE_PRECONDITION2(ok, false, "${signature_name} : Error processing arguments");
#else
cobj->${func.func_name}($arg_list);
#end if
return true;
}
} while(false);
#set $arg_idx = $arg_idx + 1
#end while
#end if
#end for
SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc);
return false;
}
SE_BIND_FUNC(${signature_name})

View File

@@ -0,0 +1,66 @@
do {
if (${in_value}.isObject() && ${in_value}.toObject()->isFunction())
{
se::Value jsThis(s.thisObject());
se::Value jsFunc(${in_value});
#if $is_static or $is_persistent
jsFunc.toObject()->root();
#else
jsThis.toObject()->attachObject(jsFunc.toObject());
#end if
auto lambda = [=](${lambda_parameters}) -> ${ret_type.name} {
se::ScriptEngine::getInstance()->clearException();
se::AutoHandleScope hs;
#set arg_count = len($param_types)
#if $arg_count > 0 or $ret_type.name != "void"
CC_UNUSED bool ok = true;
#end if
#if $arg_count > 0
se::ValueArray args;
args.resize($arg_count);
#end if
#set $count = 0
#while $count < $arg_count
#set $arg = $param_types[$count]
#set $arg_type = $arg.to_string($generator)
${arg.from_native({"generator": $generator,
"arg_type": $arg_type,
"in_value": "larg" + str(count),
"out_value": "args[" + str(count) + "]",
"class_name": $class_name,
"level": 2,
"ntype": str($arg)})};
#set $count = $count + 1
#end while
se::Value rval;
se::Object* thisObj = jsThis.isObject() ? jsThis.toObject() : nullptr;
se::Object* funcObj = jsFunc.toObject();
#if $arg_count > 0
bool succeed = funcObj->call(args, thisObj, &rval);
#else
bool succeed = funcObj->call(se::EmptyValueArray, thisObj, &rval);
#end if
if (!succeed) {
se::ScriptEngine::getInstance()->clearException();
}
#if $ret_type.name != "void"
#set $ret_type_name = $ret_type.get_whole_name($generator)
$ret_type_name result;
${ret_type.to_native({"generator": $generator,
"arg_type": $ret_type_name,
"in_value": "rval",
"out_value": "result",
"ntype": str($ret_type),
"level": 2})};
SE_PRECONDITION2(ok, result, "lambda function : Error processing return value with type ${ret_type.name}");
return result;
#end if
};
${out_value} = lambda;
}
else
{
${out_value} = nullptr;
}
} while(false)

View File

@@ -0,0 +1,28 @@
bool register_all_${prefix}(se::Object* obj)
{
#if $target_ns
// Get the ns
se::Value nsVal;
if (!obj->getProperty("${target_ns}", &nsVal))
{
se::HandleObject jsobj(se::Object::createPlainObject());
nsVal.setObject(jsobj);
obj->setProperty("${target_ns}", nsVal);
}
se::Object* ns = nsVal.toObject();
#else
// Get the global ns
se::Object* ns = se::ScriptEngine::getInstance()->getGlobalObject();
#end if
#for jsclass in $sorted_classes
#if $in_listed_classes(jsclass)
js_register_${prefix}_${jsclass}(ns);
#end if
#end for
return true;
}
#if $macro_judgement
\#endif //$macro_judgement
#end if

View File

@@ -0,0 +1,4 @@
#if $macro_judgement
\#endif //$macro_judgement
#end if

View File

@@ -0,0 +1,25 @@
\#include "scripting/js-bindings/auto/${out_file}.hpp"
#if $macro_judgement
$macro_judgement
#end if
\#include "scripting/js-bindings/manual/jsb_conversions.hpp"
\#include "scripting/js-bindings/manual/jsb_global.h"
#for header in $headers
#set include_header = os.path.basename(header)
#if $replace_headers.has_key(include_header)
\#include "${replace_headers[include_header]}"
#else
#set relative = os.path.relpath(header, $search_path)
#if not '..' in relative
\#include "${relative.replace(os.path.sep, '/')}"
#else
\#include "${include_header}"
#end if
#end if
#end for
#if $cpp_headers
#for header in $cpp_headers
\#include "${header}"
#end for
#end if

View File

@@ -0,0 +1,12 @@
#pragma once
\#include "base/ccConfig.h"
#if $macro_judgement
$macro_judgement
#end if
\#include "cocos/scripting/js-bindings/jswrapper/SeApi.h"
#if $hpp_headers
#for header in $hpp_headers
\#include "${header}"
#end for
#end if

View File

@@ -0,0 +1,3 @@
#set generator = $current_class.generator
se::Object* __jsb_${current_class.underlined_class_name}_proto = nullptr;
se::Class* __jsb_${current_class.underlined_class_name}_class = nullptr;

View File

@@ -0,0 +1,7 @@
#set generator = $current_class.generator
extern se::Object* __jsb_${current_class.underlined_class_name}_proto;
extern se::Class* __jsb_${current_class.underlined_class_name}_class;
bool js_register_${current_class.underlined_class_name}(se::Object* obj);
bool register_all_${generator.prefix}(se::Object* obj);

View File

@@ -0,0 +1,75 @@
## ===== member implementation template
static bool ${signature_name}_get_${name}(se::State& s)
{
${namespaced_class_name}* cobj = (${namespaced_class_name}*)s.nativeThisObject();
SE_PRECONDITION2(cobj, false, "${signature_name}_get_${name} : Invalid Native Object");
CC_UNUSED bool ok = true;
se::Value jsret;
#if $ntype.is_object and not $ntype.object_can_convert($generator, False)
${ntype.from_native({"generator": $generator,
"type_name": $ntype.namespaced_class_name.replace("*", ""),
"ntype": $ntype.get_whole_name($generator),
"level": 2,
"in_value": "cobj->" + $pretty_name,
"out_value": "jsret"
})};
#else
${ntype.from_native({"generator": $generator,
"type_name": $ntype.namespaced_class_name.replace("*", ""),
"ntype": $ntype.get_whole_name($generator),
"level": 2,
"scriptname": $generator.scriptname_from_native($ntype.namespaced_class_name, $ntype.namespace_name),
"in_value":"cobj->" + $pretty_name,
"out_value": "jsret"
})};
#end if
s.rval() = jsret;
return true;
}
SE_BIND_PROP_GET(${signature_name}_get_${name})
static bool ${signature_name}_set_${name}(se::State& s)
{
const auto& args = s.args();
${namespaced_class_name}* cobj = (${namespaced_class_name}*)s.nativeThisObject();
SE_PRECONDITION2(cobj, false, "${signature_name}_set_${name} : Invalid Native Object");
CC_UNUSED bool ok = true;
#set $arg_type = $ntype.to_string($generator)
#if $ntype.is_numeric
$arg_type arg0 = 0;
#elif $ntype.is_pointer
$arg_type arg0 = nullptr;
#else
$arg_type arg0;
#end if
#if $ntype.is_object and not $ntype.object_can_convert($generator)
${ntype.to_native({"generator": $generator,
"arg_idx": 2,
"arg_type": $arg_type,
"ntype": $ntype.get_whole_name($generator),
"in_value": "args[0]",
"out_value": "arg0",
"func_name": $name,
"level": 2,
"arg":$ntype,
})};
#else
${ntype.to_native({"generator": $generator,
"arg_idx": 2,
"arg_type": $arg_type,
"in_value": "args[0]",
"out_value": "arg0",
"func_name": $name,
"scriptname": $generator.scriptname_from_native($ntype.namespaced_class_name, $ntype.namespace_name),
"level": 2,
"arg":$ntype,
})};
#end if
SE_PRECONDITION2(ok, false, "${signature_name}_set_${name} : Error processing new value");
cobj->$pretty_name = arg0;
return true;
}
SE_BIND_PROP_SET(${signature_name}_set_${name})

View File

@@ -0,0 +1,131 @@
#set has_constructor = False
#set generator = $current_class.generator
#set methods = $current_class.methods_clean()
#set st_methods = $current_class.static_methods_clean()
#set public_fields = $current_class.public_fields
#if $current_class.methods.has_key('constructor')
#set has_constructor = True
#set constructor = $current_class.methods.constructor
${current_class.methods.constructor.generate_code($current_class)}
#end if
#if $generator.in_listed_extend_classed($current_class.class_name) and $has_constructor
#if not $constructor.is_overloaded
${constructor.generate_code($current_class, None, False, True)}
#else
${constructor.generate_code($current_class, False, True)}
#end if
#end if
#if len($current_class.parents) > 0
extern se::Object* __jsb_${current_class.parents[0].underlined_class_name}_proto;
#end if
#if not $current_class.is_abstract
static bool js_${current_class.underlined_class_name}_finalize(se::State& s)
{
#if $current_class.rename_destructor is None
CCLOGINFO("jsbindings: finalizing JS object %p (${current_class.namespaced_class_name})", s.nativeThisObject());
#if $current_class.is_ref_class
${current_class.namespaced_class_name}* cobj = (${current_class.namespaced_class_name}*)s.nativeThisObject();
cobj->release();
#else
#if not $current_class.is_class_owned_by_cpp
auto iter = se::NonRefNativePtrCreatedByCtorMap::find(s.nativeThisObject());
if (iter != se::NonRefNativePtrCreatedByCtorMap::end())
{
se::NonRefNativePtrCreatedByCtorMap::erase(iter);
${current_class.namespaced_class_name}* cobj = (${current_class.namespaced_class_name}*)s.nativeThisObject();
delete cobj;
}
#end if
#end if
#else
// destructor is skipped
#end if
return true;
}
SE_BIND_FINALIZE_FUNC(js_${current_class.underlined_class_name}_finalize)
#end if
#if $current_class.rename_destructor is not None
static bool js_${current_class.underlined_class_name}_${current_class.rename_destructor}(se::State& s)
{
CCLOGINFO("jsbindings: destory JS object %p (${current_class.namespaced_class_name})", s.nativeThisObject());
#if $current_class.is_ref_class
${current_class.namespaced_class_name}* cobj = (${current_class.namespaced_class_name}*)s.nativeThisObject();
cobj->release();
#else
#if not $current_class.is_class_owned_by_cpp
auto iter = se::NonRefNativePtrCreatedByCtorMap::find(s.nativeThisObject());
if (iter != se::NonRefNativePtrCreatedByCtorMap::end())
{
se::NonRefNativePtrCreatedByCtorMap::erase(iter);
${current_class.namespaced_class_name}* cobj = (${current_class.namespaced_class_name}*)s.nativeThisObject();
delete cobj;
}
#end if
#end if
auto objIter = se::NativePtrToObjectMap::find(s.nativeThisObject());
if(objIter != se::NativePtrToObjectMap::end())
{
objIter->second->clearPrivateData(true);
}
return true;
}
SE_BIND_FUNC(js_${current_class.underlined_class_name}_${current_class.rename_destructor})
#end if
bool js_register_${generator.prefix}_${current_class.class_name}(se::Object* obj)
{
#if has_constructor
#if len($current_class.parents) > 0
auto cls = se::Class::create("${current_class.target_class_name}", obj, __jsb_${current_class.parents[0].underlined_class_name}_proto, _SE(js_${generator.prefix}_${current_class.class_name}_constructor));
#else
auto cls = se::Class::create("${current_class.target_class_name}", obj, nullptr, _SE(js_${generator.prefix}_${current_class.class_name}_constructor));
#end if
#else
#if len($current_class.parents) > 0
auto cls = se::Class::create("${current_class.target_class_name}", obj, __jsb_${current_class.parents[0].underlined_class_name}_proto, nullptr);
#else
auto cls = se::Class::create("${current_class.target_class_name}", obj, nullptr, nullptr);
#end if
#end if
#for m in public_fields
#if $generator.should_bind_field($current_class.class_name, m.name)
cls->defineProperty("${m.name}", _SE(${m.signature_name}_get_${m.name}), _SE(${m.signature_name}_set_${m.name}));
#end if
#end for
#for m in methods
#set fn = m['impl']
cls->defineFunction("${m['name']}", _SE(${fn.signature_name}));
#end for
#if $generator.in_listed_extend_classed($current_class.class_name) and $has_constructor
cls->defineFunction("ctor", _SE(js_${generator.prefix}_${current_class.class_name}_ctor));
#end if
#if $current_class.rename_destructor is not None
cls->defineFunction("${current_class.rename_destructor}", _SE(js_${current_class.underlined_class_name}_${current_class.rename_destructor}));
#end if
#if len(st_methods) > 0
#for m in st_methods
#set fn = m['impl']
cls->defineStaticFunction("${m['name']}", _SE(${fn.signature_name}));
#end for
#end if
#if not $current_class.is_abstract
cls->defineFinalizeFunction(_SE(js_${current_class.underlined_class_name}_finalize));
#end if
cls->install();
JSBClassType::registerClass<${current_class.namespaced_class_name}>(cls);
__jsb_${current_class.underlined_class_name}_proto = cls->getProto();
__jsb_${current_class.underlined_class_name}_class = cls;
#if $generator.in_listed_extend_classed($current_class.class_name) and not $current_class.is_abstract
jsb_set_extend_property("${generator.target_ns}", "${current_class.target_class_name}");
#end if
se::ScriptEngine::getInstance()->clearException();
return true;
}

View File

@@ -0,0 +1,88 @@
## ===== static function implementation template
static bool ${signature_name}(se::State& s)
{
const auto& args = s.args();
size_t argc = args.size();
#if len($arguments) >= $min_args
#set arg_count = len($arguments)
#set arg_idx = $min_args
#if ($arg_count > 0 or str($ret_type) != "void")
CC_UNUSED bool ok = true;
#end if
#while $arg_idx <= $arg_count
if (argc == ${arg_idx}) {
#set arg_list = ""
#set arg_array = []
#set $count = 0
#while $count < $arg_idx
#set $arg = $arguments[$count]
#set $arg_type = $arg.to_string($generator)
#if $arg.is_numeric
$arg_type arg${count} = 0;
#elif $arg.is_pointer
$arg_type arg${count} = nullptr;
#else
$arg_type arg${count};
#end if
#set $count = $count + 1
#end while
#set $count = 0
#while $count < $arg_idx
#set $arg = $arguments[$count]
#set $arg_type = $arg.to_string($generator)
${arg.to_native({"generator": $generator,
"arg_type": $arg_type,
"in_value": "args[" + str(count) + "]",
"out_value": "arg" + str(count),
"class_name": $class_name,
"level": 2,
"is_static": True,
"is_persistent": $is_persistent,
"ntype": str($arg)})};
#set $arg_array += ["arg"+str($count)]
#set $count = $count + 1
#end while
#if $arg_idx > 0
SE_PRECONDITION2(ok, false, "${signature_name} : Error processing arguments");
#end if
#set $arg_list = ", ".join($arg_array)
#if str($ret_type) != "void"
#if $func_name.startswith("create") and $is_ref_class
auto result = ${namespaced_class_name}::${func_name}($arg_list);
result->retain();
auto obj = se::Object::createObjectWithClass(__jsb_${underlined_class_name}_class);
obj->setPrivateData(result);
s.rval().setObject(obj);
#elif $func_name.startswith("getInstance") and $is_ref_class
auto result = ${namespaced_class_name}::${func_name}($arg_list);
se::Value instanceVal;
native_ptr_to_seval<${namespaced_class_name}>(result, __jsb_${underlined_class_name}_class, &instanceVal);
instanceVal.toObject()->root();
s.rval() = instanceVal;
#else
#if $ret_type.is_enum
$ret_type.enum_declare_type result = ($ret_type.enum_declare_type)${namespaced_class_name}::${func_name}($arg_list);
#else
${ret_type.get_whole_name($generator)} result = ${namespaced_class_name}::${func_name}($arg_list);
#end if
${ret_type.from_native({"generator": $generator,
"in_value": "result",
"out_value": "s.rval()",
"class_name": $ret_type.get_class_name($generator),
"ntype": str($ret_type),
"level": 1})};
SE_PRECONDITION2(ok, false, "${signature_name} : Error processing arguments");
#end if
#else
${namespaced_class_name}::${func_name}($arg_list);
#end if
return true;
}
#set $arg_idx = $arg_idx + 1
#end while
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, $arg_count);
#end if
return false;
}
SE_BIND_FUNC(${signature_name})

View File

@@ -0,0 +1,70 @@
## ===== static function implementation template - for overloaded functions
static bool ${signature_name}(se::State& s)
{
CC_UNUSED bool ok = true;
const auto& args = s.args();
size_t argc = args.size();
#for func in $implementations
#if len($func.arguments) >= $func.min_args
#set arg_count = len($func.arguments)
#set arg_idx = $func.min_args
#while $arg_idx <= $arg_count
do {
if (argc == ${arg_idx}) {
#set arg_list = ""
#set arg_array = []
#set count = 0
#while $count < $arg_idx
#set $arg = $func.arguments[$count]
#set $arg_type = $arg.to_string($generator)
#if $arg.is_numeric
$arg_type arg${count} = 0;
#elif $arg.is_pointer
$arg_type arg${count} = nullptr;
#else
$arg_type arg${count};
#end if
${arg.to_native({"generator": $generator,
"arg_type": $arg_type,
"in_value": "args[" + str(count) + "]",
"out_value": "arg" + str(count),
"class_name": $class_name,
"level": 3,
"is_static": True,
"is_persistent": $is_persistent,
"ntype": str($arg)})};
#set $arg_array += ["arg"+str(count)]
#set $count = $count + 1
#if $arg_idx > 0
if (!ok) { ok = true; break; }
#end if
#end while
#set $arg_list = ", ".join($arg_array)
#if str($func.ret_type) != "void"
#if $func.ret_type.is_enum
$ret_type.enum_declare_type result = ($ret_type.enum_declare_type)${namespaced_class_name}::${func.func_name}($arg_list);
#else
${func.ret_type.get_whole_name($generator)} result = ${namespaced_class_name}::${func.func_name}($arg_list);
#end if
${func.ret_type.from_native({"generator": $generator,
"in_value": "result",
"out_value": "s.rval()",
"class_name": $func.ret_type.get_class_name($generator),
"ntype": str($func.ret_type),
"level": 3})};
SE_PRECONDITION2(ok, false, "${signature_name} : Error processing arguments");
#else
${namespaced_class_name}::${func.func_name}($arg_list);
#end if
return true;
}
#set $arg_idx = $arg_idx + 1
} while (false);
#end while
#end if
#end for
SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc);
return false;
}
SE_BIND_FUNC(${signature_name})

View File

@@ -0,0 +1,63 @@
*.py[cod]
# C extensions
*.so
# Packages
*.egg
*.egg-info
dist
build
eggs
parts
var
sdist
develop-eggs
.installed.cfg
# Installer logs
pip-log.txt
# Unit test / coverage reports
.coverage
.tox
nosetests.xml
# Translations
*.mo
# Mr Developer
.mr.developer.cfg
.project
.pydevproject
# Ignore files build by xcode
*.mode*v*
*.pbxuser
*.xcbkptlist
*.xcscheme
*.xcworkspacedata
*.xcuserstate
xcschememanagement.plist
build/
.DS_Store
._.*
xcuserdata/
DerivedData/
.idea/*
# Ignore the files from download
bin/sdkbox*
plugins/plugin_compile/build_web/bin
plugins/plugin_jscompile/
plugins/plugin_luacompile/bin/msvcr110.dll
plugins/plugin_generate/proj_modifier/plutil-win32/
version.json
v*-console-*.zip
# vim
*~
# Ignore the files generated by toexec/build-console
toexec/output/
toexec/build/

View File

@@ -0,0 +1,142 @@
# cocos2d-console
## Download
```sh
$ NOT DONE YET
```
## Install
```sh
$ NOT DONE YET
```
## Vision of cocos2d-console
A command line tool that lets you create, run, publish, debug, etc… your game. It is the swiss-army knife for cocos2d.
This command line tool is in its early stages.
Examples:
```
# starts a new project called "My Game" for multi-platform
$ cocos new MyGame -l cpp -p org.cocos2d.mygame
$ cd MyGame
# Will deploy the project to device and run it
$ cocos run -p android
```
# Devel Info
## Internals
`cocos.py` is an script whose only responsability is to call its plugins.
`cocos.bat` will invoke `cocos.py` on windows
`cocos` will invoke `cocos.py` on Mac OS X and linux
To get a list of all the registered plugins:
```
$ cocos
```
To run the "new" plugin:
```
$ cocos new
```
## Adding a new plugin to the console
You have to edit `bin/cocos2d.ini`, and add the class name of your new plugin there. Let's say that you want to add a plugin that deploys the project:
```
# should be a subclass of CCPlugin
project_deploy.CCPluginDeploy
```
And now you have to create a file called `project_deploy.py` in the `plugins` folder.
A new, empty plugin, would look like the code shown below:
```
import cocos
# Plugins should be a sublass of CCPlugin
class CCPluginDeploy(cocos.CCPlugin):
# in default category
@staticmethod
def plugin_category():
return ""
@staticmethod
def plugin_name():
return "deploy"
@staticmethod
def brief_description():
return "Deploy the project to target."
def run(self, argv, dependencies):
print "plugin called!"
print argv
```
Plugins are divided by category, depending on it's function: project, engine, ...
The plugins of `project` is in default category, it's an empty stirng `""`.
# Generate Executable
Now you can use the `toexec/build_console.py` for generating a executable file of `cocos` command.
## Environment Requirement
* [Python 2.7](https://www.python.org) (2.7.5 is well tested)
* [PyInstaller](https://pypi.python.org/pypi/PyInstaller) (PyInstaller 2.1 is well tested)
* Necessary PATH environment for python & pyinstaller.
__Attention:To keep compatible with both Windows-32bit & Windows-64bit, please install 32bit python on Windows.__
## Steps
Run `python build_console.py` in command line. Then the executable file & necessary files will be generated in `toexec/output/PLATFORM`.
The usage of `build_console.py`:
```
usage: build_console.py [-h] [-s SRC_PATH] [-d DST_PATH]
Generate executable file for cocos2d-console by PyInstaller.
optional arguments:
-h, --help show this help message and exit
-s SRC_PATH, --src-path SRC_PATH
Specify the path of cocos2d-console.
-d DST_PATH, --dst-path DST_PATH
Specify the path of output.
```
## Using the Executable
The generated executable files can replace the source code of cocos2d-console.
To fit the limitation of the cocos2d-console implementation. The generated executable files should located at `ENGINE_PATH/tools/cocos2d-console/bin`.
Then you can use the executable file as same as the source code.
# Commands Required
Please see this [issue](https://github.com/cocos2d/cocos2d-console/issues/27)

View File

@@ -0,0 +1,6 @@
{
"version":"creator-console-2",
"zip_file_size":"45045282",
"repo_name":"console-binary",
"repo_parent":"https://github.com/cocos2d/"
}

View File

@@ -0,0 +1,307 @@
#!/usr/bin/env python
#coding=utf-8
#
# ./download-bin.py
#
# Download cocos2d-console resources from github (https://github.com/natural-law/console-binary) and extract from ZIP
#
# Helps prevent repo bloat due to large binary files since they can
# be hosted separately.
#
"""****************************************************************************
Copyright (c) 2014 cocos2d-x.org
Copyright (c) 2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************"""
import os.path,zipfile
import shutil
import sys
import traceback
import distutils
import fileinput
import json
from optparse import OptionParser
from time import time
from sys import stdout
from distutils.errors import DistutilsError
from distutils.dir_util import copy_tree, remove_tree
class UnrecognizedFormat:
def __init__(self, prompt):
self._prompt = prompt
def __str__(self):
return self._prompt
class CocosZipInstaller(object):
def __init__(self, workpath, config_path, version_path, remote_version_key = None):
self._workpath = workpath
self._config_path = config_path
self._version_path = version_path
data = self.load_json_file(config_path)
self._current_version = data["version"]
self._repo_name = data["repo_name"]
self._filename = self._current_version + '.zip'
self._url = data["repo_parent"] + self._repo_name + '/archive/' + self._filename
self._zip_file_size = int(data["zip_file_size"])
current_version = self._current_version
# 'v' letter was swallowed by github, so we need to substring it from the 2nd letter
if current_version[0] == 'v':
current_version = current_version[1:]
self._extracted_folder_name = self._repo_name + '-' + current_version
try:
data = self.load_json_file(version_path)
if remote_version_key == None:
self._remote_version = data["version"]
else:
self._remote_version = data[remote_version_key]
except:
print("==> version file doesn't exist")
def get_input_value(self, prompt):
ret = raw_input(prompt)
ret.rstrip(" \t")
return ret
def download_file(self):
print("==> Ready to download '%s' from '%s'" % (self._filename, self._url))
import urllib2
try:
u = urllib2.urlopen(self._url)
except urllib2.HTTPError as e:
if e.code == 404:
print("==> Error: Could not find the file from url: '%s'" % (self._url))
print("==> Http request failed, error code: " + str(e.code) + ", reason: " + e.read())
sys.exit(1)
f = open(self._filename, 'wb')
meta = u.info()
content_len = meta.getheaders("Content-Length")
file_size = 0
if content_len and len(content_len) > 0:
file_size = int(content_len[0])
else:
# github server may not reponse a header information which contains `Content-Length`,
# therefore, the size needs to be written hardcode here. While server doesn't return
# `Content-Length`, use it instead
print("==> WARNING: Couldn't grab the file size from remote, use 'zip_file_size' section in '%s'" % self._config_path)
file_size = self._zip_file_size
print("==> Start to download, please wait ...")
file_size_dl = 0
block_sz = 8192
block_size_per_second = 0
old_time=time()
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
block_size_per_second += len(buffer)
f.write(buffer)
new_time = time()
if (new_time - old_time) > 1:
speed = block_size_per_second / (new_time - old_time) / 1000.0
status = ""
if file_size != 0:
percent = file_size_dl * 100. / file_size
status = r"Downloaded: %6dK / Total: %dK, Percent: %3.2f%%, Speed: %6.2f KB/S " % (file_size_dl / 1000, file_size / 1000, percent, speed)
else:
status = r"Downloaded: %6dK, Speed: %6.2f KB/S " % (file_size_dl / 1000, speed)
status = status + chr(8)*(len(status)+1)
print(status),
sys.stdout.flush()
block_size_per_second = 0
old_time = new_time
print("==> Downloading finished!")
f.close()
def ensure_directory(self, target):
if not os.path.exists(target):
os.mkdir(target)
def unpack_zipfile(self, extract_dir):
"""Unpack zip `filename` to `extract_dir`
Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined
by ``zipfile.is_zipfile()``).
"""
if not zipfile.is_zipfile(self._filename):
raise UnrecognizedFormat("%s is not a zip file" % (self._filename))
print("==> Extracting files, please wait ...")
z = zipfile.ZipFile(self._filename)
try:
for info in z.infolist():
name = info.filename
# don't extract absolute paths or ones with .. in them
if name.startswith('/') or '..' in name:
continue
target = os.path.join(extract_dir, *name.split('/'))
if not target:
continue
if name.endswith('/'):
# directory
self.ensure_directory(target)
else:
# file
data = z.read(info.filename)
f = open(target,'wb')
try:
f.write(data)
finally:
f.close()
del data
unix_attributes = info.external_attr >> 16
if unix_attributes:
os.chmod(target, unix_attributes)
finally:
z.close()
print("==> Extraction done!")
def ask_to_delete_downloaded_zip_file(self):
ret = self.get_input_value("==> Whether to delete '%s' file? It may be reused when you execute this script next time! (yes/no): " % self._filename)
ret = ret.strip()
if ret != 'yes' and ret != 'no':
print("==> Invalid answer, please answer 'yes' or 'no'!")
return self.ask_to_delete_downloaded_zip_file()
else:
return True if ret == 'yes' else False
def download_zip_file(self):
if not os.path.isfile(self._filename):
self.download_file()
try:
if not zipfile.is_zipfile(self._filename):
raise UnrecognizedFormat("%s is not a zip file" % (self._filename))
except UnrecognizedFormat as e:
print("==> Unrecognized zip format from your local '%s' file!" % (self._filename))
if os.path.isfile(self._filename):
os.remove(self._filename)
print("==> Download it from internet again, please wait...")
self.download_zip_file()
def need_to_update(self):
if not os.path.isfile(self._version_path):
return True
with open(self._version_path) as data_file:
data = json.load(data_file)
if self._remote_version == self._current_version:
return False
return True
def load_json_file(self, file_path):
if not os.path.isfile(file_path):
raise Exception("Could not find (%s)" % (file_path))
with open(file_path) as data_file:
data = json.load(data_file)
return data
def run(self, folder_for_extracting, remove_downloaded, force_update, download_only):
if not force_update and not self.need_to_update():
print("==> Not need to update!")
return
if os.path.exists(self._extracted_folder_name):
shutil.rmtree(self._extracted_folder_name)
self.download_zip_file()
if not download_only:
self.unpack_zipfile(self._workpath)
print("==> Copying files...")
dst_folder_path = os.path.join(self._workpath, folder_for_extracting)
if not os.path.exists(dst_folder_path):
os.makedirs(dst_folder_path)
distutils.dir_util.copy_tree(self._extracted_folder_name, dst_folder_path)
print("==> Cleaning...")
if os.path.exists(self._extracted_folder_name):
shutil.rmtree(self._extracted_folder_name)
if os.path.isfile(self._filename):
if remove_downloaded != None:
if remove_downloaded == 'yes':
os.remove(self._filename)
elif self.ask_to_delete_downloaded_zip_file():
os.remove(self._filename)
else:
print("==> Download (%s) finish!" % self._filename)
def _check_python_version():
major_ver = sys.version_info[0]
if major_ver > 2:
print ("The python version is %d.%d. But python 2.x is required. (Version 2.7 is well tested)\n"
"Download it here: https://www.python.org/" % (major_ver, sys.version_info[1]))
return False
return True
def main():
workpath = os.path.dirname(os.path.realpath(__file__))
if not _check_python_version():
sys.exit(1)
parser = OptionParser()
parser.add_option('-r', '--remove-download',
action="store", type="string", dest='remove_downloaded', default=None,
help="Whether to remove downloaded zip file, 'yes' or 'no'")
parser.add_option("-f", "--force-update",
action="store_true", dest="force_update", default=False,
help="Whether to force update the third party libraries")
parser.add_option("-d", "--download-only",
action="store_true", dest="download_only", default=False,
help="Only download zip file of the third party libraries, will not extract it")
(opts, args) = parser.parse_args()
print("=======================================================")
print("==> Prepare to download console binaries!")
installer = CocosZipInstaller(workpath, os.path.join(workpath, 'config.json'), os.path.join(workpath, 'version.json'), "version")
installer.run("", opts.remove_downloaded, opts.force_update, opts.download_only)
# -------------- main --------------
if __name__ == '__main__':
try:
main()
except Exception as e:
traceback.print_exc()
sys.exit(1)

View File

@@ -0,0 +1,65 @@
#!/usr/bin/python
# ----------------------------------------------------------------------------
# cocos2d "clean" plugin
#
# Author: Luis Parravicini
#
# License: MIT
# ----------------------------------------------------------------------------
'''
"clean" plugin for cocos2d command line tool
'''
__docformat__ = 'restructuredtext'
import os
import shutil
import cocos2d
from plugin_dist import CCPluginDist
class CCPluginClean(cocos2d.CCPlugin):
"""
cleans a project
"""
@staticmethod
def plugin_name():
return "clean"
@staticmethod
def brief_description():
return "removes files produced by compilation"
def clean_android(self):
if not self._platforms.is_android_active():
return
project_dir = self._platforms.project_path()
cocos2d.Logging.info("cleaning native")
obj_path = os.path.join(project_dir, 'obj')
self._rmdir(obj_path)
cocos2d.Logging.info("cleaning java")
self._run_cmd("cd \"%s\" && ant clean" % project_dir)
def clean_ios(self):
if not self._platforms.is_ios_active():
return
project_dir = self._platforms.project_path()
cocos2d.Logging.info("removing intermediate files")
self._run_cmd("cd \"%s\" && xcodebuild clean" % project_dir)
self._rmdir(CCPluginDist.target_path(project_dir))
def _rmdir(self, path):
if os.path.exists(path):
try:
shutil.rmtree(path)
except OSError as e:
raise cocos2d.CCPluginError("Error removing directory: " + str(e.args))
def run(self, argv, dependencies):
self.parse_args(argv)
self.clean_android()
self.clean_ios()

View File

@@ -0,0 +1 @@
from project_compile import CCPluginCompile

View File

@@ -0,0 +1,539 @@
#!/usr/bin/python
# build_native.py
# Build native codes
import sys
import os, os.path
import shutil
from optparse import OptionParser
import cocos
from MultiLanguage import MultiLanguage
import cocos_project
import json
import re
from xml.dom import minidom
import utils
import project_compile
BUILD_CFIG_FILE="build-cfg.json"
class AndroidBuilder(object):
CFG_KEY_COPY_TO_ASSETS = "copy_to_assets"
CFG_KEY_MUST_COPY_TO_ASSERTS = "must_copy_to_assets"
CFG_KEY_STORE = "key_store"
CFG_KEY_STORE_PASS = "key_store_pass"
CFG_KEY_ALIAS = "alias"
CFG_KEY_ALIAS_PASS = "alias_pass"
GRADLE_KEY_STORE = "RELEASE_STORE_FILE"
GRADLE_KEY_ALIAS = "RELEASE_KEY_ALIAS"
GRADLE_KEY_STORE_PASS = "RELEASE_STORE_PASSWORD"
GRADLE_KEY_ALIAS_PASS = "RELEASE_KEY_PASSWORD"
def __init__(self, verbose, app_android_root, no_res, proj_obj):
self._verbose = verbose
self.app_android_root = app_android_root
self._no_res = no_res
self._project = proj_obj
# check environment variable
self.sdk_root = cocos.check_environment_variable('ANDROID_SDK_ROOT')
self.sign_prop_file = os.path.join(self.app_android_root, "gradle.properties")
self._parse_cfg()
def _run_cmd(self, command, cwd=None):
cocos.CMDRunner.run_cmd(command, self._verbose, cwd=cwd)
def _parse_cfg(self):
self.cfg_path = os.path.join(self.app_android_root, BUILD_CFIG_FILE)
try:
f = open(self.cfg_path)
cfg = json.load(f, encoding='utf8')
f.close()
except Exception:
raise cocos.CCPluginError(MultiLanguage.get_string('COMPILE_ERROR_PARSE_CFG_FAILED_FMT', self.cfg_path),
cocos.CCPluginError.ERROR_PARSE_FILE)
if cfg.has_key(project_compile.CCPluginCompile.CFG_KEY_MUST_COPY_RESOURCES):
if self._no_res:
self.res_files = cfg[project_compile.CCPluginCompile.CFG_KEY_MUST_COPY_RESOURCES]
else:
self.res_files = cfg[project_compile.CCPluginCompile.CFG_KEY_MUST_COPY_RESOURCES] + cfg[project_compile.CCPluginCompile.CFG_KEY_COPY_RESOURCES]
else:
self.res_files = cfg[project_compile.CCPluginCompile.CFG_KEY_COPY_RESOURCES]
self.ndk_module_paths = cfg['ndk_module_path']
# get the properties for sign release apk
self.key_store_str = AndroidBuilder.GRADLE_KEY_STORE
self.key_alias_str = AndroidBuilder.GRADLE_KEY_ALIAS
self.key_store_pass_str = AndroidBuilder.GRADLE_KEY_STORE_PASS
self.key_alias_pass_str = AndroidBuilder.GRADLE_KEY_ALIAS_PASS
move_cfg = {}
self.key_store = None
if cfg.has_key(AndroidBuilder.CFG_KEY_STORE):
self.key_store = cfg[AndroidBuilder.CFG_KEY_STORE]
move_cfg[self.key_store_str] = self.key_store
del cfg[AndroidBuilder.CFG_KEY_STORE]
self.key_store_pass = None
if cfg.has_key(AndroidBuilder.CFG_KEY_STORE_PASS):
self.key_store_pass = cfg[AndroidBuilder.CFG_KEY_STORE_PASS]
move_cfg[self.key_store_pass_str] = self.key_store_pass
del cfg[AndroidBuilder.CFG_KEY_STORE_PASS]
self.alias = None
if cfg.has_key(AndroidBuilder.CFG_KEY_ALIAS):
self.alias = cfg[AndroidBuilder.CFG_KEY_ALIAS]
move_cfg[self.key_alias_str] = self.alias
del cfg[AndroidBuilder.CFG_KEY_ALIAS]
self.alias_pass = None
if cfg.has_key(AndroidBuilder.CFG_KEY_ALIAS_PASS):
self.alias_pass = cfg[AndroidBuilder.CFG_KEY_ALIAS_PASS]
move_cfg[self.key_alias_pass_str] = self.alias_pass
del cfg[AndroidBuilder.CFG_KEY_ALIAS_PASS]
if len(move_cfg) > 0:
# move the config into ant.properties
self._move_cfg(move_cfg)
with open(self.cfg_path, 'w') as outfile:
json.dump(cfg, outfile, sort_keys = True, indent = 4)
outfile.close()
def has_keystore_in_signprops(self):
keystore = None
pattern = re.compile(r"^RELEASE_STORE_FILE=(.+)")
try:
file_obj = open(self.sign_prop_file)
for line in file_obj:
str1 = line.replace(' ', '')
str2 = str1.replace('\t', '')
match = pattern.match(str2)
if match is not None:
keystore = match.group(1)
break
file_obj.close()
except:
pass
if keystore is None:
return False
else:
return True
def _write_sign_properties(self, cfg):
file_obj = open(self.sign_prop_file, "a+")
for key in cfg.keys():
str_cfg = "%s=%s\n" % (key, cfg[key])
file_obj.write(str_cfg)
file_obj.close()
def _move_cfg(self, cfg):
if not self.has_keystore_in_signprops():
self._write_sign_properties(cfg)
def remove_c_libs(self, libs_dir):
for file_name in os.listdir(libs_dir):
lib_file = os.path.join(libs_dir, file_name)
if os.path.isfile(lib_file):
ext = os.path.splitext(lib_file)[1]
if ext == ".a" or ext == ".so":
os.remove(lib_file)
def _get_android_sdk_tools_ver(self, sdk_tools_path):
cfg_file = os.path.join(sdk_tools_path, 'source.properties')
if os.path.isfile(cfg_file):
f = open(cfg_file)
lines = f.readlines()
pattern = r'^Pkg\.Revision=(\d+)\.(\d+)'
for l in lines:
match = re.match(pattern, l.strip())
if match:
return ((int)(match.group(1)), (int)(match.group(2)))
raise cocos.CCPluginError(MultiLanguage.get_string('COMPILE_ERROR_UNKNOWN_ANDROID_SDK_TOOLS_VERSION'),
cocos.CCPluginError.ERROR_PATH_NOT_FOUND)
def _update_project_properties(self, folder_path, target_str):
props_path = os.path.join(folder_path, 'project.properties')
f = open(props_path)
lines = f.readlines()
f.close()
pattern = r'^target=(.*)$'
matched = False
new_line = 'target=%s\n' % target_str
for i in range(0, len(lines)):
l = lines[i]
match = re.match(pattern, l.strip())
if match:
lines[i] = new_line
matched = True
if not matched:
lines.append('\n')
lines.append(new_line)
f = open(props_path, 'w')
f.writelines(lines)
f.close()
def _write_local_properties(self, folder_path):
local_porps_path = os.path.join(folder_path, 'local.properties')
sdk_dir = self.sdk_root
ndk_dir = cocos.check_environment_variable('NDK_ROOT')
if cocos.os_is_win32():
# On Windows, the path should be like:
# sdk.dir = C:\\path\\android-sdk
sdk_dir = sdk_dir.replace('\\', '\\\\')
ndk_dir = ndk_dir.replace('\\', '\\\\')
lines = [
'sdk.dir=%s\n' % sdk_dir,
'ndk.dir=%s\n' % ndk_dir
]
f = open(local_porps_path, 'w')
f.writelines(lines)
f.close()
def update_project(self, android_platform):
manifest_path = os.path.join(self.app_android_root, 'app')
# check the android platform
target_str = self.check_android_platform(self.sdk_root, android_platform, manifest_path)
# should manually update the project
self._write_local_properties(manifest_path)
self._update_project_properties(manifest_path, target_str)
# copy the local.properties to the app_android_root
file_name = 'local.properties'
src_path = os.path.normpath(os.path.join(manifest_path, file_name))
dst_path = os.path.normpath(os.path.join(self.app_android_root, file_name))
if src_path != dst_path:
if os.path.isfile(dst_path):
os.remove(dst_path)
shutil.copy(src_path, dst_path)
def get_toolchain_version(self, ndk_root, compile_obj):
return "4.9"
def do_ndk_build(self, ndk_build_param, build_mode, compile_obj):
cocos.Logging.info(MultiLanguage.get_string('COMPILE_INFO_NDK_MODE', build_mode))
ndk_root = cocos.check_environment_variable('NDK_ROOT')
toolchain_version = self.get_toolchain_version(ndk_root, compile_obj)
ndk_work_dir = os.path.join(self.app_android_root, 'app')
reload(sys)
sys.setdefaultencoding('utf8')
ndk_path = cocos.CMDRunner.convert_path_to_cmd(os.path.join(ndk_root, "ndk-build"))
module_paths = []
for cfg_path in self.ndk_module_paths:
the_path = cocos.replace_env_variable(cfg_path)
if not os.path.isabs(the_path):
the_path = os.path.normpath(os.path.join(self.app_android_root, the_path))
module_paths.append(the_path)
# delete template static and dynamic files
obj_local_dir = os.path.join(ndk_work_dir, "obj", "local")
if os.path.isdir(obj_local_dir):
for abi_dir in os.listdir(obj_local_dir):
static_file_path = os.path.join(ndk_work_dir, "obj", "local", abi_dir)
if os.path.isdir(static_file_path):
self.remove_c_libs(static_file_path)
# windows should use ";" to seperate module paths
if cocos.os_is_win32():
ndk_module_path = ';'.join(module_paths)
else:
ndk_module_path = ':'.join(module_paths)
ndk_module_path= 'NDK_MODULE_PATH=' + ndk_module_path
if ndk_build_param is None:
ndk_build_cmd = '%s -C %s %s' % (ndk_path, ndk_work_dir, ndk_module_path)
else:
ndk_build_cmd = '%s -C %s %s %s' % (ndk_path, ndk_work_dir, ' '.join(ndk_build_param), ndk_module_path)
ndk_build_cmd = '%s NDK_TOOLCHAIN_VERSION=%s' % (ndk_build_cmd, toolchain_version)
if build_mode == 'debug':
ndk_build_cmd = '%s NDK_DEBUG=1' % ndk_build_cmd
self._run_cmd(ndk_build_cmd)
def _xml_attr(self, dir, file_name, node_name, attr):
doc = minidom.parse(os.path.join(dir, file_name))
return doc.getElementsByTagName(node_name)[0].getAttribute(attr)
def update_lib_projects(self, sdk_root, sdk_tool_path, android_platform, property_path):
property_file = os.path.join(property_path, "project.properties")
if not os.path.isfile(property_file):
return
patten = re.compile(r'^android\.library\.reference\.[\d]+=(.+)')
for line in open(property_file):
str1 = line.replace(' ', '')
str2 = str1.replace('\t', '')
match = patten.match(str2)
if match is not None:
# a lib project is found
lib_path = match.group(1)
abs_lib_path = os.path.join(property_path, lib_path)
abs_lib_path = os.path.normpath(abs_lib_path)
if os.path.isdir(abs_lib_path):
target_str = self.check_android_platform(sdk_root, android_platform, abs_lib_path)
command = "%s update lib-project -p %s -t %s" % (cocos.CMDRunner.convert_path_to_cmd(sdk_tool_path), abs_lib_path, target_str)
self._run_cmd(command)
self.update_lib_projects(sdk_root, sdk_tool_path, android_platform, abs_lib_path)
def get_api_level(self, target_str, raise_error=True):
match = re.match(r'android-(\d+)', target_str)
if match is not None:
ret = int(match.group(1))
else:
if raise_error:
raise cocos.CCPluginError(MultiLanguage.get_string('COMPILE_ERROR_NOT_VALID_AP_FMT', target_str),
cocos.CCPluginError.ERROR_PARSE_FILE)
else:
ret = -1
return ret
def get_target_config(self, proj_path):
property_file = os.path.join(proj_path, "project.properties")
if not os.path.isfile(property_file):
raise cocos.CCPluginError(MultiLanguage.get_string('COMPILE_ERROR_FILE_NOT_FOUND_FMT', property_file),
cocos.CCPluginError.ERROR_PATH_NOT_FOUND)
patten = re.compile(r'^target=(.+)')
for line in open(property_file):
str1 = line.replace(' ', '')
str2 = str1.replace('\t', '')
match = patten.match(str2)
if match is not None:
target = match.group(1)
target_num = self.get_api_level(target)
if target_num > 0:
return target_num
raise cocos.CCPluginError(MultiLanguage.get_string('COMPILE_ERROR_TARGET_NOT_FOUND_FMT', property_file),
cocos.CCPluginError.ERROR_PARSE_FILE)
# check the selected android platform
def check_android_platform(self, sdk_root, android_platform, proj_path):
ret = android_platform
if android_platform is None:
min_platform = self.get_target_config(proj_path)
# not specified platform, use the one in project.properties
ret = 'android-%d' % min_platform
ret_path = os.path.join(cocos.CMDRunner.convert_path_to_python(sdk_root), "platforms", ret)
if not os.path.isdir(ret_path):
raise cocos.CCPluginError(MultiLanguage.get_string('COMPILE_ERROR_NO_AP_IN_SDK_FMT', ret),
cocos.CCPluginError.ERROR_PATH_NOT_FOUND)
return ret
def gradle_build_apk(self, build_mode, instant_game):
# check the compileSdkVersion & buildToolsVersion
check_file = os.path.join(self.app_android_root, 'app', 'build.gradle')
f = open(check_file)
lines = f.readlines()
f.close()
compile_sdk_ver = None
build_tools_ver = None
compile_sdk_pattern = r'compileSdkVersion[ \t]+([\d]+)'
build_tools_pattern = r'buildToolsVersion[ \t]+"(.+)"'
for line in lines:
line_str = line.strip()
match1 = re.match(compile_sdk_pattern, line_str)
if match1:
compile_sdk_ver = match1.group(1)
match2 = re.match(build_tools_pattern, line_str)
if match2:
build_tools_ver = match2.group(1)
if compile_sdk_ver is not None:
# check the compileSdkVersion
check_folder_name = 'android-%s' % compile_sdk_ver
check_path = os.path.join(self.sdk_root, 'platforms', check_folder_name)
if not os.path.isdir(check_path):
cocos.Logging.warning(MultiLanguage.get_string('COMPILE_WARNING_COMPILE_SDK_FMT',
(compile_sdk_ver, check_path)))
if build_tools_ver is not None:
# check the buildToolsVersion
check_path = os.path.join(self.sdk_root, 'build-tools', build_tools_ver)
if not os.path.isdir(check_path):
cocos.Logging.warning(MultiLanguage.get_string('COMPILE_WARNING_BUILD_TOOLS_FMT',
(build_tools_ver, check_path)))
# invoke gradlew for gradle building
if cocos.os_is_win32():
gradle_path = os.path.join(self.app_android_root, 'gradlew.bat')
else:
gradle_path = os.path.join(self.app_android_root, 'gradlew')
if not os.path.isfile(gradle_path):
raise cocos.CCPluginError(MultiLanguage.get_string('COMPILE_ERROR_GRALEW_NOT_EXIST_FMT', gradle_path),
cocos.CCPluginError.ERROR_PATH_NOT_FOUND)
mode_str = 'Debug' if build_mode == 'debug' else 'Release'
cmd = '"%s" --parallel --info ' % (gradle_path)
if instant_game:
cmd += ':instantapp:'
cmd += 'assemble%s' % (mode_str)
self._run_cmd(cmd, cwd=self.app_android_root)
def do_build_apk(self, build_mode, no_apk, instant_game, output_dir, custom_step_args, compile_obj):
project_name = None
setting_file = os.path.join(self.app_android_root, 'settings.gradle')
if os.path.isfile(setting_file):
# get project name from settings.gradle
f = open(setting_file)
lines = f.readlines()
f.close()
pattern = r"project\(':(.*)'\)\.projectDir[ \t]*=[ \t]*new[ \t]*File\(settingsDir, 'app'\)"
for line in lines:
line_str = line.strip()
match = re.match(pattern, line_str)
if match:
project_name = match.group(1)
break
if instant_game:
project_name = 'instantapp'
if project_name is None:
# use default project name
project_name = 'app'
if instant_game:
relative_path = '%s/build/outputs/apk' % (project_name)
gen_apk_folder = os.path.join(self.app_android_root, relative_path)
else:
gen_apk_folder = os.path.join(self.app_android_root, 'app/build/outputs/apk')
if not no_apk:
# remove old apk file
if os.path.isdir(gen_apk_folder):
shutil.rmtree(gen_apk_folder)
# gather the sign info if necessary
if build_mode == "release" and not self.has_keystore_in_signprops():
self._gather_sign_info()
# build apk
self.gradle_build_apk(build_mode, instant_game)
# copy the apk to output dir
if output_dir:
apk_name = '%s-%s' % (project_name, build_mode)
apk_name += '.apk'
gen_apk_path = os.path.join(gen_apk_folder, apk_name)
# Android Studio 2.x.x uses 'app/build/outputs/apk' as output directory,
# but Android Studio 3.x.x appends 'debug' or 'release' directory after 'app/build/outputs/apk'.
if not os.path.exists(gen_apk_path):
gen_apk_path = os.path.join(gen_apk_folder, build_mode, apk_name)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
shutil.copy(gen_apk_path, output_dir)
cocos.Logging.info(MultiLanguage.get_string('COMPILE_INFO_MOVE_APK_FMT', output_dir))
if build_mode == "release":
signed_name = "%s-%s-signed" % (project_name, build_mode)
signed_name += '.apk'
apk_path = os.path.join(output_dir, signed_name)
if os.path.exists(apk_path):
os.remove(apk_path)
os.rename(os.path.join(output_dir, apk_name), apk_path)
else:
apk_path = os.path.join(output_dir, apk_name)
return apk_path
else:
raise cocos.CCPluginError(MultiLanguage.get_string('COMPILE_ERROR_NOT_SPECIFY_OUTPUT'),
cocos.CCPluginError.ERROR_WRONG_ARGS)
def _gather_sign_info(self):
user_cfg = {}
# get the path of keystore file
while True:
inputed = self._get_user_input(MultiLanguage.get_string('COMPILE_TIP_INPUT_KEYSTORE'))
inputed = inputed.strip()
if not os.path.isabs(inputed):
start_path = os.path.join(self.app_android_root, 'app')
abs_path = os.path.join(start_path, inputed)
else:
abs_path = inputed
if os.path.isfile(abs_path):
user_cfg[self.key_store_str] = inputed.replace('\\', '/')
break
else:
cocos.Logging.warning(MultiLanguage.get_string('COMPILE_INFO_NOT_A_FILE'))
# get the alias of keystore file
user_cfg[self.key_alias_str] = self._get_user_input(MultiLanguage.get_string('COMPILE_TIP_INPUT_ALIAS'))
# get the keystore password
user_cfg[self.key_store_pass_str] = self._get_user_input(MultiLanguage.get_string('COMPILE_TIP_INPUT_KEY_PASS'))
# get the alias password
user_cfg[self.key_alias_pass_str] = self._get_user_input(MultiLanguage.get_string('COMPILE_TIP_INPUT_ALIAS_PASS'))
# write the config into ant.properties
self._write_sign_properties(user_cfg)
def _get_user_input(self, tip_msg):
cocos.Logging.warning(tip_msg)
ret = None
while True:
ret = raw_input()
break
return ret
def get_apk_info(self):
manifest_path = os.path.join(self.app_android_root, 'app')
gradle_cfg_path = os.path.join(manifest_path, 'build.gradle')
package = None
if os.path.isfile(gradle_cfg_path):
# get package name from build.gradle
f = open(gradle_cfg_path)
for line in f.readlines():
line_str = line.strip()
pattern = r'applicationId[ \t]+"(.*)"'
match = re.match(pattern, line_str)
if match:
package = match.group(1)
break
if package is None:
# get package name from AndroidManifest.xml
package = self._xml_attr(manifest_path, 'AndroidManifest.xml', 'manifest', 'package')
activity_name = self._xml_attr(manifest_path, 'AndroidManifest.xml', 'activity', 'android:name')
if activity_name.startswith('.'):
activity = package + activity_name
else:
activity = activity_name
ret = (package, activity)
return ret

View File

@@ -0,0 +1,145 @@
#!/usr/bin/python
import os
import json
import cocos
from MultiLanguage import MultiLanguage
import sys
import subprocess
JDK_1_7 = "1.7"
JDK_1_6 = "1.6"
def check_jdk_version():
commands = [
"java",
"-version"
]
child = subprocess.Popen(commands, stderr=subprocess.PIPE)
jdk_version = None
for line in child.stderr:
if 'java version' in line:
if '1.6' in line:
jdk_version = JDK_1_6
else:
jdk_version = JDK_1_7
child.wait()
if jdk_version is None:
raise cocos.CCPluginError(MultiLanguage.get_string('COMPILE_ERROR_NO_VALID_JDK'),
cocos.CCPluginError.ERROR_TOOLS_NOT_FOUND)
return jdk_version
def gen_buildxml(project_dir, project_json, output_dir, build_opts):
# get engine dir (not real)
engineDir = project_json["engineDir"]
# get real engine dir
engine_dir = os.path.normpath(os.path.join(project_dir, engineDir))
# get real publish dir
publish_dir = output_dir
# get tools dir
if getattr(sys, 'frozen', None):
tools_dir = os.path.realpath(os.path.dirname(sys.executable))
else:
tools_dir = os.path.realpath(os.path.dirname(__file__))
# download the binary files
compiler_1_6 = os.path.join(tools_dir, "bin", "compiler-1.6.jar")
compiler_1_7 = os.path.join(tools_dir, "bin", "compiler-1.7.jar")
if not os.path.exists(compiler_1_6) or not os.path.exists(compiler_1_7):
download_cmd_path = os.path.join(tools_dir, os.pardir, os.pardir, os.pardir)
subprocess.call("python %s -f" % (os.path.join(download_cmd_path, "download-bin.py")), shell=True, cwd=download_cmd_path)
try:
f = open(os.path.join(engine_dir, "moduleConfig.json"))
module_cfg = json.load(f)
finally:
f.close()
ccModuleMap = module_cfg["module"]
modules = project_json.get("modules", ["core"])
renderMode = project_json.get("renderMode", 0)
mainJs = project_json.get("main", "main.js")
ccJsList = [module_cfg["bootFile"]]
userJsList = project_json.get("jsList", [])
if renderMode != 1 and "base4webgl" not in modules:
modules[0:0] = ["base4webgl"]
for item in modules:
arr = _getJsListOfModule(ccModuleMap, item)
if arr != None:
ccJsList += arr
userJsList.append(mainJs)
buildXmlTempFile = open(os.path.join(tools_dir, "template", "build.xml"))
try:
buildContent = buildXmlTempFile.read()
finally:
buildXmlTempFile.close()
jdk_version = check_jdk_version()
sourceMapOpened = build_opts.get("sourceMapOpened")
if jdk_version == JDK_1_6:
sourceMapOpened = False
sourceMapContent = 'sourceMapOutputFile="' + os.path.join(publish_dir, "sourcemap") + '" sourceMapFormat="V3"' if sourceMapOpened else ""
buildContent = buildContent.replace("%projectDir%", project_dir)
buildContent = buildContent.replace("%engineDir%", engine_dir)
buildContent = buildContent.replace("%publishDir%", publish_dir)
buildContent = buildContent.replace("%outputFileName%", build_opts["outputFileName"])
buildContent = buildContent.replace("%toolsDir%", tools_dir)
buildContent = buildContent.replace("%compiler%", "compiler-%s.jar" % jdk_version)
buildContent = buildContent.replace("%compilationLevel%", build_opts["compilationLevel"])
buildContent = buildContent.replace("%sourceMapCfg%", sourceMapContent)
buildContent = buildContent.replace("%ccJsList%", _getFileArrStr(ccJsList))
buildContent = buildContent.replace("%userJsList%", _getFileArrStr(userJsList))
buildContent = buildContent.replace("%debug%", build_opts["debug"])
buildXmlOutputFile = open(os.path.join(publish_dir, "build.xml"), "w")
buildXmlOutputFile.write(buildContent)
buildXmlOutputFile.close()
_jsAddedCache = {}
def _getJsListOfModule(moduleMap, moduleName):
if _jsAddedCache.get(moduleName) != None:
return None
_jsAddedCache[moduleName] = True
jsList = []
tempList = moduleMap[moduleName]
for item in tempList:
if _jsAddedCache.get(item):
continue
extname = os.path.splitext(item)[1]
if extname == None or extname == "":
arr = _getJsListOfModule(moduleMap, item)
if arr != None:
jsList += arr
elif extname == ".js":
jsList.append(item)
_jsAddedCache[item] = True
return jsList
def _getFileArrStr(jsList):
str = ""
index = 0
for item in jsList:
str += ' <file name="' + item + '"/>\r\n'
return str

View File

@@ -0,0 +1,23 @@
<?xml version="1.0"?>
<project name="Javascript compress project" basedir="%projectDir%" default="compile">
<taskdef name="jscomp" classname="com.google.javascript.jscomp.ant.CompileTask"
classpath="%toolsDir%/bin/%compiler%"/>
<target name="compile">
<jscomp compilationLevel="%compilationLevel%"
warning="quiet"
debug="%debug%"
output="%publishDir%/%outputFileName%"
languagein="ECMASCRIPT5"
%sourceMapCfg%
>
<sources dir="%engineDir%">
%ccJsList%
</sources>
<sources dir="${basedir}">
%userJsList%
</sources>
</jscomp>
</target>
</project>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,231 @@
#!/usr/bin/python
# ----------------------------------------------------------------------------
# cocos "install" plugin
#
# Copyright 2013 (C) Luis Parravicini
#
# License: MIT
# ----------------------------------------------------------------------------
'''
"install" plugin for cocos command line tool
'''
__docformat__ = 'restructuredtext'
import os
import cocos
from MultiLanguage import MultiLanguage
class CCPluginDeploy(cocos.CCPlugin):
"""
Install a project
"""
@staticmethod
def depends_on():
return ('compile',)
@staticmethod
def plugin_name():
return "deploy"
@staticmethod
def brief_description():
return MultiLanguage.get_string('DEPLOY_BRIEF')
def _add_custom_options(self, parser):
parser.add_argument("-m", "--mode", dest="mode", default='debug',
help=MultiLanguage.get_string('DEPLOY_ARG_MODE'))
parser.add_argument("--instant-game", dest="instant_game", action="store_true",
help=MultiLanguage.get_string('DEPLOY_ARG_INSTANT_GAME'))
parser.add_argument("--launch-url", dest="launch_url", default='',
help=MultiLanguage.get_string('RUN_ARG_LAUNCH_URL'))
def _check_custom_options(self, args):
if args.mode != 'release':
args.mode = 'debug'
self._mode = 'debug'
self._instant_game = args.instant_game
self._launch_url = args.launch_url
if 'release' == args.mode:
self._mode = args.mode
def _is_debug_mode(self):
return self._mode == 'debug'
def _get_install_target_sdk_version(self, adb_path):
import subprocess
cmds = [adb_path, 'shell', 'getprop', 'ro.build.version.sdk']
child = subprocess.Popen(cmds, stdout=subprocess.PIPE)
out = child.stdout.read()
child.wait()
errCode = child.returncode
return (errCode, out)
def deploy_ios(self, dependencies):
if not self._platforms.is_ios_active():
return
compile_dep = dependencies['compile']
self._iosapp_path = compile_dep._iosapp_path
self._use_sdk = compile_dep.use_sdk
def deploy_mac(self, dependencies):
if not self._platforms.is_mac_active():
return
compile_dep = dependencies['compile']
self._macapp_path = compile_dep._macapp_path
self.target_name = compile_dep.target_name
def deploy_web(self, dependencies):
if not self._platforms.is_web_active():
return
compile_dep = dependencies['compile']
self.sub_url = compile_dep.sub_url
self.run_root = compile_dep.run_root
def deploy_win32(self, dependencies):
if not self._platforms.is_win32_active():
return
compile_dep = dependencies['compile']
self.run_root = compile_dep.run_root
self.project_name = compile_dep.project_name
def find_xap_deploy_tool(self):
import _winreg
import re
if cocos.os_is_32bit_windows():
reg_flag_list = [ _winreg.KEY_WOW64_32KEY ]
else:
reg_flag_list = [ _winreg.KEY_WOW64_64KEY, _winreg.KEY_WOW64_32KEY ]
pattern = re.compile(r"v(\d+).(\d+)")
find_ret = None
find_major = -1
find_minor = -1
for reg_flag in reg_flag_list:
cocos.Logging.info(MultiLanguage.get_string('DEPLOY_INFO_FIND_XAP_FMT',
("32bit" if reg_flag == _winreg.KEY_WOW64_32KEY else "64bit")))
try:
wp = _winreg.OpenKey(
_winreg.HKEY_LOCAL_MACHINE,
r"SOFTWARE\Microsoft\Microsoft SDKs\WindowsPhone",
0,
_winreg.KEY_READ | reg_flag
)
except:
# windows phone not found, continue
continue
i = 0
while True:
try:
version = _winreg.EnumKey(wp, i)
except:
break
i += 1
match = re.match(pattern, version)
if match:
major = int(match.group(1))
minor = int(match.group(2))
if major > 7:
try:
key = _winreg.OpenKey(wp, "%s\Install Path" % version)
value, type = _winreg.QueryValueEx(key, "Install Path")
tool_path = os.path.join(value, "Tools", "XAP Deployment", "XapDeployCmd.exe")
if os.path.isfile(tool_path):
if (find_ret is None) or (major > find_major) or (major == find_major and minor > find_minor):
find_ret = tool_path
find_major = major
find_minor = minor
except:
pass
return find_ret
def deploy_wp8(self, dependencies):
if not self._platforms.is_wp8_active():
return
compile_dep = dependencies['compile']
run_root = compile_dep.run_root
product_id = compile_dep.product_id
xap_file_name = compile_dep.xap_file_name
self.xap_path = os.path.join(run_root, xap_file_name)
# find the XapDeployCmd.exe
self.deploy_tool = self.find_xap_deploy_tool()
if self.deploy_tool is None:
raise cocos.CCPluginError(MultiLanguage.get_string('DEPLOY_ERROR_XAPCMD_NOT_FOUND'),
cocos.CCPluginError.ERROR_TOOLS_NOT_FOUND)
# uninstall the app on wp8 by product ID
try:
uninstall_cmd = '"%s" /uninstall %s /targetdevice:xd' % (self.deploy_tool, product_id)
self._run_cmd(uninstall_cmd)
except:
pass
def deploy_linux(self, dependencies):
if not self._platforms.is_linux_active():
return
compile_dep = dependencies['compile']
self.run_root = compile_dep.run_root
self.project_name = compile_dep.project_name
def deploy_android(self, dependencies):
if not self._platforms.is_android_active():
return
cocos.Logging.info(MultiLanguage.get_string('DEPLOY_INFO_INSTALLING_APK'))
compile_dep = dependencies['compile']
self.package = compile_dep.android_package
self.activity = compile_dep.android_activity
apk_path = compile_dep.apk_path
sdk_root = cocos.check_environment_variable('ANDROID_SDK_ROOT')
if self._instant_game:
ia_path = cocos.CMDRunner.convert_path_to_cmd(os.path.join(sdk_root, 'extras', 'google', 'instantapps', 'tools', 'ia.jar'))
if self._launch_url:
adb_install = "java -jar %s run -u %s %s" % (ia_path, self._launch_url, apk_path)
else:
adb_install = "java -jar %s run %s" % (ia_path, apk_path)
else:
adb_path = cocos.CMDRunner.convert_path_to_cmd(os.path.join(sdk_root, 'platform-tools', 'adb'))
# do uninstall only when that app is installed
if cocos.app_is_installed(adb_path, self.package):
adb_uninstall= "%s uninstall %s" % (adb_path, self.package)
self._run_cmd(adb_uninstall)
adb_install = "%s install -r \"%s\"" % (adb_path, apk_path)
self._run_cmd(adb_install)
def get_filename_by_extention(self, ext, path):
filelist = os.listdir(path)
for fname in filelist:
name, extention = os.path.splitext(fname)
if extention == ext:
return fname
return None
def run(self, argv, dependencies):
self.parse_args(argv)
cocos.Logging.info(MultiLanguage.get_string('DEPLOY_INFO_MODE_FMT', self._mode))
self.deploy_ios(dependencies)
self.deploy_mac(dependencies)
self.deploy_android(dependencies)
self.deploy_web(dependencies)
self.deploy_win32(dependencies)
self.deploy_linux(dependencies)
self.deploy_wp8(dependencies)

View File

@@ -0,0 +1,94 @@
#!/usr/bin/python
# ----------------------------------------------------------------------------
# cocos2d "dist" plugin
#
# Copyright 2014 (C) Luis Parravicini
#
# License: MIT
# ----------------------------------------------------------------------------
'''
"dist" plugin for cocos2d command line tool
'''
__docformat__ = 'restructuredtext'
import re
import os
import cocos2d
class CCPluginDist(cocos2d.CCPlugin):
"""
builds a project for distribution
"""
@staticmethod
def plugin_name():
return "dist"
@staticmethod
def brief_description():
return "builds a project for distribution"
def init(self, options, working_dir):
super(CCPluginDist, self).init(options, working_dir)
if self._platforms.is_ios_active():
if not options.provisioning:
raise cocos2d.CCPluginError("Provisioning profile is needed")
else:
self._provisioning = options.provisioning
def _add_custom_options(self, parser):
parser.add_option("-f", "--provisioning",
dest="provisioning",
help="provisioning profile to use (needed for iOS distribution)")
def dist_android(self):
if not self._platforms.is_android_active():
return
project_dir = self._platforms.project_path()
raise cocos2d.CCPluginError("unimplemented")
def _find_ios_scheme(self, project_dir):
out = self._output_for("cd \"%s\" && xcodebuild -list" % project_dir)
match = re.search('Schemes:(.*)', out, re.DOTALL)
if match is None:
raise cocos2d.CCPluginError("Couldn't find the schemes list")
schemes = match.group(1).split()
if len(schemes) == 0:
raise cocos2d.CCPluginError("Couldn't find a scheme")
return schemes[0]
@staticmethod
def target_path(project_dir):
return os.path.join(project_dir, '..', 'target')
def dist_ios(self):
if not self._platforms.is_ios_active():
return
project_dir = self._platforms.project_path()
scheme = self._find_ios_scheme(project_dir)
cocos2d.Logging.info("using scheme %s" % scheme)
archive_path = os.path.join(CCPluginDist.target_path(project_dir), scheme + '.xcarchive')
cocos2d.Logging.info("archiving")
self._run_cmd("cd '%s' && xcodebuild -scheme '%s' -archivePath '%s' archive" % (project_dir, scheme, archive_path))
cocos2d.Logging.info("exporting archive")
ipa_path = os.path.join(os.path.dirname(archive_path), scheme + '.ipa')
if os.path.exists(ipa_path):
os.remove(ipa_path)
self._run_cmd("cd '%s' && xcodebuild -exportArchive -exportFormat IPA -archivePath '%s' -exportPath '%s' -exportProvisioningProfile '%s'" % (project_dir, archive_path, ipa_path, self._provisioning))
cocos2d.Logging.info("\nThe ipa was created at:\n%s" % os.path.abspath(ipa_path))
cocos2d.Logging.info("\nNow you can use 'Application Loader' to submit the .ipa\n")
def run(self, argv, dependencies):
self.parse_args(argv)
self.dist_android()
self.dist_ios()

View File

@@ -0,0 +1,2 @@
from plugin_framework import CCPluginFramework

View File

@@ -0,0 +1,31 @@
import cocos
from MultiLanguage import MultiLanguage
from package.helper import ProjectHelper
class FrameworkAdd(cocos.CCPlugin):
@staticmethod
def plugin_name():
return "add-framework"
@staticmethod
def brief_description():
return MultiLanguage.get_string('FRAMEWORK_ADD_BRIEF')
# parse arguments
def parse_args(self, argv):
from argparse import ArgumentParser
parser = ArgumentParser(prog="cocos %s" % self.__class__.plugin_name(),
description=self.__class__.brief_description())
parser.add_argument("name", metavar="NAME", help=MultiLanguage.get_string('FRAMEWORK_ADD_ARG_NAME'))
return parser.parse_args(argv)
def run(self, argv):
args = self.parse_args(argv)
name = args.name
project = ProjectHelper.get_current_project()
ProjectHelper.add_framework(project, name)

View File

@@ -0,0 +1,31 @@
import cocos
from MultiLanguage import MultiLanguage
from package.helper import ProjectHelper
class FrameworkCreate(cocos.CCPlugin):
@staticmethod
def plugin_name():
return "create-framework"
@staticmethod
def brief_description():
return MultiLanguage.get_string('FRAMEWORK_CREATE_BRIEF')
# parse arguments
def parse_args(self, argv):
from argparse import ArgumentParser
parser = ArgumentParser(prog="cocos %s" % self.__class__.plugin_name(),
description=self.__class__.brief_description())
parser.add_argument("name", metavar="NAME", help=MultiLanguage.get_string('FRAMEWORK_CREATE_ARG_NAME'))
return parser.parse_args(argv)
def run(self, argv):
args = self.parse_args(argv)
name = args.name
project = ProjectHelper.get_current_project()
ProjectHelper.create_framework(project, name)

View File

@@ -0,0 +1,31 @@
import cocos
from MultiLanguage import MultiLanguage
from package.helper import ProjectHelper
class FrameworkRemove(cocos.CCPlugin):
@staticmethod
def plugin_name():
return "remove-framework"
@staticmethod
def brief_description():
return MultiLanguage.get_string('FRAMEWORK_REMOVE_BRIEF')
# parse arguments
def parse_args(self, argv):
from argparse import ArgumentParser
parser = ArgumentParser(prog="cocos %s" % self.__class__.plugin_name(),
description=self.__class__.brief_description())
parser.add_argument("name", metavar="NAME", help=MultiLanguage.get_string('FRAMEWORK_REMOVE_ARG_NAME'))
return parser.parse_args(argv)
def run(self, argv):
args = self.parse_args(argv)
name = args.name
project = ProjectHelper.get_current_project()
ProjectHelper.remove_framework(project, name)

View File

@@ -0,0 +1,31 @@
import cocos
from MultiLanguage import MultiLanguage
from package.helper import ProjectHelper
class FrameworkSet(cocos.CCPlugin):
@staticmethod
def plugin_name():
return "set-framework"
@staticmethod
def brief_description():
return MultiLanguage.get_string('FRAMEWORK_SET_BRIEF')
# parse arguments
def parse_args(self, argv):
from argparse import ArgumentParser
parser = ArgumentParser(prog="cocos %s" % self.__class__.plugin_name(),
description=self.__class__.brief_description())
parser.add_argument("name", metavar="NAME", help=MultiLanguage.get_string('FRAMEWORK_SET_ARG_NAME'))
return parser.parse_args(argv)
def run(self, argv):
args = self.parse_args(argv)
name = args.name
project = ProjectHelper.get_current_project()
ProjectHelper.set_framework(project, name, "1.0")

View File

@@ -0,0 +1,31 @@
import cocos
from MultiLanguage import MultiLanguage
from package.helper import ProjectHelper
class FrameworkUpdate(cocos.CCPlugin):
@staticmethod
def plugin_name():
return "update-framework"
@staticmethod
def brief_description():
return MultiLanguage.get_string('FRAMEWORK_UPDATE_BRIEF')
# parse arguments
def parse_args(self, argv):
from argparse import ArgumentParser
parser = ArgumentParser(prog="cocos %s" % self.__class__.plugin_name(),
description=self.__class__.brief_description())
parser.add_argument("name", metavar="NAME", help=MultiLanguage.get_string('FRAMEWORK_UPDATE_ARG_NAME'))
return parser.parse_args(argv)
def run(self, argv):
args = self.parse_args(argv)
name = args.name
project = ProjectHelper.get_current_project()
ProjectHelper.update_framework(project, name)

View File

@@ -0,0 +1,62 @@
# ----------------------------------------------------------------------------
# cocos "package" plugin
#
# Copyright 2014 (C) cocos2d-x.org
#
# License: MIT
# ----------------------------------------------------------------------------
'''
"framework" plugins
'''
__docformat__ = 'restructuredtext'
import cocos
from MultiLanguage import MultiLanguage
class CCPluginFramework(cocos.CCPlugin):
@staticmethod
def plugin_name():
return "framework"
@staticmethod
def brief_description():
return MultiLanguage.get_string('FRAMEWORK_BRIEF')
def parse_args(self, argv):
if len(argv) < 1:
print "usage: cocos framework [-h] COMMAND arg [arg ...]"
print MultiLanguage.get_string('FRAMEWORK_ERROR_TOO_FEW_ARGS')
return None
return {"command": argv[0]}
def run(self, argv, dependencies):
args = self.parse_args(argv)
if args is None:
return
command = args["command"]
if command == "add":
from framework_add import FrameworkAdd
CommandClass = FrameworkAdd
elif command == "remove":
from framework_remove import FrameworkRemove
CommandClass = FrameworkRemove
elif command == "update":
from framework_update import FrameworkUpdate
CommandClass = FrameworkUpdate
elif command == "create":
from framework_create import FrameworkCreate
CommandClass = FrameworkCreate
elif command == "set":
from framework_set import FrameworkSet
CommandClass = FrameworkSet
else:
message = MultiLanguage.get_string('FRAMEWORK_ERROR_INVALID_CMD_FMT', command)
raise cocos.CCPluginError(message, cocos.CCPluginError.ERROR_CMD_NOT_FOUND)
commandObject = CommandClass()
commandObject.run(argv[1:])

View File

@@ -0,0 +1,3 @@
from gen_libs import LibsCompiler
from gen_simulator import SimulatorCompiler
from gen_templates import TemplateGenerator

View File

@@ -0,0 +1,67 @@
#include "AppDelegate.h"
#include "HelloWorldScene.h"
USING_NS_CC;
AppDelegate::AppDelegate() {
}
AppDelegate::~AppDelegate()
{
}
//if you want a different context,just modify the value of glContextAttrs
//it will takes effect on all platforms
void AppDelegate::initGLContextAttrs()
{
//set OpenGL context attributions,now can only set six attributions:
//red,green,blue,alpha,depth,stencil
GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};
GLView::setGLContextAttrs(glContextAttrs);
}
bool AppDelegate::applicationDidFinishLaunching() {
// initialize director
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
if(!glview) {
glview = GLViewImpl::createWithRect("HelloCpp", Rect(0, 0, 960, 640));
director->setOpenGLView(glview);
}
director->getOpenGLView()->setDesignResolutionSize(960, 640, ResolutionPolicy::SHOW_ALL);
// turn on display FPS
director->setDisplayStats(true);
// set FPS. the default value is 1.0/60 if you don't call this
director->setAnimationInterval(1.0 / 60);
FileUtils::getInstance()->addSearchPath("res");
// create a scene. it's an autorelease object
auto scene = HelloWorld::createScene();
// run
director->runWithScene(scene);
return true;
}
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground() {
Director::getInstance()->stopAnimation();
// if you use SimpleAudioEngine, it must be pause
// SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() {
Director::getInstance()->startAnimation();
// if you use SimpleAudioEngine, it must resume here
// SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}

View File

@@ -0,0 +1,92 @@
#include "HelloWorldScene.h"
#include "cocostudio/CocoStudio.h"
#include "ui/CocosGUI.h"
USING_NS_CC;
using namespace cocostudio::timeline;
Scene* HelloWorld::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
/** you can create scene with following comment code instead of using csb file.
// 1. super init first
if ( !Layer::init() )
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it.
// add a "close" icon to exit the progress. it's an autorelease object
auto closeItem = MenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
origin.y + closeItem->getContentSize().height/2));
// create menu, it's an autorelease object
auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);
/////////////////////////////
// 3. add your codes below...
// add a label shows "Hello World"
// create and initialize a label
auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24);
// position the label on the center of the screen
label->setPosition(Vec2(origin.x + visibleSize.width/2,
origin.y + visibleSize.height - label->getContentSize().height));
// add the label as a child to this layer
this->addChild(label, 1);
// add "HelloWorld" splash screen"
auto sprite = Sprite::create("HelloWorld.png");
// position the sprite on the center of the screen
sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
// add the sprite as a child to this layer
this->addChild(sprite, 0);
**/
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
auto rootNode = CSLoader::createNode("MainScene.csb");
addChild(rootNode);
return true;
}

View File

@@ -0,0 +1,19 @@
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
class HelloWorld : public cocos2d::Layer
{
public:
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::Scene* createScene();
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
};
#endif // __HELLOWORLD_SCENE_H__

View File

@@ -0,0 +1,110 @@
{
"do_default":{
"exclude_from_template": [
"res-landscape",
"res-portrait"
],
"append_from_template": {
"from": "res-landscape",
"to": ""
},
"project_rename":{
"src_project_name":"HelloCpp",
"files":[
"proj.win32/PROJECT_NAME.vcxproj",
"proj.win32/PROJECT_NAME.vcxproj.filters",
"proj.win32/PROJECT_NAME.vcxproj.user",
"proj.win32/PROJECT_NAME.sln",
"proj.ios_mac/PROJECT_NAME.xcodeproj",
"PROJECT_NAME.ccs",
"PROJECT_NAME.cfg",
"PROJECT_NAME.udf"
]
},
"project_replace_project_name":{
"src_project_name":"HelloCpp",
"files":[
"Classes/AppDelegate.cpp",
"proj.win32/PROJECT_NAME.vcxproj",
"proj.win32/PROJECT_NAME.vcxproj.filters",
"proj.win32/PROJECT_NAME.vcxproj.user",
"proj.win32/PROJECT_NAME.sln",
"PROJECT_NAME.ccs",
"proj.win32/main.cpp",
"proj.android/.project",
"proj.android/.cproject",
"proj.android/AndroidManifest.xml",
"proj.android/build.xml",
"proj.android/res/values/strings.xml",
"proj.ios_mac/ios/main.m",
"proj.ios_mac/ios/Prefix.pch",
"proj.ios_mac/PROJECT_NAME.xcodeproj/project.pbxproj"
]
},
"project_replace_package_name":{
"src_package_name":"org.cocos2dx.hellocpp",
"files":[
"proj.android/AndroidManifest.xml"
]
},
"project_replace_mac_bundleid": {
"src_bundle_id": "org.cocos2dx.hellocpp",
"files": [
"proj.ios_mac/mac/Info.plist"
]
},
"project_replace_ios_bundleid": {
"src_bundle_id": "org.cocos2dx.hellocpp",
"files": [
"proj.ios_mac/ios/Info.plist"
]
}
},
"change_orientation": {
"append_from_template": {
"from": "res-portrait",
"to": ""
},
"modify_files": [
{
"file_path": "Classes/AppDelegate.cpp",
"pattern": "GLViewImpl::createWithRect\\((.*),\\s*Rect\\(\\s*(\\d+),\\s*(\\d+),\\s*(\\d+),\\s*(\\d+)\\)\\)",
"replace_string": "GLViewImpl::createWithRect(\\1, Rect(\\2, \\3, \\5, \\4))"
},
{
"file_path": "Classes/AppDelegate.cpp",
"pattern": "setDesignResolutionSize\\(\\s*(\\d+),\\s*(\\d+),(.*)\\)",
"replace_string": "setDesignResolutionSize(\\2, \\1,\\3)"
},
{
"file_path": "proj.ios_mac/ios/Info.plist",
"pattern": "UIInterfaceOrientationLandscapeRight",
"replace_string": "UIInterfaceOrientationPortrait"
},
{
"file_path": "proj.ios_mac/ios/Info.plist",
"pattern": "UIInterfaceOrientationLandscapeLeft",
"replace_string": "UIInterfaceOrientationPortraitUpsideDown"
},
{
"file_path": "proj.android/AndroidManifest.xml",
"pattern": "android:screenOrientation=\\\".*\\\"",
"replace_string": "android:screenOrientation=\"portrait\""
}
],
"project_rename":{
"src_project_name":"HelloCpp",
"files":[
"PROJECT_NAME.ccs",
"PROJECT_NAME.cfg",
"PROJECT_NAME.udf"
]
},
"project_replace_project_name":{
"src_project_name":"HelloCpp",
"files":[
"PROJECT_NAME.ccs"
]
}
}
}

View File

@@ -0,0 +1,20 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloCpp", "HelloCpp.vcxproj", "{76A39BB2-9B84-4C65-98A5-654D86B86F2A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{76A39BB2-9B84-4C65-98A5-654D86B86F2A}.Debug|Win32.ActiveCfg = Debug|Win32
{76A39BB2-9B84-4C65-98A5-654D86B86F2A}.Debug|Win32.Build.0 = Debug|Win32
{76A39BB2-9B84-4C65-98A5-654D86B86F2A}.Release|Win32.ActiveCfg = Release|Win32
{76A39BB2-9B84-4C65-98A5-654D86B86F2A}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,11 @@
<Solution>
<PropertyGroup Name="HelloCpp" Version="2.1.0.0" Type="CocosStudio" />
<SolutionFolder>
<Group ctype="ResourceGroup">
<RootFolder Name=".">
<Project Name="MainScene.csd" />
<Image Name="HelloWorld.png" />
</RootFolder>
</Group>
</SolutionFolder>
</Solution>

View File

@@ -0,0 +1 @@
<Properties PublishDirectory="Resources/res" SolutionSize="960 * 640" DefaultSerializer="Serializer_FlatBuffers" CustomSerializer="Serializer_FlatBuffers" />

View File

@@ -0,0 +1,6 @@
<UserData>
<OpenedDocuments>
<FilePathData Path="MainScene.csd" />
</OpenedDocuments>
<ActiveDocument Path="MainScene.csd" />
</UserData>

View File

@@ -0,0 +1,29 @@
<GameProjectFile>
<PropertyGroup Type="Scene" Name="MainScene" ID="a2ee0952-26b5-49ae-8bf9-4f1d6279b798" Version="2.1.0.0" />
<Content ctype="GameProjectContent">
<Content>
<Animation Duration="0" Speed="1.0000" />
<ObjectData Name="Scene" FrameEvent="" RightMargin="-960.0000" TopMargin="-640.0000" ctype="SingleNodeObjectData">
<Position X="0.0000" Y="0.0000" />
<Scale ScaleX="1.0000" ScaleY="1.0000" />
<AnchorPoint />
<CColor A="255" R="255" G="255" B="255" />
<Size X="960.0000" Y="640.0000" />
<PrePosition X="0.0000" Y="0.0000" />
<PreSize X="0.0000" Y="0.0000" />
<Children>
<NodeObjectData Name="Default" ActionTag="953446860" FrameEvent="" Tag="5" ObjectIndex="2" ctype="SpriteObjectData">
<Position X="480.0000" Y="320.0000" />
<Scale ScaleX="1.0000" ScaleY="1.0000" />
<AnchorPoint ScaleX="0.5000" ScaleY="0.5000" />
<CColor A="255" R="255" G="255" B="255" />
<Size X="960.0000" Y="640.0000" />
<PrePosition X="0.5000" Y="0.5000" />
<PreSize X="0.0000" Y="0.0000" />
<FileData Type="Normal" Path="HelloWorld.png" />
</NodeObjectData>
</Children>
</ObjectData>
</Content>
</Content>
</GameProjectFile>

View File

@@ -0,0 +1,11 @@
<Solution>
<PropertyGroup Name="HelloCpp" Version="2.1.0.0" Type="CocosStudio" />
<SolutionFolder>
<Group ctype="ResourceGroup">
<RootFolder Name=".">
<Project Name="MainScene.csd" />
<Image Name="HelloWorld.png" />
</RootFolder>
</Group>
</SolutionFolder>
</Solution>

View File

@@ -0,0 +1 @@
<Properties publishHasCocos2dxCode="False" PublishDirectory="Resources/res" SolutionSize="640 * 960" DefaultSerializer="Serializer_FlatBuffers" CustomSerializer="Serializer_FlatBuffers" />

View File

@@ -0,0 +1,6 @@
<UserData>
<OpenedDocuments>
<FilePathData Path="MainScene.csd" />
</OpenedDocuments>
<ActiveDocument Path="MainScene.csd" />
</UserData>

View File

@@ -0,0 +1,29 @@
<GameProjectFile>
<PropertyGroup Type="Scene" Name="MainScene" ID="a2ee0952-26b5-49ae-8bf9-4f1d6279b798" Version="2.1.0.0" />
<Content ctype="GameProjectContent">
<Content>
<Animation Duration="0" Speed="1.0000" />
<ObjectData Name="Scene" FrameEvent="" ctype="SingleNodeObjectData">
<Position X="0.0000" Y="0.0000" />
<Scale ScaleX="1.0000" ScaleY="1.0000" />
<AnchorPoint />
<CColor A="255" R="255" G="255" B="255" />
<Size X="640.0000" Y="960.0000" />
<PrePosition X="0.0000" Y="0.0000" />
<PreSize X="0.0000" Y="0.0000" />
<Children>
<NodeObjectData Name="Default" ActionTag="-620272433" FrameEvent="" Tag="5" ObjectIndex="3" ctype="SpriteObjectData">
<Position X="320.0000" Y="480.0000" />
<Scale ScaleX="1.0000" ScaleY="1.0000" />
<AnchorPoint ScaleX="0.5000" ScaleY="0.5000" />
<CColor A="255" R="255" G="255" B="255" />
<Size X="640.0000" Y="960.0000" />
<PrePosition X="0.5000" Y="0.5000" />
<PreSize X="0.0000" Y="0.0000" />
<FileData Type="Normal" Path="HelloWorld.png" />
</NodeObjectData>
</Children>
</ObjectData>
</Content>
</Content>
</GameProjectFile>

View File

@@ -0,0 +1,170 @@
{
"do_default":{
"exclude_from_template":[
"frameworks/runtime-src",
"res-landscape",
"res-portrait"
],
"append_from_template": {
"from": "res-landscape",
"to": ""
},
"project_rename": {
"src_project_name": "HelloJavascript",
"files": [
"PROJECT_NAME.ccs",
"PROJECT_NAME.cfg",
"PROJECT_NAME.udf"
]
},
"project_replace_project_name":{
"src_project_name":"HelloJavascript",
"files":[
"config.json",
".project",
"PROJECT_NAME.ccs"
]
},
"append_dir":[
{
"from": "cocos/scripting/js-bindings/script",
"to": "script",
"include": [
"*.js"
]
},
{
"from": "web",
"to": "frameworks/cocos2d-html5"
}
]
},
"do_add_native_support":{
"append_from_template":{
"from":"frameworks/runtime-src",
"to":"frameworks/runtime-src",
"exclude":[
"proj.android/bin",
"proj.android/assets",
"proj.ios_mac/HelloJavascript.xcodeproj/project.xcworkspace",
"proj.ios_mac/HelloJavascript.xcodeproj/xcuserdata",
"proj.win32/Debug.win32",
"proj.win32/Release.win32",
"proj.win32/HelloJavascript.sdf"
]
},
"append_dir":[
{
"from":"tools/bindings-generator",
"to":"tools/bindings-generator",
"exclude":[
".git"
]
},
{
"from":"tools",
"to":"tools",
"include":[
"tojs"
]
}
],
"project_rename":{
"src_project_name":"HelloJavascript",
"files":[
"frameworks/runtime-src/proj.win32/PROJECT_NAME.vcxproj",
"frameworks/runtime-src/proj.win32/PROJECT_NAME.vcxproj.filters",
"frameworks/runtime-src/proj.win32/PROJECT_NAME.vcxproj.user",
"frameworks/runtime-src/proj.win32/PROJECT_NAME.sln",
"frameworks/runtime-src/proj.ios_mac/PROJECT_NAME.xcodeproj"
]
},
"project_replace_project_name":{
"src_project_name":"HelloJavascript",
"files":[
"config.json",
".project",
"frameworks/runtime-src/proj.win32/PROJECT_NAME.vcxproj",
"frameworks/runtime-src/proj.win32/PROJECT_NAME.vcxproj.filters",
"frameworks/runtime-src/proj.win32/PROJECT_NAME.vcxproj.user",
"frameworks/runtime-src/proj.win32/PROJECT_NAME.sln",
"frameworks/runtime-src/proj.win32/main.cpp",
"frameworks/runtime-src/proj.android/.project",
"frameworks/runtime-src/proj.android/AndroidManifest.xml",
"frameworks/runtime-src/proj.android/build.xml",
"frameworks/runtime-src/proj.android/res/values/strings.xml",
"frameworks/runtime-src/proj.ios_mac/ios/main.m",
"frameworks/runtime-src/proj.ios_mac/ios/Prefix.pch",
"frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.mm",
"frameworks/runtime-src/proj.ios_mac/PROJECT_NAME.xcodeproj/project.pbxproj",
"frameworks/runtime-src/Classes/AppDelegate.cpp"
]
},
"project_replace_package_name":{
"src_package_name":"org.cocos2dx.hellojavascript",
"files":[
"frameworks/runtime-src/proj.android/AndroidManifest.xml"
]
},
"project_replace_mac_bundleid":{
"src_bundle_id":"org.cocos2dx.hellojavascript",
"files":[
"frameworks/runtime-src/proj.ios_mac/mac/Info.plist"
]
},
"project_replace_ios_bundleid":{
"src_bundle_id":"org.cocos2dx.hellojavascript",
"files":[
"frameworks/runtime-src/proj.ios_mac/ios/Info.plist"
]
}
},
"change_orientation": {
"append_from_template": {
"from": "res-portrait",
"to": ""
},
"modify_files": [
{
"file_path": "config.json",
"pattern": "\\\"isLandscape\\\"\\s*:.*,",
"replace_string": "\"isLandscape\": false,"
},
{
"file_path": "main.js",
"pattern": "setDesignResolutionSize\\(\\s*(\\d+),\\s*(\\d+),(.*)\\)",
"replace_string": "setDesignResolutionSize(\\2, \\1,\\3)"
},
{
"file_path": "frameworks/runtime-src/proj.ios_mac/ios/Info.plist",
"pattern": "UIInterfaceOrientationLandscapeRight",
"replace_string": "UIInterfaceOrientationPortrait"
},
{
"file_path": "frameworks/runtime-src/proj.ios_mac/ios/Info.plist",
"pattern": "UIInterfaceOrientationLandscapeLeft",
"replace_string": "UIInterfaceOrientationPortraitUpsideDown"
},
{
"file_path": "frameworks/runtime-src/proj.android/AndroidManifest.xml",
"pattern": "android:screenOrientation=\\\".*\\\"",
"replace_string": "android:screenOrientation=\"portrait\""
}
],
"project_rename":{
"src_project_name":"HelloJavascript",
"files":[
"PROJECT_NAME.ccs",
"PROJECT_NAME.cfg",
"PROJECT_NAME.udf"
]
},
"project_replace_project_name":{
"src_project_name":"HelloJavascript",
"files":[
"PROJECT_NAME.ccs"
]
}
}
}

View File

@@ -0,0 +1,20 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloJavascript", "HelloJavascript.vcxproj", "{3B0B58B1-2734-488E-A542-ECEC11EB2455}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3B0B58B1-2734-488E-A542-ECEC11EB2455}.Debug|Win32.ActiveCfg = Debug|Win32
{3B0B58B1-2734-488E-A542-ECEC11EB2455}.Debug|Win32.Build.0 = Debug|Win32
{3B0B58B1-2734-488E-A542-ECEC11EB2455}.Release|Win32.ActiveCfg = Release|Win32
{3B0B58B1-2734-488E-A542-ECEC11EB2455}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,11 @@
<Solution>
<PropertyGroup Name="HelloJavascript" Version="2.1.0.0" Type="CocosStudio" />
<SolutionFolder>
<Group ctype="ResourceGroup">
<RootFolder Name=".">
<Project Name="MainScene.csd" />
<Image Name="HelloWorld.png" />
</RootFolder>
</Group>
</SolutionFolder>
</Solution>

View File

@@ -0,0 +1 @@
<Properties PublishDirectory="res" SolutionSize="960 * 640" DefaultSerializer="Serializer_FlatBuffers" CustomSerializer="Serializer_FlatBuffers" />

View File

@@ -0,0 +1,6 @@
<UserData>
<OpenedDocuments>
<FilePathData Path="MainScene.csd" />
</OpenedDocuments>
<ActiveDocument Path="MainScene.csd" />
</UserData>

View File

@@ -0,0 +1,29 @@
<GameProjectFile>
<PropertyGroup Type="Scene" Name="MainScene" ID="a2ee0952-26b5-49ae-8bf9-4f1d6279b798" Version="2.1.0.0" />
<Content ctype="GameProjectContent">
<Content>
<Animation Duration="0" Speed="1.0000" />
<ObjectData Name="Scene" FrameEvent="" RightMargin="-960.0000" TopMargin="-640.0000" ctype="SingleNodeObjectData">
<Position X="0.0000" Y="0.0000" />
<Scale ScaleX="1.0000" ScaleY="1.0000" />
<AnchorPoint />
<CColor A="255" R="255" G="255" B="255" />
<Size X="960.0000" Y="640.0000" />
<PrePosition X="0.0000" Y="0.0000" />
<PreSize X="0.0000" Y="0.0000" />
<Children>
<NodeObjectData Name="Default" ActionTag="953446860" FrameEvent="" Tag="5" ObjectIndex="2" ctype="SpriteObjectData">
<Position X="480.0000" Y="320.0000" />
<Scale ScaleX="1.0000" ScaleY="1.0000" />
<AnchorPoint ScaleX="0.5000" ScaleY="0.5000" />
<CColor A="255" R="255" G="255" B="255" />
<Size X="960.0000" Y="640.0000" />
<PrePosition X="0.5000" Y="0.5000" />
<PreSize X="0.0000" Y="0.0000" />
<FileData Type="Normal" Path="HelloWorld.png" />
</NodeObjectData>
</Children>
</ObjectData>
</Content>
</Content>
</GameProjectFile>

View File

@@ -0,0 +1,85 @@
{
"ID": "a2ee0952-26b5-49ae-8bf9-4f1d6279b798",
"Version": "2.1.0.0",
"Type": "Scene",
"Name": "MainScene",
"Content": {
"Content": {
"Animation": {
"Duration": 0,
"Speed": 1.0,
"Timelines": [],
"ctype": "TimelineActionData"
},
"AnimationList": [],
"ObjectData": {
"PrePosition": {
"X": 0.0,
"Y": 0.0
},
"PreSize": {
"X": 0.0,
"Y": 0.0
},
"RightMargin": -960.0,
"TopMargin": -640.0,
"Children": [
{
"FileData": {
"Type": "Normal",
"Path": "HelloWorld.png"
},
"Tag": 5,
"PrePosition": {
"X": 0.5,
"Y": 0.5
},
"PreSize": {
"X": 0.0,
"Y": 0.0
},
"ActionTag": 953446860,
"Position": {
"X": 480.0,
"Y": 320.0
},
"Scale": {
"ScaleX": 1.0,
"ScaleY": 1.0
},
"AnchorPoint": {
"ScaleX": 0.5,
"ScaleY": 0.5
},
"CColor": {},
"Size": {
"X": 960.0,
"Y": 640.0
},
"FrameEvent": "",
"Name": "Default",
"ctype": "SpriteObjectData"
}
],
"Position": {
"X": 0.0,
"Y": 0.0
},
"Scale": {
"ScaleX": 1.0,
"ScaleY": 1.0
},
"AnchorPoint": {},
"CColor": {},
"Size": {
"X": 960.0,
"Y": 640.0
},
"FrameEvent": "",
"Name": "Scene",
"ctype": "SingleNodeObjectData"
},
"ctype": "GameProjectData"
}
}
}

View File

@@ -0,0 +1,11 @@
<Solution>
<PropertyGroup Name="HelloJavascript" Version="2.1.0.0" Type="CocosStudio" />
<SolutionFolder>
<Group ctype="ResourceGroup">
<RootFolder Name=".">
<Project Name="MainScene.csd" />
<Image Name="HelloWorld.png" />
</RootFolder>
</Group>
</SolutionFolder>
</Solution>

View File

@@ -0,0 +1 @@
<Properties publishHasCocos2dxCode="False" PublishDirectory="res" SolutionSize="640 * 960" DefaultSerializer="Serializer_FlatBuffers" CustomSerializer="Serializer_FlatBuffers" />

View File

@@ -0,0 +1,6 @@
<UserData>
<OpenedDocuments>
<FilePathData Path="MainScene.csd" />
</OpenedDocuments>
<ActiveDocument Path="MainScene.csd" />
</UserData>

View File

@@ -0,0 +1,29 @@
<GameProjectFile>
<PropertyGroup Type="Scene" Name="MainScene" ID="a2ee0952-26b5-49ae-8bf9-4f1d6279b798" Version="2.1.0.0" />
<Content ctype="GameProjectContent">
<Content>
<Animation Duration="0" Speed="1.0000" />
<ObjectData Name="Scene" FrameEvent="" ctype="SingleNodeObjectData">
<Position X="0.0000" Y="0.0000" />
<Scale ScaleX="1.0000" ScaleY="1.0000" />
<AnchorPoint />
<CColor A="255" R="255" G="255" B="255" />
<Size X="640.0000" Y="960.0000" />
<PrePosition X="0.0000" Y="0.0000" />
<PreSize X="0.0000" Y="0.0000" />
<Children>
<NodeObjectData Name="Default" ActionTag="-620272433" FrameEvent="" Tag="5" ObjectIndex="3" ctype="SpriteObjectData">
<Position X="320.0000" Y="480.0000" />
<Scale ScaleX="1.0000" ScaleY="1.0000" />
<AnchorPoint ScaleX="0.5000" ScaleY="0.5000" />
<CColor A="255" R="255" G="255" B="255" />
<Size X="640.0000" Y="960.0000" />
<PrePosition X="0.5000" Y="0.5000" />
<PreSize X="0.0000" Y="0.0000" />
<FileData Type="Normal" Path="HelloWorld.png" />
</NodeObjectData>
</Children>
</ObjectData>
</Content>
</Content>
</GameProjectFile>

View File

@@ -0,0 +1,83 @@
{
"ID": "a2ee0952-26b5-49ae-8bf9-4f1d6279b798",
"Version": "2.1.0.0",
"Type": "Scene",
"Name": "MainScene",
"Content": {
"Content": {
"Animation": {
"Duration": 0,
"Speed": 1.0,
"Timelines": [],
"ctype": "TimelineActionData"
},
"AnimationList": [],
"ObjectData": {
"PrePosition": {
"X": 0.0,
"Y": 0.0
},
"PreSize": {
"X": 0.0,
"Y": 0.0
},
"Children": [
{
"FileData": {
"Type": "Normal",
"Path": "HelloWorld.png"
},
"Tag": 5,
"PrePosition": {
"X": 0.5,
"Y": 0.5
},
"PreSize": {
"X": 0.0,
"Y": 0.0
},
"ActionTag": -620272433,
"Position": {
"X": 320.0,
"Y": 480.0
},
"Scale": {
"ScaleX": 1.0,
"ScaleY": 1.0
},
"AnchorPoint": {
"ScaleX": 0.5,
"ScaleY": 0.5
},
"CColor": {},
"Size": {
"X": 640.0,
"Y": 960.0
},
"FrameEvent": "",
"Name": "Default",
"ctype": "SpriteObjectData"
}
],
"Position": {
"X": 0.0,
"Y": 0.0
},
"Scale": {
"ScaleX": 1.0,
"ScaleY": 1.0
},
"AnchorPoint": {},
"CColor": {},
"Size": {
"X": 640.0,
"Y": 960.0
},
"FrameEvent": "",
"Name": "Scene",
"ctype": "SingleNodeObjectData"
},
"ctype": "GameProjectData"
}
}
}

Some files were not shown because too many files have changed in this diff Show More