Commit bfabb962 bfabb962900dbf3ff83cd53779d6737d44a41170 by jinwawa

0802

1 parent fe27a2a7
Showing 313 changed files with 3747 additions and 8 deletions
......@@ -9,6 +9,6 @@
<isEffect>1</isEffect>
<fanpai_best>10</fanpai_best>
<candy_best>2391</candy_best>
<candy_game_play_cnt>33</candy_game_play_cnt>
<candy_game_play_cnt>34</candy_game_play_cnt>
<is_game_vip>1</is_game_vip>
</userDefaultRoot>
......
......@@ -5,8 +5,7 @@
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>E439935D-B2A2-46AE-856D-2AA408428F33</ProjectGuid>
<!--$guid1$-->
<ProjectHome>
</ProjectHome>
<ProjectHome>.</ProjectHome>
<StartupFile>
</StartupFile>
<SearchPath>
......
......@@ -185,7 +185,7 @@ function GameScene:createBoomFun()
self:createCandy(1,-_info.boom_speed);
end
end
--防护罩
function GameScene:createShieldFun()
local _info = game_data.get_info_by_score(self.score);
......
......@@ -33,12 +33,9 @@
<OpenedDocuments>
<FilePathData Path="ui/candy/LoadingScene.csd" />
<FilePathData Path="ui/candy/GameStartLayer.csd" />
<FilePathData Path="ui/candy/GameStartLayer_shdx.csd" />
<FilePathData Path="ui/candy/LoadingScene_shdx.csd" />
<FilePathData Path="ui/candy/GameScene.csd" />
<FilePathData Path="ui/candy/Girl.csd" />
</OpenedDocuments>
<ActiveDocument Path="ui/candy/Girl.csd" />
<ActiveDocument Path="ui/candy/GameStartLayer.csd" />
</Value>
</Item>
</Properties>
......
{
"engine_type": "prebuilt",
"engine_version": "cocos2d-x-3.10",
"has_native": true,
"project_type": "lua"
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>rubbish</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
<nature>org.ccdt.cocosproject</nature>
<nature>org.eclipse.koneki.ldt.nature</nature>
</natures>
</projectDescription>
{
"engineVersion": "cocos2d-x-3.10",
"runtimeVersion": "2.0",
"templateVersion": "2.0"
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<userDefaultRoot>
<Account>wwj0728112</Account>
<exp>-5</exp>
<versionnum>201801291657</versionnum>
<best>4186</best>
<guess_best>89</guess_best>
<isMusic>1</isMusic>
<isEffect>1</isEffect>
<fanpai_best>10</fanpai_best>
<candy_best>2391</candy_best>
<candy_game_play_cnt>34</candy_game_play_cnt>
<is_game_vip>1</is_game_vip>
</userDefaultRoot>
{
"init_cfg": {
"isLandscape": true,
"isWindowTop": false,
"name": "rubbish",
"width": 960,
"height": 640,
"entry": "src/main.lua",
"consolePort": 6050,
"uploadPort": 6060
},
"simulator_screen_size": [
{
"title": "iPhone 3Gs (480x320)",
"width": 480,
"height": 320
},
{
"title": "iPhone 4 (960x640)",
"width": 960,
"height": 640
},
{
"title": "iPhone 5 (1136x640)",
"width": 1136,
"height": 640
},
{
"title": "iPad (1024x768)",
"width": 1024,
"height": 768
},
{
"title": "iPad Retina (2048x1536)",
"width": 2048,
"height": 1536
},
{
"title": "Android (800x480)",
"width": 800,
"height": 480
},
{
"title": "Android (854x480)",
"width": 854,
"height": 480
},
{
"title": "Android (1280x720)",
"width": 1280,
"height": 720
},
{
"title": "Android (1920x1080)",
"width": 1920,
"height": 1080
}
]
}
\ No newline at end of file
No preview for this file type
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ProjectView>ShowAllFiles</ProjectView>
</PropertyGroup>
</Project>
\ No newline at end of file

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.30501.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{5697748A-77EF-44CA-8824-4F5637E5945B}") = "rubbish", "rubbish.luaproj", "{E439935D-B2A2-46AE-856D-2AA408428F33}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E439935D-B2A2-46AE-856D-2AA408428F33}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E439935D-B2A2-46AE-856D-2AA408428F33}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E439935D-B2A2-46AE-856D-2AA408428F33}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E439935D-B2A2-46AE-856D-2AA408428F33}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
No preview for this file type
#include "AppDelegate.h"
#include "CCLuaEngine.h"
#include "SimpleAudioEngine.h"
#include "cocos2d.h"
#include "lua_module_register.h"
#if (CC_TARGET_PLATFORM != CC_PLATFORM_LINUX)
#include "ide-support/CodeIDESupport.h"
#endif
#if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)
#include "runtime/Runtime.h"
#include "ide-support/RuntimeLuaImpl.h"
#endif
using namespace CocosDenshion;
USING_NS_CC;
using namespace std;
AppDelegate::AppDelegate()
{
}
AppDelegate::~AppDelegate()
{
SimpleAudioEngine::end();
#if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)
// NOTE:Please don't remove this call if you want to debug with Cocos Code IDE
RuntimeEngine::getInstance()->end();
#endif
}
//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);
}
// If you want to use packages manager to install more packages,
// don't modify or remove this function
static int register_all_packages()
{
return 0; //flag for packages manager
}
bool AppDelegate::applicationDidFinishLaunching()
{
// set default FPS
Director::getInstance()->setAnimationInterval(1.0 / 60.0f);
// register lua module
auto engine = LuaEngine::getInstance();
ScriptEngineManager::getInstance()->setScriptEngine(engine);
lua_State* L = engine->getLuaStack()->getLuaState();
lua_module_register(L);
register_all_packages();
LuaStack* stack = engine->getLuaStack();
stack->setXXTEAKeyAndSign("2dxLua", strlen("2dxLua"), "XXTEA", strlen("XXTEA"));
//register custom function
//LuaStack* stack = engine->getLuaStack();
//register_custom_function(stack->getLuaState());
#if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)
// NOTE:Please don't remove this call if you want to debug with Cocos Code IDE
auto runtimeEngine = RuntimeEngine::getInstance();
runtimeEngine->addRuntime(RuntimeLuaImpl::create(), kRuntimeEngineLua);
runtimeEngine->start();
#else
if (engine->executeScriptFile("src/main.lua"))
{
return false;
}
#endif
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();
SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground()
{
Director::getInstance()->startAnimation();
SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}
#ifndef __APP_DELEGATE_H__
#define __APP_DELEGATE_H__
#include "cocos2d.h"
/**
@brief The cocos2d Application.
The reason for implement as private inheritance is to hide some interface call by Director.
*/
class AppDelegate : private cocos2d::Application
{
public:
AppDelegate();
virtual ~AppDelegate();
virtual void initGLContextAttrs();
/**
@brief Implement Director and Scene init code here.
@return true Initialize success, app continue.
@return false Initialize failed, app terminate.
*/
virtual bool applicationDidFinishLaunching();
/**
@brief The function be called when the application enter background
@param the pointer of the application
*/
virtual void applicationDidEnterBackground();
/**
@brief The function be called when the application enter foreground
@param the pointer of the application
*/
virtual void applicationWillEnterForeground();
};
#endif // __APP_DELEGATE_H__
#ifndef __CODE_IDE_SUPPORT_H__
#define __CODE_IDE_SUPPORT_H__
// define 1 to open Cocos Code IDE support, 0 to disable
#define CC_CODE_IDE_DEBUG_SUPPORT 0
#endif /* __CODE_IDE_SUPPORT_H__ */
//
// RuntimeLuaImpl.h
// Simulator
//
//
#ifndef __Simulator__RuntimeLuaImpl__
#define __Simulator__RuntimeLuaImpl__
#include "CodeIDESupport.h"
#include "cocos2d.h"
#if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)
#include "runtime/RuntimeProtocol.h"
class RuntimeLuaImpl : public RuntimeProtocol
{
public:
static RuntimeLuaImpl *create();
void onStartDebuger(const rapidjson::Document& dArgParse, rapidjson::Document& dReplyParse);
void onReload(const rapidjson::Document& dArgParse, rapidjson::Document& dReplyParse);
void startScript(const std::string& strDebugArg);
private:
void init();
};
#endif // (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)
#endif /* defined(__Simulator__RuntimeLua__) */
#include "json/document.h"
#include "json/filestream.h"
#include "json/stringbuffer.h"
#include "json/writer.h"
#include "SimpleConfigParser.h"
// SimpleConfigParser
SimpleConfigParser *SimpleConfigParser::s_sharedSimpleConfigParserInstance = NULL;
SimpleConfigParser *SimpleConfigParser::getInstance(void)
{
if (!s_sharedSimpleConfigParserInstance)
{
s_sharedSimpleConfigParserInstance = new SimpleConfigParser();
s_sharedSimpleConfigParserInstance->readConfig();
}
return s_sharedSimpleConfigParserInstance;
}
void SimpleConfigParser::purge()
{
CC_SAFE_DELETE(s_sharedSimpleConfigParserInstance);
}
void SimpleConfigParser::readConfig(const string &filepath)
{
string fullPathFile = filepath;
// read config file
if (fullPathFile.empty())
{
fullPathFile = FileUtils::getInstance()->fullPathForFilename(CONFIG_FILE);
}
string fileContent = FileUtils::getInstance()->getStringFromFile(fullPathFile);
if(fileContent.empty())
return;
if (_docRootjson.Parse<0>(fileContent.c_str()).HasParseError()) {
cocos2d::log("read json file %s failed because of %d", fullPathFile.c_str(), _docRootjson.GetParseError());
return;
}
if (_docRootjson.HasMember("init_cfg"))
{
if(_docRootjson["init_cfg"].IsObject())
{
const rapidjson::Value& objectInitView = _docRootjson["init_cfg"];
if (objectInitView.HasMember("isLandscape") && objectInitView["isLandscape"].IsBool())
{
_isLandscape = objectInitView["isLandscape"].GetBool();
}
}
}
}
SimpleConfigParser::SimpleConfigParser(void) :
_isLandscape(true)
{
}
rapidjson::Document& SimpleConfigParser::getConfigJsonRoot()
{
return _docRootjson;
}
bool SimpleConfigParser::isLanscape()
{
return _isLandscape;
}
#ifndef __SIMPLE_CONFIG_PARSER_H__
#define __SIMPLE_CONFIG_PARSER_H__
#include <string>
#include <vector>
#include "cocos2d.h"
#include "json/document.h"
using namespace std;
USING_NS_CC;
#define CONFIG_FILE "config.json"
class SimpleConfigParser
{
public:
static SimpleConfigParser *getInstance(void);
static void purge();
void readConfig(const string &filepath = "");
bool isLanscape();
rapidjson::Document& getConfigJsonRoot();
private:
SimpleConfigParser(void);
static SimpleConfigParser *s_sharedSimpleConfigParserInstance;
bool _isLandscape;
rapidjson::Document _docRootjson;
};
#endif // __SIMPLE_CONFIG_PARSER_H__
{
"zh-CN": {
"View": "视图(&V)",
"Exit": "退出(&X)",
"File": "文件(&F)",
"Portrait": "竖屏",
"Landscape": "横屏",
"Refresh": "刷新(重启)",
"Zoom Out": "缩放",
"Simulator": "模拟器",
"Open File": "打开文件",
"Open Project": "打开工程",
"Error": "错误",
"Help": "帮助(&H)",
"About": "关于(&A)"
},
"zh-Hans": {
"View": "视图",
"Exit": "退出",
"File": "文件",
"Portrait": "竖屏",
"Landscape": "横屏",
"Refresh": "刷新(重启)",
"Zoom Out": "缩放",
"Simulator": "模拟器",
"Help": "帮助(&H)",
"About": "关于(&A)"
}
}
\ No newline at end of file
This diff could not be displayed because it is too large.
/* lua_debugger.h.h */
#ifndef __LUA_MODULES_049C000C96FE547176CCBB7690BA01B6_H_
#define __LUA_MODULES_049C000C96FE547176CCBB7690BA01B6_H_
#if __cplusplus
extern "C" {
#endif
#include "lua.h"
void luaopen_lua_debugger(lua_State* L);
/*
int luaopen_lua_m_debugger(lua_State* L);
*/
#if __cplusplus
}
#endif
#endif /* __LUA_MODULES_049C000C96FE547176CCBB7690BA01B6_H_ */
#ifndef __LUA_TEMPLATE_RUNTIME_FRAMEWORKS_RUNTIME_SRC_CLASSES_LUA_MODULE_REGISTER_H__
#define __LUA_TEMPLATE_RUNTIME_FRAMEWORKS_RUNTIME_SRC_CLASSES_LUA_MODULE_REGISTER_H__
#include "lua.h"
#include "Lua-BindingsExport.h"
CC_LUA_DLL int lua_module_register(lua_State* L);
#endif // __LUA_TEMPLATE_RUNTIME_FRAMEWORKS_RUNTIME_SRC_CLASSES_LUA_MODULE_REGISTER_H__
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>rubbish</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
org.eclipse.jdt.core.compiler.compliance=1.6
org.eclipse.jdt.core.compiler.source=1.6
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.cocos2dx.rubbish"
android:versionCode="1"
android:versionName="1.0"
android:installLocation="auto">
<uses-sdk android:minSdkVersion="9"/>
<uses-feature android:glEsVersion="0x00020000" />
<application android:label="@string/app_name"
android:icon="@drawable/icon">
<!-- Tell Cocos2dxActivity the name of our .so -->
<meta-data android:name="android.app.lib_name"
android:value="cocos2dlua" />
<activity android:name="org.cocos2dx.lua.AppActivity"
android:label="@string/app_name"
android:screenOrientation="landscape"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:configChanges="orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<supports-screens android:anyDensity="true"
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:xlargeScreens="true"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
# This file is used to override default values used by the Ant build system.
#
# This file must be checked into Version Control Systems, as it is
# integral to the build system of your project.
# This file is only used by the Ant script.
# You can use this to override default values such as
# 'source.dir' for the location of your java source folder and
# 'out.dir' for the location of your output folder.
# You can also use it define how the release builds are signed by declaring
# the following properties:
# 'key.store' for the location of your keystore and
# 'key.alias' for the name of the key to use.
# The password will be asked during the build when you use the 'release' target.
{
"ndk_module_path" :[
"${COCOS_X_ROOT}/cocos2d-x-3.10",
"${COCOS_X_ROOT}/cocos2d-x-3.10/cocos/",
"${COCOS_X_ROOT}/cocos2d-x-3.10/external",
"${COCOS_X_ROOT}/cocos2d-x-3.10/cocos/scripting"
],
"copy_resources": [
{
"from": "../../../src",
"to": "src"
},
{
"from": "../../../res",
"to": "res"
}
],
"must_copy_resources": [
{
"from": "../../../config.json",
"to": ""
}
]
}
<?xml version="1.0" encoding="UTF-8"?>
<project name="rubbish" default="debug">
<!-- The local.properties file is created and updated by the 'android' tool.
It contains the path to the SDK. It should *NOT* be checked into
Version Control Systems. -->
<property file="local.properties" />
<!-- The ant.properties file can be created by you. It is only edited by the
'android' tool to add properties to it.
This is the place to change some Ant specific build properties.
Here are some properties you may want to change/update:
source.dir
The name of the source directory. Default is 'src'.
out.dir
The name of the output directory. Default is 'bin'.
For other overridable properties, look at the beginning of the rules
files in the SDK, at tools/ant/build.xml
Properties related to the SDK location or the project target should
be updated using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your
application and should be checked into Version Control Systems.
-->
<property file="ant.properties" />
<!-- The project.properties file is created and updated by the 'android'
tool, as well as ADT.
This contains project specific properties such as project target, and library
dependencies. Lower level build properties are stored in ant.properties
(or in .classpath for Eclipse projects).
This file is an integral part of the build system for your
application and should be checked into Version Control Systems. -->
<loadproperties srcFile="project.properties" />
<!-- quick check on sdk.dir -->
<fail
message="sdk.dir is missing. Make sure to generate local.properties using 'android update project' or to inject it through an env var"
unless="sdk.dir"
/>
<!--
Import per project custom build rules if present at the root of the project.
This is the place to put custom intermediary targets such as:
-pre-build
-pre-compile
-post-compile (This is typically used for code obfuscation.
Compiled code location: ${out.classes.absolute.dir}
If this is not done in place, override ${out.dex.input.absolute.dir})
-post-package
-post-build
-pre-clean
-->
<import file="custom_rules.xml" optional="true" />
<!-- Import the actual build file.
To customize existing targets, there are two options:
- Customize only one target:
- copy/paste the target into this file, *before* the
<import> task.
- customize it to your needs.
- Customize the whole content of build.xml
- copy/paste the content of the rules files (minus the top node)
into this file, replacing the <import> task.
- customize to your needs.
***********************
****** IMPORTANT ******
***********************
In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
in order to avoid having your file be overridden by tools such as "android update project"
-->
<!-- version-tag: 1 -->
<import file="${sdk.dir}/tools/ant/build.xml" />
</project>
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := cocos2dlua_shared
LOCAL_MODULE_FILENAME := libcocos2dlua
LOCAL_SRC_FILES := \
../../Classes/AppDelegate.cpp \
../../Classes/ide-support/SimpleConfigParser.cpp \
../../Classes/ide-support/RuntimeLuaImpl.cpp \
../../Classes/ide-support/lua_debugger.c \
hellolua/main.cpp
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes
# _COCOS_HEADER_ANDROID_BEGIN
# _COCOS_HEADER_ANDROID_END
LOCAL_STATIC_LIBRARIES := cocos2d_lua_static
LOCAL_STATIC_LIBRARIES += cocos2d_simulator_static
# _COCOS_LIB_ANDROID_BEGIN
# _COCOS_LIB_ANDROID_END
include $(BUILD_SHARED_LIBRARY)
$(call import-module,scripting/lua-bindings/proj.android/prebuilt-mk)
$(call import-module,tools/simulator/libsimulator/proj.android/prebuilt-mk)
# _COCOS_LIB_IMPORT_ANDROID_BEGIN
# _COCOS_LIB_IMPORT_ANDROID_END
APP_STL := gnustl_static
APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -std=c++11 -fsigned-char
APP_LDFLAGS := -latomic
ifeq ($(NDK_DEBUG),1)
APP_CPPFLAGS += -DCOCOS2D_DEBUG=1
APP_OPTIM := debug
else
APP_CPPFLAGS += -DNDEBUG
APP_OPTIM := release
endif
#include "AppDelegate.h"
#include "cocos2d.h"
#include "platform/android/jni/JniHelper.h"
#include <jni.h>
#include <android/log.h>
#include "ide-support/SimpleConfigParser.h"
#include "ide-support/CodeIDESupport.h"
#define LOG_TAG "main"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
using namespace cocos2d;
void cocos_android_app_init (JNIEnv* env) {
LOGD("cocos_android_app_init");
AppDelegate *pAppDelegate = new AppDelegate();
}
extern "C"
{
bool Java_org_cocos2dx_lua_AppActivity_nativeIsLandScape(JNIEnv *env, jobject thisz)
{
return SimpleConfigParser::getInstance()->isLanscape();
}
bool Java_org_cocos2dx_lua_AppActivity_nativeIsDebug(JNIEnv *env, jobject thisz)
{
#if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)
return true;
#else
return false;
#endif
}
}
# To enable ProGuard in your project, edit project.properties
# to define the proguard.config property as described in that file.
#
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in ${sdk.dir}/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "ant.properties", and override values to adapt the script to your
# project structure.
# Project target.
target=android-10
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">rubbish</string>
</resources>
/****************************************************************************
Copyright (c) 2015 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package com.chukong.cocosplay.client;
import android.app.Activity;
public class CocosPlayClient {
public static boolean init(Activity activity, boolean isDemo) {
return false;
}
public static boolean isEnabled() {
return false;
}
public static boolean isDemo() {
return false;
}
public static boolean isNotifyFileLoadedEnabled() {
return false;
}
public static void notifyFileLoaded(String filePath) {
}
public static void updateAssets(String filePath) {
}
public static String getGameRoot() {
return "";
}
public static native String[] getSearchPaths();
}
package com.enhance.gameservice;
interface IGameTuningService
{
int setPreferredResolution(int resolution);
int setFramePerSecond(int fps);
int boostUp(int seconds);
int getAbstractTemperature();
int setGamePowerSaving(boolean enable);
}
\ No newline at end of file
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.content.Context;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager;
public class Cocos2dxAccelerometer implements SensorEventListener {
// ===========================================================
// Constants
// ===========================================================
private static final String TAG = Cocos2dxAccelerometer.class.getSimpleName();
// ===========================================================
// Fields
// ===========================================================
private final Context mContext;
private final SensorManager mSensorManager;
private final Sensor mAccelerometer;
private final int mNaturalOrientation;
// ===========================================================
// Constructors
// ===========================================================
public Cocos2dxAccelerometer(final Context context) {
this.mContext = context;
this.mSensorManager = (SensorManager) this.mContext.getSystemService(Context.SENSOR_SERVICE);
this.mAccelerometer = this.mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
final Display display = ((WindowManager) this.mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
this.mNaturalOrientation = display.getOrientation();
}
// ===========================================================
// Getter & Setter
// ===========================================================
public void enable() {
this.mSensorManager.registerListener(this, this.mAccelerometer, SensorManager.SENSOR_DELAY_GAME);
}
public void setInterval(float interval) {
// Honeycomb version is 11
if(android.os.Build.VERSION.SDK_INT < 11) {
this.mSensorManager.registerListener(this, this.mAccelerometer, SensorManager.SENSOR_DELAY_GAME);
} else {
//convert seconds to microseconds
this.mSensorManager.registerListener(this, this.mAccelerometer, (int)(interval*100000));
}
}
public void disable() {
this.mSensorManager.unregisterListener(this);
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onSensorChanged(final SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
return;
}
float x = sensorEvent.values[0];
float y = sensorEvent.values[1];
final float z = sensorEvent.values[2];
/*
* Because the axes are not swapped when the device's screen orientation
* changes. So we should swap it here. In tablets such as Motorola Xoom,
* the default orientation is landscape, so should consider this.
*/
final int orientation = this.mContext.getResources().getConfiguration().orientation;
if ((orientation == Configuration.ORIENTATION_LANDSCAPE) && (this.mNaturalOrientation != Surface.ROTATION_0)) {
final float tmp = x;
x = -y;
y = tmp;
} else if ((orientation == Configuration.ORIENTATION_PORTRAIT) && (this.mNaturalOrientation != Surface.ROTATION_0)) {
final float tmp = x;
x = y;
y = -tmp;
}
Cocos2dxGLSurfaceView.queueAccelerometer(x,y,z,sensorEvent.timestamp);
/*
if(BuildConfig.DEBUG) {
Log.d(TAG, "x = " + sensorEvent.values[0] + " y = " + sensorEvent.values[1] + " z = " + pSensorEvent.values[2]);
}
*/
}
@Override
public void onAccuracyChanged(final Sensor sensor, final int accuracy) {
}
// ===========================================================
// Methods
// Native method called from Cocos2dxGLSurfaceView (To be in the same thread)
// ===========================================================
public static native void onSensorChanged(final float x, final float y, final float z, final long timestamp);
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2015 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Log;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public final class Cocos2dxBitmap {
// ===========================================================
// Constants
// ===========================================================
/* The values are the same as cocos2dx/platform/CCImage.h. */
private static final int HORIZONTAL_ALIGN_LEFT = 1;
private static final int HORIZONTAL_ALIGN_RIGHT = 2;
private static final int HORIZONTAL_ALIGN_CENTER = 3;
private static final int VERTICAL_ALIGN_TOP = 1;
private static final int VERTICAL_ALIGN_BOTTOM = 2;
private static final int VERTICAL_ALIGN_CENTER = 3;
// ===========================================================
// Fields
// ===========================================================
private static Context sContext;
// ===========================================================
// Getter & Setter
// ===========================================================
public static void setContext(final Context context) {
Cocos2dxBitmap.sContext = context;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
private static native void nativeInitBitmapDC(final int width,
final int height, final byte[] pixels);
public static boolean createTextBitmapShadowStroke(byte[] bytes, final String fontName, int fontSize,
int fontTintR, int fontTintG, int fontTintB, int fontTintA,
int alignment, int width, int height,
boolean shadow, float shadowDX, float shadowDY, float shadowBlur, float shadowOpacity,
boolean stroke, int strokeR, int strokeG, int strokeB, int strokeA, float strokeSize) {
String string;
if (bytes == null || bytes.length == 0) {
return false;
} else {
string = new String(bytes);
}
Layout.Alignment hAlignment = Layout.Alignment.ALIGN_NORMAL;
int horizontalAlignment = alignment & 0x0F;
switch (horizontalAlignment) {
case HORIZONTAL_ALIGN_CENTER:
hAlignment = Layout.Alignment.ALIGN_CENTER;
break;
case HORIZONTAL_ALIGN_RIGHT:
hAlignment = Layout.Alignment.ALIGN_OPPOSITE;
break;
case HORIZONTAL_ALIGN_LEFT:
break;
default:
break;
}
TextPaint paint = Cocos2dxBitmap.newPaint(fontName, fontSize);
if (stroke) {
paint.setStyle(TextPaint.Style.STROKE);
paint.setStrokeWidth(strokeSize);
}
int maxWidth = width;
if (maxWidth <= 0) {
maxWidth = (int)Math.ceil( StaticLayout.getDesiredWidth(string, paint));
}
StaticLayout staticLayout = new StaticLayout(string, paint, maxWidth , hAlignment,1.0f,0.0f,false);
int layoutWidth = staticLayout.getWidth();
int layoutHeight = staticLayout.getLineTop(staticLayout.getLineCount());
int bitmapWidth = Math.max(layoutWidth, width);
int bitmapHeight = layoutHeight;
if (height > 0) {
bitmapHeight = height;
}
if (bitmapWidth == 0 || bitmapHeight == 0) {
return false;
}
int offsetX = 0;
if (horizontalAlignment == HORIZONTAL_ALIGN_CENTER) {
offsetX = (bitmapWidth - layoutWidth) / 2;
}
else if (horizontalAlignment == HORIZONTAL_ALIGN_RIGHT) {
offsetX = bitmapWidth - layoutWidth;
}
int offsetY = 0;
int verticalAlignment = (alignment >> 4) & 0x0F;
switch (verticalAlignment)
{
case VERTICAL_ALIGN_CENTER:
offsetY = (bitmapHeight - layoutHeight) / 2;
break;
case VERTICAL_ALIGN_BOTTOM:
offsetY = bitmapHeight - layoutHeight;
break;
}
Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.translate(offsetX, offsetY);
if ( stroke )
{
paint.setARGB(strokeA, strokeR, strokeG, strokeB);
staticLayout.draw(canvas);
}
paint.setStyle(TextPaint.Style.FILL);
paint.setARGB(fontTintA, fontTintR, fontTintG, fontTintB);
staticLayout.draw(canvas);
Cocos2dxBitmap.initNativeObject(bitmap);
return true;
}
private static TextPaint newPaint(final String fontName, final int fontSize) {
final TextPaint paint = new TextPaint();
paint.setTextSize(fontSize);
paint.setAntiAlias(true);
// Set type face for paint, now it support .ttf file.
if (fontName.endsWith(".ttf")) {
try {
final Typeface typeFace = Cocos2dxTypefaces.get(
Cocos2dxBitmap.sContext, fontName);
paint.setTypeface(typeFace);
} catch (final Exception e) {
Log.e("Cocos2dxBitmap", "error to create ttf type face: "
+ fontName);
// The file may not find, use system font.
paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL));
}
} else {
paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL));
}
return paint;
}
private static void initNativeObject(final Bitmap bitmap) {
final byte[] pixels = Cocos2dxBitmap.getPixels(bitmap);
if (pixels == null) {
return;
}
Cocos2dxBitmap.nativeInitBitmapDC(bitmap.getWidth(),
bitmap.getHeight(), pixels);
}
private static byte[] getPixels(final Bitmap bitmap) {
if (bitmap != null) {
final byte[] pixels = new byte[bitmap.getWidth()
* bitmap.getHeight() * 4];
final ByteBuffer buf = ByteBuffer.wrap(pixels);
buf.order(ByteOrder.nativeOrder());
bitmap.copyPixelsToBuffer(buf);
return pixels;
}
return null;
}
public static int getFontSizeAccordingHeight(int height) {
TextPaint paint = new TextPaint();
Rect bounds = new Rect();
paint.setTypeface(Typeface.DEFAULT);
int text_size = 1;
boolean found_desired_size = false;
while (!found_desired_size) {
paint.setTextSize(text_size);
String text = "SghMNy";
paint.getTextBounds(text, 0, text.length(), bounds);
text_size++;
if (height - bounds.height() <= 2) {
found_desired_size = true;
}
}
return text_size;
}
private static String getStringWithEllipsis(String string, float width,
float fontSize) {
if (TextUtils.isEmpty(string)) {
return "";
}
TextPaint paint = new TextPaint();
paint.setTypeface(Typeface.DEFAULT);
paint.setTextSize(fontSize);
return TextUtils.ellipsize(string, paint, width,
TextUtils.TruncateAt.END).toString();
}
}
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2015 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.InputFilter;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
public class Cocos2dxEditBox extends EditText {
/**
* The user is allowed to enter any text, including line breaks.
*/
private final int kEditBoxInputModeAny = 0;
/**
* The user is allowed to enter an e-mail address.
*/
private final int kEditBoxInputModeEmailAddr = 1;
/**
* The user is allowed to enter an integer value.
*/
private final int kEditBoxInputModeNumeric = 2;
/**
* The user is allowed to enter a phone number.
*/
private final int kEditBoxInputModePhoneNumber = 3;
/**
* The user is allowed to enter a URL.
*/
private final int kEditBoxInputModeUrl = 4;
/**
* The user is allowed to enter a real number value. This extends kEditBoxInputModeNumeric by allowing a decimal point.
*/
private final int kEditBoxInputModeDecimal = 5;
/**
* The user is allowed to enter any text, except for line breaks.
*/
private final int kEditBoxInputModeSingleLine = 6;
/**
* Indicates that the text entered is confidential data that should be obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE.
*/
private final int kEditBoxInputFlagPassword = 0;
/**
* Indicates that the text entered is sensitive data that the implementation must never store into a dictionary or table for use in predictive, auto-completing, or other accelerated input schemes. A credit card number is an example of sensitive data.
*/
private final int kEditBoxInputFlagSensitive = 1;
/**
* This flag is a hint to the implementation that during text editing, the initial letter of each word should be capitalized.
*/
private final int kEditBoxInputFlagInitialCapsWord = 2;
/**
* This flag is a hint to the implementation that during text editing, the initial letter of each sentence should be capitalized.
*/
private final int kEditBoxInputFlagInitialCapsSentence = 3;
/**
* Capitalize all characters automatically.
*/
private final int kEditBoxInputFlagInitialCapsAllCharacters = 4;
private final int kKeyboardReturnTypeDefault = 0;
private final int kKeyboardReturnTypeDone = 1;
private final int kKeyboardReturnTypeSend = 2;
private final int kKeyboardReturnTypeSearch = 3;
private final int kKeyboardReturnTypeGo = 4;
private int mInputFlagConstraints;
private int mInputModeConstraints;
private int mMaxLength;
//OpenGL view scaleX
private float mScaleX;
public Cocos2dxEditBox(Context context){
super(context);
}
public void setEditBoxViewRect(int left, int top, int maxWidth, int maxHeight) {
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
layoutParams.leftMargin = left;
layoutParams.topMargin = top;
layoutParams.width = maxWidth;
layoutParams.height = maxHeight;
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
this.setLayoutParams(layoutParams);
}
public float getOpenGLViewScaleX() {
return mScaleX;
}
public void setOpenGLViewScaleX(float mScaleX) {
this.mScaleX = mScaleX;
}
public void setMaxLength(int maxLength){
this.mMaxLength = maxLength;
this.setFilters(new InputFilter[]{new InputFilter.LengthFilter(this.mMaxLength) });
}
public void setMultilineEnabled(boolean flag){
this.mInputModeConstraints |= InputType.TYPE_TEXT_FLAG_MULTI_LINE;
}
public void setReturnType(int returnType) {
switch (returnType) {
case kKeyboardReturnTypeDefault:
this.setImeOptions(EditorInfo.IME_ACTION_NONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
break;
case kKeyboardReturnTypeDone:
this.setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
break;
case kKeyboardReturnTypeSend:
this.setImeOptions(EditorInfo.IME_ACTION_SEND | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
break;
case kKeyboardReturnTypeSearch:
this.setImeOptions(EditorInfo.IME_ACTION_SEARCH | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
break;
case kKeyboardReturnTypeGo:
this.setImeOptions(EditorInfo.IME_ACTION_GO | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
break;
default:
this.setImeOptions(EditorInfo.IME_ACTION_NONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
break;
}
}
public void setInputMode(int inputMode){
switch (inputMode) {
case kEditBoxInputModeAny:
this.mInputModeConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE;
break;
case kEditBoxInputModeEmailAddr:
this.mInputModeConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
break;
case kEditBoxInputModeNumeric:
this.mInputModeConstraints = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED;
break;
case kEditBoxInputModePhoneNumber:
this.mInputModeConstraints = InputType.TYPE_CLASS_PHONE;
break;
case kEditBoxInputModeUrl:
this.mInputModeConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI;
break;
case kEditBoxInputModeDecimal:
this.mInputModeConstraints = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED;
break;
case kEditBoxInputModeSingleLine:
this.mInputModeConstraints = InputType.TYPE_CLASS_TEXT;
break;
default:
break;
}
this.setInputType(this.mInputModeConstraints | this.mInputFlagConstraints);
}
@Override
public boolean onKeyDown(final int pKeyCode, final KeyEvent pKeyEvent) {
switch (pKeyCode) {
case KeyEvent.KEYCODE_BACK:
Cocos2dxActivity activity = (Cocos2dxActivity)this.getContext();
//To prevent program from going to background
activity.getGLSurfaceView().requestFocus();
return true;
default:
return super.onKeyDown(pKeyCode, pKeyEvent);
}
}
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
return super.onKeyPreIme(keyCode, event);
}
public void setInputFlag(int inputFlag) {
switch (inputFlag) {
case kEditBoxInputFlagPassword:
this.mInputFlagConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
this.setTypeface(Typeface.DEFAULT);
this.setTransformationMethod(new PasswordTransformationMethod());
break;
case kEditBoxInputFlagSensitive:
this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
break;
case kEditBoxInputFlagInitialCapsWord:
this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_WORDS;
break;
case kEditBoxInputFlagInitialCapsSentence:
this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_SENTENCES;
break;
case kEditBoxInputFlagInitialCapsAllCharacters:
this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS;
break;
default:
break;
}
this.setInputType(this.mInputFlagConstraints | this.mInputModeConstraints);
}
}
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import java.lang.ref.WeakReference;
public class Cocos2dxHandler extends Handler {
// ===========================================================
// Constants
// ===========================================================
public final static int HANDLER_SHOW_DIALOG = 1;
// ===========================================================
// Fields
// ===========================================================
private WeakReference<Cocos2dxActivity> mActivity;
// ===========================================================
// Constructors
// ===========================================================
public Cocos2dxHandler(Cocos2dxActivity activity) {
this.mActivity = new WeakReference<Cocos2dxActivity>(activity);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void handleMessage(Message msg) {
switch (msg.what) {
case Cocos2dxHandler.HANDLER_SHOW_DIALOG:
showDialog(msg);
break;
}
}
private void showDialog(Message msg) {
Cocos2dxActivity theActivity = this.mActivity.get();
DialogMessage dialogMessage = (DialogMessage)msg.obj;
new AlertDialog.Builder(theActivity)
.setTitle(dialogMessage.titile)
.setMessage(dialogMessage.message)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).create().show();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static class DialogMessage {
public String titile;
public String message;
public DialogMessage(String title, String message) {
this.titile = title;
this.message = message;
}
}
}
/*
* Copyright (c) 2013-2014 Chukong Technologies Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.cocos2dx.lib;
public class Cocos2dxJavascriptJavaBridge {
public static native int evalString(String value);
}
/****************************************************************************
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class Cocos2dxLocalStorage {
private static final String TAG = "Cocos2dxLocalStorage";
private static String DATABASE_NAME = "jsb.sqlite";
private static String TABLE_NAME = "data";
private static final int DATABASE_VERSION = 1;
private static DBOpenHelper mDatabaseOpenHelper = null;
private static SQLiteDatabase mDatabase = null;
/**
* Constructor
* @param context The Context within which to work, used to create the DB
* @return
*/
public static boolean init(String dbName, String tableName) {
if (Cocos2dxActivity.getContext() != null) {
DATABASE_NAME = dbName;
TABLE_NAME = tableName;
mDatabaseOpenHelper = new DBOpenHelper(Cocos2dxActivity.getContext());
mDatabase = mDatabaseOpenHelper.getWritableDatabase();
return true;
}
return false;
}
public static void destory() {
if (mDatabase != null) {
mDatabase.close();
}
}
public static void setItem(String key, String value) {
try {
String sql = "replace into "+TABLE_NAME+"(key,value)values(?,?)";
mDatabase.execSQL(sql, new Object[] { key, value });
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getItem(String key) {
String ret = null;
try {
String sql = "select value from "+TABLE_NAME+" where key=?";
Cursor c = mDatabase.rawQuery(sql, new String[]{key});
while (c.moveToNext()) {
// only return the first value
if (ret != null)
{
Log.e(TAG, "The key contains more than one value.");
break;
}
ret = c.getString(c.getColumnIndex("value"));
}
c.close();
} catch (Exception e) {
e.printStackTrace();
}
return ret == null ? "" : ret;
}
public static void removeItem(String key) {
try {
String sql = "delete from "+TABLE_NAME+" where key=?";
mDatabase.execSQL(sql, new Object[] {key});
} catch (Exception e) {
e.printStackTrace();
}
}
public static void clear() {
try {
String sql = "delete from "+TABLE_NAME;
mDatabase.execSQL(sql);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* This creates/opens the database.
*/
private static class DBOpenHelper extends SQLiteOpenHelper {
DBOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS "+TABLE_NAME+"(key TEXT PRIMARY KEY,value TEXT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
//db.execSQL("DROP TABLE IF EXISTS " + VIRTUAL_TABLE);
//onCreate(db);
}
}
}
/****************************************************************************
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
public class Cocos2dxLuaJavaBridge
{
public static native int callLuaFunctionWithString(int luaFunctionId, String value);
public static native int callLuaGlobalFunctionWithString(String luaFunctionName, String value);
public static native int retainLuaFunction(int luaFunctionId);
public static native int releaseLuaFunction(int luaFunctionId);
}
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.util.Log;
import com.chukong.cocosplay.client.CocosPlayClient;
import java.io.FileInputStream;
public class Cocos2dxMusic {
// ===========================================================
// Constants
// ===========================================================
private static final String TAG = Cocos2dxMusic.class.getSimpleName();
// ===========================================================
// Fields
// ===========================================================
private final Context mContext;
private MediaPlayer mBackgroundMediaPlayer;
private float mLeftVolume;
private float mRightVolume;
private boolean mPaused; // whether music is paused state.
private boolean mIsLoop = false;
private boolean mManualPaused = false; // whether music is paused manually before the program is switched to the background.
private String mCurrentPath;
// ===========================================================
// Constructors
// ===========================================================
public Cocos2dxMusic(final Context context) {
this.mContext = context;
this.initData();
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void preloadBackgroundMusic(final String path) {
if ((this.mCurrentPath == null) || (!this.mCurrentPath.equals(path))) {
// preload new background music
// release old resource and create a new one
if (this.mBackgroundMediaPlayer != null) {
this.mBackgroundMediaPlayer.release();
}
this.mBackgroundMediaPlayer = this.createMediaplayer(path);
// record the path
this.mCurrentPath = path;
}
}
public void playBackgroundMusic(final String path, final boolean isLoop) {
if (mCurrentPath == null) {
// it is the first time to play background music or end() was called
mBackgroundMediaPlayer = createMediaplayer(path);
mCurrentPath = path;
} else {
if (!mCurrentPath.equals(path)) {
// play new background music
// release old resource and create a new one
if (mBackgroundMediaPlayer != null) {
mBackgroundMediaPlayer.release();
}
mBackgroundMediaPlayer = createMediaplayer(path);
// record the path
mCurrentPath = path;
}
}
if (mBackgroundMediaPlayer == null) {
Log.e(Cocos2dxMusic.TAG, "playBackgroundMusic: background media player is null");
} else {
try {
// if the music is playing or paused, stop it
if (mPaused) {
mBackgroundMediaPlayer.seekTo(0);
mBackgroundMediaPlayer.start();
} else if (mBackgroundMediaPlayer.isPlaying()) {
mBackgroundMediaPlayer.seekTo(0);
} else {
mBackgroundMediaPlayer.start();
}
mBackgroundMediaPlayer.setLooping(isLoop);
mPaused = false;
mIsLoop = isLoop;
} catch (final Exception e) {
Log.e(Cocos2dxMusic.TAG, "playBackgroundMusic: error state");
}
}
}
public void stopBackgroundMusic() {
if (this.mBackgroundMediaPlayer != null) {
mBackgroundMediaPlayer.release();
mBackgroundMediaPlayer = createMediaplayer(mCurrentPath);
/**
* should set the state, if not, the following sequence will be error
* play -> pause -> stop -> resume
*/
this.mPaused = false;
}
}
public void pauseBackgroundMusic() {
if (this.mBackgroundMediaPlayer != null && this.mBackgroundMediaPlayer.isPlaying()) {
this.mBackgroundMediaPlayer.pause();
this.mPaused = true;
this.mManualPaused = true;
}
}
public void resumeBackgroundMusic() {
if (this.mBackgroundMediaPlayer != null && this.mPaused) {
this.mBackgroundMediaPlayer.start();
this.mPaused = false;
this.mManualPaused = false;
}
}
public void rewindBackgroundMusic() {
if (this.mBackgroundMediaPlayer != null) {
playBackgroundMusic(mCurrentPath, mIsLoop);
}
}
public boolean isBackgroundMusicPlaying() {
boolean ret = false;
if (this.mBackgroundMediaPlayer == null) {
ret = false;
} else {
ret = this.mBackgroundMediaPlayer.isPlaying();
}
return ret;
}
public void end() {
if (this.mBackgroundMediaPlayer != null) {
this.mBackgroundMediaPlayer.release();
}
this.initData();
}
public float getBackgroundVolume() {
if (this.mBackgroundMediaPlayer != null) {
return (this.mLeftVolume + this.mRightVolume) / 2;
} else {
return 0.0f;
}
}
public void setBackgroundVolume(float volume) {
if (volume < 0.0f) {
volume = 0.0f;
}
if (volume > 1.0f) {
volume = 1.0f;
}
this.mLeftVolume = this.mRightVolume = volume;
if (this.mBackgroundMediaPlayer != null) {
this.mBackgroundMediaPlayer.setVolume(this.mLeftVolume, this.mRightVolume);
}
}
public void onEnterBackground(){
if (this.mBackgroundMediaPlayer != null && this.mBackgroundMediaPlayer.isPlaying()) {
this.mBackgroundMediaPlayer.pause();
this.mPaused = true;
}
}
public void onEnterForeground(){
if(!this.mManualPaused){
if (this.mBackgroundMediaPlayer != null && this.mPaused) {
this.mBackgroundMediaPlayer.start();
this.mPaused = false;
}
}
}
private void initData() {
this.mLeftVolume = 0.5f;
this.mRightVolume = 0.5f;
this.mBackgroundMediaPlayer = null;
this.mPaused = false;
this.mCurrentPath = null;
}
/**
* create mediaplayer for music
*
* @param pPath
* the pPath relative to assets
* @return
*/
private MediaPlayer createMediaplayer(final String path) {
MediaPlayer mediaPlayer = new MediaPlayer();
try {
if (CocosPlayClient.isEnabled() && !CocosPlayClient.isDemo()) {
CocosPlayClient.updateAssets(path);
}
CocosPlayClient.notifyFileLoaded(path);
if (path.startsWith("/")) {
final FileInputStream fis = new FileInputStream(path);
mediaPlayer.setDataSource(fis.getFD());
fis.close();
} else {
final AssetFileDescriptor assetFileDescritor = this.mContext.getAssets().openFd(path);
mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(), assetFileDescritor.getStartOffset(), assetFileDescritor.getLength());
}
mediaPlayer.prepare();
mediaPlayer.setVolume(this.mLeftVolume, this.mRightVolume);
} catch (final Exception e) {
mediaPlayer = null;
Log.e(Cocos2dxMusic.TAG, "error: " + e.getMessage(), e);
}
return mediaPlayer;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.opengl.GLSurfaceView;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
public class Cocos2dxRenderer implements GLSurfaceView.Renderer {
// ===========================================================
// Constants
// ===========================================================
private final static long NANOSECONDSPERSECOND = 1000000000L;
private final static long NANOSECONDSPERMICROSECOND = 1000000;
private static long sAnimationInterval = (long) (1.0 / 60 * Cocos2dxRenderer.NANOSECONDSPERSECOND);
// ===========================================================
// Fields
// ===========================================================
private long mLastTickInNanoSeconds;
private int mScreenWidth;
private int mScreenHeight;
private boolean mNativeInitCompleted = false;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
public static void setAnimationInterval(final float animationInterval) {
Cocos2dxRenderer.sAnimationInterval = (long) (animationInterval * Cocos2dxRenderer.NANOSECONDSPERSECOND);
}
public void setScreenWidthAndHeight(final int surfaceWidth, final int surfaceHeight) {
this.mScreenWidth = surfaceWidth;
this.mScreenHeight = surfaceHeight;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onSurfaceCreated(final GL10 GL10, final EGLConfig EGLConfig) {
Cocos2dxRenderer.nativeInit(this.mScreenWidth, this.mScreenHeight);
this.mLastTickInNanoSeconds = System.nanoTime();
mNativeInitCompleted = true;
}
@Override
public void onSurfaceChanged(final GL10 GL10, final int width, final int height) {
Cocos2dxRenderer.nativeOnSurfaceChanged(width, height);
}
@Override
public void onDrawFrame(final GL10 gl) {
/*
* No need to use algorithm in default(60 FPS) situation,
* since onDrawFrame() was called by system 60 times per second by default.
*/
if (sAnimationInterval <= 1.0 / 60 * Cocos2dxRenderer.NANOSECONDSPERSECOND) {
Cocos2dxRenderer.nativeRender();
} else {
final long now = System.nanoTime();
final long interval = now - this.mLastTickInNanoSeconds;
if (interval < Cocos2dxRenderer.sAnimationInterval) {
try {
Thread.sleep((Cocos2dxRenderer.sAnimationInterval - interval) / Cocos2dxRenderer.NANOSECONDSPERMICROSECOND);
} catch (final Exception e) {
}
}
/*
* Render time MUST be counted in, or the FPS will slower than appointed.
*/
this.mLastTickInNanoSeconds = System.nanoTime();
Cocos2dxRenderer.nativeRender();
}
}
// ===========================================================
// Methods
// ===========================================================
private static native void nativeTouchesBegin(final int id, final float x, final float y);
private static native void nativeTouchesEnd(final int id, final float x, final float y);
private static native void nativeTouchesMove(final int[] ids, final float[] xs, final float[] ys);
private static native void nativeTouchesCancel(final int[] ids, final float[] xs, final float[] ys);
private static native boolean nativeKeyEvent(final int keyCode,boolean isPressed);
private static native void nativeRender();
private static native void nativeInit(final int width, final int height);
private static native void nativeOnSurfaceChanged(final int width, final int height);
private static native void nativeOnPause();
private static native void nativeOnResume();
public void handleActionDown(final int id, final float x, final float y) {
Cocos2dxRenderer.nativeTouchesBegin(id, x, y);
}
public void handleActionUp(final int id, final float x, final float y) {
Cocos2dxRenderer.nativeTouchesEnd(id, x, y);
}
public void handleActionCancel(final int[] ids, final float[] xs, final float[] ys) {
Cocos2dxRenderer.nativeTouchesCancel(ids, xs, ys);
}
public void handleActionMove(final int[] ids, final float[] xs, final float[] ys) {
Cocos2dxRenderer.nativeTouchesMove(ids, xs, ys);
}
public void handleKeyDown(final int keyCode) {
Cocos2dxRenderer.nativeKeyEvent(keyCode, true);
}
public void handleKeyUp(final int keyCode) {
Cocos2dxRenderer.nativeKeyEvent(keyCode, false);
}
public void handleOnPause() {
/**
* onPause may be invoked before onSurfaceCreated,
* and engine will be initialized correctly after
* onSurfaceCreated is invoked. Can not invoke any
* native method before onSurfaceCreated is invoked
*/
if (! mNativeInitCompleted)
return;
Cocos2dxHelper.onEnterBackground();
Cocos2dxRenderer.nativeOnPause();
}
public void handleOnResume() {
Cocos2dxHelper.onEnterForeground();
Cocos2dxRenderer.nativeOnResume();
}
private static native void nativeInsertText(final String text);
private static native void nativeDeleteBackward();
private static native String nativeGetContentText();
public void handleInsertText(final String text) {
Cocos2dxRenderer.nativeInsertText(text);
}
public void handleDeleteBackward() {
Cocos2dxRenderer.nativeDeleteBackward();
}
public String getContentText() {
return Cocos2dxRenderer.nativeGetContentText();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class Cocos2dxTextInputWraper implements TextWatcher, OnEditorActionListener {
// ===========================================================
// Constants
// ===========================================================
private static final String TAG = Cocos2dxTextInputWraper.class.getSimpleName();
// ===========================================================
// Fields
// ===========================================================
private final Cocos2dxGLSurfaceView mCocos2dxGLSurfaceView;
private String mText;
private String mOriginText;
// ===========================================================
// Constructors
// ===========================================================
public Cocos2dxTextInputWraper(final Cocos2dxGLSurfaceView pCocos2dxGLSurfaceView) {
this.mCocos2dxGLSurfaceView = pCocos2dxGLSurfaceView;
}
// ===========================================================
// Getter & Setter
// ===========================================================
private boolean isFullScreenEdit() {
final TextView textField = this.mCocos2dxGLSurfaceView.getCocos2dxEditText();
final InputMethodManager imm = (InputMethodManager) textField.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
return imm.isFullscreenMode();
}
public void setOriginText(final String pOriginText) {
this.mOriginText = pOriginText;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void afterTextChanged(final Editable s) {
if (this.isFullScreenEdit()) {
return;
}
int old_i = 0;
int new_i = 0;
while (old_i < this.mText.length() && new_i < s.length()) {
if (this.mText.charAt(old_i) != s.charAt(new_i)) {
break;
}
old_i += 1;
new_i += 1;
}
for (; old_i < this.mText.length(); ++old_i) {
this.mCocos2dxGLSurfaceView.deleteBackward();
}
int nModified = s.length() - new_i;
if (nModified > 0) {
final String insertText = s.subSequence(new_i, s.length()).toString();
this.mCocos2dxGLSurfaceView.insertText(insertText);
}
this.mText = s.toString();
}
@Override
public void beforeTextChanged(final CharSequence pCharSequence, final int start, final int count, final int after) {
this.mText = pCharSequence.toString();
}
@Override
public void onTextChanged(final CharSequence pCharSequence, final int start, final int before, final int count) {
}
@Override
public boolean onEditorAction(final TextView pTextView, final int pActionID, final KeyEvent pKeyEvent) {
if (this.mCocos2dxGLSurfaceView.getCocos2dxEditText() == pTextView && this.isFullScreenEdit()) {
// user press the action button, delete all old text and insert new text
if (null != mOriginText) {
for (int i = this.mOriginText.length(); i > 0; i--) {
this.mCocos2dxGLSurfaceView.deleteBackward();
}
}
String text = pTextView.getText().toString();
if (text != null) {
/* If user input nothing, translate "\n" to engine. */
if ( text.compareTo("") == 0) {
text = "\n";
}
if ( '\n' != text.charAt(text.length() - 1)) {
text += '\n';
}
}
final String insertText = text;
this.mCocos2dxGLSurfaceView.insertText(insertText);
}
if (pActionID == EditorInfo.IME_ACTION_DONE) {
this.mCocos2dxGLSurfaceView.requestFocus();
}
return false;
}
}
\ No newline at end of file
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.content.Context;
import android.graphics.Typeface;
import java.util.HashMap;
public class Cocos2dxTypefaces {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static final HashMap<String, Typeface> sTypefaceCache = new HashMap<String, Typeface>();
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static synchronized Typeface get(final Context context, final String assetName) {
if (!Cocos2dxTypefaces.sTypefaceCache.containsKey(assetName)) {
Typeface typeface = null;
if (assetName.startsWith("/"))
{
typeface = Typeface.createFromFile(assetName);
}
else
{
typeface = Typeface.createFromAsset(context.getAssets(), assetName);
}
Cocos2dxTypefaces.sTypefaceCache.put(assetName, typeface);
}
return Cocos2dxTypefaces.sTypefaceCache.get(assetName);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
package org.cocos2dx.lib;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import android.view.Gravity;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.concurrent.CountDownLatch;
class ShouldStartLoadingWorker implements Runnable {
private CountDownLatch mLatch;
private boolean[] mResult;
private final int mViewTag;
private final String mUrlString;
ShouldStartLoadingWorker(CountDownLatch latch, boolean[] result, int viewTag, String urlString) {
this.mLatch = latch;
this.mResult = result;
this.mViewTag = viewTag;
this.mUrlString = urlString;
}
@Override
public void run() {
this.mResult[0] = Cocos2dxWebViewHelper._shouldStartLoading(mViewTag, mUrlString);
this.mLatch.countDown(); // notify that result is ready
}
}
public class Cocos2dxWebView extends WebView {
private static final String TAG = Cocos2dxWebViewHelper.class.getSimpleName();
private int mViewTag;
private String mJSScheme;
public Cocos2dxWebView(Context context) {
this(context, -1);
}
@SuppressLint("SetJavaScriptEnabled")
public Cocos2dxWebView(Context context, int viewTag) {
super(context);
this.mViewTag = viewTag;
this.mJSScheme = "";
this.setFocusable(true);
this.setFocusableInTouchMode(true);
this.getSettings().setSupportZoom(false);
this.getSettings().setJavaScriptEnabled(true);
// `searchBoxJavaBridge_` has big security risk. http://jvn.jp/en/jp/JVN53768697
try {
Method method = this.getClass().getMethod("removeJavascriptInterface", new Class[]{String.class});
method.invoke(this, "searchBoxJavaBridge_");
} catch (Exception e) {
Log.d(TAG, "This API level do not support `removeJavascriptInterface`");
}
this.setWebViewClient(new Cocos2dxWebViewClient());
this.setWebChromeClient(new WebChromeClient());
}
public void setJavascriptInterfaceScheme(String scheme) {
this.mJSScheme = scheme != null ? scheme : "";
}
public void setScalesPageToFit(boolean scalesPageToFit) {
this.getSettings().setSupportZoom(scalesPageToFit);
}
class Cocos2dxWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, final String urlString) {
Cocos2dxActivity activity = (Cocos2dxActivity)getContext();
try {
URI uri = URI.create(urlString);
if (uri != null && uri.getScheme().equals(mJSScheme)) {
activity.runOnGLThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebViewHelper._onJsCallback(mViewTag, urlString);
}
});
return true;
}
} catch (Exception e) {
Log.d(TAG, "Failed to create URI from url");
}
boolean[] result = new boolean[] { true };
CountDownLatch latch = new CountDownLatch(1);
// run worker on cocos thread
activity.runOnGLThread(new ShouldStartLoadingWorker(latch, result, mViewTag, urlString));
// wait for result from cocos thread
try {
latch.await();
} catch (InterruptedException ex) {
Log.d(TAG, "'shouldOverrideUrlLoading' failed");
}
return result[0];
}
@Override
public void onPageFinished(WebView view, final String url) {
super.onPageFinished(view, url);
Cocos2dxActivity activity = (Cocos2dxActivity)getContext();
activity.runOnGLThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebViewHelper._didFinishLoading(mViewTag, url);
}
});
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, final String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Cocos2dxActivity activity = (Cocos2dxActivity)getContext();
activity.runOnGLThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebViewHelper._didFailLoading(mViewTag, failingUrl);
}
});
}
}
public void setWebViewRect(int left, int top, int maxWidth, int maxHeight) {
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
layoutParams.leftMargin = left;
layoutParams.topMargin = top;
layoutParams.width = maxWidth;
layoutParams.height = maxHeight;
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
this.setLayoutParams(layoutParams);
}
}
package org.cocos2dx.lib;
import android.os.Handler;
import android.os.Looper;
import android.util.SparseArray;
import android.view.View;
import android.widget.FrameLayout;
import com.chukong.cocosplay.client.CocosPlayClient;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Cocos2dxWebViewHelper {
private static final String TAG = Cocos2dxWebViewHelper.class.getSimpleName();
private static Handler sHandler;
private static Cocos2dxActivity sCocos2dxActivity;
private static FrameLayout sLayout;
private static SparseArray<Cocos2dxWebView> webViews;
private static int viewTag = 0;
public Cocos2dxWebViewHelper(FrameLayout layout) {
Cocos2dxWebViewHelper.sLayout = layout;
Cocos2dxWebViewHelper.sHandler = new Handler(Looper.myLooper());
Cocos2dxWebViewHelper.sCocos2dxActivity = (Cocos2dxActivity) Cocos2dxActivity.getContext();
Cocos2dxWebViewHelper.webViews = new SparseArray<Cocos2dxWebView>();
}
private static native boolean shouldStartLoading(int index, String message);
public static boolean _shouldStartLoading(int index, String message) {
return !shouldStartLoading(index, message);
}
private static native void didFinishLoading(int index, String message);
public static void _didFinishLoading(int index, String message) {
didFinishLoading(index, message);
}
private static native void didFailLoading(int index, String message);
public static void _didFailLoading(int index, String message) {
didFailLoading(index, message);
}
private static native void onJsCallback(int index, String message);
public static void _onJsCallback(int index, String message) {
onJsCallback(index, message);
}
public static int createWebView() {
final int index = viewTag;
sCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = new Cocos2dxWebView(sCocos2dxActivity, index);
FrameLayout.LayoutParams lParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
sLayout.addView(webView, lParams);
webViews.put(index, webView);
}
});
return viewTag++;
}
public static void removeWebView(final int index) {
sCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = webViews.get(index);
if (webView != null) {
webViews.remove(index);
sLayout.removeView(webView);
}
}
});
}
public static void setVisible(final int index, final boolean visible) {
sCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = webViews.get(index);
if (webView != null) {
webView.setVisibility(visible ? View.VISIBLE : View.GONE);
}
}
});
}
public static void setWebViewRect(final int index, final int left, final int top, final int maxWidth, final int maxHeight) {
sCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = webViews.get(index);
if (webView != null) {
webView.setWebViewRect(left, top, maxWidth, maxHeight);
}
}
});
}
public static void setJavascriptInterfaceScheme(final int index, final String scheme) {
sCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = webViews.get(index);
if (webView != null) {
webView.setJavascriptInterfaceScheme(scheme);
}
}
});
}
public static void loadData(final int index, final String data, final String mimeType, final String encoding, final String baseURL) {
sCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = webViews.get(index);
if (webView != null) {
webView.loadDataWithBaseURL(baseURL, data, mimeType, encoding, null);
}
}
});
}
public static void loadHTMLString(final int index, final String data, final String baseUrl) {
sCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = webViews.get(index);
if (webView != null) {
webView.loadDataWithBaseURL(baseUrl, data, null, null, null);
}
}
});
}
public static void loadUrl(final int index, final String url) {
sCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = webViews.get(index);
if (webView != null) {
webView.loadUrl(url);
}
}
});
}
public static void loadFile(final int index, final String filePath) {
if (CocosPlayClient.isEnabled() && !CocosPlayClient.isDemo()) {
CocosPlayClient.updateAssets(filePath);
}
CocosPlayClient.notifyFileLoaded(filePath);
sCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = webViews.get(index);
if (webView != null) {
webView.loadUrl(filePath);
}
}
});
}
public static void stopLoading(final int index) {
sCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = webViews.get(index);
if (webView != null) {
webView.stopLoading();
}
}
});
}
public static void reload(final int index) {
sCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = webViews.get(index);
if (webView != null) {
webView.reload();
}
}
});
}
public static <T> T callInMainThread(Callable<T> call) throws ExecutionException, InterruptedException {
FutureTask<T> task = new FutureTask<T>(call);
sHandler.post(task);
return task.get();
}
public static boolean canGoBack(final int index) {
Callable<Boolean> callable = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
Cocos2dxWebView webView = webViews.get(index);
return webView != null && webView.canGoBack();
}
};
try {
return callInMainThread(callable);
} catch (ExecutionException e) {
return false;
} catch (InterruptedException e) {
return false;
}
}
public static boolean canGoForward(final int index) {
Callable<Boolean> callable = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
Cocos2dxWebView webView = webViews.get(index);
return webView != null && webView.canGoForward();
}
};
try {
return callInMainThread(callable);
} catch (ExecutionException e) {
return false;
} catch (InterruptedException e) {
return false;
}
}
public static void goBack(final int index) {
sCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = webViews.get(index);
if (webView != null) {
webView.goBack();
}
}
});
}
public static void goForward(final int index) {
sCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = webViews.get(index);
if (webView != null) {
webView.goForward();
}
}
});
}
public static void evaluateJS(final int index, final String js) {
sCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = webViews.get(index);
if (webView != null) {
webView.loadUrl("javascript:" + js);
}
}
});
}
public static void setScalesPageToFit(final int index, final boolean scalesPageToFit) {
sCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = webViews.get(index);
if (webView != null) {
webView.setScalesPageToFit(scalesPageToFit);
}
}
});
}
}
package org.cocos2dx.lib;
import java.util.ArrayList;
public class GameControllerAdapter {
private static ArrayList<Runnable> sRunnableFrameStartList = null;
public static void addRunnableToFrameStartList(Runnable runnable) {
if (sRunnableFrameStartList == null)
sRunnableFrameStartList = new ArrayList<Runnable>();
sRunnableFrameStartList.add(runnable);
}
public static void removeRunnableFromFrameStartList(Runnable runnable) {
if (sRunnableFrameStartList != null)
sRunnableFrameStartList.remove(runnable);
}
public static void onDrawFrameStart() {
if (sRunnableFrameStartList != null)
{
int size = sRunnableFrameStartList.size();
for (int i = 0; i < size; ++i) {
sRunnableFrameStartList.get(i).run();
}
}
}
public static void onConnected(final String vendorName, final int controller)
{
Cocos2dxHelper.runOnGLThread(new Runnable() {
@Override
public void run() {
nativeControllerConnected(vendorName, controller);
}
});
}
public static void onDisconnected(final String vendorName, final int controller)
{
Cocos2dxHelper.runOnGLThread(new Runnable() {
@Override
public void run() {
nativeControllerDisconnected(vendorName, controller);
}
});
}
public static void onButtonEvent(final String vendorName, final int controller, final int button, final boolean isPressed, final float value, final boolean isAnalog)
{
Cocos2dxHelper.runOnGLThread(new Runnable() {
@Override
public void run() {
nativeControllerButtonEvent(vendorName, controller, button, isPressed, value, isAnalog);
}
});
}
public static void onAxisEvent(final String vendorName, final int controller, final int axisID, final float value, final boolean isAnalog)
{
Cocos2dxHelper.runOnGLThread(new Runnable() {
@Override
public void run() {
nativeControllerAxisEvent(vendorName, controller, axisID, value, isAnalog);
}
});
}
private static native void nativeControllerConnected(final String vendorName, final int controller);
private static native void nativeControllerDisconnected(final String vendorName, final int controller);
private static native void nativeControllerButtonEvent(final String vendorName, final int controller, final int button, final boolean isPressed, final float value, final boolean isAnalog);
private static native void nativeControllerAxisEvent(final String vendorName, final int controller, final int axisID, final float value, final boolean isAnalog);
}
package org.cocos2dx.lib;
import android.content.Context;
import android.view.KeyEvent;
import android.view.MotionEvent;
public interface GameControllerDelegate {
static final int KEY_BASE = 1000;
public static final int THUMBSTICK_LEFT_X = KEY_BASE;
public static final int THUMBSTICK_LEFT_Y = KEY_BASE + 1;
public static final int THUMBSTICK_RIGHT_X = KEY_BASE + 2;
public static final int THUMBSTICK_RIGHT_Y = KEY_BASE + 3;
public static final int BUTTON_A = KEY_BASE + 4;
public static final int BUTTON_B = KEY_BASE + 5;
public static final int BUTTON_C = KEY_BASE + 6;
public static final int BUTTON_X = KEY_BASE + 7;
public static final int BUTTON_Y = KEY_BASE + 8;
public static final int BUTTON_Z = KEY_BASE + 9;
public static final int BUTTON_DPAD_UP = KEY_BASE + 10;
public static final int BUTTON_DPAD_DOWN = KEY_BASE + 11;
public static final int BUTTON_DPAD_LEFT = KEY_BASE + 12;
public static final int BUTTON_DPAD_RIGHT = KEY_BASE + 13;
public static final int BUTTON_DPAD_CENTER = KEY_BASE + 14;
public static final int BUTTON_LEFT_SHOULDER = KEY_BASE + 15;
public static final int BUTTON_RIGHT_SHOULDER = KEY_BASE + 16;
public static final int BUTTON_LEFT_TRIGGER = KEY_BASE + 17;
public static final int BUTTON_RIGHT_TRIGGER = KEY_BASE + 18;
public static final int BUTTON_LEFT_THUMBSTICK = KEY_BASE + 19;
public static final int BUTTON_RIGHT_THUMBSTICK = KEY_BASE + 20;
public static final int BUTTON_START = KEY_BASE + 21;
public static final int BUTTON_SELECT = KEY_BASE + 22;
void onCreate(Context context);
void onPause();
void onResume();
void onDestroy();
boolean dispatchKeyEvent(KeyEvent event);
boolean dispatchGenericMotionEvent(MotionEvent event);
void setControllerEventListener(ControllerEventListener listener);
public interface ControllerEventListener {
void onButtonEvent(String vendorName, int controller, int button, boolean isPressed, float value, boolean isAnalog);
void onAxisEvent(String vendorName, int controller, int axisID, float value, boolean isAnalog);
void onConnected(String vendorName, int controller);
void onDisconnected(String vendorName, int controller);
}
}
package org.cocos2dx.lib;
import java.io.File;
import java.io.FileInputStream;
public class GameControllerUtils {
public static void ensureDirectoryExist(String path){
File sdkDir = new File(path);
if(!sdkDir.exists()){
sdkDir.mkdirs();
}
}
public static String readJsonFile(String filePath) {
File file = new File(filePath);
if (!file.exists()){
return null;
}
try {
FileInputStream is = new FileInputStream(file);;
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String jsonstr = new String(buffer, "UTF-8");
return jsonstr;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
/****************************************************************************
Copyright (c) 2010-2013 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.FrameLayout;
public class ResizeLayout extends FrameLayout {
private boolean mEnableForceDoLayout = false;
public ResizeLayout(Context context){
super(context);
}
public ResizeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setEnableForceDoLayout(boolean flag){
mEnableForceDoLayout = flag;
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
if(mEnableForceDoLayout){
/*This is a hot-fix for some android devices which don't do layout when the main window
* is paned. We refersh the layout in 24 frames per seconds.
* When the editBox is lose focus or when user begin to type, the do layout is disabled.
*/
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
requestLayout();
invalidate();
}
}, 1000 / 24);
}
}
}
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lua;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.ArrayList;
import org.cocos2dx.lib.Cocos2dxActivity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.ActivityInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.provider.Settings;
import android.text.format.Formatter;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;
public class AppActivity extends Cocos2dxActivity{
static String hostIPAdress = "0.0.0.0";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(nativeIsLandScape()) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
//2.Set the format of window
// Check the wifi is opened when the native is debug.
if(nativeIsDebug())
{
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if(!isNetworkConnected())
{
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Warning");
builder.setMessage("Please open WIFI for debuging...");
builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
finish();
System.exit(0);
}
});
builder.setNegativeButton("Cancel", null);
builder.setCancelable(true);
builder.show();
}
hostIPAdress = getHostIpAddress();
}
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
ArrayList networkTypes = new ArrayList();
networkTypes.add(ConnectivityManager.TYPE_WIFI);
try {
networkTypes.add(ConnectivityManager.class.getDeclaredField("TYPE_ETHERNET").getInt(null));
} catch (NoSuchFieldException nsfe) {
}
catch (IllegalAccessException iae) {
throw new RuntimeException(iae);
}
if (networkInfo != null && networkTypes.contains(networkInfo.getType())) {
return true;
}
}
return false;
}
public String getHostIpAddress() {
WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
return ((ip & 0xFF) + "." + ((ip >>>= 8) & 0xFF) + "." + ((ip >>>= 8) & 0xFF) + "." + ((ip >>>= 8) & 0xFF));
}
public static String getLocalIpAddress() {
return hostIPAdress;
}
private static native boolean nativeIsLandScape();
private static native boolean nativeIsDebug();
}
/****************************************************************************
Copyright (c) 2010-2013 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
@class RootViewController;
@interface AppController : NSObject <UIApplicationDelegate>
{
UIWindow *window;
RootViewController *viewController;
}
@end
/****************************************************************************
Copyright (c) 2010-2013 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#import <UIKit/UIKit.h>
#import "cocos2d.h"
#import "AppController.h"
#import "AppDelegate.h"
#import "RootViewController.h"
#import "platform/ios/CCEAGLView-ios.h"
@implementation AppController
#pragma mark -
#pragma mark Application lifecycle
// cocos2d application instance
static AppDelegate s_sharedApplication;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
cocos2d::Application *app = cocos2d::Application::getInstance();
app->initGLContextAttrs();
cocos2d::GLViewImpl::convertAttrs();
// Override point for customization after application launch.
// Add the view controller's view to the window and display.
window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
CCEAGLView *eaglView = [CCEAGLView viewWithFrame: [window bounds]
pixelFormat: (NSString*)cocos2d::GLViewImpl::_pixelFormat
depthFormat: cocos2d::GLViewImpl::_depthFormat
preserveBackbuffer: NO
sharegroup: nil
multiSampling: NO
numberOfSamples: 0 ];
[eaglView setMultipleTouchEnabled:YES];
// Use RootViewController manage CCEAGLView
viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
viewController.wantsFullScreenLayout = YES;
viewController.view = eaglView;
// Set RootViewController to window
if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0)
{
// warning: addSubView doesn't work on iOS6
[window addSubview: viewController.view];
}
else
{
// use this method on ios6
[window setRootViewController:viewController];
}
[window makeKeyAndVisible];
[[UIApplication sharedApplication] setStatusBarHidden: YES];
// IMPORTANT: Setting the GLView should be done after creating the RootViewController
cocos2d::GLView *glview = cocos2d::GLViewImpl::createWithEAGLView(eaglView);
cocos2d::Director::getInstance()->setOpenGLView(glview);
app->run();
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
/*
Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
*/
cocos2d::Director::getInstance()->pause();
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
/*
Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
*/
cocos2d::Director::getInstance()->resume();
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
/*
Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
*/
cocos2d::Application::getInstance()->applicationDidEnterBackground();
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
/*
Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
*/
cocos2d::Application::getInstance()->applicationWillEnterForeground();
}
- (void)applicationWillTerminate:(UIApplication *)application {
/*
Called when the application is about to terminate.
See also applicationDidEnterBackground:.
*/
}
#pragma mark -
#pragma mark Memory management
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
/*
Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
*/
cocos2d::Director::getInstance()->purgeCachedData();
}
- (void)dealloc {
[super dealloc];
}
@end
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleDisplayName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>org.cocos2dx.rubbish</string>
<key>CFBundleIconFile</key>
<string>Icon-57.png</string>
<key>CFBundleIconFiles</key>
<array>
<string>Icon-29</string>
<string>Icon-40</string>
<string>Icon-50</string>
<string>Icon-57</string>
<string>Icon-58</string>
<string>Icon-72</string>
<string>Icon-76</string>
<string>Icon-80</string>
<string>Icon-87</string>
<string>Icon-100</string>
<string>Icon-114</string>
<string>Icon-120</string>
<string>Icon-144</string>
<string>Icon-152</string>
<string>Icon-180</string>
</array>
<key>CFBundleIconFiles~ipad</key>
<array>
<string>Icon-29</string>
<string>Icon-40</string>
<string>Icon-50</string>
<string>Icon-57</string>
<string>Icon-58</string>
<string>Icon-72</string>
<string>Icon-76</string>
<string>Icon-80</string>
<string>Icon-87</string>
<string>Icon-100</string>
<string>Icon-114</string>
<string>Icon-120</string>
<string>Icon-144</string>
<string>Icon-152</string>
<string>Icon-180</string>
</array>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIPrerenderedIcon</key>
<true/>
<key>UIRequiredDeviceCapabilities</key>
<dict>
<key>accelerometer</key>
<true/>
<key>opengles-1</key>
<true/>
</dict>
<key>UIStatusBarHidden</key>
<true/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationLandscapeRight</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
</array>
</dict>
</plist>
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2010 Ricardo Quesada
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#import <UIKit/UIKit.h>
@interface RootViewController : UIViewController {
}
- (BOOL)prefersStatusBarHidden;
@end
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2010 Ricardo Quesada
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#import "RootViewController.h"
#import "cocos2d.h"
#import "platform/ios/CCEAGLView-ios.h"
#include "ide-support/SimpleConfigParser.h"
@implementation RootViewController
/*
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
// Override to allow orientations other than the default portrait orientation.
// This method is deprecated on ios6
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
if (SimpleConfigParser::getInstance()->isLanscape()) {
return UIInterfaceOrientationIsLandscape( interfaceOrientation );
}else{
return UIInterfaceOrientationIsPortrait( interfaceOrientation );
}
}
// For ios6, use supportedInterfaceOrientations & shouldAutorotate instead
- (NSUInteger) supportedInterfaceOrientations{
#ifdef __IPHONE_6_0
if (SimpleConfigParser::getInstance()->isLanscape()) {
return UIInterfaceOrientationMaskLandscape;
}else{
return UIInterfaceOrientationMaskPortrait;
}
#endif
}
- (BOOL) shouldAutorotate {
if (SimpleConfigParser::getInstance()->isLanscape()) {
return YES;
}else{
return NO;
}
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
cocos2d::GLView *glview = cocos2d::Director::getInstance()->getOpenGLView();
if (glview)
{
CCEAGLView *eaglview = (CCEAGLView*) glview->getEAGLView();
if (eaglview)
{
CGSize s = CGSizeMake([eaglview getWidth], [eaglview getHeight]);
cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height);
}
}
}
//fix not hide status on ios7
- (BOOL)prefersStatusBarHidden
{
return YES;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end

13.4 KB | W: | H:

12.4 KB | W: | H:

  • 2-up
  • Swipe
  • Onion skin

17.3 KB | W: | H:

15.8 KB | W: | H:

  • 2-up
  • Swipe
  • Onion skin

12.6 KB | W: | H:

11.5 KB | W: | H:

  • 2-up
  • Swipe
  • Onion skin

11.9 KB | W: | H:

10.7 KB | W: | H:

  • 2-up
  • Swipe
  • Onion skin

9.91 KB | W: | H:

9.68 KB | W: | H:

  • 2-up
  • Swipe
  • Onion skin