Merge branch 'v3' of https://github.com/cocos2d/cocos2d-x into fix-crash

This commit is contained in:
minggo 2014-07-01 15:59:43 +08:00
commit d130bf84e5
76 changed files with 3212 additions and 887 deletions

View File

@ -144,14 +144,42 @@ ComAttribute* ComAttribute::create(void)
bool ComAttribute::serialize(void* r) bool ComAttribute::serialize(void* r)
{ {
bool bRet = false; bool ret = false;
do do
{ {
CC_BREAK_IF(r == nullptr); CC_BREAK_IF(r == nullptr);
rapidjson::Value *v = (rapidjson::Value *)r; SerData *serData = (SerData *)(r);
const char *className = DICTOOL->getStringValue_json(*v, "classname"); const rapidjson::Value *v = serData->_rData;
stExpCocoNode *cocoNode = serData->_cocoNode;
const char *className = nullptr;
const char *comName = nullptr;
const char *file = nullptr;
std::string filePath;
int resType = 0;
if (v != nullptr)
{
className = DICTOOL->getStringValue_json(*v, "classname");
CC_BREAK_IF(className == nullptr); CC_BREAK_IF(className == nullptr);
const char *comName = DICTOOL->getStringValue_json(*v, "name"); comName = DICTOOL->getStringValue_json(*v, "name");
const rapidjson::Value &fileData = DICTOOL->getSubDictionary_json(*v, "fileData");
CC_BREAK_IF(!DICTOOL->checkObjectExist_json(fileData));
file = DICTOOL->getStringValue_json(fileData, "path");
CC_BREAK_IF(file == nullptr);
resType = DICTOOL->getIntValue_json(fileData, "resourceType", -1);
CC_BREAK_IF(resType != 0);
}
else if (cocoNode != nullptr)
{
className = cocoNode[1].GetValue();
CC_BREAK_IF(className == nullptr);
comName = cocoNode[2].GetValue();
stExpCocoNode *fileData = cocoNode[3].GetChildArray();
CC_BREAK_IF(!fileData);
file = fileData[0].GetValue();
CC_BREAK_IF(file == nullptr);
resType = atoi(fileData[2].GetValue());
CC_BREAK_IF(resType != 0);
}
if (comName != nullptr) if (comName != nullptr)
{ {
setName(comName); setName(comName);
@ -160,22 +188,17 @@ bool ComAttribute::serialize(void* r)
{ {
setName(className); setName(className);
} }
const rapidjson::Value &fileData = DICTOOL->getSubDictionary_json(*v, "fileData");
CC_BREAK_IF(!DICTOOL->checkObjectExist_json(fileData));
const char *file = DICTOOL->getStringValue_json(fileData, "path");
CC_BREAK_IF(file == nullptr);
std::string filePath;
if (file != nullptr) if (file != nullptr)
{ {
filePath.assign(cocos2d::FileUtils::getInstance()->fullPathForFilename(file)); filePath.assign(cocos2d::FileUtils::getInstance()->fullPathForFilename(file));
} }
int resType = DICTOOL->getIntValue_json(fileData, "resourceType", -1); if (parse(filePath.c_str()))
CC_BREAK_IF(resType != 0); {
parse(filePath.c_str()); ret = true;
bRet = true; }
} while (0);
return bRet; }while (0);
return ret;
} }
bool ComAttribute::parse(const std::string &jsonFile) bool ComAttribute::parse(const std::string &jsonFile)

View File

@ -69,14 +69,46 @@ void ComAudio::setEnabled(bool b)
bool ComAudio::serialize(void* r) bool ComAudio::serialize(void* r)
{ {
bool bRet = false; bool ret = false;
do do
{ {
CC_BREAK_IF(r == nullptr); CC_BREAK_IF(r == nullptr);
rapidjson::Value *v = (rapidjson::Value *)r; SerData *serData = (SerData *)(r);
const char *className = DICTOOL->getStringValue_json(*v, "classname"); const rapidjson::Value *v = serData->_rData;
stExpCocoNode *cocoNode = serData->_cocoNode;
const char *className = nullptr;
const char *comName = nullptr;
const char *file = nullptr;
std::string filePath;
int resType = 0;
bool loop = false;
if (v != nullptr)
{
className = DICTOOL->getStringValue_json(*v, "classname");
CC_BREAK_IF(className == nullptr); CC_BREAK_IF(className == nullptr);
const char *comName = DICTOOL->getStringValue_json(*v, "name"); comName = DICTOOL->getStringValue_json(*v, "name");
const rapidjson::Value &fileData = DICTOOL->getSubDictionary_json(*v, "fileData");
CC_BREAK_IF(!DICTOOL->checkObjectExist_json(fileData));
file = DICTOOL->getStringValue_json(fileData, "path");
CC_BREAK_IF(file == nullptr);
resType = DICTOOL->getIntValue_json(fileData, "resourceType", -1);
CC_BREAK_IF(resType != 0);
loop = DICTOOL->getIntValue_json(*v, "loop") != 0? true:false;
}
else if (cocoNode != nullptr)
{
className = cocoNode[1].GetValue();
CC_BREAK_IF(className == nullptr);
comName = cocoNode[2].GetValue();
stExpCocoNode *pfileData = cocoNode[4].GetChildArray();
CC_BREAK_IF(!pfileData);
file = pfileData[0].GetValue();
CC_BREAK_IF(file == nullptr);
resType = atoi(pfileData[2].GetValue());
CC_BREAK_IF(resType != 0);
loop = atoi(cocoNode[5].GetValue()) != 0? true:false;
ret = true;
}
if (comName != nullptr) if (comName != nullptr)
{ {
setName(comName); setName(comName);
@ -85,17 +117,14 @@ bool ComAudio::serialize(void* r)
{ {
setName(className); setName(className);
} }
const rapidjson::Value &fileData = DICTOOL->getSubDictionary_json(*v, "fileData");
CC_BREAK_IF(!DICTOOL->checkObjectExist_json(fileData));
const char *file = DICTOOL->getStringValue_json(fileData, "path");
CC_BREAK_IF(file == nullptr);
std::string filePath;
if (file != nullptr) if (file != nullptr)
{ {
if (strcmp(file, "") == 0)
{
continue;
}
filePath.assign(cocos2d::FileUtils::getInstance()->fullPathForFilename(file)); filePath.assign(cocos2d::FileUtils::getInstance()->fullPathForFilename(file));
} }
int resType = DICTOOL->getIntValue_json(fileData, "resourceType", -1);
CC_BREAK_IF(resType != 0);
if (strcmp(className, "CCBackgroundAudio") == 0) if (strcmp(className, "CCBackgroundAudio") == 0)
{ {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) #if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
@ -108,7 +137,6 @@ bool ComAudio::serialize(void* r)
filePath.replace(pos, filePath.length(), ".wav"); filePath.replace(pos, filePath.length(), ".wav");
#endif #endif
preloadBackgroundMusic(filePath.c_str()); preloadBackgroundMusic(filePath.c_str());
bool loop = DICTOOL->getIntValue_json(*v, "loop") != 0? true:false;
setLoop(loop); setLoop(loop);
playBackgroundMusic(filePath.c_str(), loop); playBackgroundMusic(filePath.c_str(), loop);
} }
@ -120,10 +148,9 @@ bool ComAudio::serialize(void* r)
{ {
CC_BREAK_IF(true); CC_BREAK_IF(true);
} }
bRet = true; ret = true;
}while (0); }while (0);
return ret;
return bRet;
} }
ComAudio* ComAudio::create(void) ComAudio* ComAudio::create(void)

View File

@ -28,6 +28,7 @@ THE SOFTWARE.
#include <string> #include <string>
#include "DictionaryHelper.h" #include "DictionaryHelper.h"
#include "base/ObjectFactory.h" #include "base/ObjectFactory.h"
#include "CocoLoader.h"
#define DECLARE_CLASS_COMPONENT_INFO \ #define DECLARE_CLASS_COMPONENT_INFO \
@ -45,5 +46,16 @@ THE SOFTWARE.
#define CREATE_CLASS_COMPONENT_INFO(className) \ #define CREATE_CLASS_COMPONENT_INFO(className) \
cocos2d::ObjectFactory::TInfo(#className, &className::createInstance) cocos2d::ObjectFactory::TInfo(#className, &className::createInstance)
struct SerData
{
const rapidjson::Value *_rData;
cocostudio::stExpCocoNode *_cocoNode;
SerData()
{
_rData = NULL;
_cocoNode = NULL;
}
};
#endif #endif

View File

@ -90,14 +90,44 @@ void ComRender::setNode(cocos2d::Node *node)
bool ComRender::serialize(void* r) bool ComRender::serialize(void* r)
{ {
bool bRet = false; bool ret = false;
do do
{ {
CC_BREAK_IF(r == nullptr); CC_BREAK_IF(r == nullptr);
rapidjson::Value *v = (rapidjson::Value *)r; SerData *serData = (SerData *)(r);
const char *className = DICTOOL->getStringValue_json(*v, "classname"); const rapidjson::Value *v = serData->_rData;
stExpCocoNode *cocoNode = serData->_cocoNode;
const char *className = nullptr;
const char *comName = nullptr;
const char *file = nullptr;
const char *plist = nullptr;
std::string filePath;
std::string plistPath;
int resType = 0;
if (v != nullptr)
{
className = DICTOOL->getStringValue_json(*v, "classname");
CC_BREAK_IF(className == nullptr); CC_BREAK_IF(className == nullptr);
const char *comName = DICTOOL->getStringValue_json(*v, "name"); comName = DICTOOL->getStringValue_json(*v, "name");
const rapidjson::Value &fileData = DICTOOL->getSubDictionary_json(*v, "fileData");
CC_BREAK_IF(!DICTOOL->checkObjectExist_json(fileData));
file = DICTOOL->getStringValue_json(fileData, "path");
plist = DICTOOL->getStringValue_json(fileData, "plistFile");
CC_BREAK_IF(file == nullptr && plist == nullptr);
resType = DICTOOL->getIntValue_json(fileData, "resourceType", -1);
}
else if(cocoNode != nullptr)
{
className = cocoNode[1].GetValue();
CC_BREAK_IF(className == nullptr);
comName = cocoNode[2].GetValue();
stExpCocoNode *pfileData = cocoNode[4].GetChildArray();
CC_BREAK_IF(!pfileData);
file = pfileData[0].GetValue();
plist = pfileData[1].GetValue();
CC_BREAK_IF(file == nullptr && plist == nullptr);
resType = atoi(pfileData[2].GetValue());
}
if (comName != nullptr) if (comName != nullptr)
{ {
setName(comName); setName(comName);
@ -106,49 +136,50 @@ bool ComRender::serialize(void* r)
{ {
setName(className); setName(className);
} }
const rapidjson::Value &fileData = DICTOOL->getSubDictionary_json(*v, "fileData");
CC_BREAK_IF(!DICTOOL->checkObjectExist_json(fileData));
const char *file = DICTOOL->getStringValue_json(fileData, "path");
const char *plist = DICTOOL->getStringValue_json(fileData, "plistFile");
CC_BREAK_IF(file == nullptr && plist == nullptr);
std::string filePath;
std::string plistPath;
if (file != nullptr) if (file != nullptr)
{ {
filePath.assign(cocos2d::CCFileUtils::getInstance()->fullPathForFilename(file)); filePath.assign(cocos2d::FileUtils::getInstance()->fullPathForFilename(file));
} }
if (plist != nullptr) if (plist != nullptr)
{ {
plistPath.assign(cocos2d::CCFileUtils::getInstance()->fullPathForFilename(plist)); plistPath.assign(cocos2d::FileUtils::getInstance()->fullPathForFilename(plist));
} }
int resType = DICTOOL->getIntValue_json(fileData, "resourceType", -1);
if (resType == 0) if (resType == 0)
{ {
if (strcmp(className, "CCSprite") == 0 && filePath.find(".png") != std::string::npos) if (strcmp(className, "CCSprite") == 0 && (filePath.find(".png") != filePath.npos || filePath.find(".pvr.ccz") != filePath.npos))
{ {
_render = Sprite::create(filePath.c_str()); _render = CCSprite::create(filePath.c_str());
_render->retain(); _render->retain();
ret = true;
} }
else if(strcmp(className, "CCTMXTiledMap") == 0 && filePath.find(".tmx") != std::string::npos) else if(strcmp(className, "CCTMXTiledMap") == 0 && filePath.find(".tmx") != filePath.npos)
{ {
_render = TMXTiledMap::create(filePath.c_str()); _render = CCTMXTiledMap::create(filePath.c_str());
_render->retain(); _render->retain();
ret = true;
} }
else if(strcmp(className, "CCParticleSystemQuad") == 0 && filePath.find(".plist") != std::string::npos) else if(strcmp(className, "CCParticleSystemQuad") == 0 && filePath.find(".plist") != filePath.npos)
{ {
_render = ParticleSystemQuad::create(filePath.c_str()); _render = CCParticleSystemQuad::create(filePath.c_str());
_render->setPosition(Vec2(0.0f, 0.0f)); _render->setPosition(Point(0.0f, 0.0f));
_render->retain(); _render->retain();
ret = true;
} }
else if(strcmp(className, "CCArmature") == 0) else if(strcmp(className, "CCArmature") == 0)
{ {
std::string reDir = filePath; std::string file_extension = filePath;
std::string file_path = ""; size_t pos = filePath.find_last_of('.');
size_t pos = reDir.find_last_of('/');
if (pos != std::string::npos) if (pos != std::string::npos)
{ {
file_path = reDir.substr(0, pos+1); file_extension = filePath.substr(pos, filePath.length());
std::transform(file_extension.begin(),file_extension.end(), file_extension.begin(), (int(*)(int))toupper);
} }
if (file_extension == ".JSON" || file_extension == ".EXPORTJSON")
{
rapidjson::Document doc; rapidjson::Document doc;
if(!readJson(filePath.c_str(), doc)) if(!readJson(filePath.c_str(), doc))
{ {
@ -161,17 +192,119 @@ bool ComRender::serialize(void* r)
Armature *pAr = Armature::create(name); Armature *pAr = Armature::create(name);
_render = pAr; _render = pAr;
_render->retain(); _render->retain();
const char *actionName = DICTOOL->getStringValue_json(*v, "selectedactionname"); const char *actionName = nullptr;
if (cocoNode != nullptr)
{
actionName = cocoNode[6].GetValue();//DICTOOL->getStringValue_json(*v, "selectedactionname");
}
else
{
actionName = DICTOOL->getStringValue_json(*v, "selectedactionname");
}
if (actionName != nullptr && pAr->getAnimation() != nullptr) if (actionName != nullptr && pAr->getAnimation() != nullptr)
{ {
pAr->getAnimation()->play(actionName); pAr->getAnimation()->play(actionName);
} }
ret = true;
}
else if (file_extension == ".CSB")
{
ssize_t size = 0;
unsigned char *pBytes = nullptr;
std::string binaryFilePath = FileUtils::getInstance()->fullPathForFilename(filePath.c_str());
pBytes = cocos2d::FileUtils::getInstance()->getFileData(binaryFilePath.c_str(), "rb", &size);
CC_BREAK_IF(pBytes == nullptr || strcmp((char*)pBytes, "") == 0);
CocoLoader tCocoLoader;
if (tCocoLoader.ReadCocoBinBuff((char*)pBytes))
{
stExpCocoNode *tpRootCocoNode = tCocoLoader.GetRootCocoNode();
rapidjson::Type tType = tpRootCocoNode->GetType(&tCocoLoader);
if (rapidjson::kObjectType == tType)
{
int count = tpRootCocoNode->GetChildNum();
stExpCocoNode *tpChildArray = tpRootCocoNode->GetChildArray();
for (int i = 0; i < count; ++i)
{
std::string key = tpChildArray[i].GetName(&tCocoLoader);
if (key.compare("armature_data") == 0)
{
int length = tpChildArray[i].GetChildNum();
stExpCocoNode *armature_dataArray = tpChildArray[i].GetChildArray();
if (length < 1)
{
continue;
}
length = armature_dataArray[0].GetChildNum();
stExpCocoNode *armature_data = armature_dataArray[0].GetChildArray();
for (int j = 0; j < length; ++j)
{
std::string key1 = armature_data[j].GetName(&tCocoLoader);
const char *str1 = armature_data[j].GetValue();
if (key.compare("name") == 0)
{
if (str1 != nullptr)
{
ArmatureDataManager::getInstance()->addArmatureFileInfo(filePath.c_str());
Armature *pAr = CCArmature::create(str1);
_render = pAr;
_render->retain();
const char *actionName = nullptr;
if (cocoNode != nullptr)
{
actionName = cocoNode[6].GetValue();
}
else
{
actionName = DICTOOL->getStringValue_json(*v, "selectedactionname");
}
if (actionName != nullptr && pAr->getAnimation() != nullptr)
{
pAr->getAnimation()->play(actionName);
}
ret = true;
}
}
}
}
}
}
}
else
{
continue;
}
}
else
{
continue;
}
} }
else if(strcmp(className, "GUIComponent") == 0) else if(strcmp(className, "GUIComponent") == 0)
{ {
std::string file_extension = filePath;
size_t pos = filePath.find_last_of('.');
if (pos != std::string::npos)
{
file_extension = filePath.substr(pos, filePath.length());
std::transform(file_extension.begin(),file_extension.end(), file_extension.begin(), (int(*)(int))toupper);
}
if (file_extension == ".JSON" || file_extension == ".EXPORTJSON")
{
cocos2d::ui::Widget* widget = GUIReader::getInstance()->widgetFromJsonFile(filePath.c_str()); cocos2d::ui::Widget* widget = GUIReader::getInstance()->widgetFromJsonFile(filePath.c_str());
_render = widget; _render = widget;
_render->retain(); _render->retain();
ret = true;
}
else if (file_extension == ".CSB")
{
cocos2d::ui::Widget* widget = GUIReader::getInstance()->widgetFromBinaryFile(filePath.c_str());
_render = widget;
_render->retain();
ret = true;
}
} }
else else
{ {
@ -190,8 +323,10 @@ bool ComRender::serialize(void* r)
} }
strPngFile.replace(pos, strPngFile.length(), ".png"); strPngFile.replace(pos, strPngFile.length(), ".png");
SpriteFrameCache::getInstance()->addSpriteFramesWithFile(plistPath.c_str(), strPngFile.c_str()); SpriteFrameCache::getInstance()->addSpriteFramesWithFile(plistPath.c_str(), strPngFile.c_str());
_render = Sprite::createWithSpriteFrameName(filePath.c_str()); _render = CCSprite::createWithSpriteFrameName(filePath.c_str());
_render->retain(); _render->retain();
ret = true;
} }
else else
{ {
@ -202,10 +337,9 @@ bool ComRender::serialize(void* r)
{ {
CC_BREAK_IF(true); CC_BREAK_IF(true);
} }
bRet = true;
} while (0); } while (0);
return bRet; return ret;
} }
ComRender* ComRender::create(void) ComRender* ComRender::create(void)

View File

@ -55,6 +55,16 @@ const char* SceneReader::sceneReaderVersion()
} }
cocos2d::Node* SceneReader::createNodeWithSceneFile(const std::string &fileName, AttachComponentType attachComponent /*= AttachComponentType::EMPTY_NODE*/) cocos2d::Node* SceneReader::createNodeWithSceneFile(const std::string &fileName, AttachComponentType attachComponent /*= AttachComponentType::EMPTY_NODE*/)
{
std::string reDir = fileName;
std::string file_extension = "";
size_t pos = reDir.find_last_of('.');
if (pos != std::string::npos)
{
file_extension = reDir.substr(pos, reDir.length());
std::transform(file_extension.begin(),file_extension.end(), file_extension.begin(), (int(*)(int))toupper);
}
if (file_extension == ".JSON")
{ {
_node = nullptr; _node = nullptr;
rapidjson::Document jsonDict; rapidjson::Document jsonDict;
@ -66,18 +76,113 @@ cocos2d::Node* SceneReader::createNodeWithSceneFile(const std::string &fileName,
return _node; return _node;
} }
else if(file_extension == ".CSB")
{
ssize_t size = 0;
unsigned char *pBytes = nullptr;
do {
std::string binaryFilePath = CCFileUtils::getInstance()->fullPathForFilename(fileName);
pBytes = cocos2d::FileUtils::getInstance()->getFileData(binaryFilePath.c_str(), "rb", &size);
CC_BREAK_IF(pBytes == nullptr || strcmp((char*)pBytes, "") == 0);
CocoLoader tCocoLoader;
if (tCocoLoader.ReadCocoBinBuff((char*)pBytes))
{
stExpCocoNode *tpRootCocoNode = tCocoLoader.GetRootCocoNode();
rapidjson::Type tType = tpRootCocoNode->GetType(&tCocoLoader);
if (rapidjson::kObjectType == tType)
{
stExpCocoNode *tpChildArray = tpRootCocoNode->GetChildArray();
CC_BREAK_IF(tpRootCocoNode->GetChildNum() == 0);
_node = Node::create();
int nCount = 0;
std::vector<Component*> _vecComs;
ComRender *pRender = nullptr;
std::string key = tpChildArray[15].GetName(&tCocoLoader);
if (key == "components")
{
nCount = tpChildArray[15].GetChildNum();
}
stExpCocoNode *pComponents = tpChildArray[15].GetChildArray();
SerData *data = new SerData();
for (int i = 0; i < nCount; i++)
{
stExpCocoNode *subDict = pComponents[i].GetChildArray();
if (subDict == nullptr)
{
continue;
}
std::string key = subDict[1].GetName(&tCocoLoader);
const char *comName = subDict[1].GetValue();
Component *pCom = nullptr;
if (key == "classname" && comName != nullptr)
{
pCom = createComponent(comName);
}
CCLOG("classname = %s", comName);
if (pCom != nullptr)
{
data->_rData = nullptr;
data->_cocoNode = subDict;
if (pCom->serialize(data))
{
ComRender *pTRender = dynamic_cast<ComRender*>(pCom);
if (pTRender != nullptr)
{
pRender = pTRender;
}
else
{
_vecComs.push_back(pCom);
}
}
else
{
CC_SAFE_RELEASE_NULL(pCom);
}
}
if(_fnSelector != nullptr)
{
_fnSelector(pCom, (void*)(data));
}
}
setPropertyFromJsonDict(&tCocoLoader, tpRootCocoNode, _node);
for (std::vector<Component*>::iterator iter = _vecComs.begin(); iter != _vecComs.end(); ++iter)
{
_node->addComponent(*iter);
}
stExpCocoNode *pGameObjects = tpChildArray[11].GetChildArray();
int length = tpChildArray[11].GetChildNum();
for (int i = 0; i < length; ++i)
{
createObject(&tCocoLoader, &pGameObjects[i], _node, attachComponent);
}
TriggerMng::getInstance()->parse(&tCocoLoader, tpChildArray);
}
}
}while (0);
return _node;
}
else
{
log("read file [%s] error!\n", fileName.c_str());
}
return nullptr;
}
bool SceneReader::readJson(const std::string &fileName, rapidjson::Document &doc) bool SceneReader::readJson(const std::string &fileName, rapidjson::Document &doc)
{ {
bool bRet = false; bool ret = false;
do { do {
std::string jsonpath = FileUtils::getInstance()->fullPathForFilename(fileName); std::string jsonpath = FileUtils::getInstance()->fullPathForFilename(fileName);
std::string contentStr = FileUtils::getInstance()->getStringFromFile(jsonpath); std::string contentStr = FileUtils::getInstance()->getStringFromFile(jsonpath);
doc.Parse<0>(contentStr.c_str()); doc.Parse<0>(contentStr.c_str());
CC_BREAK_IF(doc.HasParseError()); CC_BREAK_IF(doc.HasParseError());
bRet = true; ret = true;
} while (0); } while (0);
return bRet; return ret;
} }
Node* SceneReader::nodeByTag(Node *parent, int tag) Node* SceneReader::nodeByTag(Node *parent, int tag)
@ -172,9 +277,13 @@ Node* SceneReader::createObject(const rapidjson::Value &dict, cocos2d::Node* par
} }
const char *comName = DICTOOL->getStringValue_json(subDict, "classname"); const char *comName = DICTOOL->getStringValue_json(subDict, "classname");
Component *com = this->createComponent(comName); Component *com = this->createComponent(comName);
CCLOG("classname = %s", comName);
SerData *data = new SerData();
if (com != nullptr) if (com != nullptr)
{ {
if (com->serialize((void*)(&subDict))) data->_rData = &subDict;
data->_cocoNode = nullptr;
if (com->serialize(data))
{ {
ComRender *tRender = dynamic_cast<ComRender*>(com); ComRender *tRender = dynamic_cast<ComRender*>(com);
if (tRender == nullptr) if (tRender == nullptr)
@ -187,9 +296,10 @@ Node* SceneReader::createObject(const rapidjson::Value &dict, cocos2d::Node* par
} }
} }
} }
CC_SAFE_DELETE(data);
if(_fnSelector != nullptr) if(_fnSelector != nullptr)
{ {
_fnSelector(com, (void*)(&subDict)); _fnSelector(com, data);
} }
} }
@ -235,6 +345,111 @@ Node* SceneReader::createObject(const rapidjson::Value &dict, cocos2d::Node* par
return nullptr; return nullptr;
} }
cocos2d::Node* SceneReader::createObject(CocoLoader *cocoLoader, stExpCocoNode *cocoNode, cocos2d::Node* parent, AttachComponentType attachComponent)
{
const char *className = nullptr;
stExpCocoNode *pNodeArray = cocoNode->GetChildArray();
std::string Key = pNodeArray[1].GetName(cocoLoader);
if (Key == "classname")
{
className = pNodeArray[1].GetValue();
}
if(strcmp(className, "CCNode") == 0)
{
Node* gb = nullptr;
std::vector<Component*> _vecComs;
ComRender *pRender = nullptr;
int count = 0;
std::string key = pNodeArray[13].GetName(cocoLoader);
if (key == "components")
{
count = pNodeArray[13].GetChildNum();
}
stExpCocoNode *pComponents = pNodeArray[13].GetChildArray();
SerData *data = new SerData();
for (int i = 0; i < count; ++i)
{
stExpCocoNode *subDict = pComponents[i].GetChildArray();
if (subDict == nullptr)
{
continue;
}
std::string key = subDict[1].GetName(cocoLoader);
const char *comName = subDict[1].GetValue();//DICTOOL->getStringValue_json(subDict, "classname");
Component *pCom = nullptr;
if (key == "classname" && comName != nullptr)
{
pCom = createComponent(comName);
}
CCLOG("classname = %s", comName);
if (pCom != nullptr)
{
data->_rData = nullptr;
data->_cocoNode = subDict;
if (pCom->serialize(data))
{
ComRender *pTRender = dynamic_cast<ComRender*>(pCom);
if (pTRender != nullptr)
{
pRender = pTRender;
}
else
{
_vecComs.push_back(pCom);
}
}
else
{
CC_SAFE_RELEASE_NULL(pCom);
}
}
if(_fnSelector != nullptr)
{
_fnSelector(pCom, (void*)(data));
}
}
CC_SAFE_DELETE(data);
if (parent != nullptr)
{
if (pRender == nullptr || attachComponent == AttachComponentType::EMPTY_NODE)
{
gb = CCNode::create();
if (pRender != nullptr)
{
_vecComs.push_back(pRender);
}
}
else
{
gb = pRender->getNode();
gb->retain();
pRender->setNode(nullptr);
CC_SAFE_RELEASE_NULL(pRender);
}
parent->addChild(gb);
}
setPropertyFromJsonDict(cocoLoader, cocoNode, gb);
for (std::vector<Component*>::iterator iter = _vecComs.begin(); iter != _vecComs.end(); ++iter)
{
gb->addComponent(*iter);
}
stExpCocoNode *pGameObjects = pNodeArray[12].GetChildArray();
if (pGameObjects != nullptr)
{
int length = pNodeArray[12].GetChildNum();
for (int i = 0; i < length; ++i)
{
createObject(cocoLoader, &pGameObjects[i], gb, attachComponent);
}
}
return gb;
}
return nullptr;
}
void SceneReader::setTarget(const std::function<void(cocos2d::Ref* obj, void* doc)>& selector) void SceneReader::setTarget(const std::function<void(cocos2d::Ref* obj, void* doc)>& selector)
{ {
_fnSelector = selector; _fnSelector = selector;
@ -277,6 +492,62 @@ void SceneReader::setPropertyFromJsonDict(const rapidjson::Value &root, cocos2d:
node->setRotation(fRotationZ); node->setRotation(fRotationZ);
} }
void SceneReader::setPropertyFromJsonDict(CocoLoader *cocoLoader, stExpCocoNode *cocoNode, cocos2d::Node *node)
{
stExpCocoNode *stChildArray = cocoNode->GetChildArray();
float x = 0.0f, y = 0.0f, fScaleX = 1.0f, fScaleY = 1.0f, fRotationZ = 1.0f;
bool bVisible = false;
int nTag = 0, nZorder = -1;
for (int i = 0; i < cocoNode->GetChildNum(); ++i)
{
std::string key = stChildArray[i].GetName(cocoLoader);
std::string value = stChildArray[i].GetValue();
if (key == "x")
{
x = atof(value.c_str());
node->setPositionX(x);
}
else if (key == "y")
{
y = atof(value.c_str());
node->setPositionY(y);
}
else if (key == "visible")
{
bVisible = (bool)atoi(value.c_str());
node->setVisible(bVisible);
}
else if (key == "objecttag")
{
nTag = atoi(value.c_str());
node->setTag(nTag);
}
else if (key == "zorder")
{
nZorder = atoi(value.c_str());
node->setZOrder(nZorder);
}
else if(key == "scalex")
{
fScaleX = atof(value.c_str());
node->setScaleX(fScaleX);
}
else if(key == "scaley")
{
fScaleY = atof(value.c_str());
node->setScaleY(fScaleY);
}
else if(key == "rotation")
{
fRotationZ = atof(value.c_str());
node->setRotation(fRotationZ);
}
}
}
SceneReader* SceneReader::getInstance() SceneReader* SceneReader::getInstance()
{ {
if (s_sharedReader == nullptr) if (s_sharedReader == nullptr)

View File

@ -76,6 +76,10 @@ private:
cocos2d::Node* createObject(const rapidjson::Value& dict, cocos2d::Node* parent, AttachComponentType attachComponent); cocos2d::Node* createObject(const rapidjson::Value& dict, cocos2d::Node* parent, AttachComponentType attachComponent);
void setPropertyFromJsonDict(const rapidjson::Value& dict, cocos2d::Node *node); void setPropertyFromJsonDict(const rapidjson::Value& dict, cocos2d::Node *node);
bool readJson(const std::string &fileName, rapidjson::Document& doc); bool readJson(const std::string &fileName, rapidjson::Document& doc);
cocos2d::Node* createObject(CocoLoader *cocoLoader, stExpCocoNode *cocoNode, cocos2d::Node* parent, AttachComponentType attachComponent);
void setPropertyFromJsonDict(CocoLoader *cocoLoader, stExpCocoNode *cocoNode, cocos2d::Node *node);
cocos2d::Node* nodeByTag(cocos2d::Node *parent, int tag); cocos2d::Node* nodeByTag(cocos2d::Node *parent, int tag);
private: private:
static SceneReader* s_sharedReader; static SceneReader* s_sharedReader;

View File

@ -105,6 +105,44 @@ void TriggerMng::parse(const rapidjson::Value &root)
} }
} }
void TriggerMng::parse(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)
{
CCLOG("%s", triggerMngVersion());
int count = pCocoNode[13].GetChildNum();
stExpCocoNode *pTriggersArray = pCocoNode[13].GetChildArray();
#if CC_ENABLE_SCRIPT_BINDING
ScriptEngineProtocol* engine = ScriptEngineManager::getInstance()->getScriptEngine();
bool useBindings = engine != NULL;
if (useBindings)
{
if (count > 0 )
{
rapidjson::Document document;
buildJson(document, pCocoLoader, pCocoNode);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
document.Accept(writer);
engine->parseConfig(ScriptEngineProtocol::ConfigType::COCOSTUDIO, buffer.GetString());
}
}
else
#endif // #if CC_ENABLE_SCRIPT_BINDING
{
for (int i = 0; i < count; ++i)
{
TriggerObj *obj = TriggerObj::create();
obj->serialize(pCocoLoader, &pTriggersArray[i]);
_triggerObjs.insert(std::pair<unsigned int, TriggerObj*>(obj->getId(), obj));
obj->retain();
}
}
}
TriggerObj* TriggerMng::getTriggerObj(unsigned int id) const TriggerObj* TriggerMng::getTriggerObj(unsigned int id) const
{ {
auto iter = _triggerObjs.find(id); auto iter = _triggerObjs.find(id);
@ -152,6 +190,217 @@ bool TriggerMng::isEmpty(void) const
return _triggerObjs.empty(); return _triggerObjs.empty();
} }
void TriggerMng::buildJson(rapidjson::Document &document, cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)
{
int count = pCocoNode[13].GetChildNum();
int length = 0;
int num = 0;
int size = 0;
int extent = 0;
int border = 0;
std::string key;
stExpCocoNode *pTriggersArray = pCocoNode[13].GetChildArray();
document.SetArray();
rapidjson::Document::AllocatorType& allocator = document.GetAllocator();
for (int i = 0; i < count; ++i)
{
rapidjson::Value vElemItem(rapidjson::kObjectType);
border = pTriggersArray[i].GetChildNum();
stExpCocoNode *pTriggerArray = pTriggersArray[i].GetChildArray();
for (int i = 0; i < border; ++i)
{
std::string key = pTriggerArray[i].GetName(pCocoLoader);
const char *str = pTriggerArray[i].GetValue();
rapidjson::Type type = pTriggerArray[i].GetType(pCocoLoader);
if (key.compare("actions") == 0)
{
rapidjson::Value actionsItem(rapidjson::kArrayType);
length = pTriggerArray[i].GetChildNum();
stExpCocoNode *pActionsArray = pTriggerArray[i].GetChildArray();
for (int i = 0; i < length; ++i)
{
rapidjson::Value action(rapidjson::kObjectType);
num = pActionsArray[i].GetChildNum();
stExpCocoNode *pActionArray = pActionsArray[i].GetChildArray();
for (int i = 0; i < num; ++i)
{
std::string key = pActionArray[i].GetName(pCocoLoader);
const char *str = pActionArray[i].GetValue();
if (key.compare("classname") == 0)
{
if (str != NULL)
{
action.AddMember("classname", str, allocator);
}
}
else if (key.compare("dataitems") == 0)
{
rapidjson::Value dataitems(rapidjson::kArrayType);
size = pActionArray[i].GetChildNum();
stExpCocoNode *pDataItemsArray = pActionArray[i].GetChildArray();
for (int i = 0; i < size; ++i)
{
rapidjson::Value dataitem(rapidjson::kObjectType);
extent = pDataItemsArray[i].GetChildNum();
stExpCocoNode *pDataItemArray = pDataItemsArray[i].GetChildArray();
for (int i = 0; i < extent; ++i)
{
std::string key = pDataItemArray[i].GetName(pCocoLoader);
const char *str = pDataItemArray[i].GetValue();
if (key.compare("key") == 0)
{
if (str != NULL)
{
dataitem.AddMember("key", str, allocator);
}
}
else
{
rapidjson::Type type = pDataItemArray[i].GetType(pCocoLoader);
if (type == rapidjson::kStringType)
{
dataitem.AddMember("value", str, allocator);
}
else if(type == rapidjson::kNumberType)
{
int nV = atoi(str);
float fV = atof(str);
if (fabs(nV - fV) < 0.0000001)
{
dataitem.AddMember("value", nV, allocator);
}
else
{
dataitem.AddMember("value", fV, allocator);
}
}
}
}
dataitems.PushBack(dataitem, allocator);
}
action.AddMember("dataitems", dataitems, allocator);
}
}
actionsItem.PushBack(action, allocator);
}
vElemItem.AddMember("actions", actionsItem, allocator);
}
else if (key.compare("conditions") == 0)
{
rapidjson::Value condsItem(rapidjson::kArrayType);
length = pTriggerArray[i].GetChildNum();
stExpCocoNode *pConditionsArray = pTriggerArray[i].GetChildArray();
for (int i = 0; i < length; ++i)
{
rapidjson::Value cond(rapidjson::kObjectType);
num = pConditionsArray[i].GetChildNum();
stExpCocoNode *pConditionArray = pConditionsArray[i].GetChildArray();
for (int i = 0; i < num; ++i)
{
std::string key = pConditionArray[i].GetName(pCocoLoader);
const char *str = pConditionArray[i].GetValue();
if (key.compare("classname") == 0)
{
if (str != NULL)
{
cond.AddMember("classname", str, allocator);
}
}
else if (key.compare("dataitems") == 0)
{
rapidjson::Value dataitems(rapidjson::kArrayType);
size = pConditionArray[i].GetChildNum();
stExpCocoNode *pDataItemsArray = pConditionArray[i].GetChildArray();
for (int i = 0; i < size; ++i)
{
rapidjson::Value dataitem(rapidjson::kObjectType);
extent = pDataItemsArray[i].GetChildNum();
stExpCocoNode *pDataItemArray = pDataItemsArray[i].GetChildArray();
for (int i = 0; i < extent; ++i)
{
std::string key = pDataItemArray[i].GetName(pCocoLoader);
const char *str = pDataItemArray[i].GetValue();
if (key.compare("key") == 0)
{
if (str != NULL)
{
dataitem.AddMember("key", str, allocator);
}
}
else
{
rapidjson::Type type = pDataItemArray[i].GetType(pCocoLoader);
if (type == rapidjson::kStringType)
{
dataitem.AddMember("value", str, allocator);
}
else if(type == rapidjson::kNumberType)
{
int nV = atoi(str);
float fV = atof(str);
if (fabs(nV - fV) < 0.0000001)
{
dataitem.AddMember("value", nV, allocator);
}
else
{
dataitem.AddMember("value", fV, allocator);
}
}
}
}
dataitems.PushBack(dataitem, allocator);
}
cond.AddMember("dataitems", dataitems, allocator);
}
}
condsItem.PushBack(cond, allocator);
}
vElemItem.AddMember("conditions", condsItem, allocator);
}
else if (key.compare("events") == 0)
{
rapidjson::Value eventsItem(rapidjson::kArrayType);
length = pTriggerArray[i].GetChildNum();
stExpCocoNode *pEventsArray = pTriggerArray[i].GetChildArray();
for (int i = 0; i < length; ++i)
{
rapidjson::Value event(rapidjson::kObjectType);
stExpCocoNode *pEventArray = pEventsArray->GetChildArray();
std::string key = pEventArray[0].GetName(pCocoLoader);
const char *str = pEventArray[0].GetValue();
if (key.compare("id") == 0 && str != NULL)
{
event.AddMember("id", atoi(str), allocator);
eventsItem.PushBack(event, allocator);
}
}
vElemItem.AddMember("events", eventsItem, allocator);
}
else if (key.compare("id") == 0)
{
if (str != NULL)
{
vElemItem.AddMember("id", atoi(str), allocator);
}
}
}
document.PushBack(vElemItem, allocator);
}
}
void TriggerMng::addArmatureMovementCallBack(Armature *pAr, Ref *pTarget, SEL_MovementEventCallFunc mecf) void TriggerMng::addArmatureMovementCallBack(Armature *pAr, Ref *pTarget, SEL_MovementEventCallFunc mecf)
{ {
if (pAr == nullptr || _movementDispatches == nullptr || pTarget == nullptr || mecf == nullptr) if (pAr == nullptr || _movementDispatches == nullptr || pTarget == nullptr || mecf == nullptr)

View File

@ -64,6 +64,7 @@ public:
public: public:
void parse(const rapidjson::Value &root); void parse(const rapidjson::Value &root);
void parse(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode);
void removeAll(void); void removeAll(void);
cocos2d::Vector<TriggerObj*>* get(unsigned int event) const; cocos2d::Vector<TriggerObj*>* get(unsigned int event) const;
TriggerObj* getTriggerObj(unsigned int id) const; TriggerObj* getTriggerObj(unsigned int id) const;
@ -78,6 +79,8 @@ public:
void dispatchEvent(cocos2d::EventCustom* tEvent); void dispatchEvent(cocos2d::EventCustom* tEvent);
void removeEventListener(cocos2d::EventListener* listener); void removeEventListener(cocos2d::EventListener* listener);
void addEventListenerWithFixedPriority(cocos2d::EventListener* listener, int fixedPriority); void addEventListenerWithFixedPriority(cocos2d::EventListener* listener, int fixedPriority);
private:
void buildJson(rapidjson::Document &document, cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode);
private: private:
static TriggerMng *_sharedTriggerMng; static TriggerMng *_sharedTriggerMng;

View File

@ -49,6 +49,11 @@ void BaseTriggerCondition::serialize(const rapidjson::Value &val)
{ {
} }
void BaseTriggerCondition::serialize(cocostudio::CocoLoader *cocoLoader, cocostudio::stExpCocoNode *cocoNode)
{
}
void BaseTriggerCondition::removeAll() void BaseTriggerCondition::removeAll()
{ {
} }
@ -75,6 +80,10 @@ void BaseTriggerAction::serialize(const rapidjson::Value &val)
{ {
} }
void BaseTriggerAction::serialize(cocostudio::CocoLoader *cocoLoader, cocostudio::stExpCocoNode *cocoNode)
{
}
void BaseTriggerAction::removeAll() void BaseTriggerAction::removeAll()
{ {
} }
@ -231,6 +240,102 @@ void TriggerObj::serialize(const rapidjson::Value &val)
} }
} }
void TriggerObj::serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)
{
int length = pCocoNode->GetChildNum();
int count = 0;
int num = 0;
stExpCocoNode *pTriggerObjArray = pCocoNode->GetChildArray();
for (int i = 0; i < length; ++i)
{
std::string key = pTriggerObjArray[i].GetName(pCocoLoader);
const char* str = pTriggerObjArray[i].GetValue();
if (key.compare("id") == 0)
{
if (str != NULL)
{
_id = atoi(str); //(unsigned int)(DICTOOL->getIntValue_json(val, "id"));
}
}
else if (key.compare("conditions") == 0)
{
count = pTriggerObjArray[i].GetChildNum();
stExpCocoNode *pConditionsArray = pTriggerObjArray[i].GetChildArray();
for (int i = 0; i < count; ++i)
{
num = pConditionsArray[i].GetChildNum();
stExpCocoNode *pConditionArray = pConditionsArray[i].GetChildArray();
const char *classname = pConditionArray[0].GetValue();
if (classname == NULL)
{
continue;
}
BaseTriggerCondition *con = dynamic_cast<BaseTriggerCondition*>(ObjectFactory::getInstance()->createObject(classname));
CCAssert(con != NULL, "class named classname can not implement!");
con->serialize(pCocoLoader, &pConditionArray[1]);
con->init();
_cons.pushBack(con);
}
}
else if (key.compare("actions") == 0)
{
count = pTriggerObjArray[i].GetChildNum();
stExpCocoNode *pActionsArray = pTriggerObjArray[i].GetChildArray();
for (int i = 0; i < count; ++i)
{
num = pActionsArray[i].GetChildNum();
stExpCocoNode *pActionArray = pActionsArray[i].GetChildArray();
const char *classname = pActionArray[0].GetValue();
if (classname == NULL)
{
continue;
}
BaseTriggerAction *act = dynamic_cast<BaseTriggerAction*>(ObjectFactory::getInstance()->createObject(classname));
CCAssert(act != NULL, "class named classname can not implement!");
act->serialize(pCocoLoader, &pActionArray[1]);
act->init();
_acts.pushBack(act);
}
}
else if (key.compare("events") == 0)
{
count = pTriggerObjArray[i].GetChildNum();
stExpCocoNode *pEventsArray = pTriggerObjArray[i].GetChildArray();
for (int i = 0; i < count; ++i)
{
num = pEventsArray[i].GetChildNum();
stExpCocoNode *pEventArray = pEventsArray[i].GetChildArray();
const char *str = pEventArray[0].GetValue();
if (str == NULL)
{
continue;
}
int event = atoi(str);
if (event < 0)
{
continue;
}
char* buf = new char[10];
sprintf(buf, "%d", event);
std::string custom_event_name(buf);
CC_SAFE_DELETE_ARRAY(buf);
EventListenerCustom* listener = EventListenerCustom::create(custom_event_name, [=](EventCustom* evt){
if (detect())
{
done();
}
});
_listeners.pushBack(listener);
TriggerMng::getInstance()->addEventListenerWithFixedPriority(listener, 1);
}
}
}
}
unsigned int TriggerObj::getId() unsigned int TriggerObj::getId()
{ {
return _id; return _id;

View File

@ -44,6 +44,7 @@ public:
virtual bool init(); virtual bool init();
virtual bool detect(); virtual bool detect();
virtual void serialize(const rapidjson::Value &val); virtual void serialize(const rapidjson::Value &val);
virtual void serialize(cocostudio::CocoLoader *cocoLoader, cocostudio::stExpCocoNode *cocoNode);
virtual void removeAll(); virtual void removeAll();
}; };
@ -56,6 +57,7 @@ public:
virtual bool init(); virtual bool init();
virtual void done(); virtual void done();
virtual void serialize(const rapidjson::Value &val); virtual void serialize(const rapidjson::Value &val);
virtual void serialize(cocostudio::CocoLoader *cocoLoader, cocostudio::stExpCocoNode *cocoNode);
virtual void removeAll(); virtual void removeAll();
}; };
@ -72,6 +74,7 @@ public:
virtual void done(); virtual void done();
virtual void removeAll(); virtual void removeAll();
virtual void serialize(const rapidjson::Value &val); virtual void serialize(const rapidjson::Value &val);
virtual void serialize(cocostudio::CocoLoader *cocoLoader, cocostudio::stExpCocoNode *cocoNode);
unsigned int getId(); unsigned int getId();
void setEnabled(bool enabled); void setEnabled(bool enabled);

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<projectDescription> <projectDescription>
<name>libcontrollerdelegate</name> <name>libControllerAutoAdapter</name>
<comment></comment> <comment></comment>
<projects> <projects>
</projects> </projects>

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project name="androidcontrollernibiru" default="help"> <project name="androidControllerAutoAdapter" default="help">
<!-- The local.properties file is created and updated by the 'android' tool. <!-- 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 It contains the path to the SDK. It should *NOT* be checked into

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<lint>
<issue id="NewApi">
<ignore path="src/org/cocos2dx/lib/GameControllerHelper.java" />
</issue>
</lint>

View File

@ -0,0 +1,16 @@
# 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 edit
# "ant.properties", and override values to adapt the script to your
# project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
android.library=true
# Project target.
target=android-16
android.library.reference.1=../java

View File

@ -0,0 +1,284 @@
/****************************************************************************
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 org.cocos2dx.lib.GameControllerDelegate.ControllerEventListener;
import org.cocos2dx.lib.inputmanagercompat.InputManagerCompat;
import org.cocos2dx.lib.inputmanagercompat.InputManagerCompat.InputDeviceListener;
import org.cocos2dx.lib.Cocos2dxActivity;
import android.os.Bundle;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.util.Log;
public abstract class GameControllerActivity extends Cocos2dxActivity implements InputDeviceListener {
// ===========================================================
// Constants
// ===========================================================
private final static String TAG = GameControllerActivity.class.getSimpleName();
public static final int DRIVERTYPE_NIBIRU = 0;
public static final int DRIVERTYPE_MOGA = 1;
public static final int DRIVERTYPE_OUYA = 2;
public static final int DRIVERTYPE_STANDARD = 3;
public static final int DRIVERTYPE_UNKNOWN = 4;
// ===========================================================
// Fields
// ===========================================================
private static GameControllerActivity sGameControllerActivity;
private InputManagerCompat mInputManager = null;
protected GameControllerHelper mControllerHelper = null;
protected GameControllerDelegate mControllerNibiru = null;
protected GameControllerDelegate mControllerMoga = null;
protected GameControllerDelegate mControllerOuya = null;
public void connectController(){
mControllerHelper.connectController();
}
public void setGameControllerInstance(GameControllerDelegate controllerDelegate, int driveType) {
if (driveType == DRIVERTYPE_NIBIRU) {
mControllerNibiru = controllerDelegate;
}else if (driveType == DRIVERTYPE_MOGA) {
mControllerMoga = controllerDelegate;
}
else if (driveType == DRIVERTYPE_OUYA) {
mControllerOuya = controllerDelegate;
}
controllerDelegate.setControllerEventListener(mControllerEventListener);
controllerDelegate.onCreate(sGameControllerActivity);
}
public GameControllerDelegate getGameControllerDelegate(int driveType){
if (driveType == DRIVERTYPE_NIBIRU) {
return mControllerNibiru;
}else if (driveType == DRIVERTYPE_MOGA) {
return mControllerMoga;
}
else if (driveType == DRIVERTYPE_OUYA) {
return mControllerOuya;
}
return null;
}
ControllerEventListener mControllerEventListener = new ControllerEventListener() {
@Override
public void onButtonEvent(String vendorName, int controller, int button,
boolean isPressed, float value, boolean isAnalog) {
GameControllerAdapter.onButtonEvent(vendorName, controller, button, isPressed, value, isAnalog);
}
@Override
public void onAxisEvent(String vendorName, int controller, int axisID,
float value, boolean isAnalog) {
GameControllerAdapter.onAxisEvent(vendorName, controller, axisID, value, isAnalog);
}
@Override
public void onConnected(String vendorName, int controller) {
GameControllerAdapter.onConnected(vendorName, controller);
}
@Override
public void onDisconnected(String vendorName, int controller) {
GameControllerAdapter.onDisconnected(vendorName, controller);
}
};
// ===========================================================
// Constructors
// ===========================================================
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sGameControllerActivity = this;
mInputManager = InputManagerCompat.Factory.getInputManager(this);
mInputManager.registerInputDeviceListener(this, null);
if (mControllerNibiru != null) {
mControllerNibiru.onCreate(this);
}
if (mControllerMoga != null) {
mControllerMoga.onCreate(this);
}
if (mControllerOuya != null) {
mControllerOuya.onCreate(this);
}
if (mControllerHelper == null) {
mControllerHelper = new GameControllerHelper(this);
}
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
boolean handled = false;
if (mControllerNibiru != null) {
handled |= mControllerNibiru.dispatchKeyEvent(event);
}
if (mControllerMoga != null) {
handled |= mControllerMoga.dispatchKeyEvent(event);
}
if (mControllerOuya != null) {
handled |= mControllerOuya.dispatchKeyEvent(event);
}
handled |= mControllerHelper.dispatchKeyEvent(event);
Log.d(TAG, "dispatchKeyEvent:" + handled);
return handled || super.dispatchKeyEvent(event);
}
@Override
public boolean dispatchGenericMotionEvent(MotionEvent event) {
boolean handled = false;
if (mControllerNibiru != null) {
handled |= mControllerNibiru.dispatchGenericMotionEvent(event);
}
if (mControllerMoga != null) {
handled |= mControllerMoga.dispatchGenericMotionEvent(event);
}
if (mControllerOuya != null) {
handled |= mControllerOuya.dispatchGenericMotionEvent(event);
}
handled |= mControllerHelper.dispatchGenericMotionEvent(event);
return handled || super.dispatchGenericMotionEvent(event);
}
@Override
public void onInputDeviceAdded(int deviceId) {
Log.d(TAG,"onInputDeviceAdded:" + deviceId);
InputDevice device = InputDevice.getDevice(deviceId);
int deviceSource = device.getSources();
if ( ((deviceSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
|| ((deviceSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) )
{
GameControllerAdapter.onConnected("Standard", deviceId);
}
}
/*
* This is an unusual case. Input devices don't typically change, but they
* certainly can --- for example a device may have different modes. We use
* this to make sure that the ship has an up-to-date InputDevice.
*
* @see
* com.example.inputmanagercompat.InputManagerCompat.InputDeviceListener
* #onInputDeviceChanged(int)
*/
@Override
public void onInputDeviceChanged(int deviceId) {
Log.d(TAG,"onInputDeviceChanged:" + deviceId);
}
/*
* Remove any ship associated with the ID.
*
* @see
* com.example.inputmanagercompat.InputManagerCompat.InputDeviceListener
* #onInputDeviceRemoved(int)
*/
@Override
public void onInputDeviceRemoved(int deviceId) {
Log.d(TAG,"onInputDeviceRemoved:" + deviceId);
InputDevice device = InputDevice.getDevice(deviceId);
int deviceSource = device.getSources();
if ( ((deviceSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
|| ((deviceSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) )
{
GameControllerAdapter.onDisconnected("Standard", deviceId);
}
}
@Override
protected void onResume() {
super.onResume();
if (mControllerNibiru != null) {
mControllerNibiru.onResume();
}
if (mControllerMoga != null) {
mControllerMoga.onResume();
}
if (mControllerOuya != null) {
mControllerOuya.onResume();
}
}
@Override
protected void onPause() {
if (mControllerNibiru != null) {
mControllerNibiru.onPause();
}
if (mControllerMoga != null) {
mControllerMoga.onPause();
}
if (mControllerOuya != null) {
mControllerOuya.onPause();
}
super.onPause();
}
@Override
protected void onDestroy() {
if (mControllerNibiru != null) {
mControllerNibiru.onDestroy();
}
if (mControllerMoga != null) {
mControllerMoga.onDestroy();
}
if (mControllerOuya != null) {
mControllerOuya.onDestroy();
}
mControllerHelper.destrory();
super.onDestroy();
}
}

View File

@ -42,12 +42,6 @@ public class GameControllerHelper {
public static final String StandardControllerName = "Standard"; public static final String StandardControllerName = "Standard";
public static final String[] DRIVERS_NAME = {"nibiru","moga","ouya",StandardControllerName}; public static final String[] DRIVERS_NAME = {"nibiru","moga","ouya",StandardControllerName};
public static final int DRIVERTYPE_NIBIRU = 0;
public static final int DRIVERTYPE_MOGA = 1;
public static final int DRIVERTYPE_OUYA = 2;
public static final int DRIVERTYPE_STANDARD = 3;
public static final int DRIVERTYPE_UNKNOWN = 4;
public static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB"; public static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
SparseIntArray ControllerKeyMap; SparseIntArray ControllerKeyMap;
@ -58,24 +52,21 @@ public class GameControllerHelper {
private static final String NIBIRU_DEP_PACKAGE = "com.nibiru"; private static final String NIBIRU_DEP_PACKAGE = "com.nibiru";
private static final String MOGA__DEP_PACKAGE = "com.bda.pivot.mogapgp"; private static final String MOGA__DEP_PACKAGE = "com.bda.pivot.mogapgp";
private static Cocos2dxActivity sCocos2dxActivity; private static GameControllerActivity sGameControllerActivity;
private static GameControllerHelper sControllerHelper; private static GameControllerHelper sControllerHelper;
private String mLibAdapterFileName;
private int mLibAdapterFileSize;
private List<String> mNibiruSupportedDrives; private List<String> mNibiruSupportedDrives;
private String mNibiruDepFileName; private String mNibiruDepFileName;
private String mNibiruLibFileName;
private int mNibiruLibFileSize;
private int mNibiruDepFileSize; private int mNibiruDepFileSize;
private List<String> mMogaSupportedDrives; private List<String> mMogaSupportedDrives;
private String mMogaDepFileName; private String mMogaDepFileName;
private String mMogaLibFileName;
private int mMogaLibFileSize;
private int mMogaDepFileSize; private int mMogaDepFileSize;
private List<String> mOuyaSupportedDrives; private List<String> mOuyaSupportedDrives;
private String mOuyaLibFileName;
private int mOuyaLibFileSize;
private AsyncHttpClient mDownDepsHttpClient = null; private AsyncHttpClient mDownDepsHttpClient = null;
@ -111,8 +102,17 @@ public class GameControllerHelper {
mControllerListener = listener; mControllerListener = listener;
} }
public GameControllerHelper(Cocos2dxActivity activity){ private static final int AXIS_X = 0;
sCocos2dxActivity = activity; private static final int AXIS_Y = 1;
private static final int AXIS_Z = 11;
private static final int AXIS_RZ = 14;
public static final int AXIS_LTRIGGER = 17;
public static final int AXIS_RTRIGGER = 18;
public static final int AXIS_BRAKE = 23;
public static final int AXIS_THROTTLE = 19;
public GameControllerHelper(GameControllerActivity activity){
sGameControllerActivity = activity;
sControllerHelper = this; sControllerHelper = this;
ControllerKeyMap = new SparseIntArray(25); ControllerKeyMap = new SparseIntArray(25);
@ -137,14 +137,16 @@ public class GameControllerHelper {
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_L2, GameControllerDelegate.BUTTON_LEFT_TRIGGER); ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_L2, GameControllerDelegate.BUTTON_LEFT_TRIGGER);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_R2, GameControllerDelegate.BUTTON_RIGHT_TRIGGER); ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_R2, GameControllerDelegate.BUTTON_RIGHT_TRIGGER);
ControllerKeyMap.put(MotionEvent.AXIS_X, GameControllerDelegate.THUMBSTICK_LEFT_X); ControllerKeyMap.put(AXIS_X, GameControllerDelegate.THUMBSTICK_LEFT_X);
ControllerKeyMap.put(MotionEvent.AXIS_Y, GameControllerDelegate.THUMBSTICK_LEFT_Y); ControllerKeyMap.put(AXIS_Y, GameControllerDelegate.THUMBSTICK_LEFT_Y);
ControllerKeyMap.put(MotionEvent.AXIS_Z, GameControllerDelegate.THUMBSTICK_RIGHT_X); ControllerKeyMap.put(AXIS_Z, GameControllerDelegate.THUMBSTICK_RIGHT_X);
ControllerKeyMap.put(MotionEvent.AXIS_RZ, GameControllerDelegate.THUMBSTICK_RIGHT_Y); ControllerKeyMap.put(AXIS_RZ, GameControllerDelegate.THUMBSTICK_RIGHT_Y);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_START, GameControllerDelegate.BUTTON_START); ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_START, GameControllerDelegate.BUTTON_START);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_SELECT, GameControllerDelegate.BUTTON_SELECT); ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_SELECT, GameControllerDelegate.BUTTON_SELECT);
//KEYCODE_BUTTON_MODE //KEYCODE_BUTTON_MODE
mDownDepsHttpClient = new AsyncHttpClient();
mDownDepsHttpClient.setTimeout(360 * 1000);
} }
public void connectController(){ public void connectController(){
@ -155,18 +157,19 @@ public class GameControllerHelper {
mOuyaSupportedDrives = new ArrayList<String>(5); mOuyaSupportedDrives = new ArrayList<String>(5);
mLocalSavePath = Environment.getExternalStorageDirectory() + File.separator + "CocosGameController" + File.separator; mLocalSavePath = Environment.getExternalStorageDirectory() + File.separator + "CocosGameController" + File.separator;
mConfigFilePath = sCocos2dxActivity.getFilesDir().getAbsolutePath() + File.separator + COCOS_CONTROLLER_CONFIG; Log.i(TAG, "mLocalSavePath:" + mLocalSavePath);
mDownDepsHttpClient = new AsyncHttpClient(); mConfigFilePath = sGameControllerActivity.getFilesDir().getAbsolutePath() + File.separator + COCOS_CONTROLLER_CONFIG;
mDownDepsHttpClient.setTimeout(360 * 1000); Log.i(TAG, "mConfigFilePath:" + mConfigFilePath);
} }
if (mControllerListener != null) { if (mControllerListener != null) {
mControllerListener.onDownloadConfigStarted(); mControllerListener.onDownloadConfigStarted();
} }
if (mLazyConfigInit) { if (mLazyConfigInit) {
if (mDownDepsHttpClient != null) { //if (mDownDepsHttpClient != null) {
mDownDepsHttpClient.cancelRequests(sCocos2dxActivity, true); // mDownDepsHttpClient.cancelRequests(sGameControllerActivity, true);
} //}
requestControllerConfig(); requestControllerConfig();
} }
else { else {
@ -187,7 +190,7 @@ public class GameControllerHelper {
public void destrory(){ public void destrory(){
if (mDownDepsHttpClient != null) { if (mDownDepsHttpClient != null) {
mDownDepsHttpClient.cancelRequests(sCocos2dxActivity, true); mDownDepsHttpClient.cancelRequests(sGameControllerActivity, true);
} }
} }
@ -213,12 +216,12 @@ public class GameControllerHelper {
//filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); //filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
sCocos2dxActivity.registerReceiver(mBluetoothReceiver, filter); sGameControllerActivity.registerReceiver(mBluetoothReceiver, filter);
IntentFilter appFilter = new IntentFilter(); IntentFilter appFilter = new IntentFilter();
appFilter.addAction("android.intent.action.PACKAGE_ADDED"); appFilter.addAction("android.intent.action.PACKAGE_ADDED");
appFilter.addDataScheme("package"); appFilter.addDataScheme("package");
sCocos2dxActivity.registerReceiver(mAppReceiver, appFilter); sGameControllerActivity.registerReceiver(mAppReceiver, appFilter);
} }
if (!mBluetoothAdapter.isEnabled()) { if (!mBluetoothAdapter.isEnabled()) {
@ -238,34 +241,34 @@ public class GameControllerHelper {
String deviceName = device.getName(); String deviceName = device.getName();
if (mNibiruSupportedDrives.contains(deviceName)) { if (mNibiruSupportedDrives.contains(deviceName)) {
return DRIVERTYPE_NIBIRU; return GameControllerActivity.DRIVERTYPE_NIBIRU;
} }
else if (mMogaSupportedDrives.contains(deviceName)) { else if (mMogaSupportedDrives.contains(deviceName)) {
return DRIVERTYPE_MOGA; return GameControllerActivity.DRIVERTYPE_MOGA;
} }
else if (mOuyaSupportedDrives.contains(deviceName)) { else if (mOuyaSupportedDrives.contains(deviceName)) {
return DRIVERTYPE_OUYA; return GameControllerActivity.DRIVERTYPE_OUYA;
} }
else { else {
} }
return DRIVERTYPE_UNKNOWN; return GameControllerActivity.DRIVERTYPE_UNKNOWN;
} }
public static void installApplication(String filePath){ public static void installApplication(String filePath){
if (sCocos2dxActivity != null) { if (sGameControllerActivity != null) {
Intent intent = new Intent(); Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW); intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive"); intent.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sCocos2dxActivity.startActivity(intent); sGameControllerActivity.startActivity(intent);
} }
} }
public static boolean checkApplication(String packName){ public static boolean checkApplication(String packName){
try { try {
ApplicationInfo applicationInfo = sCocos2dxActivity.getPackageManager().getApplicationInfo(packName, PackageManager.GET_UNINSTALLED_PACKAGES); ApplicationInfo applicationInfo = sGameControllerActivity.getPackageManager().getApplicationInfo(packName, PackageManager.GET_UNINSTALLED_PACKAGES);
Log.d(TAG, applicationInfo.toString()); Log.d(TAG, applicationInfo.toString());
return true; return true;
} catch (NameNotFoundException e) { } catch (NameNotFoundException e) {
@ -297,7 +300,7 @@ public class GameControllerHelper {
mBluetoothDevices.add(device); mBluetoothDevices.add(device);
int type = checkDriverType(device); int type = checkDriverType(device);
if (type != DRIVERTYPE_UNKNOWN) { if (type != GameControllerActivity.DRIVERTYPE_UNKNOWN) {
mTargetDriverType = type; mTargetDriverType = type;
mClearDevices += 1; mClearDevices += 1;
} }
@ -312,7 +315,7 @@ public class GameControllerHelper {
else { else {
if (mBluetoothDevices.size() == 0) { if (mBluetoothDevices.size() == 0) {
if (checkApplication(NIBIRU_DEP_PACKAGE)) { if (checkApplication(NIBIRU_DEP_PACKAGE)) {
downControllerDeps(DRIVERTYPE_NIBIRU); downControllerDeps(GameControllerActivity.DRIVERTYPE_NIBIRU);
} }
Log.w(TAG, "Not found any supported bluetooth game controller!"); Log.w(TAG, "Not found any supported bluetooth game controller!");
}else { }else {
@ -320,7 +323,10 @@ public class GameControllerHelper {
downControllerDeps(mTargetDriverType); downControllerDeps(mTargetDriverType);
} }
else { else {
Log.i(TAG, "More than one device"); Log.i(TAG, "Not clear target!");
if (checkApplication(NIBIRU_DEP_PACKAGE)) {
downControllerDeps(GameControllerActivity.DRIVERTYPE_NIBIRU);
}
//todo:show sel //todo:show sel
} }
} }
@ -335,7 +341,7 @@ public class GameControllerHelper {
mBluetoothDevices.clear(); mBluetoothDevices.clear();
mDevicesDriver.clear(); mDevicesDriver.clear();
mClearDevices = 0; mClearDevices = 0;
mTargetDriverType = DRIVERTYPE_UNKNOWN; mTargetDriverType = GameControllerActivity.DRIVERTYPE_UNKNOWN;
//check moga controller //check moga controller
Iterator<BluetoothDevice> it = mBluetoothAdapter.getBondedDevices().iterator(); Iterator<BluetoothDevice> it = mBluetoothAdapter.getBondedDevices().iterator();
@ -348,7 +354,7 @@ public class GameControllerHelper {
mBluetoothDevices.add(device); mBluetoothDevices.add(device);
int type = checkDriverType(device); int type = checkDriverType(device);
Log.d(TAG, "BluetoothDevice objects that are bonded (paired) to the local adapter :" + device.getName()); Log.d(TAG, "BluetoothDevice objects that are bonded (paired) to the local adapter :" + device.getName());
if (type != DRIVERTYPE_UNKNOWN) { if (type != GameControllerActivity.DRIVERTYPE_UNKNOWN) {
mClearDevices += 1; mClearDevices += 1;
mTargetDriverType = type; mTargetDriverType = type;
} }
@ -361,7 +367,7 @@ public class GameControllerHelper {
}; };
private static int depsCount = 0; private static int depsCount = 0;
private static int mTargetDriverType = DRIVERTYPE_UNKNOWN; private static int mTargetDriverType = GameControllerActivity.DRIVERTYPE_UNKNOWN;
private static int mDownloadTotalSize; private static int mDownloadTotalSize;
private static int mDownloadLibSize; private static int mDownloadLibSize;
@ -369,7 +375,9 @@ public class GameControllerHelper {
private static int mDepDownloadCompletedSize; private static int mDepDownloadCompletedSize;
public void downControllerDeps(int driverType){ public void downControllerDeps(int driverType){
if (driverType == DRIVERTYPE_STANDARD || driverType == DRIVERTYPE_UNKNOWN) { if (driverType != GameControllerActivity.DRIVERTYPE_NIBIRU
&& driverType != GameControllerActivity.DRIVERTYPE_MOGA
&& driverType != GameControllerActivity.DRIVERTYPE_OUYA) {
return; return;
} }
@ -388,64 +396,37 @@ public class GameControllerHelper {
String remoteDir = COCOS_CONTROLLER_URL + DRIVERS_NAME[driverType] + File.separator; String remoteDir = COCOS_CONTROLLER_URL + DRIVERS_NAME[driverType] + File.separator;
if (driverType == DRIVERTYPE_NIBIRU) { if (driverType == GameControllerActivity.DRIVERTYPE_NIBIRU) {
mDownloadLibSize = mNibiruLibFileSize;
mDownloadTotalSize += mNibiruLibFileSize;
if (!checkApplication(NIBIRU_DEP_PACKAGE)) { if (!checkApplication(NIBIRU_DEP_PACKAGE)) {
depsCount += 1; depsCount += 1;
mDownloadTotalSize += mNibiruDepFileSize; mDownloadTotalSize += mNibiruDepFileSize;
mDownDepsHttpClient.get(remoteDir + mNibiruDepFileName, new MyDepsAsyncHandler( mDownDepsHttpClient.get(remoteDir + mNibiruDepFileName, new MyDepsAsyncHandler(
new File(mLocalSavePath + mNibiruDepFileName), MyDepsAsyncHandler.FILETYPE_DEP_APK)); new File(mLocalSavePath + mNibiruDepFileName), MyDepsAsyncHandler.FILETYPE_DEP_APK));
} }
File libFile = new File(mLocalSavePath + mNibiruLibFileName);
if (libFile.exists() && libFile.length() == mNibiruLibFileSize) {
depsCount -= 1;
if (depsCount == 0) {
onDepsReady();
} }
} else if (driverType == GameControllerActivity.DRIVERTYPE_MOGA) {
else {
mDownDepsHttpClient.get(remoteDir + mNibiruLibFileName, new MyDepsAsyncHandler(
libFile, MyDepsAsyncHandler.FILETYPE_JAR));
}
}
else if (driverType == DRIVERTYPE_MOGA) {
mDownloadLibSize = mMogaLibFileSize;
mDownloadTotalSize += mMogaLibFileSize;
if (!checkApplication(MOGA__DEP_PACKAGE)) { if (!checkApplication(MOGA__DEP_PACKAGE)) {
mDownloadTotalSize += mMogaDepFileSize; mDownloadTotalSize += mMogaDepFileSize;
depsCount += 1; depsCount += 1;
mDownDepsHttpClient.get(remoteDir + mMogaDepFileName, new MyDepsAsyncHandler( mDownDepsHttpClient.get(remoteDir + mMogaDepFileName, new MyDepsAsyncHandler(
new File(mLocalSavePath + mMogaDepFileName), MyDepsAsyncHandler.FILETYPE_DEP_APK)); new File(mLocalSavePath + mMogaDepFileName), MyDepsAsyncHandler.FILETYPE_DEP_APK));
} }
}
else if(driverType == GameControllerActivity.DRIVERTYPE_OUYA){
File libFile = new File(mLocalSavePath + mMogaLibFileName); }
if (libFile.exists() && libFile.length() == mMogaLibFileSize) {
File libFile = new File(mLocalSavePath + mLibAdapterFileName);
if (libFile.exists() && libFile.length() == mLibAdapterFileSize) {
depsCount -= 1; depsCount -= 1;
if (depsCount == 0) { if (depsCount == 0) {
onDepsReady(); onDepsReady();
} }
}else { }else {
mDownDepsHttpClient.get(remoteDir + mMogaLibFileName, new MyDepsAsyncHandler( mDownloadLibSize = mLibAdapterFileSize;
libFile, MyDepsAsyncHandler.FILETYPE_JAR)); mDownloadTotalSize += mDownloadLibSize;
} mDownDepsHttpClient.get(COCOS_CONTROLLER_URL + mLibAdapterFileName, new MyDepsAsyncHandler(
} new File(mLocalSavePath + mLibAdapterFileName), MyDepsAsyncHandler.FILETYPE_JAR));
else if(driverType == DRIVERTYPE_OUYA){
mDownloadLibSize = mOuyaLibFileSize;
mDownloadTotalSize += mOuyaLibFileSize;
File libFile = new File(mLocalSavePath + mOuyaLibFileName);
if (libFile.exists() && libFile.length() == mOuyaLibFileSize) {
depsCount -= 1;
if (depsCount == 0) {
onDepsReady();
}
}else {
mDownDepsHttpClient.get(remoteDir + mOuyaLibFileName, new MyDepsAsyncHandler(
new File(mLocalSavePath + mOuyaLibFileName), MyDepsAsyncHandler.FILETYPE_JAR));
}
} }
} }
@ -484,19 +465,6 @@ public class GameControllerHelper {
Log.e(TAG,"Failed to download:" + file.getName()); Log.e(TAG,"Failed to download:" + file.getName());
} }
@Override
public void onSuccess(File file) {
Log.d(TAG, "Down file success:" + file.getName());
depsCount -= 1;
if (depsCount == 0) {
if (mControllerListener != null) {
mControllerListener.onDownloadDepsFinished(true);
}
sControllerHelper.onDepsReady();
}
}
@Override @Override
public void onProgress(int bytesWritten, int totalSize) { public void onProgress(int bytesWritten, int totalSize) {
if (mFileType == FILETYPE_JAR) { if (mFileType == FILETYPE_JAR) {
@ -510,14 +478,41 @@ public class GameControllerHelper {
} }
Log.d(TAG, "totalSize:" + totalSize + ", bytesWritten:" + bytesWritten); Log.d(TAG, "totalSize:" + totalSize + ", bytesWritten:" + bytesWritten);
} }
public void onSuccess(File file) {
Log.d(TAG, "11Down file success:" + file.getName());
depsCount -= 1;
if (depsCount == 0) {
if (mControllerListener != null) {
mControllerListener.onDownloadDepsFinished(true);
}
sControllerHelper.onDepsReady();
}
super.onSuccess(file);
}
/*@Override
public void onSuccess(int arg0, Header[] arg1, File file) {
Log.d(TAG, "22Down file success:" + file.getName());
depsCount -= 1;
if (depsCount == 0) {
if (mControllerListener != null) {
mControllerListener.onDownloadDepsFinished(true);
}
sControllerHelper.onDepsReady();
}
}*/
} }
private void onDepsReady(){ private void onDepsReady(){
Log.d(TAG, "onDepsReady:" + mTargetDriverType); Log.d(TAG, "onDepsReady:" + mTargetDriverType);
if (mTargetDriverType == DRIVERTYPE_NIBIRU) { if (mTargetDriverType == GameControllerActivity.DRIVERTYPE_NIBIRU) {
if (checkApplication(NIBIRU_DEP_PACKAGE)) { if (checkApplication(NIBIRU_DEP_PACKAGE)) {
createControllerInstance(mLocalSavePath + mNibiruLibFileName, mTargetDriverType); createControllerInstance(mLocalSavePath + mLibAdapterFileName, mTargetDriverType);
} }
else { else {
if (mControllerListener != null) { if (mControllerListener != null) {
@ -526,9 +521,9 @@ public class GameControllerHelper {
installApplication(mLocalSavePath + mNibiruDepFileName); installApplication(mLocalSavePath + mNibiruDepFileName);
} }
} }
else if (mTargetDriverType == DRIVERTYPE_MOGA) { else if (mTargetDriverType == GameControllerActivity.DRIVERTYPE_MOGA) {
if (checkApplication(MOGA__DEP_PACKAGE)) { if (checkApplication(MOGA__DEP_PACKAGE)) {
createControllerInstance(mLocalSavePath + mMogaLibFileName, mTargetDriverType); createControllerInstance(mLocalSavePath + mLibAdapterFileName, mTargetDriverType);
} }
else { else {
if (mControllerListener != null) { if (mControllerListener != null) {
@ -537,25 +532,14 @@ public class GameControllerHelper {
installApplication(mLocalSavePath + mMogaDepFileName); installApplication(mLocalSavePath + mMogaDepFileName);
} }
} }
else if (mTargetDriverType == DRIVERTYPE_OUYA) { else if (mTargetDriverType == GameControllerActivity.DRIVERTYPE_OUYA) {
/*if (checkApplication(OUYA_FRAMEWORK_PACKAGE)) { createControllerInstance(mLocalSavePath + mLibAdapterFileName, mTargetDriverType);
if (checkApplication(OUYA_LAUNCHER_PACKAGE)) {
createControllerInstance(mLocalSavePath + mOuyaLibFileName, mTargetSDK);
}
else {
installApplication(mLocalSavePath + mOuyaLauncherFileName);
}
}
else {
installApplication(mLocalSavePath + mOuyaFrameworkFileName);
}*/
createControllerInstance(mLocalSavePath + mOuyaLibFileName, mTargetDriverType);
} }
} }
private static final String CONFIGKEY_DRIVES = "drives"; private static final String CONFIGKEY_DRIVES = "drives";
private static final String CONFIGKEY_LIB_FILENAME = "lib"; private static final String CONFIGKEY_LIBADAPTER_FILENAME = "adapter-file";
private static final String CONFIGKEY_LIB_FILESIZE = "lib-size"; private static final String CONFIGKEY_LIBADAPTER_FILESIZE = "adapter-filesize";
private static final String CONFIGKEY_DEP_FILENAME = "dep-apk"; private static final String CONFIGKEY_DEP_FILENAME = "dep-apk";
private static final String CONFIGKEY_DEP_FILESIZE = "dep-size"; private static final String CONFIGKEY_DEP_FILESIZE = "dep-size";
@ -565,7 +549,14 @@ public class GameControllerHelper {
mOuyaSupportedDrives.clear(); mOuyaSupportedDrives.clear();
try { try {
int tint = 9879;
JSONObject jsonObject = new JSONObject();
jsonObject.put("intvalue",tint);
Log.w(TAG, "intJson:" + jsonObject);
JSONObject configObject = new JSONObject(jsonString); JSONObject configObject = new JSONObject(jsonString);
mLibAdapterFileName = configObject.getString(CONFIGKEY_LIBADAPTER_FILENAME);
mLibAdapterFileSize = configObject.getInt(CONFIGKEY_LIBADAPTER_FILESIZE);
JSONObject nibiruObject = configObject.getJSONObject("nibiru"); JSONObject nibiruObject = configObject.getJSONObject("nibiru");
JSONArray drives = nibiruObject.getJSONArray(CONFIGKEY_DRIVES); JSONArray drives = nibiruObject.getJSONArray(CONFIGKEY_DRIVES);
@ -575,8 +566,6 @@ public class GameControllerHelper {
} }
mNibiruDepFileName = nibiruObject.getString(CONFIGKEY_DEP_FILENAME); mNibiruDepFileName = nibiruObject.getString(CONFIGKEY_DEP_FILENAME);
mNibiruDepFileSize = nibiruObject.getInt(CONFIGKEY_DEP_FILESIZE); mNibiruDepFileSize = nibiruObject.getInt(CONFIGKEY_DEP_FILESIZE);
mNibiruLibFileName = nibiruObject.getString(CONFIGKEY_LIB_FILENAME);
mNibiruLibFileSize = nibiruObject.getInt(CONFIGKEY_LIB_FILESIZE);
JSONObject mogaObject = configObject.getJSONObject("moga"); JSONObject mogaObject = configObject.getJSONObject("moga");
drives = mogaObject.getJSONArray(CONFIGKEY_DRIVES); drives = mogaObject.getJSONArray(CONFIGKEY_DRIVES);
@ -586,8 +575,6 @@ public class GameControllerHelper {
} }
mMogaDepFileName = mogaObject.getString(CONFIGKEY_DEP_FILENAME); mMogaDepFileName = mogaObject.getString(CONFIGKEY_DEP_FILENAME);
mMogaDepFileSize = mogaObject.getInt(CONFIGKEY_DEP_FILESIZE); mMogaDepFileSize = mogaObject.getInt(CONFIGKEY_DEP_FILESIZE);
mMogaLibFileName = mogaObject.getString(CONFIGKEY_LIB_FILENAME);
mMogaLibFileSize = mogaObject.getInt(CONFIGKEY_LIB_FILESIZE);
JSONObject ouyaObject = configObject.getJSONObject("ouya"); JSONObject ouyaObject = configObject.getJSONObject("ouya");
drives = ouyaObject.getJSONArray(CONFIGKEY_DRIVES); drives = ouyaObject.getJSONArray(CONFIGKEY_DRIVES);
@ -595,10 +582,7 @@ public class GameControllerHelper {
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
mOuyaSupportedDrives.add(drives.getString(i)); mOuyaSupportedDrives.add(drives.getString(i));
} }
mOuyaLibFileName = ouyaObject.getString(CONFIGKEY_LIB_FILENAME);
mOuyaLibFileSize = ouyaObject.getInt(CONFIGKEY_LIB_FILESIZE);
//mOuyaFrameworkFileName = ouyaObject.getString("dep-framework");
//mOuyaLauncherFileName = ouyaObject.getString("dep-launcher");
mLazyConfigInit = false; mLazyConfigInit = false;
return true; return true;
} catch (Exception e1) { } catch (Exception e1) {
@ -677,7 +661,6 @@ public class GameControllerHelper {
if (mControllerListener != null) { if (mControllerListener != null) {
mControllerListener.onDownloadConfigFinished(false); mControllerListener.onDownloadConfigFinished(false);
} }
Log.e(TAG, "Failed to download controller config!");
} }
}; };
@ -685,10 +668,14 @@ public class GameControllerHelper {
} }
private static void showToast(String message){ private static void showToast(String message){
Toast.makeText(sCocos2dxActivity, message, Toast.LENGTH_SHORT).show(); Toast.makeText(sGameControllerActivity, message, Toast.LENGTH_SHORT).show();
} }
private static void createControllerInstance(String libFilePath,int sdkType) { private static void createControllerInstance(String libFilePath,int driveType) {
//if (sGameControllerActivity.getGameControllerDelegate(driveType) != null) {
// return;
//}
File libFile = new File(libFilePath); File libFile = new File(libFilePath);
if (! libFile.exists()) { if (! libFile.exists()) {
Log.w(TAG, libFile.toString() + "not exist!"); Log.w(TAG, libFile.toString() + "not exist!");
@ -698,21 +685,20 @@ public class GameControllerHelper {
DexClassLoader classLoader = null; DexClassLoader classLoader = null;
try { try {
File dexOutputDir = sCocos2dxActivity.getDir("dex", Context.MODE_PRIVATE); File dexOutputDir = sGameControllerActivity.getDir("dex", Context.MODE_PRIVATE);
classLoader = new DexClassLoader(libFile.getCanonicalPath(), dexOutputDir.getCanonicalPath(), classLoader = new DexClassLoader(libFile.getCanonicalPath(), dexOutputDir.getCanonicalPath(),
null, sCocos2dxActivity.getClassLoader()); null, sGameControllerActivity.getClassLoader());
} catch (Exception e1) { } catch (Exception e1) {
e1.printStackTrace(); e1.printStackTrace();
} }
try { try {
Class<?> controllerDelegate = null; Class<?> controllerDelegate = null;
if (sdkType == DRIVERTYPE_MOGA) { if (driveType == GameControllerActivity.DRIVERTYPE_MOGA) {
controllerDelegate = classLoader.loadClass("org.cocos2dx.lib.GameControllerMoga"); controllerDelegate = classLoader.loadClass("org.cocos2dx.lib.GameControllerMoga");
} else if (sdkType == DRIVERTYPE_NIBIRU) { } else if (driveType == GameControllerActivity.DRIVERTYPE_NIBIRU) {
controllerDelegate = classLoader.loadClass("org.cocos2dx.lib.GameControllerNibiru"); controllerDelegate = classLoader.loadClass("org.cocos2dx.lib.GameControllerNibiru");
} else if (sdkType == DRIVERTYPE_OUYA) { } else if (driveType == GameControllerActivity.DRIVERTYPE_OUYA) {
controllerDelegate = classLoader.loadClass("org.cocos2dx.lib.GameControllerOuya"); controllerDelegate = classLoader.loadClass("org.cocos2dx.lib.GameControllerOuya");
} }
@ -721,8 +707,8 @@ public class GameControllerHelper {
if (mControllerListener != null) { if (mControllerListener != null) {
mControllerListener.onConnectController(); mControllerListener.onConnectController();
} }
sCocos2dxActivity.setGameControllerInstance(instance); sGameControllerActivity.setGameControllerInstance(instance, driveType);
if (sdkType == DRIVERTYPE_NIBIRU) { if (driveType == GameControllerActivity.DRIVERTYPE_NIBIRU) {
Method method = controllerDelegate.getDeclaredMethod("onResume"); Method method = controllerDelegate.getDeclaredMethod("onResume");
method.invoke(instance); method.invoke(instance);
} }
@ -739,10 +725,10 @@ public class GameControllerHelper {
String packageName = intent.getDataString(); String packageName = intent.getDataString();
Log.d(TAG, "mAppReceiver:" + intent); Log.d(TAG, "mAppReceiver:" + intent);
if (packageName.contains(NIBIRU_DEP_PACKAGE)) { if (packageName.contains(NIBIRU_DEP_PACKAGE)) {
createControllerInstance(mLocalSavePath + mNibiruLibFileName, DRIVERTYPE_NIBIRU); createControllerInstance(mLocalSavePath + mLibAdapterFileName, GameControllerActivity.DRIVERTYPE_NIBIRU);
} }
else if (packageName.contains(MOGA__DEP_PACKAGE)) { else if (packageName.contains(MOGA__DEP_PACKAGE)) {
createControllerInstance(mLocalSavePath + mMogaLibFileName, DRIVERTYPE_MOGA); createControllerInstance(mLocalSavePath + mLibAdapterFileName, GameControllerActivity.DRIVERTYPE_MOGA);
} }
} }
}; };
@ -768,35 +754,35 @@ public class GameControllerHelper {
if (event.getAction() == MotionEvent.ACTION_MOVE) { if (event.getAction() == MotionEvent.ACTION_MOVE) {
int devicedId = event.getDeviceId(); int devicedId = event.getDeviceId();
float newAXIS_LX = event.getAxisValue(MotionEvent.AXIS_X); float newAXIS_LX = event.getAxisValue(AXIS_X);
if (Float.compare(newAXIS_LX , mOldLeftThumbstickX) != 0) { if (Float.compare(newAXIS_LX , mOldLeftThumbstickX) != 0) {
GameControllerAdapter.onAxisEvent(StandardControllerName, devicedId, GameControllerDelegate.THUMBSTICK_LEFT_X, newAXIS_LX, true); GameControllerAdapter.onAxisEvent(StandardControllerName, devicedId, GameControllerDelegate.THUMBSTICK_LEFT_X, newAXIS_LX, true);
mOldLeftThumbstickX = newAXIS_LX; mOldLeftThumbstickX = newAXIS_LX;
handled = true; handled = true;
} }
float newAXIS_LY = event.getAxisValue(MotionEvent.AXIS_Y); float newAXIS_LY = event.getAxisValue(AXIS_Y);
if (Float.compare(newAXIS_LY , mOldLeftThumbstickY) != 0) { if (Float.compare(newAXIS_LY , mOldLeftThumbstickY) != 0) {
GameControllerAdapter.onAxisEvent(StandardControllerName, devicedId, GameControllerDelegate.THUMBSTICK_LEFT_Y, newAXIS_LY, true); GameControllerAdapter.onAxisEvent(StandardControllerName, devicedId, GameControllerDelegate.THUMBSTICK_LEFT_Y, newAXIS_LY, true);
mOldLeftThumbstickY = newAXIS_LY; mOldLeftThumbstickY = newAXIS_LY;
handled = true; handled = true;
} }
float newAXIS_RX = event.getAxisValue(MotionEvent.AXIS_Z); float newAXIS_RX = event.getAxisValue(AXIS_Z);
if (Float.compare(newAXIS_RX , mOldRightThumbstickX) != 0) { if (Float.compare(newAXIS_RX , mOldRightThumbstickX) != 0) {
GameControllerAdapter.onAxisEvent(StandardControllerName, devicedId, GameControllerDelegate.THUMBSTICK_RIGHT_X, newAXIS_RX, true); GameControllerAdapter.onAxisEvent(StandardControllerName, devicedId, GameControllerDelegate.THUMBSTICK_RIGHT_X, newAXIS_RX, true);
mOldRightThumbstickX = newAXIS_RX; mOldRightThumbstickX = newAXIS_RX;
handled = true; handled = true;
} }
float newAXIS_RY = event.getAxisValue(MotionEvent.AXIS_RZ); float newAXIS_RY = event.getAxisValue(AXIS_RZ);
if (Float.compare(newAXIS_RY , mOldRightThumbstickY) != 0) { if (Float.compare(newAXIS_RY , mOldRightThumbstickY) != 0) {
GameControllerAdapter.onAxisEvent(StandardControllerName, devicedId, GameControllerDelegate.THUMBSTICK_RIGHT_Y, newAXIS_RY, true); GameControllerAdapter.onAxisEvent(StandardControllerName, devicedId, GameControllerDelegate.THUMBSTICK_RIGHT_Y, newAXIS_RY, true);
mOldRightThumbstickY = newAXIS_RY; mOldRightThumbstickY = newAXIS_RY;
handled = true; handled = true;
} }
float newAXIS_LTRIGGER = event.getAxisValue(MotionEvent.AXIS_LTRIGGER); float newAXIS_LTRIGGER = event.getAxisValue(AXIS_LTRIGGER);
if (Float.compare(newAXIS_LTRIGGER , mOldLeftTrigger) != 0) { if (Float.compare(newAXIS_LTRIGGER , mOldLeftTrigger) != 0) {
if (Float.compare(newAXIS_LTRIGGER, 0.0f) == 0) { if (Float.compare(newAXIS_LTRIGGER, 0.0f) == 0) {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, false, 0.0f, true); GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, false, 0.0f, true);
@ -807,7 +793,7 @@ public class GameControllerHelper {
handled = true; handled = true;
} }
float newAXIS_RTRIGGER = event.getAxisValue(MotionEvent.AXIS_RTRIGGER); float newAXIS_RTRIGGER = event.getAxisValue(AXIS_RTRIGGER);
if (Float.compare(newAXIS_RTRIGGER , mOldRightTrigger) != 0) { if (Float.compare(newAXIS_RTRIGGER , mOldRightTrigger) != 0) {
if (Float.compare(newAXIS_RTRIGGER, 0.0f) == 0) { if (Float.compare(newAXIS_RTRIGGER, 0.0f) == 0) {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, false, 0.0f, true); GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, false, 0.0f, true);
@ -818,7 +804,7 @@ public class GameControllerHelper {
handled = true; handled = true;
} }
float newAXIS_BRAKE = event.getAxisValue(MotionEvent.AXIS_BRAKE); float newAXIS_BRAKE = event.getAxisValue(AXIS_BRAKE);
if (Float.compare(newAXIS_BRAKE , mOldBrake) != 0) { if (Float.compare(newAXIS_BRAKE , mOldBrake) != 0) {
if (Float.compare(newAXIS_BRAKE, 0.0f) == 0) { if (Float.compare(newAXIS_BRAKE, 0.0f) == 0) {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, false, 0.0f, true); GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, false, 0.0f, true);
@ -829,7 +815,7 @@ public class GameControllerHelper {
handled = true; handled = true;
} }
float newAXIS_THROTTLE = event.getAxisValue(MotionEvent.AXIS_THROTTLE); float newAXIS_THROTTLE = event.getAxisValue(AXIS_THROTTLE);
if (Float.compare(newAXIS_THROTTLE , mOldThrottle) != 0) { if (Float.compare(newAXIS_THROTTLE , mOldThrottle) != 0) {
if (Float.compare(newAXIS_THROTTLE, 0.0f) == 0) { if (Float.compare(newAXIS_THROTTLE, 0.0f) == 0) {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, false, 0.0f, true); GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, false, 0.0f, true);

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<projectDescription> <projectDescription>
<name>libcontrollerouya</name> <name>libControllerManualAdapter</name>
<comment></comment> <comment></comment>
<projects> <projects>
</projects> </projects>

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project name="androidcontrollerdelegate" default="help"> <project name="androidControllerManualAdapter" default="help">
<!-- The local.properties file is created and updated by the 'android' tool. <!-- 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 It contains the path to the SDK. It should *NOT* be checked into

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<lint>
<issue id="NewApi">
<ignore path="src/org/cocos2dx/lib/GameControllerHelper.java" />
</issue>
</lint>

View File

@ -0,0 +1,316 @@
/****************************************************************************
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 java.lang.reflect.Method;
import org.cocos2dx.lib.GameControllerDelegate.ControllerEventListener;
import org.cocos2dx.lib.inputmanagercompat.InputManagerCompat;
import org.cocos2dx.lib.inputmanagercompat.InputManagerCompat.InputDeviceListener;
import org.cocos2dx.lib.Cocos2dxActivity;
import android.os.Bundle;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.util.Log;
public abstract class GameControllerActivity extends Cocos2dxActivity implements InputDeviceListener {
// ===========================================================
// Constants
// ===========================================================
private final static String TAG = GameControllerActivity.class.getSimpleName();
public static final int DRIVERTYPE_NIBIRU = 0;
public static final int DRIVERTYPE_MOGA = 1;
public static final int DRIVERTYPE_OUYA = 2;
public static final int DRIVERTYPE_STANDARD = 3;
public static final int DRIVERTYPE_UNKNOWN = 4;
// ===========================================================
// Fields
// ===========================================================
private static GameControllerActivity sGameControllerActivity;
private InputManagerCompat mInputManager = null;
protected GameControllerHelper mControllerHelper = null;
protected GameControllerDelegate mControllerNibiru = null;
protected GameControllerDelegate mControllerMoga = null;
protected GameControllerDelegate mControllerOuya = null;
public void connectController(int driveType){
try {
ClassLoader loader = sGameControllerActivity.getClassLoader();
Class<?> controllerDelegate = null;
if (driveType == DRIVERTYPE_MOGA) {
if (mControllerMoga != null) {
return;
}
controllerDelegate = loader.loadClass("org.cocos2dx.lib.GameControllerMoga");
} else if (driveType == DRIVERTYPE_NIBIRU) {
if (mControllerNibiru != null) {
mControllerNibiru.onCreate(sGameControllerActivity);
mControllerNibiru.onResume();
return;
}
controllerDelegate = loader.loadClass("org.cocos2dx.lib.GameControllerNibiru");
} else if (driveType == DRIVERTYPE_OUYA) {
if (mControllerOuya != null) {
return;
}
controllerDelegate = loader.loadClass("org.cocos2dx.lib.GameControllerOuya");
}
GameControllerDelegate instance = (GameControllerDelegate)controllerDelegate.newInstance();
sGameControllerActivity.setGameControllerInstance(instance, driveType);
if (driveType == DRIVERTYPE_NIBIRU) {
Method method = controllerDelegate.getDeclaredMethod("onResume");
method.invoke(instance);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public void setGameControllerInstance(GameControllerDelegate controllerDelegate, int driveType) {
if (driveType == DRIVERTYPE_NIBIRU) {
mControllerNibiru = controllerDelegate;
}else if (driveType == DRIVERTYPE_MOGA) {
mControllerMoga = controllerDelegate;
}
else if (driveType == DRIVERTYPE_OUYA) {
mControllerOuya = controllerDelegate;
}
controllerDelegate.setControllerEventListener(mControllerEventListener);
controllerDelegate.onCreate(sGameControllerActivity);
}
public GameControllerDelegate getGameControllerDelegate(int driveType){
if (driveType == DRIVERTYPE_NIBIRU) {
return mControllerNibiru;
}else if (driveType == DRIVERTYPE_MOGA) {
return mControllerMoga;
}
else if (driveType == DRIVERTYPE_OUYA) {
return mControllerOuya;
}
return null;
}
ControllerEventListener mControllerEventListener = new ControllerEventListener() {
@Override
public void onButtonEvent(String vendorName, int controller, int button,
boolean isPressed, float value, boolean isAnalog) {
GameControllerAdapter.onButtonEvent(vendorName, controller, button, isPressed, value, isAnalog);
}
@Override
public void onAxisEvent(String vendorName, int controller, int axisID,
float value, boolean isAnalog) {
GameControllerAdapter.onAxisEvent(vendorName, controller, axisID, value, isAnalog);
}
@Override
public void onConnected(String vendorName, int controller) {
GameControllerAdapter.onConnected(vendorName, controller);
}
@Override
public void onDisconnected(String vendorName, int controller) {
GameControllerAdapter.onDisconnected(vendorName, controller);
}
};
// ===========================================================
// Constructors
// ===========================================================
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sGameControllerActivity = this;
mInputManager = InputManagerCompat.Factory.getInputManager(this);
mInputManager.registerInputDeviceListener(this, null);
if (mControllerNibiru != null) {
mControllerNibiru.onCreate(this);
}
if (mControllerMoga != null) {
mControllerMoga.onCreate(this);
}
if (mControllerOuya != null) {
mControllerOuya.onCreate(this);
}
if (mControllerHelper == null) {
mControllerHelper = new GameControllerHelper(this);
}
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
boolean handled = false;
if (mControllerNibiru != null) {
handled |= mControllerNibiru.dispatchKeyEvent(event);
}
if (mControllerMoga != null) {
handled |= mControllerMoga.dispatchKeyEvent(event);
}
if (mControllerOuya != null) {
handled |= mControllerOuya.dispatchKeyEvent(event);
}
handled |= mControllerHelper.dispatchKeyEvent(event);
return handled || super.dispatchKeyEvent(event);
}
@Override
public boolean dispatchGenericMotionEvent(MotionEvent event) {
boolean handled = false;
if (mControllerNibiru != null) {
handled |= mControllerNibiru.dispatchGenericMotionEvent(event);
}
if (mControllerMoga != null) {
handled |= mControllerMoga.dispatchGenericMotionEvent(event);
}
if (mControllerOuya != null) {
handled |= mControllerOuya.dispatchGenericMotionEvent(event);
}
handled |= mControllerHelper.dispatchGenericMotionEvent(event);
return handled || super.dispatchGenericMotionEvent(event);
}
@Override
public void onInputDeviceAdded(int deviceId) {
Log.d(TAG,"onInputDeviceAdded:" + deviceId);
InputDevice device = InputDevice.getDevice(deviceId);
int deviceSource = device.getSources();
if ( ((deviceSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
|| ((deviceSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) )
{
GameControllerAdapter.onConnected("Standard", deviceId);
}
}
/*
* This is an unusual case. Input devices don't typically change, but they
* certainly can --- for example a device may have different modes. We use
* this to make sure that the ship has an up-to-date InputDevice.
*
* @see
* com.example.inputmanagercompat.InputManagerCompat.InputDeviceListener
* #onInputDeviceChanged(int)
*/
@Override
public void onInputDeviceChanged(int deviceId) {
Log.d(TAG,"onInputDeviceChanged:" + deviceId);
}
/*
* Remove any ship associated with the ID.
*
* @see
* com.example.inputmanagercompat.InputManagerCompat.InputDeviceListener
* #onInputDeviceRemoved(int)
*/
@Override
public void onInputDeviceRemoved(int deviceId) {
Log.d(TAG,"onInputDeviceRemoved:" + deviceId);
InputDevice device = InputDevice.getDevice(deviceId);
int deviceSource = device.getSources();
if ( ((deviceSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
|| ((deviceSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) )
{
GameControllerAdapter.onDisconnected("Standard", deviceId);
}
}
@Override
protected void onResume() {
super.onResume();
if (mControllerNibiru != null) {
mControllerNibiru.onResume();
}
if (mControllerMoga != null) {
mControllerMoga.onResume();
}
if (mControllerOuya != null) {
mControllerOuya.onResume();
}
}
@Override
protected void onPause() {
if (mControllerNibiru != null) {
mControllerNibiru.onPause();
}
if (mControllerMoga != null) {
mControllerMoga.onPause();
}
if (mControllerOuya != null) {
mControllerOuya.onPause();
}
super.onPause();
}
@Override
protected void onDestroy() {
if (mControllerNibiru != null) {
mControllerNibiru.onDestroy();
}
if (mControllerMoga != null) {
mControllerMoga.onDestroy();
}
if (mControllerOuya != null) {
mControllerOuya.onDestroy();
}
super.onDestroy();
}
}

View File

@ -0,0 +1,177 @@
package org.cocos2dx.lib;
import android.util.SparseIntArray;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
public class GameControllerHelper {
public static final String StandardControllerName = "Standard";
SparseIntArray ControllerKeyMap;
private static final int AXIS_X = 0;
private static final int AXIS_Y = 1;
private static final int AXIS_Z = 11;
private static final int AXIS_RZ = 14;
private static final int AXIS_LTRIGGER = 17;
private static final int AXIS_RTRIGGER = 18;
private static final int AXIS_BRAKE = 23;
private static final int AXIS_THROTTLE = 19;
public GameControllerHelper(GameControllerActivity activity){
ControllerKeyMap = new SparseIntArray(25);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_A, GameControllerDelegate.BUTTON_A);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_B, GameControllerDelegate.BUTTON_B);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_C, GameControllerDelegate.BUTTON_C);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_X, GameControllerDelegate.BUTTON_X);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_Y, GameControllerDelegate.BUTTON_Y);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_Z, GameControllerDelegate.BUTTON_Z);
ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_UP, GameControllerDelegate.BUTTON_DPAD_UP);
ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_DOWN, GameControllerDelegate.BUTTON_DPAD_DOWN);
ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_LEFT, GameControllerDelegate.BUTTON_DPAD_LEFT);
ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_RIGHT, GameControllerDelegate.BUTTON_DPAD_RIGHT);
ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_CENTER, GameControllerDelegate.BUTTON_DPAD_CENTER);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_THUMBL, GameControllerDelegate.BUTTON_LEFT_THUMBSTICK);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_THUMBR, GameControllerDelegate.BUTTON_RIGHT_THUMBSTICK);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_L1, GameControllerDelegate.BUTTON_LEFT_SHOULDER);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_R1, GameControllerDelegate.BUTTON_RIGHT_SHOULDER);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_L2, GameControllerDelegate.BUTTON_LEFT_TRIGGER);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_R2, GameControllerDelegate.BUTTON_RIGHT_TRIGGER);
ControllerKeyMap.put(AXIS_X, GameControllerDelegate.THUMBSTICK_LEFT_X);
ControllerKeyMap.put(AXIS_Y, GameControllerDelegate.THUMBSTICK_LEFT_Y);
ControllerKeyMap.put(AXIS_Z, GameControllerDelegate.THUMBSTICK_RIGHT_X);
ControllerKeyMap.put(AXIS_RZ, GameControllerDelegate.THUMBSTICK_RIGHT_Y);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_START, GameControllerDelegate.BUTTON_START);
ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_SELECT, GameControllerDelegate.BUTTON_SELECT);
//KEYCODE_BUTTON_MODE
}
private float mOldLeftThumbstickX = 0.0f;
private float mOldLeftThumbstickY = 0.0f;
private float mOldRightThumbstickX = 0.0f;
private float mOldRightThumbstickY = 0.0f;
private float mOldLeftTrigger = 0.0f;
private float mOldRightTrigger = 0.0f;
private float mOldThrottle = 0.0f;
private float mOldBrake = 0.0f;
public boolean dispatchGenericMotionEvent(MotionEvent event) {
boolean handled = false;
int eventSource = event.getSource();
if ( ((eventSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
|| ((eventSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) )
{
if (event.getAction() == MotionEvent.ACTION_MOVE) {
int devicedId = event.getDeviceId();
float newAXIS_LX = event.getAxisValue(AXIS_X);
if (Float.compare(newAXIS_LX , mOldLeftThumbstickX) != 0) {
GameControllerAdapter.onAxisEvent(StandardControllerName, devicedId, GameControllerDelegate.THUMBSTICK_LEFT_X, newAXIS_LX, true);
mOldLeftThumbstickX = newAXIS_LX;
handled = true;
}
float newAXIS_LY = event.getAxisValue(AXIS_Y);
if (Float.compare(newAXIS_LY , mOldLeftThumbstickY) != 0) {
GameControllerAdapter.onAxisEvent(StandardControllerName, devicedId, GameControllerDelegate.THUMBSTICK_LEFT_Y, newAXIS_LY, true);
mOldLeftThumbstickY = newAXIS_LY;
handled = true;
}
float newAXIS_RX = event.getAxisValue(AXIS_Z);
if (Float.compare(newAXIS_RX , mOldRightThumbstickX) != 0) {
GameControllerAdapter.onAxisEvent(StandardControllerName, devicedId, GameControllerDelegate.THUMBSTICK_RIGHT_X, newAXIS_RX, true);
mOldRightThumbstickX = newAXIS_RX;
handled = true;
}
float newAXIS_RY = event.getAxisValue(AXIS_RZ);
if (Float.compare(newAXIS_RY , mOldRightThumbstickY) != 0) {
GameControllerAdapter.onAxisEvent(StandardControllerName, devicedId, GameControllerDelegate.THUMBSTICK_RIGHT_Y, newAXIS_RY, true);
mOldRightThumbstickY = newAXIS_RY;
handled = true;
}
float newAXIS_LTRIGGER = event.getAxisValue(AXIS_LTRIGGER);
if (Float.compare(newAXIS_LTRIGGER , mOldLeftTrigger) != 0) {
if (Float.compare(newAXIS_LTRIGGER, 0.0f) == 0) {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, false, 0.0f, true);
}else {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, true, newAXIS_LTRIGGER, true);
}
mOldLeftTrigger = newAXIS_LTRIGGER;
handled = true;
}
float newAXIS_RTRIGGER = event.getAxisValue(AXIS_RTRIGGER);
if (Float.compare(newAXIS_RTRIGGER , mOldRightTrigger) != 0) {
if (Float.compare(newAXIS_RTRIGGER, 0.0f) == 0) {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, false, 0.0f, true);
}else {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, true, newAXIS_RTRIGGER, true);
}
mOldRightTrigger = newAXIS_RTRIGGER;
handled = true;
}
float newAXIS_BRAKE = event.getAxisValue(AXIS_BRAKE);
if (Float.compare(newAXIS_BRAKE , mOldBrake) != 0) {
if (Float.compare(newAXIS_BRAKE, 0.0f) == 0) {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, false, 0.0f, true);
}else {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, true, newAXIS_BRAKE, true);
}
mOldBrake = newAXIS_BRAKE;
handled = true;
}
float newAXIS_THROTTLE = event.getAxisValue(AXIS_THROTTLE);
if (Float.compare(newAXIS_THROTTLE , mOldThrottle) != 0) {
if (Float.compare(newAXIS_THROTTLE, 0.0f) == 0) {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, false, 0.0f, true);
}else {
GameControllerAdapter.onButtonEvent(StandardControllerName, devicedId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, true, newAXIS_THROTTLE, true);
}
mOldThrottle = newAXIS_THROTTLE;
handled = true;
}
}
}
return handled;
}
public boolean dispatchKeyEvent(KeyEvent event) {
boolean handled = false;
int eventSource = event.getSource();
int controllerKey = ControllerKeyMap.get(event.getKeyCode());
if (controllerKey != 0 && (((eventSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
|| ((eventSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK)
|| ((eventSource & InputDevice.SOURCE_DPAD) == InputDevice.SOURCE_DPAD)))
{
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
handled = true;
GameControllerAdapter.onButtonEvent(StandardControllerName,event.getDeviceId(), controllerKey,true, 1.0f, false);
}else if (action == KeyEvent.ACTION_UP) {
handled = true;
GameControllerAdapter.onButtonEvent(StandardControllerName,event.getDeviceId(), controllerKey,false, 0.0f, false);
}
}
return handled;
}
}

View File

@ -0,0 +1,140 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cocos2dx.lib.inputmanagercompat;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.view.InputDevice;
import android.view.MotionEvent;
public interface InputManagerCompat {
/**
* Gets information about the input device with the specified id.
*
* @param id The device id
* @return The input device or null if not found
*/
public InputDevice getInputDevice(int id);
/**
* Gets the ids of all input devices in the system.
*
* @return The input device ids.
*/
public int[] getInputDeviceIds();
/**
* Registers an input device listener to receive notifications about when
* input devices are added, removed or changed.
*
* @param listener The listener to register.
* @param handler The handler on which the listener should be invoked, or
* null if the listener should be invoked on the calling thread's
* looper.
*/
public void registerInputDeviceListener(InputManagerCompat.InputDeviceListener listener,
Handler handler);
/**
* Unregisters an input device listener.
*
* @param listener The listener to unregister.
*/
public void unregisterInputDeviceListener(InputManagerCompat.InputDeviceListener listener);
/*
* The following three calls are to simulate V16 behavior on pre-Jellybean
* devices. If you don't call them, your callback will never be called
* pre-API 16.
*/
/**
* Pass the motion events to the InputManagerCompat. This is used to
* optimize for polling for controllers. If you do not pass these events in,
* polling will cause regular object creation.
*
* @param event the motion event from the app
*/
public void onGenericMotionEvent(MotionEvent event);
/**
* Tell the V9 input manager that it should stop polling for disconnected
* devices. You can call this during onPause in your activity, although you
* might want to call it whenever your game is not active (or whenever you
* don't care about being notified of new input devices)
*/
public void onPause();
/**
* Tell the V9 input manager that it should start polling for disconnected
* devices. You can call this during onResume in your activity, although you
* might want to call it less often (only when the gameplay is actually
* active)
*/
public void onResume();
public interface InputDeviceListener {
/**
* Called whenever the input manager detects that a device has been
* added. This will only be called in the V9 version when a motion event
* is detected.
*
* @param deviceId The id of the input device that was added.
*/
void onInputDeviceAdded(int deviceId);
/**
* Called whenever the properties of an input device have changed since
* they were last queried. This will not be called for the V9 version of
* the API.
*
* @param deviceId The id of the input device that changed.
*/
void onInputDeviceChanged(int deviceId);
/**
* Called whenever the input manager detects that a device has been
* removed. For the V9 version, this can take some time depending on the
* poll rate.
*
* @param deviceId The id of the input device that was removed.
*/
void onInputDeviceRemoved(int deviceId);
}
/**
* Use this to construct a compatible InputManager.
*/
public static class Factory {
/**
* Constructs and returns a compatible InputManger
*
* @param context the Context that will be used to get the system
* service from
* @return a compatible implementation of InputManager
*/
public static InputManagerCompat getInputManager(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
return new InputManagerV16(context);
} else {
return new InputManagerV9();
}
}
}
}

View File

@ -0,0 +1,107 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cocos2dx.lib.inputmanagercompat;
import android.annotation.TargetApi;
import android.content.Context;
import android.hardware.input.InputManager;
import android.os.Build;
import android.os.Handler;
import android.view.InputDevice;
import android.view.MotionEvent;
import java.util.HashMap;
import java.util.Map;
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class InputManagerV16 implements InputManagerCompat {
private final InputManager mInputManager;
private final Map<InputManagerCompat.InputDeviceListener, V16InputDeviceListener> mListeners;
public InputManagerV16(Context context) {
mInputManager = (InputManager) context.getSystemService(Context.INPUT_SERVICE);
mListeners = new HashMap<InputManagerCompat.InputDeviceListener, V16InputDeviceListener>();
}
@Override
public InputDevice getInputDevice(int id) {
return mInputManager.getInputDevice(id);
}
@Override
public int[] getInputDeviceIds() {
return mInputManager.getInputDeviceIds();
}
static class V16InputDeviceListener implements InputManager.InputDeviceListener {
final InputManagerCompat.InputDeviceListener mIDL;
public V16InputDeviceListener(InputDeviceListener idl) {
mIDL = idl;
}
@Override
public void onInputDeviceAdded(int deviceId) {
mIDL.onInputDeviceAdded(deviceId);
}
@Override
public void onInputDeviceChanged(int deviceId) {
mIDL.onInputDeviceChanged(deviceId);
}
@Override
public void onInputDeviceRemoved(int deviceId) {
mIDL.onInputDeviceRemoved(deviceId);
}
}
@Override
public void registerInputDeviceListener(InputDeviceListener listener, Handler handler) {
V16InputDeviceListener v16Listener = new V16InputDeviceListener(listener);
mInputManager.registerInputDeviceListener(v16Listener, handler);
mListeners.put(listener, v16Listener);
}
@Override
public void unregisterInputDeviceListener(InputDeviceListener listener) {
V16InputDeviceListener curListener = mListeners.remove(listener);
if (null != curListener)
{
mInputManager.unregisterInputDeviceListener(curListener);
}
}
@Override
public void onGenericMotionEvent(MotionEvent event) {
// unused in V16
}
@Override
public void onPause() {
// unused in V16
}
@Override
public void onResume() {
// unused in V16
}
}

View File

@ -0,0 +1,211 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cocos2dx.lib.inputmanagercompat;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.util.SparseArray;
import android.view.InputDevice;
import android.view.MotionEvent;
import java.lang.ref.WeakReference;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
public class InputManagerV9 implements InputManagerCompat {
private static final String LOG_TAG = "InputManagerV9";
private static final int MESSAGE_TEST_FOR_DISCONNECT = 101;
private static final long CHECK_ELAPSED_TIME = 3000L;
private static final int ON_DEVICE_ADDED = 0;
private static final int ON_DEVICE_CHANGED = 1;
private static final int ON_DEVICE_REMOVED = 2;
private final SparseArray<long[]> mDevices;
private final Map<InputDeviceListener, Handler> mListeners;
private final Handler mDefaultHandler;
private static class PollingMessageHandler extends Handler {
private final WeakReference<InputManagerV9> mInputManager;
PollingMessageHandler(InputManagerV9 im) {
mInputManager = new WeakReference<InputManagerV9>(im);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MESSAGE_TEST_FOR_DISCONNECT:
InputManagerV9 imv = mInputManager.get();
if (null != imv) {
long time = SystemClock.elapsedRealtime();
int size = imv.mDevices.size();
for (int i = 0; i < size; i++) {
long[] lastContact = imv.mDevices.valueAt(i);
if (null != lastContact) {
if (time - lastContact[0] > CHECK_ELAPSED_TIME) {
// check to see if the device has been
// disconnected
int id = imv.mDevices.keyAt(i);
if (null == InputDevice.getDevice(id)) {
// disconnected!
imv.notifyListeners(ON_DEVICE_REMOVED, id);
imv.mDevices.remove(id);
} else {
lastContact[0] = time;
}
}
}
}
sendEmptyMessageDelayed(MESSAGE_TEST_FOR_DISCONNECT,
CHECK_ELAPSED_TIME);
}
break;
}
}
}
public InputManagerV9() {
mDevices = new SparseArray<long[]>();
mListeners = new HashMap<InputDeviceListener, Handler>();
mDefaultHandler = new PollingMessageHandler(this);
// as a side-effect, populates our collection of watched
// input devices
getInputDeviceIds();
}
@Override
public InputDevice getInputDevice(int id) {
return InputDevice.getDevice(id);
}
@Override
public int[] getInputDeviceIds() {
// add any hitherto unknown devices to our
// collection of watched input devices
int[] activeDevices = InputDevice.getDeviceIds();
long time = SystemClock.elapsedRealtime();
for ( int id : activeDevices ) {
long[] lastContact = mDevices.get(id);
if ( null == lastContact ) {
// we have a new device
mDevices.put(id, new long[] { time });
}
}
return activeDevices;
}
@Override
public void registerInputDeviceListener(InputDeviceListener listener, Handler handler) {
mListeners.remove(listener);
if (handler == null) {
handler = mDefaultHandler;
}
mListeners.put(listener, handler);
}
@Override
public void unregisterInputDeviceListener(InputDeviceListener listener) {
mListeners.remove(listener);
}
private void notifyListeners(int why, int deviceId) {
// the state of some device has changed
if (!mListeners.isEmpty()) {
// yes... this will cause an object to get created... hopefully
// it won't happen very often
for (InputDeviceListener listener : mListeners.keySet()) {
Handler handler = mListeners.get(listener);
DeviceEvent odc = DeviceEvent.getDeviceEvent(why, deviceId, listener);
handler.post(odc);
}
}
}
private static class DeviceEvent implements Runnable {
private int mMessageType;
private int mId;
private InputDeviceListener mListener;
private static Queue<DeviceEvent> sEventQueue = new ArrayDeque<DeviceEvent>();
private DeviceEvent() {
}
static DeviceEvent getDeviceEvent(int messageType, int id,
InputDeviceListener listener) {
DeviceEvent curChanged = sEventQueue.poll();
if (null == curChanged) {
curChanged = new DeviceEvent();
}
curChanged.mMessageType = messageType;
curChanged.mId = id;
curChanged.mListener = listener;
return curChanged;
}
@Override
public void run() {
switch (mMessageType) {
case ON_DEVICE_ADDED:
mListener.onInputDeviceAdded(mId);
break;
case ON_DEVICE_CHANGED:
mListener.onInputDeviceChanged(mId);
break;
case ON_DEVICE_REMOVED:
mListener.onInputDeviceRemoved(mId);
break;
default:
Log.e(LOG_TAG, "Unknown Message Type");
break;
}
// dump this runnable back in the queue
sEventQueue.offer(this);
}
}
@Override
public void onGenericMotionEvent(MotionEvent event) {
// detect new devices
int id = event.getDeviceId();
long[] timeArray = mDevices.get(id);
if (null == timeArray) {
notifyListeners(ON_DEVICE_ADDED, id);
timeArray = new long[1];
mDevices.put(id, timeArray);
}
long time = SystemClock.elapsedRealtime();
timeArray[0] = time;
}
@Override
public void onPause() {
mDefaultHandler.removeMessages(MESSAGE_TEST_FOR_DISCONNECT);
}
@Override
public void onResume() {
mDefaultHandler.sendEmptyMessage(MESSAGE_TEST_FOR_DISCONNECT);
}
}

View File

@ -1,33 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>libcontrollermoga</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>

View File

@ -1,83 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="androidcontrollermoga" default="help">
<!-- 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>

View File

@ -1,9 +0,0 @@
<?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 exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>

View File

@ -1,33 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>libcontrollernibiru</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>

View File

@ -1,4 +0,0 @@
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

View File

@ -1,9 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.cocos2dx.lib"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10"/>
</manifest>

View File

@ -1,17 +0,0 @@
# 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.

View File

@ -1,20 +0,0 @@
# 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 *;
#}

View File

@ -1,9 +0,0 @@
<?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 exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>

View File

@ -1,4 +0,0 @@
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

View File

@ -1,9 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.cocos2dx.lib"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10"/>
</manifest>

View File

@ -1,17 +0,0 @@
# 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.

View File

@ -1,83 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="androidcontrollerouya" default="help">
<!-- 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>

View File

@ -1,20 +0,0 @@
# 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 *;
#}

View File

@ -12,5 +12,4 @@
android.library=true android.library=true
# Project target. # Project target.
target=android-16 target=android-10
android.library.reference.1=../ControllerDelegate

View File

@ -24,9 +24,6 @@ THE SOFTWARE.
package org.cocos2dx.lib; package org.cocos2dx.lib;
import org.cocos2dx.lib.Cocos2dxHelper.Cocos2dxHelperListener; import org.cocos2dx.lib.Cocos2dxHelper.Cocos2dxHelperListener;
import org.cocos2dx.lib.GameControllerDelegate.ControllerEventListener;
import org.cocos2dx.lib.inputmanagercompat.InputManagerCompat;
import org.cocos2dx.lib.inputmanagercompat.InputManagerCompat.InputDeviceListener;
import android.app.Activity; import android.app.Activity;
import android.content.Context; import android.content.Context;
@ -36,15 +33,12 @@ import android.content.pm.PackageManager;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.Message; import android.os.Message;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.util.Log; import android.util.Log;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.preference.PreferenceManager.OnActivityResultListener; import android.preference.PreferenceManager.OnActivityResultListener;
public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelperListener, InputDeviceListener { public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelperListener {
// =========================================================== // ===========================================================
// Constants // Constants
// =========================================================== // ===========================================================
@ -59,10 +53,6 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
private Cocos2dxHandler mHandler; private Cocos2dxHandler mHandler;
private static Cocos2dxActivity sContext = null; private static Cocos2dxActivity sContext = null;
private Cocos2dxVideoHelper mVideoHelper = null; private Cocos2dxVideoHelper mVideoHelper = null;
private InputManagerCompat mInputManager = null;
protected GameControllerHelper mControllerHelper = null;
protected GameControllerDelegate mControllerDelegate = null;
public static Context getContext() { public static Context getContext() {
return sContext; return sContext;
@ -79,45 +69,6 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
} }
} }
public void setGameControllerInstance(GameControllerDelegate controllerDelegate) {
if (mControllerDelegate != null) {
mControllerDelegate.onDestroy();
mControllerDelegate = null;
}
mControllerDelegate = controllerDelegate;
mControllerDelegate.setControllerEventListener(mControllerEventListener);
mControllerDelegate.onCreate(this);
}
public GameControllerDelegate getGameControllerInstance(){
return mControllerDelegate;
}
ControllerEventListener mControllerEventListener = new ControllerEventListener() {
@Override
public void onButtonEvent(String vendorName, int controller, int button,
boolean isPressed, float value, boolean isAnalog) {
GameControllerAdapter.onButtonEvent(vendorName, controller, button, isPressed, value, isAnalog);
}
@Override
public void onAxisEvent(String vendorName, int controller, int axisID,
float value, boolean isAnalog) {
GameControllerAdapter.onAxisEvent(vendorName, controller, axisID, value, isAnalog);
}
@Override
public void onConnected(String vendorName, int controller) {
GameControllerAdapter.onConnected(vendorName, controller);
}
@Override
public void onDisconnected(String vendorName, int controller) {
GameControllerAdapter.onDisconnected(vendorName, controller);
}
};
// =========================================================== // ===========================================================
// Constructors // Constructors
// =========================================================== // ===========================================================
@ -137,16 +88,6 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
if (mVideoHelper == null) { if (mVideoHelper == null) {
mVideoHelper = new Cocos2dxVideoHelper(this, mFrameLayout); mVideoHelper = new Cocos2dxVideoHelper(this, mFrameLayout);
} }
mInputManager = InputManagerCompat.Factory.getInputManager(this);
mInputManager.registerInputDeviceListener(this, null);
if (mControllerDelegate != null) {
mControllerDelegate.onCreate(this);
}
if (mControllerHelper == null) {
mControllerHelper = new GameControllerHelper(this);
}
} }
// =========================================================== // ===========================================================
@ -157,96 +98,16 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
// Methods for/from SuperClass/Interfaces // Methods for/from SuperClass/Interfaces
// =========================================================== // ===========================================================
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
boolean handled = false;
if (mControllerDelegate != null) {
handled = mControllerDelegate.dispatchKeyEvent(event);
}
else {
handled = mControllerHelper.dispatchKeyEvent(event);
}
return handled || super.dispatchKeyEvent(event);
}
@Override
public boolean dispatchGenericMotionEvent(MotionEvent event) {
boolean handled = false;
if (mControllerDelegate != null) {
handled = mControllerDelegate.dispatchGenericMotionEvent(event);
}else {
handled = mControllerHelper.dispatchGenericMotionEvent(event);
}
return handled || super.dispatchGenericMotionEvent(event);
}
@Override
public void onInputDeviceAdded(int deviceId) {
Log.d(TAG,"onInputDeviceAdded:" + deviceId);
InputDevice device = InputDevice.getDevice(deviceId);
int deviceSource = device.getSources();
if ( ((deviceSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
|| ((deviceSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) )
{
GameControllerAdapter.onConnected("Standard", deviceId);
}
}
/*
* This is an unusual case. Input devices don't typically change, but they
* certainly can --- for example a device may have different modes. We use
* this to make sure that the ship has an up-to-date InputDevice.
*
* @see
* com.example.inputmanagercompat.InputManagerCompat.InputDeviceListener
* #onInputDeviceChanged(int)
*/
@Override
public void onInputDeviceChanged(int deviceId) {
Log.d(TAG,"onInputDeviceChanged:" + deviceId);
}
/*
* Remove any ship associated with the ID.
*
* @see
* com.example.inputmanagercompat.InputManagerCompat.InputDeviceListener
* #onInputDeviceRemoved(int)
*/
@Override
public void onInputDeviceRemoved(int deviceId) {
Log.d(TAG,"onInputDeviceRemoved:" + deviceId);
InputDevice device = InputDevice.getDevice(deviceId);
int deviceSource = device.getSources();
if ( ((deviceSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
|| ((deviceSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) )
{
GameControllerAdapter.onDisconnected("Standard", deviceId);
}
}
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
Cocos2dxHelper.onResume(); Cocos2dxHelper.onResume();
this.mGLSurfaceView.onResume(); this.mGLSurfaceView.onResume();
if (mControllerDelegate != null) {
mControllerDelegate.onResume();
}
} }
@Override @Override
protected void onPause() { protected void onPause() {
if (mControllerDelegate != null) {
mControllerDelegate.onPause();
}
super.onPause(); super.onPause();
Cocos2dxHelper.onPause(); Cocos2dxHelper.onPause();
@ -255,11 +116,6 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
@Override @Override
protected void onDestroy() { protected void onDestroy() {
if (mControllerDelegate != null) {
mControllerDelegate.onDestroy();
}
mControllerHelper.destrory();
super.onDestroy(); super.onDestroy();
} }

View File

@ -747,38 +747,36 @@
"cocos/platform/android/CCGLView.h", "cocos/platform/android/CCGLView.h",
"cocos/platform/android/CCPlatformDefine.h", "cocos/platform/android/CCPlatformDefine.h",
"cocos/platform/android/CCStdC.h", "cocos/platform/android/CCStdC.h",
"cocos/platform/android/ControllerDelegate/.classpath", "cocos/platform/android/ControllerAutoAdapter/.classpath",
"cocos/platform/android/ControllerDelegate/.project", "cocos/platform/android/ControllerAutoAdapter/.project",
"cocos/platform/android/ControllerDelegate/.settings/org.eclipse.jdt.core.prefs", "cocos/platform/android/ControllerAutoAdapter/.settings/org.eclipse.jdt.core.prefs",
"cocos/platform/android/ControllerDelegate/AndroidManifest.xml", "cocos/platform/android/ControllerAutoAdapter/AndroidManifest.xml",
"cocos/platform/android/ControllerDelegate/ant.properties", "cocos/platform/android/ControllerAutoAdapter/ant.properties",
"cocos/platform/android/ControllerDelegate/build.xml", "cocos/platform/android/ControllerAutoAdapter/build.xml",
"cocos/platform/android/ControllerDelegate/proguard-project.txt", "cocos/platform/android/ControllerAutoAdapter/lint.xml",
"cocos/platform/android/ControllerDelegate/src/org/cocos2dx/lib/GameControllerDelegate.java", "cocos/platform/android/ControllerAutoAdapter/proguard-project.txt",
"cocos/platform/android/ControllerMoga/.classpath", "cocos/platform/android/ControllerAutoAdapter/project.properties",
"cocos/platform/android/ControllerMoga/.project", "cocos/platform/android/ControllerAutoAdapter/src/org/cocos2dx/lib/GameControllerActivity.java",
"cocos/platform/android/ControllerMoga/.settings/org.eclipse.jdt.core.prefs", "cocos/platform/android/ControllerAutoAdapter/src/org/cocos2dx/lib/GameControllerHelper.java",
"cocos/platform/android/ControllerMoga/AndroidManifest.xml", "cocos/platform/android/ControllerAutoAdapter/src/org/cocos2dx/lib/inputmanagercompat/InputManagerCompat.java",
"cocos/platform/android/ControllerMoga/ant.properties", "cocos/platform/android/ControllerAutoAdapter/src/org/cocos2dx/lib/inputmanagercompat/InputManagerV16.java",
"cocos/platform/android/ControllerMoga/build.xml", "cocos/platform/android/ControllerAutoAdapter/src/org/cocos2dx/lib/inputmanagercompat/InputManagerV9.java",
"cocos/platform/android/ControllerMoga/proguard-project.txt", "cocos/platform/android/ControllerManualAdapter/.classpath",
"cocos/platform/android/ControllerMoga/src/org/cocos2dx/lib/GameControllerMoga.java", "cocos/platform/android/ControllerManualAdapter/.project",
"cocos/platform/android/ControllerNibiru/.classpath", "cocos/platform/android/ControllerManualAdapter/.settings/org.eclipse.jdt.core.prefs",
"cocos/platform/android/ControllerNibiru/.project", "cocos/platform/android/ControllerManualAdapter/AndroidManifest.xml",
"cocos/platform/android/ControllerNibiru/.settings/org.eclipse.jdt.core.prefs", "cocos/platform/android/ControllerManualAdapter/ant.properties",
"cocos/platform/android/ControllerNibiru/AndroidManifest.xml", "cocos/platform/android/ControllerManualAdapter/build.xml",
"cocos/platform/android/ControllerNibiru/ant.properties", "cocos/platform/android/ControllerManualAdapter/lint.xml",
"cocos/platform/android/ControllerNibiru/build.xml", "cocos/platform/android/ControllerManualAdapter/proguard-project.txt",
"cocos/platform/android/ControllerNibiru/proguard-project.txt", "cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerActivity.java",
"cocos/platform/android/ControllerNibiru/src/org/cocos2dx/lib/GameControllerNibiru.java", "cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerHelper.java",
"cocos/platform/android/ControllerOuya/.classpath", "cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerMoga.java",
"cocos/platform/android/ControllerOuya/.project", "cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerNibiru.java",
"cocos/platform/android/ControllerOuya/.settings/org.eclipse.jdt.core.prefs", "cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerOuya.java",
"cocos/platform/android/ControllerOuya/AndroidManifest.xml", "cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/inputmanagercompat/InputManagerCompat.java",
"cocos/platform/android/ControllerOuya/ant.properties", "cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/inputmanagercompat/InputManagerV16.java",
"cocos/platform/android/ControllerOuya/build.xml", "cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/inputmanagercompat/InputManagerV9.java",
"cocos/platform/android/ControllerOuya/proguard-project.txt",
"cocos/platform/android/ControllerOuya/src/org/cocos2dx/lib/GameControllerOuya.java",
"cocos/platform/android/java/.classpath", "cocos/platform/android/java/.classpath",
"cocos/platform/android/java/.project", "cocos/platform/android/java/.project",
"cocos/platform/android/java/.settings/org.eclipse.jdt.core.prefs", "cocos/platform/android/java/.settings/org.eclipse.jdt.core.prefs",
@ -807,11 +805,8 @@
"cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoHelper.java", "cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoHelper.java",
"cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java", "cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxVideoView.java",
"cocos/platform/android/java/src/org/cocos2dx/lib/GameControllerAdapter.java", "cocos/platform/android/java/src/org/cocos2dx/lib/GameControllerAdapter.java",
"cocos/platform/android/java/src/org/cocos2dx/lib/GameControllerHelper.java", "cocos/platform/android/java/src/org/cocos2dx/lib/GameControllerDelegate.java",
"cocos/platform/android/java/src/org/cocos2dx/lib/GameControllerUtils.java", "cocos/platform/android/java/src/org/cocos2dx/lib/GameControllerUtils.java",
"cocos/platform/android/java/src/org/cocos2dx/lib/inputmanagercompat/InputManagerCompat.java",
"cocos/platform/android/java/src/org/cocos2dx/lib/inputmanagercompat/InputManagerV16.java",
"cocos/platform/android/java/src/org/cocos2dx/lib/inputmanagercompat/InputManagerV9.java",
"cocos/platform/android/javaactivity.cpp", "cocos/platform/android/javaactivity.cpp",
"cocos/platform/android/jni/DPIJni.cpp", "cocos/platform/android/jni/DPIJni.cpp",
"cocos/platform/android/jni/DPIJni.h", "cocos/platform/android/jni/DPIJni.h",

View File

@ -106,7 +106,7 @@ void SceneEditorTestScene::MainMenuCallback(Ref *pSender)
removeAllChildren(); removeAllChildren();
} }
const char* SceneEditorTestLayer::_loadtypeStr[2] = {"change to load \nwith binary file","change to load \nwith json file"};
void SceneEditorTestLayer::onEnter() void SceneEditorTestLayer::onEnter()
{ {
CCLayer::onEnter(); CCLayer::onEnter();
@ -127,6 +127,13 @@ void SceneEditorTestLayer::onEnter()
addChild(l, 1, 10001); addChild(l, 1, 10001);
l->setPosition(Vec2(VisibleRect::center().x, VisibleRect::top().y - 60) ); l->setPosition(Vec2(VisibleRect::center().x, VisibleRect::top().y - 60) );
} }
_isCsbLoad = false;
_loadtypelb = cocos2d::Label::createWithSystemFont(_loadtypeStr[0], "Arial", 12);
// #endif
MenuItemLabel* itemlb = CCMenuItemLabel::create(_loadtypelb, CC_CALLBACK_1(SceneEditorTestLayer::changeLoadTypeCallback, this));
Menu* loadtypemenu = CCMenu::create(itemlb, NULL);
loadtypemenu->setPosition(Point(VisibleRect::rightTop().x -50,VisibleRect::rightTop().y -20));
addChild(loadtypemenu,100);
// add menu // add menu
backItem = MenuItemImage::create(s_pathB1, s_pathB2, CC_CALLBACK_1(SceneEditorTestLayer::backCallback, this) ); backItem = MenuItemImage::create(s_pathB1, s_pathB2, CC_CALLBACK_1(SceneEditorTestLayer::backCallback, this) );
@ -199,6 +206,36 @@ void SceneEditorTestLayer::draw(Renderer *renderer, const Mat4 &transform, uint3
Layer::draw(renderer, transform, flags); Layer::draw(renderer, transform, flags);
} }
void SceneEditorTestLayer::changeLoadTypeCallback(cocos2d::Ref *pSender)
{
_isCsbLoad = !_isCsbLoad;
_loadtypelb->setString(_loadtypeStr[(int)_isCsbLoad]);
loadFileChangeHelper(_filePath);
if(_rootNode != NULL)
{
this->removeChild(_rootNode);
_rootNode = SceneReader::getInstance()->createNodeWithSceneFile(_filePath.c_str());
if (_rootNode == NULL)
{
return ;
}
defaultPlay();
this->addChild(_rootNode);
}
}
void SceneEditorTestLayer::loadFileChangeHelper(std::string& filePathName)
{
std::string::size_type n = filePathName.find_last_of(".");
if(n == std::string::npos)
return;
filePathName = filePathName.substr(0,n);
if(_isCsbLoad)
filePathName.append(".csb");
else
filePathName.append(".json");
}
LoadSceneEdtiorFileTest::LoadSceneEdtiorFileTest() LoadSceneEdtiorFileTest::LoadSceneEdtiorFileTest()
{ {
@ -238,12 +275,19 @@ void LoadSceneEdtiorFileTest::onExit()
cocos2d::Node* LoadSceneEdtiorFileTest::createGameScene() cocos2d::Node* LoadSceneEdtiorFileTest::createGameScene()
{ {
Node *node = SceneReader::getInstance()->createNodeWithSceneFile("scenetest/LoadSceneEdtiorFileTest/FishJoy2.json"); _filePath = "scenetest/LoadSceneEdtiorFileTest/FishJoy2.json"; //default is json
if (node == nullptr) _rootNode = SceneReader::getInstance()->createNodeWithSceneFile(_filePath.c_str());
if (_rootNode == NULL)
{ {
return nullptr; return NULL;
} }
return node; defaultPlay();
return _rootNode;
}
void LoadSceneEdtiorFileTest::defaultPlay()
{
} }
SpriteComponentTest::SpriteComponentTest() SpriteComponentTest::SpriteComponentTest()
@ -283,22 +327,29 @@ void SpriteComponentTest::onExit()
cocos2d::Node* SpriteComponentTest::createGameScene() cocos2d::Node* SpriteComponentTest::createGameScene()
{ {
Node *node = SceneReader::getInstance()->createNodeWithSceneFile("scenetest/SpriteComponentTest/SpriteComponentTest.json"); _filePath = "scenetest/SpriteComponentTest/SpriteComponentTest.json";
if (node == nullptr) _rootNode = SceneReader::getInstance()->createNodeWithSceneFile(_filePath.c_str());
if (_rootNode == NULL)
{ {
return nullptr; return NULL;
} }
defaultPlay();
return _rootNode;
}
void SpriteComponentTest::defaultPlay()
{
ActionInterval* action1 = CCBlink::create(2, 10); ActionInterval* action1 = CCBlink::create(2, 10);
ActionInterval* action2 = CCBlink::create(2, 5); ActionInterval* action2 = CCBlink::create(2, 5);
ComRender *pSister1 = static_cast<ComRender*>(node->getChildByTag(10003)->getComponent("CCSprite")); ComRender *pSister1 = static_cast<ComRender*>(_rootNode->getChildByTag(10003)->getComponent("CCSprite"));
pSister1->getNode()->runAction(action1); pSister1->getNode()->runAction(action1);
ComRender *pSister2 = static_cast<ComRender*>(node->getChildByTag(10004)->getComponent("CCSprite")); ComRender *pSister2 = static_cast<ComRender*>(_rootNode->getChildByTag(10004)->getComponent("CCSprite"));
pSister2->getNode()->runAction(action2); pSister2->getNode()->runAction(action2);
return node;
} }
ArmatureComponentTest::ArmatureComponentTest() ArmatureComponentTest::ArmatureComponentTest()
@ -338,22 +389,27 @@ void ArmatureComponentTest::onExit()
cocos2d::Node* ArmatureComponentTest::createGameScene() cocos2d::Node* ArmatureComponentTest::createGameScene()
{ {
Node *node = SceneReader::getInstance()->createNodeWithSceneFile("scenetest/ArmatureComponentTest/ArmatureComponentTest.json"); _filePath = "scenetest/ArmatureComponentTest/ArmatureComponentTest.json";
if (node == nullptr) _rootNode = SceneReader::getInstance()->createNodeWithSceneFile(_filePath.c_str());
if (_rootNode == NULL)
{ {
return nullptr; return NULL;
}
defaultPlay();
return _rootNode;
} }
ComRender *pBlowFish = static_cast<ComRender*>(node->getChildByTag(10007)->getComponent("CCArmature"));
pBlowFish->getNode()->runAction(CCMoveBy::create(10.0f, Vec2(-1000.0f, 0)));
ComRender *pButterflyfish = static_cast<ComRender*>(node->getChildByTag(10008)->getComponent("CCArmature")); void ArmatureComponentTest::defaultPlay()
pButterflyfish->getNode()->runAction(CCMoveBy::create(10.0f, Vec2(-1000.0f, 0))); {
ComRender *pBlowFish = static_cast<ComRender*>(_rootNode->getChildByTag(10007)->getComponent("CCArmature"));
pBlowFish->getNode()->runAction(MoveBy::create(10.0f, Point(-1000.0f, 0)));
ComRender *pButterflyfish = static_cast<ComRender*>(_rootNode->getChildByTag(10008)->getComponent("CCArmature"));
pButterflyfish->getNode()->runAction(MoveBy::create(10.0f, Point(-1000.0f, 0)));
return node;
} }
UIComponentTest::UIComponentTest() UIComponentTest::UIComponentTest()
: _node(nullptr)
{ {
} }
@ -389,20 +445,15 @@ void UIComponentTest::onExit()
cocos2d::Node* UIComponentTest::createGameScene() cocos2d::Node* UIComponentTest::createGameScene()
{ {
Node *node = SceneReader::getInstance()->createNodeWithSceneFile("scenetest/UIComponentTest/UIComponentTest.json"); _filePath = "scenetest/UIComponentTest/UIComponentTest.json";
if (node == nullptr) _rootNode = SceneReader::getInstance()->createNodeWithSceneFile(_filePath.c_str());
if (_rootNode == NULL)
{ {
return nullptr; return NULL;
} }
_node = node; defaultPlay();
ComRender *render = static_cast<ComRender*>(_node->getChildByTag(10025)->getComponent("GUIComponent")); return _rootNode;
Widget* widget = static_cast<cocos2d::ui::Widget*>(render->getNode());
Button* button = static_cast<Button*>(widget->getChildByName("Button_156"));
// button->addTouchEventListener(this, toucheventselector(UIComponentTest::touchEvent));
button->addTouchEventListener(CC_CALLBACK_2(UIComponentTest::touchEvent, this));
return node;
} }
void UIComponentTest::touchEvent(Ref *pSender, ui::Widget::TouchEventType type) void UIComponentTest::touchEvent(Ref *pSender, ui::Widget::TouchEventType type)
@ -411,10 +462,10 @@ void UIComponentTest::touchEvent(Ref *pSender, ui::Widget::TouchEventType type)
{ {
case ui::Widget::TouchEventType::BEGAN: case ui::Widget::TouchEventType::BEGAN:
{ {
ComRender *pBlowFish = static_cast<ComRender*>(_node->getChildByTag(10010)->getComponent("CCArmature")); ComRender *pBlowFish = static_cast<ComRender*>(_rootNode->getChildByTag(10010)->getComponent("CCArmature"));
pBlowFish->getNode()->runAction(CCMoveBy::create(10.0f, Vec2(-1000.0f, 0))); pBlowFish->getNode()->runAction(CCMoveBy::create(10.0f, Vec2(-1000.0f, 0)));
ComRender *pButterflyfish = static_cast<ComRender*>(_node->getChildByTag(10011)->getComponent("CCArmature")); ComRender *pButterflyfish = static_cast<ComRender*>(_rootNode->getChildByTag(10011)->getComponent("CCArmature"));
pButterflyfish->getNode()->runAction(CCMoveBy::create(10.0f, Vec2(-1000.0f, 0))); pButterflyfish->getNode()->runAction(CCMoveBy::create(10.0f, Vec2(-1000.0f, 0)));
} }
break; break;
@ -423,6 +474,15 @@ void UIComponentTest::touchEvent(Ref *pSender, ui::Widget::TouchEventType type)
} }
} }
void UIComponentTest::defaultPlay()
{
ComRender *render = static_cast<ComRender*>(_rootNode->getChildByTag(10025)->getComponent("GUIComponent"));
Widget* widget = static_cast<cocos2d::ui::Widget*>(render->getNode());
Button* button = static_cast<Button*>(widget->getChildByName("Button_156"));
button->addTouchEventListener(CC_CALLBACK_2(UIComponentTest::touchEvent, this));
}
TmxMapComponentTest::TmxMapComponentTest() TmxMapComponentTest::TmxMapComponentTest()
{ {
@ -460,24 +520,30 @@ void TmxMapComponentTest::onExit()
cocos2d::Node* TmxMapComponentTest::createGameScene() cocos2d::Node* TmxMapComponentTest::createGameScene()
{ {
Node *node = SceneReader::getInstance()->createNodeWithSceneFile("scenetest/TmxMapComponentTest/TmxMapComponentTest.json"); _filePath = "scenetest/TmxMapComponentTest/TmxMapComponentTest.json";
if (node == nullptr) _rootNode = SceneReader::getInstance()->createNodeWithSceneFile(_filePath.c_str());
if (_rootNode == NULL)
{ {
return nullptr; return NULL;
}
defaultPlay();
return _rootNode;
} }
ComRender *tmxMap = static_cast<ComRender*>(node->getChildByTag(10015)->getComponent("CCTMXTiledMap"));
ActionInterval *actionTo = SkewTo::create(2, 0.f, 2.f);
ActionInterval *rotateTo = RotateTo::create(2, 61.0f);
ActionInterval *actionScaleTo = ScaleTo::create(2, -0.44f, 0.47f);
ActionInterval *actionScaleToBack = ScaleTo::create(2, 1.0f, 1.0f); void TmxMapComponentTest::defaultPlay()
ActionInterval *rotateToBack = RotateTo::create(2, 0); {
ActionInterval *actionToBack = SkewTo::create(2, 0, 0); ComRender *tmxMap = static_cast<ComRender*>(_rootNode->getChildByTag(10015)->getComponent("CCTMXTiledMap"));
ActionInterval *actionTo = CCSkewTo::create(2, 0.f, 2.f);
ActionInterval *rotateTo = CCRotateTo::create(2, 61.0f);
ActionInterval *actionScaleTo = CCScaleTo::create(2, -0.44f, 0.47f);
tmxMap->getNode()->runAction(Sequence::create(actionTo, actionToBack, nullptr)); ActionInterval *actionScaleToBack = CCScaleTo::create(2, 1.0f, 1.0f);
tmxMap->getNode()->runAction(Sequence::create(rotateTo, rotateToBack, nullptr)); ActionInterval *rotateToBack = CCRotateTo::create(2, 0);
tmxMap->getNode()->runAction(Sequence::create(actionScaleTo, actionScaleToBack, nullptr)); ActionInterval *actionToBack = CCSkewTo::create(2, 0, 0);
return node;
tmxMap->getNode()->runAction(CCSequence::create(actionTo, actionToBack, NULL));
tmxMap->getNode()->runAction(CCSequence::create(rotateTo, rotateToBack, NULL));
tmxMap->getNode()->runAction(CCSequence::create(actionScaleTo, actionScaleToBack, NULL));
} }
ParticleComponentTest::ParticleComponentTest() ParticleComponentTest::ParticleComponentTest()
@ -516,22 +582,26 @@ void ParticleComponentTest::onExit()
cocos2d::Node* ParticleComponentTest::createGameScene() cocos2d::Node* ParticleComponentTest::createGameScene()
{ {
Node *node = SceneReader::getInstance()->createNodeWithSceneFile("scenetest/ParticleComponentTest/ParticleComponentTest.json"); _filePath = "scenetest/ParticleComponentTest/ParticleComponentTest.json";
if (node == nullptr) _rootNode = SceneReader::getInstance()->createNodeWithSceneFile(_filePath.c_str());
if (_rootNode == NULL)
{ {
return nullptr; return NULL;
}
defaultPlay();
return _rootNode;
} }
ComRender* Particle = static_cast<ComRender*>(node->getChildByTag(10020)->getComponent("CCParticleSystemQuad")); void ParticleComponentTest::defaultPlay()
ActionInterval* jump = JumpBy::create(5, Vec2(-500,0), 50, 4); {
FiniteTimeAction* action = Sequence::create( jump, jump->reverse(), nullptr); ComRender* Particle = static_cast<ComRender*>(_rootNode->getChildByTag(10020)->getComponent("CCParticleSystemQuad"));
ActionInterval* jump = CCJumpBy::create(5, Point(-500,0), 50, 4);
FiniteTimeAction* action = CCSequence::create( jump, jump->reverse(), NULL);
Particle->getNode()->runAction(action); Particle->getNode()->runAction(action);
return node;
} }
EffectComponentTest::EffectComponentTest() EffectComponentTest::EffectComponentTest()
: _node(nullptr)
{ {
} }
@ -567,16 +637,14 @@ void EffectComponentTest::onExit()
cocos2d::Node* EffectComponentTest::createGameScene() cocos2d::Node* EffectComponentTest::createGameScene()
{ {
Node *node = SceneReader::getInstance()->createNodeWithSceneFile("scenetest/EffectComponentTest/EffectComponentTest.json"); _filePath = "scenetest/EffectComponentTest/EffectComponentTest.json";
if (node == nullptr) _rootNode = SceneReader::getInstance()->createNodeWithSceneFile(_filePath.c_str());
if (_rootNode == NULL)
{ {
return nullptr; return NULL;
} }
_node = node; defaultPlay();
ComRender *render = static_cast<ComRender*>(_node->getChildByTag(10015)->getComponent("CCArmature")); return _rootNode;
Armature *pAr = static_cast<Armature*>(render->getNode());
pAr->getAnimation()->setMovementEventCallFunc(CC_CALLBACK_0(EffectComponentTest::animationEvent, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
return node;
} }
void EffectComponentTest::animationEvent(Armature *armature, MovementEventType movementType, const std::string& movementID) void EffectComponentTest::animationEvent(Armature *armature, MovementEventType movementType, const std::string& movementID)
@ -587,12 +655,19 @@ void EffectComponentTest::animationEvent(Armature *armature, MovementEventType m
{ {
if (id.compare("Fire") == 0) if (id.compare("Fire") == 0)
{ {
ComAudio *pAudio = static_cast<ComAudio*>(_node->getChildByTag(10015)->getComponent("CCComAudio")); ComAudio *pAudio = static_cast<ComAudio*>(_rootNode->getChildByTag(10015)->getComponent("CCComAudio"));
pAudio->playEffect(); pAudio->playEffect();
} }
} }
} }
void EffectComponentTest::defaultPlay()
{
ComRender *render = static_cast<ComRender*>(_rootNode->getChildByTag(10015)->getComponent("CCArmature"));
Armature *pAr = static_cast<Armature*>(render->getNode());
pAr->getAnimation()->setMovementEventCallFunc(CC_CALLBACK_0(EffectComponentTest::animationEvent, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
}
BackgroundComponentTest::BackgroundComponentTest() BackgroundComponentTest::BackgroundComponentTest()
{ {
@ -629,20 +704,24 @@ void BackgroundComponentTest::onExit()
cocos2d::Node* BackgroundComponentTest::createGameScene() cocos2d::Node* BackgroundComponentTest::createGameScene()
{ {
Node *node = SceneReader::getInstance()->createNodeWithSceneFile("scenetest/BackgroundComponentTest/BackgroundComponentTest.json"); _filePath = "scenetest/BackgroundComponentTest/BackgroundComponentTest.json";
if (node == nullptr) _rootNode = SceneReader::getInstance()->createNodeWithSceneFile(_filePath.c_str());
if (_rootNode == NULL)
{ {
return nullptr; return NULL;
}
defaultPlay();
return _rootNode;
} }
ComAudio *Audio = static_cast<ComAudio*>(node->getComponent("CCBackgroundAudio")); void BackgroundComponentTest::defaultPlay()
{
ComAudio *Audio = static_cast<ComAudio*>(_rootNode->getComponent("CCBackgroundAudio"));
Audio->playBackgroundMusic(); Audio->playBackgroundMusic();
return node;
} }
AttributeComponentTest::AttributeComponentTest() AttributeComponentTest::AttributeComponentTest()
: _node(nullptr)
{ {
} }
@ -663,7 +742,7 @@ void AttributeComponentTest::onEnter()
{ {
Node *root = createGameScene(); Node *root = createGameScene();
CC_BREAK_IF(!root); CC_BREAK_IF(!root);
initData(); defaultPlay();
this->addChild(root, 0, 1); this->addChild(root, 0, 1);
} while (0); } while (0);
} }
@ -682,8 +761,8 @@ bool AttributeComponentTest::initData()
bool bRet = false; bool bRet = false;
rapidjson::Document doc; rapidjson::Document doc;
do { do {
CC_BREAK_IF(_node == nullptr); CC_BREAK_IF(_rootNode == nullptr);
ComAttribute *attribute = static_cast<ComAttribute*>(_node->getChildByTag(10015)->getComponent("CCComAttribute")); ComAttribute *attribute = static_cast<ComAttribute*>(_rootNode->getChildByTag(10015)->getComponent("CCComAttribute"));
CC_BREAK_IF(attribute == nullptr); CC_BREAK_IF(attribute == nullptr);
log("Name: %s, HP: %f, MP: %f", attribute->getString("name").c_str(), attribute->getFloat("maxHP"), attribute->getFloat("maxMP")); log("Name: %s, HP: %f, MP: %f", attribute->getString("name").c_str(), attribute->getFloat("maxHP"), attribute->getFloat("maxMP"));
@ -694,13 +773,18 @@ bool AttributeComponentTest::initData()
cocos2d::Node* AttributeComponentTest::createGameScene() cocos2d::Node* AttributeComponentTest::createGameScene()
{ {
Node *node = SceneReader::getInstance()->createNodeWithSceneFile("scenetest/AttributeComponentTest/AttributeComponentTest.json"); _filePath = "scenetest/AttributeComponentTest/AttributeComponentTest.json";
if (node == nullptr) _rootNode = SceneReader::getInstance()->createNodeWithSceneFile(_filePath.c_str());
if (_rootNode == NULL)
{ {
return nullptr; return NULL;
} }
_node = node; return _rootNode;
return node; }
void AttributeComponentTest::defaultPlay()
{
initData();
} }
TriggerTest::TriggerTest() TriggerTest::TriggerTest()
@ -783,12 +867,16 @@ void TriggerTest::gameLogic(float dt)
cocos2d::Node* TriggerTest::createGameScene() cocos2d::Node* TriggerTest::createGameScene()
{ {
Node *node = SceneReader::getInstance()->createNodeWithSceneFile("scenetest/TriggerTest/TriggerTest.json"); _filePath = "scenetest/TriggerTest/TriggerTest.json";
if (node == nullptr) _rootNode = SceneReader::getInstance()->createNodeWithSceneFile(_filePath.c_str());
if (_rootNode == NULL)
{ {
return nullptr; return NULL;
} }
_node = node;
return node; defaultPlay();
return _rootNode;
}
void TriggerTest::defaultPlay()
{
} }

View File

@ -49,6 +49,20 @@ protected:
MenuItemImage *restartItem; MenuItemImage *restartItem;
MenuItemImage *nextItem; MenuItemImage *nextItem;
MenuItemImage *backItem; MenuItemImage *backItem;
protected:
virtual void changeLoadTypeCallback(cocos2d::Ref *pSender);
virtual void defaultPlay() = 0; // must to be overrided
void loadFileChangeHelper(std::string& filePathName ); // switch json& csb
private:
bool _isCsbLoad; // default is false
cocos2d::Label* _loadtypelb;
static const char* _loadtypeStr[2];
protected:
cocos2d::Node* _rootNode;
std::string _filePath;
}; };
class LoadSceneEdtiorFileTest : public SceneEditorTestLayer class LoadSceneEdtiorFileTest : public SceneEditorTestLayer
@ -61,6 +75,8 @@ public:
virtual void onEnter() override; virtual void onEnter() override;
virtual void onExit() override; virtual void onExit() override;
cocos2d::Node* createGameScene(); cocos2d::Node* createGameScene();
private:
void defaultPlay();
}; };
@ -75,6 +91,8 @@ public:
virtual void onExit() override; virtual void onExit() override;
cocos2d::Node* createGameScene(); cocos2d::Node* createGameScene();
private:
void defaultPlay();
}; };
class ArmatureComponentTest : public SceneEditorTestLayer class ArmatureComponentTest : public SceneEditorTestLayer
@ -88,6 +106,8 @@ public:
virtual void onExit() override; virtual void onExit() override;
cocos2d::Node* createGameScene(); cocos2d::Node* createGameScene();
private:
void defaultPlay();
}; };
class UIComponentTest : public SceneEditorTestLayer class UIComponentTest : public SceneEditorTestLayer
@ -102,7 +122,7 @@ public:
cocos2d::Node* createGameScene(); cocos2d::Node* createGameScene();
void touchEvent(cocos2d::Ref *pSender, ui::Widget::TouchEventType type); void touchEvent(cocos2d::Ref *pSender, ui::Widget::TouchEventType type);
private: private:
cocos2d::Node* _node; void defaultPlay();
}; };
class TmxMapComponentTest : public SceneEditorTestLayer class TmxMapComponentTest : public SceneEditorTestLayer
@ -115,6 +135,8 @@ public:
virtual void onEnter() override; virtual void onEnter() override;
virtual void onExit() override; virtual void onExit() override;
cocos2d::Node* createGameScene(); cocos2d::Node* createGameScene();
private:
void defaultPlay();
}; };
@ -128,6 +150,8 @@ public:
virtual void onEnter() override; virtual void onEnter() override;
virtual void onExit() override; virtual void onExit() override;
cocos2d::Node* createGameScene(); cocos2d::Node* createGameScene();
protected:
void defaultPlay();
}; };
class EffectComponentTest : public SceneEditorTestLayer class EffectComponentTest : public SceneEditorTestLayer
@ -142,7 +166,8 @@ public:
cocos2d::Node* createGameScene(); cocos2d::Node* createGameScene();
void animationEvent(cocostudio::Armature *armature, cocostudio::MovementEventType movementType, const std::string& movementID); void animationEvent(cocostudio::Armature *armature, cocostudio::MovementEventType movementType, const std::string& movementID);
private: private:
cocos2d::Node* _node; void defaultPlay();
}; };
class BackgroundComponentTest : public SceneEditorTestLayer class BackgroundComponentTest : public SceneEditorTestLayer
@ -155,6 +180,8 @@ public:
virtual void onEnter() override; virtual void onEnter() override;
virtual void onExit() override; virtual void onExit() override;
cocos2d::Node* createGameScene(); cocos2d::Node* createGameScene();
private:
void defaultPlay();
}; };
class AttributeComponentTest : public SceneEditorTestLayer class AttributeComponentTest : public SceneEditorTestLayer
@ -168,8 +195,9 @@ public:
virtual void onExit() override; virtual void onExit() override;
bool initData(); bool initData();
cocos2d::Node* createGameScene(); cocos2d::Node* createGameScene();
private: private:
cocos2d::Node* _node; void defaultPlay();
}; };
class TriggerTest : public SceneEditorTestLayer class TriggerTest : public SceneEditorTestLayer
@ -197,6 +225,8 @@ public:
private: private:
cocos2d::Node *_node; cocos2d::Node *_node;
cocos2d::EventListener* _touchListener; cocos2d::EventListener* _touchListener;
private:
void defaultPlay();
}; };
#endif // __HELLOWORLD_SCENE_H__ #endif // __HELLOWORLD_SCENE_H__

View File

@ -65,6 +65,44 @@ void PlayMusic::serialize(const rapidjson::Value &val)
} }
} }
void PlayMusic::serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)
{
int length = pCocoNode->GetChildNum();
int count = 0;
stExpCocoNode *pDataItemsArray = pCocoNode->GetChildArray();
std::string key;
const char *str = NULL;
for (int i = 0; i < length; ++i)
{
count = pDataItemsArray[i].GetChildNum();
stExpCocoNode *pDataItemArray = pDataItemsArray[i].GetChildArray();
key = pDataItemArray[0].GetValue();
str = pDataItemArray[1].GetValue();
if (key == "Tag")
{
if (str != NULL)
{
_tag = atoi(str);//DICTOOL->getIntValue_json(subDict, "value");
}
}
else if (key == "componentName")
{
if (str != NULL)
{
_comName = str; //DICTOOL->getStringValue_json(subDict, "value");
}
}
else if (key == "type")
{
if (str != NULL)
{
_type = atoi(str); //DICTOOL->getIntValue_json(subDict, "value");
}
}
}
}
void PlayMusic::removeAll() void PlayMusic::removeAll()
{ {
} }
@ -127,6 +165,50 @@ void TMoveTo::serialize(const rapidjson::Value &val)
} }
} }
void TMoveTo::serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)
{
int length = pCocoNode->GetChildNum();
int count = 0;
stExpCocoNode *pDataItemsArray = pCocoNode->GetChildArray();
std::string key;
const char *str = NULL;
for (int i = 0; i < length; ++i)
{
count = pDataItemsArray[i].GetChildNum();
stExpCocoNode *pDataItemArray = pDataItemsArray[i].GetChildArray();
key = pDataItemArray[0].GetValue();
str = pDataItemArray[1].GetValue();
if (key == "Tag")
{
if (str != NULL)
{
_tag = atoi(str);
}
}
else if (key == "Duration")
{
if (str != NULL)
{
_duration = atof(str);
}
}
else if (key == "x")
{
if (str != NULL)
{
_pos.x = atof(str);
}
}
else if (key == "y")
{
if (str != NULL)
{
_pos.y = atoi(str);
}
}
}
}
void TMoveTo::removeAll() void TMoveTo::removeAll()
{ {
Node *node = SceneReader::getInstance()->getNodeByTag(_tag); Node *node = SceneReader::getInstance()->getNodeByTag(_tag);
@ -205,6 +287,57 @@ void TMoveBy::serialize(const rapidjson::Value &val)
} }
} }
void TMoveBy::serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)
{
int length = pCocoNode->GetChildNum();
int count = 0;
stExpCocoNode *pDataItemsArray = pCocoNode->GetChildArray();
std::string key;
const char *str = NULL;
for (int i = 0; i < length; ++i)
{
count = pDataItemsArray[i].GetChildNum();
stExpCocoNode *pDataItemArray = pDataItemsArray[i].GetChildArray();
key = pDataItemArray[0].GetValue();
str = pDataItemArray[1].GetValue();
if (key == "Tag")
{
if (str != NULL)
{
_tag = atoi(str);
}
}
else if (key == "Duration")
{
if (str != NULL)
{
_duration = atof(str);
}
}
else if (key == "x")
{
if (str != NULL)
{
_pos.x = atof(str);
}
}
else if (key == "y")
{
if (str != NULL)
{
_pos.y = atof(str);
}
}
else if (key == "IsReverse")
{
if (str != NULL)
{
_reverse = atoi(str)!=0?true:false; //DICTOOL->getIntValue_json(subDict, "value") != 0? true: false;
}
}
}
}
void TMoveBy::removeAll() void TMoveBy::removeAll()
{ {
Node *node = SceneReader::getInstance()->getNodeByTag(_tag); Node *node = SceneReader::getInstance()->getNodeByTag(_tag);
@ -267,6 +400,43 @@ void TRotateTo::serialize(const rapidjson::Value &val)
} }
} }
void TRotateTo::serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)
{
int length = pCocoNode->GetChildNum();
int count = 0;
stExpCocoNode *pDataItemsArray = pCocoNode->GetChildArray();
std::string key;
const char *str = NULL;
for (int i = 0; i < length; ++i)
{
count = pDataItemsArray[i].GetChildNum();
stExpCocoNode *pDataItemArray = pDataItemsArray[i].GetChildArray();
key = pDataItemArray[0].GetValue();
str = pDataItemArray[1].GetValue();
if (key == "Tag")
{
if (str != NULL)
{
_tag = atoi(str);
}
}
else if (key == "Duration")
{
if (str != NULL)
{
_duration = atof(str);
}
}
else if (key == "DeltaAngle")
{
if (str != NULL)
{
_deltaAngle = atof(str);
}
}
}
}
void TRotateTo::removeAll() void TRotateTo::removeAll()
{ {
Node *node = SceneReader::getInstance()->getNodeByTag(_tag); Node *node = SceneReader::getInstance()->getNodeByTag(_tag);
@ -343,6 +513,50 @@ void TRotateBy::serialize(const rapidjson::Value &val)
} }
} }
void TRotateBy::serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)
{
int length = pCocoNode->GetChildNum();
int count = 0;
stExpCocoNode *pDataItemsArray = pCocoNode->GetChildArray();
std::string key;
const char *str = NULL;
for (int i = 0; i < length; ++i)
{
count = pDataItemsArray[i].GetChildNum();
stExpCocoNode *pDataItemArray = pDataItemsArray[i].GetChildArray();
key = pDataItemArray[0].GetValue();
str = pDataItemArray[1].GetValue();
if (key == "Tag")
{
if (str != NULL)
{
_tag = atoi(str);
}
}
else if (key == "Duration")
{
if (str != NULL)
{
_duration = atof(str);
}
}
else if (key == "DeltaAngle")
{
if (str != NULL)
{
_deltaAngle = atof(str);
}
}
else if (key == "IsReverse")
{
if (str != NULL)
{
_reverse = atoi(str)!=0?true:false;
}
}
}
}
void TRotateBy::removeAll() void TRotateBy::removeAll()
{ {
Node *node = SceneReader::getInstance()->getNodeByTag(_tag); Node *node = SceneReader::getInstance()->getNodeByTag(_tag);
@ -409,6 +623,50 @@ void TScaleTo::serialize(const rapidjson::Value &val)
} }
} }
void TScaleTo::serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)
{
int length = pCocoNode->GetChildNum();
int count = 0;
stExpCocoNode *pDataItemsArray = pCocoNode->GetChildArray();
std::string key;
const char *str = NULL;
for (int i = 0; i < length; ++i)
{
count = pDataItemsArray[i].GetChildNum();
stExpCocoNode *pDataItemArray = pDataItemsArray[i].GetChildArray();
key = pDataItemArray[0].GetValue();
str = pDataItemArray[1].GetValue();
if (key == "Tag")
{
if (str != NULL)
{
_tag = atoi(str);
}
}
else if (key == "Duration")
{
if (str != NULL)
{
_duration = atof(str);
}
}
else if (key == "ScaleX")
{
if (str != NULL)
{
_scale.x = atof(str);
}
}
else if (key == "ScaleY")
{
if (str != NULL)
{
_scale.y = atof(str);
}
}
}
}
void TScaleTo::removeAll() void TScaleTo::removeAll()
{ {
Node *node = SceneReader::getInstance()->getNodeByTag(_tag); Node *node = SceneReader::getInstance()->getNodeByTag(_tag);
@ -489,6 +747,58 @@ void TScaleBy::serialize(const rapidjson::Value &val)
} }
} }
void TScaleBy::serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)
{
int length = pCocoNode->GetChildNum();
int count = 0;
stExpCocoNode *pDataItemsArray = pCocoNode->GetChildArray();
std::string key;
const char *str = NULL;
for (int i = 0; i < length; ++i)
{
count = pDataItemsArray[i].GetChildNum();
stExpCocoNode *pDataItemArray = pDataItemsArray[i].GetChildArray();
key = pDataItemArray[0].GetValue();
str = pDataItemArray[1].GetValue();
if (key == "Tag")
{
if (str != NULL)
{
_tag = atoi(str);
}
}
else if (key == "Duration")
{
if (str != NULL)
{
_duration = atof(str);
}
}
else if (key == "ScaleX")
{
if (str != NULL)
{
_scale.x = atof(str);
}
}
else if (key == "ScaleY")
{
if (str != NULL)
{
_scale.y = atof(str);
}
}
else if (key == "IsReverse")
{
if (str != NULL)
{
_reverse = atoi(str)!=0?true:false; //DICTOOL->getIntValue_json(subDict, "value")!= 0? true:false;
}
continue;
}
}
}
void TScaleBy::removeAll() void TScaleBy::removeAll()
{ {
Node *node = SceneReader::getInstance()->getNodeByTag(_tag); Node *node = SceneReader::getInstance()->getNodeByTag(_tag);
@ -555,6 +865,50 @@ void TSkewTo::serialize(const rapidjson::Value &val)
} }
} }
void TSkewTo::serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)
{
int length = pCocoNode->GetChildNum();
int count = 0;
stExpCocoNode *pDataItemsArray = pCocoNode->GetChildArray();
std::string key;
const char *str = NULL;
for (int i = 0; i < length; ++i)
{
count = pDataItemsArray[i].GetChildNum();
stExpCocoNode *pDataItemArray = pDataItemsArray[i].GetChildArray();
key = pDataItemArray[0].GetValue();
str = pDataItemArray[1].GetValue();
if (key == "Tag")
{
if (str != NULL)
{
_tag = atoi(str);
}
}
else if (key == "Duration")
{
if (str != NULL)
{
_duration = atof(str);
}
}
else if (key == "SkewX")
{
if (str != NULL)
{
_skew.x = atof(str);
}
}
else if (key == "SkewY")
{
if (str != NULL)
{
_skew.y = atof(str);
}
}
}
}
void TSkewTo::removeAll() void TSkewTo::removeAll()
{ {
Node *node = SceneReader::getInstance()->getNodeByTag(_tag); Node *node = SceneReader::getInstance()->getNodeByTag(_tag);
@ -634,6 +988,54 @@ void TSkewBy::serialize(const rapidjson::Value &val)
} }
} }
void TSkewBy::serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)
{
int length = pCocoNode->GetChildNum();
int count = 0;
stExpCocoNode *pDataItemsArray = pCocoNode->GetChildArray();
std::string key;
const char *str = NULL;
for (int i = 0; i < length; ++i)
{
count = pDataItemsArray[i].GetChildNum();
stExpCocoNode *pDataItemArray = pDataItemsArray[i].GetChildArray();
key = pDataItemArray[0].GetValue();
str = pDataItemArray[1].GetValue();
if (key == "Tag")
{
if (str != NULL)
{
_tag = atoi(str);
}
}
else if (key == "Duration")
{
if (str != NULL)
{
_duration = atof(str);
}
}
else if (key == "SkewX")
{
if (str != NULL)
{
_skew.x = atof(str);
}
}
else if (key == "SkewY")
{
if (str != NULL)
{
_skew.y = atof(str);
}
}
else if (key == "IsReverse")
{
_reverse = atoi(str)!=0?true:false; //DICTOOL->getIntValue_json(subDict, "value")!= 0? true:false;
}
}
}
void TSkewBy::removeAll() void TSkewBy::removeAll()
{ {
Node *node = SceneReader::getInstance()->getNodeByTag(_tag); Node *node = SceneReader::getInstance()->getNodeByTag(_tag);
@ -700,6 +1102,36 @@ void TriggerState::serialize(const rapidjson::Value &val)
} }
} }
void TriggerState::serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)
{
int length = pCocoNode->GetChildNum();
int count = 0;
stExpCocoNode *pDataItemsArray = pCocoNode->GetChildArray();
std::string key;
const char *str = NULL;
for (int i = 0; i < length; ++i)
{
count = pDataItemsArray[i].GetChildNum();
stExpCocoNode *pDataItemArray = pDataItemsArray[i].GetChildArray();
key = pDataItemArray[0].GetValue();
str = pDataItemArray[1].GetValue();
if (key == "ID")
{
if (str != NULL)
{
_id = atoi(str);
}
}
else if (key == "State")
{
if (str != NULL)
{
_state = atoi(str);
}
}
}
}
void TriggerState::removeAll() void TriggerState::removeAll()
{ {
CCLOG("TriggerState::removeAll"); CCLOG("TriggerState::removeAll");
@ -726,7 +1158,7 @@ void ArmaturePlayAction::done()
{ {
Node *node = SceneReader::getInstance()->getNodeByTag(_tag); Node *node = SceneReader::getInstance()->getNodeByTag(_tag);
CC_BREAK_IF(node == nullptr); CC_BREAK_IF(node == nullptr);
ComRender *pRender = (ComRender*)(node->getComponent(_ComName.c_str())); ComRender *pRender = (ComRender*)(node->getComponent(_comName.c_str()));
CC_BREAK_IF(pRender == nullptr); CC_BREAK_IF(pRender == nullptr);
Armature *pAr = (Armature *)(pRender->getNode()); Armature *pAr = (Armature *)(pRender->getNode());
CC_BREAK_IF(pAr == nullptr); CC_BREAK_IF(pAr == nullptr);
@ -748,7 +1180,7 @@ void ArmaturePlayAction::serialize(const rapidjson::Value &val)
} }
else if (key == "componentName") else if (key == "componentName")
{ {
_ComName = DICTOOL->getStringValue_json(subDict, "value"); _comName = DICTOOL->getStringValue_json(subDict, "value");
continue; continue;
} }
else if (key == "AnimationName") else if (key == "AnimationName")
@ -759,6 +1191,43 @@ void ArmaturePlayAction::serialize(const rapidjson::Value &val)
} }
} }
void ArmaturePlayAction::serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)
{
int length = pCocoNode->GetChildNum();
int count = 0;
stExpCocoNode *pDataItemsArray = pCocoNode->GetChildArray();
std::string key;
const char *str = NULL;
for (int i = 0; i < length; ++i)
{
count = pDataItemsArray[i].GetChildNum();
stExpCocoNode *pDataItemArray = pDataItemsArray[i].GetChildArray();
key = pDataItemArray[0].GetValue();
str = pDataItemArray[1].GetValue();
if (key == "Tag")
{
if (str != NULL)
{
_tag = atoi(str);//DICTOOL->getIntValue_json(subDict, "value");
}
}
else if (key == "componentName")
{
if (str != NULL)
{
_comName = str; //DICTOOL->getStringValue_json(subDict, "value");
}
}
else if (key == "AnimationName")
{
if (str != NULL)
{
_aniname = str; //DICTOOL->getStringValue_json(subDict, "value");
}
}
}
}
void ArmaturePlayAction::removeAll() void ArmaturePlayAction::removeAll()
{ {
CCLOG("ArmaturePlayAction::removeAll"); CCLOG("ArmaturePlayAction::removeAll");

View File

@ -15,6 +15,7 @@ public:
virtual bool init(); virtual bool init();
virtual void done(); virtual void done();
virtual void serialize(const rapidjson::Value &val); virtual void serialize(const rapidjson::Value &val);
virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode);
virtual void removeAll(); virtual void removeAll();
private: private:
int _tag; int _tag;
@ -32,6 +33,7 @@ public:
virtual bool init(); virtual bool init();
virtual void done(); virtual void done();
virtual void serialize(const rapidjson::Value &val); virtual void serialize(const rapidjson::Value &val);
virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode);
virtual void removeAll(); virtual void removeAll();
private: private:
int _tag; int _tag;
@ -50,6 +52,7 @@ public:
virtual bool init(); virtual bool init();
virtual void done(); virtual void done();
virtual void serialize(const rapidjson::Value &val); virtual void serialize(const rapidjson::Value &val);
virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode);
virtual void removeAll(); virtual void removeAll();
private: private:
int _tag; int _tag;
@ -69,6 +72,7 @@ public:
virtual bool init(); virtual bool init();
virtual void done(); virtual void done();
virtual void serialize(const rapidjson::Value &val); virtual void serialize(const rapidjson::Value &val);
virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode);
virtual void removeAll(); virtual void removeAll();
private: private:
int _tag; int _tag;
@ -87,6 +91,7 @@ public:
virtual bool init(); virtual bool init();
virtual void done(); virtual void done();
virtual void serialize(const rapidjson::Value &val); virtual void serialize(const rapidjson::Value &val);
virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode);
virtual void removeAll(); virtual void removeAll();
private: private:
int _tag; int _tag;
@ -106,6 +111,7 @@ public:
virtual bool init(); virtual bool init();
virtual void done(); virtual void done();
virtual void serialize(const rapidjson::Value &val); virtual void serialize(const rapidjson::Value &val);
virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode);
virtual void removeAll(); virtual void removeAll();
private: private:
int _tag; int _tag;
@ -124,6 +130,7 @@ public:
virtual bool init(); virtual bool init();
virtual void done(); virtual void done();
virtual void serialize(const rapidjson::Value &val); virtual void serialize(const rapidjson::Value &val);
virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode);
virtual void removeAll(); virtual void removeAll();
private: private:
int _tag; int _tag;
@ -144,6 +151,7 @@ public:
virtual bool init(); virtual bool init();
virtual void done(); virtual void done();
virtual void serialize(const rapidjson::Value &val); virtual void serialize(const rapidjson::Value &val);
virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode);
virtual void removeAll(); virtual void removeAll();
private: private:
int _tag; int _tag;
@ -162,6 +170,7 @@ public:
virtual bool init(); virtual bool init();
virtual void done(); virtual void done();
virtual void serialize(const rapidjson::Value &val); virtual void serialize(const rapidjson::Value &val);
virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode);
virtual void removeAll(); virtual void removeAll();
private: private:
int _tag; int _tag;
@ -181,6 +190,7 @@ public:
virtual bool init(); virtual bool init();
virtual void done(); virtual void done();
virtual void serialize(const rapidjson::Value &val); virtual void serialize(const rapidjson::Value &val);
virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode);
virtual void removeAll(); virtual void removeAll();
private: private:
int _id; int _id;
@ -197,10 +207,11 @@ public:
virtual bool init(); virtual bool init();
virtual void done(); virtual void done();
virtual void serialize(const rapidjson::Value &val); virtual void serialize(const rapidjson::Value &val);
virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode);
virtual void removeAll(); virtual void removeAll();
private: private:
int _tag; int _tag;
std::string _ComName; std::string _comName;
std::string _aniname; std::string _aniname;
}; };

View File

@ -47,6 +47,28 @@ void TimeElapsed::serialize(const rapidjson::Value &val)
} }
} }
void TimeElapsed::serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)
{
int length = pCocoNode->GetChildNum();
int count = 0;
stExpCocoNode *pDataItemsArray = pCocoNode->GetChildArray();
std::string key;
const char *str = NULL;
for (int i = 0; i < length; ++i)
{
count = pDataItemsArray[i].GetChildNum();
stExpCocoNode *pDataItemArray = pDataItemsArray[i].GetChildArray();
key = pDataItemArray[0].GetValue();
str = pDataItemArray[1].GetValue();
if (key == "TotalTime")
{
if (str != NULL)
{
_totalTime = atof(str); //DICTOOL->getFloatValue_json(subDict, "value");
}
}
}
}
void TimeElapsed::removeAll() void TimeElapsed::removeAll()
{ {
_scheduler->unschedule(schedule_selector(TimeElapsed::update), this); _scheduler->unschedule(schedule_selector(TimeElapsed::update), this);
@ -125,6 +147,50 @@ void ArmatureActionState::serialize(const rapidjson::Value &val)
} }
} }
void ArmatureActionState::serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)
{
int length = pCocoNode->GetChildNum();
int count = 0;
stExpCocoNode *pDataItemsArray = pCocoNode->GetChildArray();
std::string key;
const char *str = NULL;
for (int i = 0; i < length; ++i)
{
count = pDataItemsArray[i].GetChildNum();
stExpCocoNode *pDataItemArray = pDataItemsArray[i].GetChildArray();
key = pDataItemArray[0].GetValue();
str = pDataItemArray[1].GetValue();
if (key == "Tag")
{
if (str != NULL)
{
_tag = atoi(str);//DICTOOL->getIntValue_json(subDict, "value");
}
}
else if (key == "componentName")
{
if (str != NULL)
{
_comName = str; //DICTOOL->getStringValue_json(subDict, "value");
}
}
else if (key == "AnimationName")
{
if (str != NULL)
{
_aniname = str; //DICTOOL->getStringValue_json(subDict, "value");
}
}
else if (key == "ActionType")
{
if (str != NULL)
{
_state = atoi(str); //DICTOOL->getIntValue_json(subDict, "value");
}
}
}
}
void ArmatureActionState::removeAll() void ArmatureActionState::removeAll()
{ {
do do
@ -209,6 +275,56 @@ void NodeInRect::serialize(const rapidjson::Value &val)
} }
} }
void NodeInRect::serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)
{
int length = pCocoNode->GetChildNum();
int count = 0;
stExpCocoNode *pDataItemsArray = pCocoNode->GetChildArray();
std::string key;
const char *str = NULL;
for (int i = 0; i < length; ++i)
{
count = pDataItemsArray[i].GetChildNum();
stExpCocoNode *pDataItemArray = pDataItemsArray[i].GetChildArray();
key = pDataItemArray[0].GetValue();
str = pDataItemArray[1].GetValue();
if (key == "Tag")
{
if (str != NULL)
{
_tag = atoi(str);//DICTOOL->getIntValue_json(subDict, "value");
}
}
else if (key == "originX")
{
if (str != NULL)
{
_origin.x = atoi(str); //DICTOOL->getIntValue_json(subDict, "value");
}
}
else if (key == "originY")
{
if (str != NULL)
{
_origin.y = atoi(str); //DICTOOL->getIntValue_json(subDict, "value");
}
}
else if (key == "sizeWidth")
{
if (str != NULL)
{
_size.width = atoi(str); //DICTOOL->getIntValue_json(subDict, "value");
}
}
else if (key == "sizeHeight")
{
if (str != NULL)
{
_size.height = atoi(str); //DICTOOL->getIntValue_json(subDict, "value");
}
}
}
}
void NodeInRect::removeAll() void NodeInRect::removeAll()
{ {
CCLOG("NodeInRect::removeAll"); CCLOG("NodeInRect::removeAll");
@ -261,6 +377,35 @@ void NodeVisible::serialize(const rapidjson::Value &val)
} }
} }
void NodeVisible::serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)
{
int length = pCocoNode->GetChildNum();
int count = 0;
stExpCocoNode *pDataItemsArray = pCocoNode->GetChildArray();
std::string key;
const char *str = NULL;
for (int i = 0; i < length; ++i)
{
count = pDataItemsArray[i].GetChildNum();
stExpCocoNode *pDataItemArray = pDataItemsArray[i].GetChildArray();
key = pDataItemArray[0].GetValue();
str = pDataItemArray[1].GetValue();
if (key == "Tag")
{
if (str != NULL)
{
_tag = atoi(str);//DICTOOL->getIntValue_json(subDict, "value");
}
}
else if (key == "Visible")
{
if (str != NULL)
{
_visible = atoi(str) != 0? true:false;//DICTOOL->getIntValue_json(subDict, "value") != 0? true:false;
}
}
}
}
void NodeVisible::removeAll() void NodeVisible::removeAll()
{ {
CCLOG("NodeVisible::removeAll"); CCLOG("NodeVisible::removeAll");

View File

@ -15,6 +15,7 @@ public:
virtual bool init(); virtual bool init();
virtual bool detect(); virtual bool detect();
virtual void serialize(const rapidjson::Value &val); virtual void serialize(const rapidjson::Value &val);
virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode);
virtual void removeAll(); virtual void removeAll();
virtual void update(float dt); virtual void update(float dt);
private: private:
@ -35,6 +36,7 @@ public:
virtual bool init(); virtual bool init();
virtual bool detect(); virtual bool detect();
virtual void serialize(const rapidjson::Value &val); virtual void serialize(const rapidjson::Value &val);
virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode);
virtual void removeAll(); virtual void removeAll();
void animationEvent(cocostudio::Armature *armature, cocostudio::MovementEventType movementType, const std::string& movementID); void animationEvent(cocostudio::Armature *armature, cocostudio::MovementEventType movementType, const std::string& movementID);
private: private:
@ -56,6 +58,7 @@ public:
virtual bool init(); virtual bool init();
virtual bool detect(); virtual bool detect();
virtual void serialize(const rapidjson::Value &val); virtual void serialize(const rapidjson::Value &val);
virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode);
virtual void removeAll(); virtual void removeAll();
private: private:
int _tag; int _tag;
@ -73,6 +76,7 @@ public:
virtual bool init(); virtual bool init();
virtual bool detect(); virtual bool detect();
virtual void serialize(const rapidjson::Value &val); virtual void serialize(const rapidjson::Value &val);
virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode);
virtual void removeAll(); virtual void removeAll();
private: private:
int _tag; int _tag;

View File

@ -341,7 +341,6 @@ Effect3DOutline::Effect3DOutline()
Effect3DOutline::~Effect3DOutline() Effect3DOutline::~Effect3DOutline()
{ {
CC_SAFE_RELEASE_NULL(_sprite);
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
Director::getInstance()->getEventDispatcher()->removeEventListener(_backToForegroundListener); Director::getInstance()->getEventDispatcher()->removeEventListener(_backToForegroundListener);
#endif #endif
@ -371,8 +370,6 @@ void Effect3DOutline::setTarget(EffectSprite3D *sprite)
if(sprite != _sprite) if(sprite != _sprite)
{ {
CC_SAFE_RETAIN(sprite);
CC_SAFE_RELEASE_NULL(_sprite);
_sprite = sprite; _sprite = sprite;
auto mesh = sprite->getMesh(); auto mesh = sprite->getMesh();

View File

@ -103,6 +103,7 @@ protected:
Vec3 _outlineColor; Vec3 _outlineColor;
float _outlineWidth; float _outlineWidth;
//weak reference
EffectSprite3D* _sprite; EffectSprite3D* _sprite;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
EventListenerCustom* _backToForegroundListener; EventListenerCustom* _backToForegroundListener;

View File

@ -10,4 +10,4 @@
# Project target. # Project target.
target=android-10 target=android-10
android.library.reference.1=../../../cocos/platform/android/java android.library.reference.1=../../../cocos/platform/android/ControllerDelegate

View File

@ -25,14 +25,14 @@ package org.cocos2dx.game_controller_test;
import java.util.ArrayList; import java.util.ArrayList;
import org.cocos2dx.lib.Cocos2dxActivity; import org.cocos2dx.lib.GameControllerActivity;
import org.cocos2dx.lib.GameControllerHelper.ControllerListener; import org.cocos2dx.lib.GameControllerHelper.ControllerListener;
import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothDevice;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log; import android.util.Log;
public class AppActivity extends Cocos2dxActivity { public class AppActivity extends GameControllerActivity {
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {