Add platform files for Emscripten.

This commit is contained in:
James Gregory 2013-04-08 18:21:53 -07:00
parent 9500448f87
commit edcd0f12e4
13 changed files with 1447 additions and 0 deletions

View File

@ -0,0 +1,31 @@
/*
* CCAccelerometer.h
*
* Created on: Aug 9, 2011
* Author: laschweinski
*/
#ifndef CCACCELEROMETER_H_
#define CCACCELEROMETER_H_
#include "platform/CCAccelerometerDelegate.h"
namespace cocos2d {
class CCAccelerometer
{
public:
CCAccelerometer(){}
~CCAccelerometer(){}
static CCAccelerometer* sharedAccelerometer() { return NULL; };
void removeDelegate(CCAccelerometerDelegate* pDelegate) {CC_UNUSED_PARAM(pDelegate);};
void addDelegate(CCAccelerometerDelegate* pDelegate) {CC_UNUSED_PARAM(pDelegate);};
void setDelegate(CCAccelerometerDelegate* pDelegate) {CC_UNUSED_PARAM(pDelegate);};
void setAccelerometerInterval(float interval) {CC_UNUSED_PARAM(interval);};
};
}//namespace cocos2d
#endif /* CCACCELEROMETER_H_ */

View File

@ -0,0 +1,107 @@
#include "CCApplication.h"
#include "platform/CCFileUtils.h"
#include "CCDirector.h"
#include "CCEGLView.h"
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <emscripten/emscripten.h>
#define LOGD(...) fprintf(stderr, __VA_ARGS__)
NS_CC_BEGIN;
// sharedApplication pointer
CCApplication * CCApplication::sm_pSharedApplication = 0;
long CCApplication::m_animationInterval = 1000;
// convert the timespec into milliseconds
static long time2millis(struct timespec *times)
{
return times->tv_sec*1000 + times->tv_nsec/1000000;
}
CCApplication::CCApplication()
{
CC_ASSERT(! sm_pSharedApplication);
sm_pSharedApplication = this;
}
CCApplication::~CCApplication()
{
CC_ASSERT(this == sm_pSharedApplication);
sm_pSharedApplication = NULL;
}
extern "C" void mainLoopIter(void)
{
CCEGLView::sharedOpenGLView()->handleEvents();
CCDirector::sharedDirector()->mainLoop();
}
int CCApplication::run()
{
struct timespec time_struct;
long update_time;
// Initialize instance and cocos2d.
if (!applicationDidFinishLaunching())
{
return 0;
}
clock_gettime(CLOCK_REALTIME, &time_struct);
update_time = time2millis(&time_struct);
// XXX: Set to 1FPS while debugging
emscripten_set_main_loop(&mainLoopIter, 0, 1);
return -1;
}
void CCApplication::setAnimationInterval(double interval)
{
// interval in milliseconds
m_animationInterval = (long)(interval * 1000);
}
void CCApplication::setResourceRootPath(const std::string& rootResDir)
{
m_resourceRootPath = rootResDir;
if (m_resourceRootPath[m_resourceRootPath.length() - 1] != '/')
{
m_resourceRootPath += '/';
}
CCFileUtils* pFileUtils = CCFileUtils::sharedFileUtils();
std::vector<std::string> searchPaths = pFileUtils->getSearchPaths();
searchPaths.insert(searchPaths.begin(), m_resourceRootPath);
pFileUtils->setSearchPaths(searchPaths);
}
const std::string& CCApplication::getResourceRootPath(void)
{
return m_resourceRootPath;
}
TargetPlatform CCApplication::getTargetPlatform()
{
return kTargetEmscripten;
}
//////////////////////////////////////////////////////////////////////////
// static member function
//////////////////////////////////////////////////////////////////////////
CCApplication* CCApplication::sharedApplication()
{
CC_ASSERT(sm_pSharedApplication);
return sm_pSharedApplication;
}
ccLanguageType CCApplication::getCurrentLanguage()
{
return kLanguageEnglish;
}
NS_CC_END;

View File

@ -0,0 +1,68 @@
#ifndef __CC_APPLICATION_BLACKBERRY_H__
#define __CC_APPLICATION_BLACKBERRY_H__
#include "platform/CCCommon.h"
#include "platform/CCApplicationProtocol.h"
#include <string>
NS_CC_BEGIN;
class CCRect;
class CC_DLL CCApplication : public CCApplicationProtocol
{
public:
CCApplication();
virtual ~CCApplication();
/**
@brief Callback by CCDirector for limit FPS.
@interval The time, which expressed in second in second, between current frame and next.
*/
void setAnimationInterval(double interval);
/**
@brief Run the message loop.
*/
int run();
/**
@brief Get current applicaiton instance.
@return Current application instance pointer.
*/
static CCApplication* sharedApplication();
/**
@brief Get current language config
@return Current language config
*/
virtual ccLanguageType getCurrentLanguage();
/**
@brief Get target platform
*/
virtual TargetPlatform getTargetPlatform();
/**
* Sets the Resource root path.
* @deprecated Please use CCFileUtils::sharedFileUtils()->setSearchPaths() instead.
*/
CC_DEPRECATED_ATTRIBUTE void setResourceRootPath(const std::string& rootResDir);
/**
* Gets the Resource root path.
* @deprecated Please use CCFileUtils::sharedFileUtils()->getSearchPaths() instead.
*/
CC_DEPRECATED_ATTRIBUTE const std::string& getResourceRootPath(void);
protected:
static CCApplication * sm_pSharedApplication;
std::string m_resourceRootPath;
static long m_animationInterval;
};
NS_CC_END
#endif // __CC_APPLICATION_BLACKBERRY_H__

View File

@ -0,0 +1,55 @@
/****************************************************************************
Copyright (c) 2010 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.
****************************************************************************/
#include "platform/CCCommon.h"
#include "CCStdC.h"
NS_CC_BEGIN
#define MAX_LEN (cocos2d::kMaxLogLen + 1)
void CCLog(const char * pszFormat, ...)
{
char buf[MAX_LEN];
va_list args;
va_start(args, pszFormat);
vsnprintf(buf, MAX_LEN, pszFormat, args);
va_end(args);
fprintf(stderr, "cocos2d-x debug info %s\n", buf);
}
void CCMessageBox(const char * pszMsg, const char * pszTitle)
{
// MessageBoxA(NULL, pszMsg, pszTitle, MB_OK);
CCLog(pszMsg);
}
void CCLuaLog(const char * pszFormat)
{
puts(pszFormat);
}
NS_CC_END

View File

@ -0,0 +1,10 @@
#include "platform/CCDevice.h"
NS_CC_BEGIN
int CCDevice::getDPI()
{
return 160;
}
NS_CC_END

View File

@ -0,0 +1,394 @@
/****************************************************************************
Copyright (c) 2010 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.
****************************************************************************/
#include "CCEGLView.h"
#include "cocoa/CCSet.h"
#include "CCDirector.h"
#include "ccMacros.h"
#include "touch_dispatcher/CCTouch.h"
#include "touch_dispatcher/CCTouchDispatcher.h"
#include "text_input_node/CCIMEDispatcher.h"
#include "keypad_dispatcher/CCKeypadDispatcher.h"
#include "CCGL.h"
#include "CCAccelerometer.h"
#include "CCApplication.h"
#include <ctype.h>
#include <stdlib.h>
// XXX: For sleep -- remove.
#include <unistd.h>
extern "C" {
void glutInit(int *argcp, char **argv);
void glutMouseFunc(void (*func)(int button, int state, int x, int y));
void glutMotionFunc(void (*func)(int x, int y));
void glutPassiveMotionFunc(void (*func)(int x, int y));
}
// Constants for mouse events (inferred from experiment)
static const int glutLeftButton = 0;
static const int glutMouseDown = 0;
static const int glutMouseUp = 1;
NS_CC_BEGIN
bool CCEGLView::m_initializedFunctions = false;
const GLubyte *CCEGLView::m_extensions = 0;
enum Orientation
{
PORTRAIT,
LANDSCAPE,
AUTO
};
static Orientation orientation = LANDSCAPE;
#define MAX_TOUCHES 4
static CCTouch *s_pTouches[MAX_TOUCHES] = { NULL };
static CCEGLView* s_pInstance = NULL;
static bool buttonDepressed = false;
extern "C" void mouseCB(int button, int state, int x, int y)
{
float fx = x;
float fy = y;
CCEGLView* pEGLView = CCEGLView::sharedOpenGLView();
int id = 0;
if(button != glutLeftButton) return;
if(state == glutMouseDown)
{
pEGLView->handleTouchesBegin(1, &id, &fx, &fy);
buttonDepressed = true;
}
else if(state == glutMouseUp)
{
pEGLView->handleTouchesEnd(1, &id, &fx, &fy);
buttonDepressed = false;
}
}
extern "C" void motionCB(int x, int y)
{
float fx = x;
float fy = y;
CCEGLView* pEGLView = CCEGLView::sharedOpenGLView();
int id = 0;
if(buttonDepressed)
{
pEGLView->handleTouchesMove(1, &id, &fx, &fy);
}
}
CCEGLView::CCEGLView()
{
m_eglDisplay = EGL_NO_DISPLAY;
m_eglContext = EGL_NO_CONTEXT;
m_eglSurface = EGL_NO_SURFACE;
strcpy(m_windowGroupID, "");
snprintf(m_windowGroupID, sizeof(m_windowGroupID), "%d", 1);
m_isGLInitialized = initGL();
if (m_isGLInitialized)
initEGLFunctions();
char *arg1 = (char*)malloc(1);
char **dummyArgv = (char**)malloc(sizeof(char*));
dummyArgv[0] = arg1;
glutInit(0, dummyArgv);
free(dummyArgv[0]);
free(dummyArgv);
glutMouseFunc(&mouseCB);
glutMotionFunc(&motionCB);
glutPassiveMotionFunc(&motionCB);
}
CCEGLView::~CCEGLView()
{
}
const char* CCEGLView::getWindowGroupId() const
{
return m_windowGroupID;
}
void CCEGLView::release()
{
if (m_eglDisplay != EGL_NO_DISPLAY)
{
eglMakeCurrent(m_eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
}
if (m_eglSurface != EGL_NO_SURFACE)
{
eglDestroySurface(m_eglDisplay, m_eglSurface);
m_eglSurface = EGL_NO_SURFACE;
}
if (m_eglContext != EGL_NO_CONTEXT)
{
eglDestroyContext(m_eglDisplay, m_eglContext);
m_eglContext = EGL_NO_CONTEXT;
}
if (m_eglDisplay != EGL_NO_DISPLAY)
{
eglTerminate(m_eglDisplay);
m_eglDisplay = EGL_NO_DISPLAY;
}
eglReleaseThread();
m_isGLInitialized = false;
exit(0);
}
void CCEGLView::initEGLFunctions()
{
m_extensions = glGetString(GL_EXTENSIONS);
m_initializedFunctions = true;
}
bool CCEGLView::isOpenGLReady()
{
// return (m_isGLInitialized && m_screenWidth != 0 && m_screenHeight != 0);
return (m_isGLInitialized && m_obScreenSize.height != 0 && m_obScreenSize.width != 0);
}
void CCEGLView::end()
{
release();
}
void CCEGLView::swapBuffers()
{
eglSwapBuffers(m_eglDisplay, m_eglSurface);
}
CCEGLView* CCEGLView::sharedOpenGLView()
{
if (!s_pInstance)
{
s_pInstance = new CCEGLView();
}
CCAssert(s_pInstance != NULL, "CCEGLView wasn't constructed yet");
return s_pInstance;
}
void CCEGLView::showKeyboard()
{
}
void CCEGLView::hideKeyboard()
{
}
void CCEGLView::setIMEKeyboardState(bool bOpen)
{
}
bool CCEGLView::isGLExtension(const char *searchName) const
{
const GLubyte *start;
GLubyte *where, *terminator;
/* It takes a bit of care to be fool-proof about parsing the
OpenGL extensions string. Don't be fooled by sub-strings,
etc. */
start = m_extensions;
for (;;)
{
where = (GLubyte *) strstr((const char *) start, searchName);
if (!where)
break;
terminator = where + strlen(searchName);
if (where == start || *(where - 1) == ' ')
if (*terminator == ' ' || *terminator == '\0')
return true;
start = terminator;
}
return false;
}
static EGLenum checkErrorEGL(const char* msg)
{
assert(msg);
static const char* errmsg[] =
{
"EGL function succeeded",
"EGL is not initialized, or could not be initialized, for the specified display",
"EGL cannot access a requested resource",
"EGL failed to allocate resources for the requested operation",
"EGL fail to access an unrecognized attribute or attribute value was passed in an attribute list",
"EGLConfig argument does not name a valid EGLConfig",
"EGLContext argument does not name a valid EGLContext",
"EGL current surface of the calling thread is no longer valid",
"EGLDisplay argument does not name a valid EGLDisplay",
"EGL arguments are inconsistent",
"EGLNativePixmapType argument does not refer to a valid native pixmap",
"EGLNativeWindowType argument does not refer to a valid native window",
"EGL one or more argument values are invalid",
"EGLSurface argument does not name a valid surface configured for rendering",
"EGL power management event has occurred",
};
EGLenum error = eglGetError();
fprintf(stderr, "%s: %s\n", msg, errmsg[error - EGL_SUCCESS]);
return error;
}
bool CCEGLView::initGL()
{
int rc = 0;
int angle = atoi(getenv("ORIENTATION"));
// Hard-coded to (0,0).
int windowPosition[] =
{
0, 0
};
EGLint eglConfigCount;
EGLConfig config;
// Hard-coded to 32-bit/OpenGL ES 2.0.
const EGLint eglConfigAttrs[] =
{
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_DEPTH_SIZE, 24,
EGL_STENCIL_SIZE, 8,
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_NONE
};
const EGLint eglContextAttrs[] =
{
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
const EGLint eglSurfaceAttrs[] =
{
EGL_RENDER_BUFFER, EGL_BACK_BUFFER,
EGL_NONE
};
// Get the EGL display and initialize.
m_eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (m_eglDisplay == EGL_NO_DISPLAY)
{
perror("eglGetDisplay");
return false;
}
sleep(1);
if (eglInitialize(m_eglDisplay, NULL, NULL) != EGL_TRUE)
{
perror("eglInitialize");
return false;
}
if (eglChooseConfig(m_eglDisplay, eglConfigAttrs, &config, 1, &eglConfigCount) != EGL_TRUE || eglConfigCount == 0)
{
checkErrorEGL("eglChooseConfig");
return false;
}
m_eglContext = eglCreateContext(m_eglDisplay, config, EGL_NO_CONTEXT, eglContextAttrs);
if (m_eglContext == EGL_NO_CONTEXT)
{
checkErrorEGL("eglCreateContext");
return false;
}
m_eglSurface = eglCreateWindowSurface(m_eglDisplay, config, NULL, eglSurfaceAttrs);
if (m_eglSurface == EGL_NO_SURFACE)
{
checkErrorEGL("eglCreateWindowSurface");
return false;
}
if (eglMakeCurrent(m_eglDisplay, m_eglSurface, m_eglSurface, m_eglContext) != EGL_TRUE)
{
checkErrorEGL("eglMakeCurrent");
return false;
}
// FIXME: Get the actual canvas size somehow.
EGLint width = 300;
EGLint height = 150;
if ((m_eglDisplay == EGL_NO_DISPLAY) || (m_eglSurface == EGL_NO_SURFACE) )
return EXIT_FAILURE;
/*
eglQuerySurface(m_eglDisplay, m_eglSurface, EGL_WIDTH, &width);
eglQuerySurface(m_eglDisplay, m_eglSurface, EGL_HEIGHT, &height);
*/
m_obScreenSize.width = width;
m_obScreenSize.height = height;
printf("width, height = %d, %d\n", width, height);
glViewport(0, 0, width, height);
// Set vsync.
// eglSwapInterval(m_eglDisplay, screenSwapInterval);
return true;
}
static long time2millis(struct timespec *times)
{
return times->tv_sec*1000 + times->tv_nsec/1000000;
}
bool CCEGLView::handleEvents()
{
return true;
}
NS_CC_END

View File

@ -0,0 +1,83 @@
/****************************************************************************
Copyright (c) 2010 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.
****************************************************************************/
#ifndef __CC_EGLVIEW_BLACKBERRY_H__
#define __CC_EGLVIEW_BLACKBERRY_H__
#include "cocoa/CCGeometry.h"
#include "platform/CCEGLViewProtocol.h"
#include "platform/CCPlatformMacros.h"
//#include <bps/event.h>
NS_CC_BEGIN
class CC_DLL CCEGLView : public CCEGLViewProtocol
{
public:
CCEGLView();
virtual ~CCEGLView();
bool isOpenGLReady();
const char* getWindowGroupId() const;
// keep compatible
void end();
void swapBuffers();
void setIMEKeyboardState(bool bOpen);
// static function
/**
@brief get the shared main open gl window
*/
static CCEGLView* sharedOpenGLView();
bool handleEvents();
private:
void release();
bool initGL();
void initEGLFunctions();
bool isGLExtension(const char *searchName) const;
bool initDriver();
void showKeyboard();
void hideKeyboard();
static bool m_initializedFunctions;
static const GLubyte *m_extensions;
bool m_isGLInitialized;
bool m_isWindowActive;
EGLDisplay m_eglDisplay;
EGLContext m_eglContext;
EGLSurface m_eglSurface;
char m_windowGroupID[16];
};
NS_CC_END
#endif // end of __CC_EGLVIEW_QNX_H__

View File

@ -0,0 +1,68 @@
#include "CCFileUtilsEmscripten.h"
#include "platform/CCCommon.h"
#include "ccMacros.h"
#include "CCApplication.h"
#include "cocoa/CCString.h"
#include <unistd.h>
using namespace std;
NS_CC_BEGIN
CCFileUtils* CCFileUtils::sharedFileUtils()
{
if (s_sharedFileUtils == NULL)
{
s_sharedFileUtils = new CCFileUtilsEmscripten();
s_sharedFileUtils->init();
}
return s_sharedFileUtils;
}
CCFileUtilsEmscripten::CCFileUtilsEmscripten()
{}
bool CCFileUtilsEmscripten::init()
{
m_strDefaultResRootPath = "app/native/Resources/";
return CCFileUtils::init();
}
string CCFileUtilsEmscripten::getWritablePath()
{
// Let's write it in the current working directory's data folder
char cwd[FILENAME_MAX] = {0};
getcwd(cwd, FILENAME_MAX - 1);
cwd[FILENAME_MAX-1] = '\0';
std::string path = cwd;
path += "/data/";
return path;
}
bool CCFileUtilsEmscripten::isAbsolutePath(const std::string& strPath)
{
if (strPath[0] == '/' || strPath.find(m_strDefaultResRootPath) == 0)
{
return true;
}
return false;
}
bool CCFileUtilsEmscripten::isFileExist(const std::string& strFilePath)
{
std::string strPath = strFilePath;
if (strPath[0] != '/')
{ // Not absolute path, add the default root path at the beginning.
if (strPath.find(m_strDefaultResRootPath) != 0)
{// Didn't find "assets/" at the beginning of the path, adding it.
strPath.insert(0, m_strDefaultResRootPath);
}
}
return access(strPath.c_str(), F_OK) != -1 ? true : false;
}
NS_CC_END

View File

@ -0,0 +1,60 @@
/****************************************************************************
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.
****************************************************************************/
#ifndef __CC_FILEUTILS_BLACKBERRY_H__
#define __CC_FILEUTILS_BLACKBERRY_H__
#include "platform/CCFileUtils.h"
#include "platform/CCPlatformMacros.h"
#include "ccTypes.h"
#include "ccTypeInfo.h"
#include <string>
#include <vector>
NS_CC_BEGIN
/**
* @addtogroup platform
* @{
*/
//! @brief Helper class to handle file operations
class CC_DLL CCFileUtilsEmscripten : public CCFileUtils
{
friend class CCFileUtils;
CCFileUtilsEmscripten();
public:
/* override funtions */
bool init();
virtual std::string getWritablePath();
virtual bool isFileExist(const std::string& strFilePath);
virtual bool isAbsolutePath(const std::string& strPath);
};
// end of platform group
/// @}
NS_CC_END
#endif // __CC_FILEUTILS_BLACKBERRY_H__

View File

@ -0,0 +1,49 @@
/****************************************************************************
Copyright (c) 2010 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.
****************************************************************************/
#ifndef __CCGL_H__
#define __CCGL_H__
#define glClearDepth glClearDepthf
#define GL_BGRA GL_BGRA_EXT
#define GL_DEPTH24_STENCIL8 GL_DEPTH24_STENCIL8_OES
#define GL_WRITE_ONLY GL_WRITE_ONLY_OES
#include <EGL/egl.h>
//#include <screen/screen.h>
// normal process
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
//declare here while define in CCEGLView.cpp
extern PFNGLGENVERTEXARRAYSOESPROC glGenVertexArrays;
extern PFNGLBINDVERTEXARRAYOESPROC glBindVertexArray;
extern PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArrays;
extern PFNGLMAPBUFFEROESPROC glMapBuffer;
extern PFNGLUNMAPBUFFEROESPROC glUnmapBuffer;
extern PFNGLGETBUFFERPOINTERVOESPROC glGetBufferPointerv;
#endif // __CCGL_H__

View File

@ -0,0 +1,450 @@
/****************************************************************************
Copyright (c) 2010 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.
****************************************************************************/
#define __CC_PLATFORM_IMAGE_CPP__
#include "platform/CCImageCommon_cpp.h"
#include <string.h>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include "platform/CCImage.h"
#include "platform/CCFileUtils.h"
#include "platform/CCCommon.h"
#include "CCStdC.h"
#include "ft2build.h"
#include FT_FREETYPE_H
#include <map>
#define szFont_kenning 2
#define RSHIFT6(num) ((num)>>6)
using namespace std;
struct TextLine {
std::string sLineStr;
int iLineWidth;
};
NS_CC_BEGIN
class BitmapDC
{
public:
BitmapDC()
{
libError = FT_Init_FreeType( &library );
iInterval = szFont_kenning;
m_pData = NULL;
reset();
}
~BitmapDC(void)
{
FT_Done_FreeType(library);
}
void reset() {
iMaxLineWidth = 0;
iMaxLineHeight = 0;
vLines.clear();
}
int utf8(char **p)
{
if ((**p & 0x80) == 0x00)
{
int a = *((*p)++);
return a;
}
if ((**p & 0xE0) == 0xC0)
{
int a = *((*p)++) & 0x1F;
int b = *((*p)++) & 0x3F;
return (a << 6) | b;
}
if ((**p & 0xF0) == 0xE0)
{
int a = *((*p)++) & 0x0F;
int b = *((*p)++) & 0x3F;
int c = *((*p)++) & 0x3F;
return (a << 12) | (b << 6) | c;
}
if ((**p & 0xF8) == 0xF0)
{
int a = *((*p)++) & 0x07;
int b = *((*p)++) & 0x3F;
int c = *((*p)++) & 0x3F;
int d = *((*p)++) & 0x3F;
return (a << 18) | (b << 12) | (c << 8) | d;
}
return 0;
}
void buildLine(std::stringstream& ss, FT_Face face, int iCurXCursor, char cLastChar )
{
TextLine oTempLine;
ss << '\0';
oTempLine.sLineStr = ss.str();
//get last glyph
FT_Load_Glyph(face, FT_Get_Char_Index(face, cLastChar), FT_LOAD_DEFAULT);
oTempLine.iLineWidth =
iCurXCursor -
RSHIFT6( face->glyph->metrics.horiAdvance +
face->glyph->metrics.horiBearingX
- face->glyph->metrics.width)/*-iInterval*/; //TODO interval
iMaxLineWidth = MAX(iMaxLineWidth, oTempLine.iLineWidth);
ss.clear();
ss.str("");
vLines.push_back(oTempLine);
}
bool divideString(FT_Face face, const char* sText, int iMaxWidth, int iMaxHeight) {
const char* pText = sText;
int iError = 0;
int iCurXCursor;
iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, *pText), FT_LOAD_DEFAULT);
if (iError) {
return false;
}
iCurXCursor = -RSHIFT6(face->glyph->metrics.horiBearingX);
//init stringstream
std::stringstream ss;
int cLastCh = 0;
while (*pText != '\0') {
if (*pText == '\n') {
buildLine(ss, face, iCurXCursor, cLastCh);
pText++;
iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, *pText), FT_LOAD_DEFAULT);
if (iError) {
return false;
}
iCurXCursor = -RSHIFT6(face->glyph->metrics.horiBearingX);
continue;
}
iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, *pText), FT_LOAD_DEFAULT);
if (iError) {
return false;
//break;
}
//check its width
//divide it when exceeding
if ((iMaxWidth > 0 && iCurXCursor + RSHIFT6(face->glyph->metrics.width) > iMaxWidth)) {
buildLine(ss, face , iCurXCursor, cLastCh);
iCurXCursor = -RSHIFT6(face->glyph->metrics.horiBearingX);
}
cLastCh = *pText;
ss << *pText;
iCurXCursor += RSHIFT6(face->glyph->metrics.horiAdvance) + iInterval;
pText++;
}
if (iError) {
return false;
}
buildLine(ss,face, iCurXCursor, cLastCh);
return true;
}
/**
* compute the start pos of every line
*
* return >0 represent the start x pos of the line
* while -1 means fail
*
*/
int computeLineStart(FT_Face face, CCImage::ETextAlign eAlignMask, char cText,
int iLineIndex) {
int iRet;
int iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, cText),
FT_LOAD_DEFAULT);
if (iError) {
return -1;
}
if (eAlignMask == CCImage::kAlignCenter) {
iRet = (iMaxLineWidth - vLines[iLineIndex].iLineWidth) / 2
- RSHIFT6(face->glyph->metrics.horiBearingX );
} else if (eAlignMask == CCImage::kAlignRight) {
iRet = (iMaxLineWidth - vLines[iLineIndex].iLineWidth)
- RSHIFT6(face->glyph->metrics.horiBearingX );
} else {
// left or other situation
iRet = -RSHIFT6(face->glyph->metrics.horiBearingX );
}
return iRet;
}
int computeLineStartY( FT_Face face, CCImage::ETextAlign eAlignMask, int txtHeight, int borderHeight ){
int iRet;
if (eAlignMask == CCImage::kAlignCenter || eAlignMask == CCImage::kAlignLeft ||
eAlignMask == CCImage::kAlignRight ) {
//vertical center
iRet = (borderHeight - txtHeight)/2 + RSHIFT6(face->size->metrics.ascender);
} else if (eAlignMask == CCImage::kAlignBottomRight ||
eAlignMask == CCImage::kAlignBottom ||
eAlignMask == CCImage::kAlignBottomLeft ) {
//vertical bottom
iRet = borderHeight - txtHeight + RSHIFT6(face->size->metrics.ascender);
} else {
// left or other situation
iRet = RSHIFT6(face->size->metrics.ascender);
}
return iRet;
}
bool getBitmap(const char *text, int nWidth, int nHeight, CCImage::ETextAlign eAlignMask, const char * pFontName, float fontSize) {
FT_Face face;
FT_Error iError;
const char* pText = text;
//data will be deleted by CCImage
// if (m_pData) {
// delete m_pData;
// }
unsigned char cTemp ;
int iY, iX, iTemp ;
uint32 offset, rowOffset ;
int iCurXCursor, iCurYCursor;
bool bRet = false;
if (libError) {
return false;
}
do {
std::string fontPath = pFontName;
if(m_fontCache.count(fontPath))
{
face = m_fontCache[fontPath];
}
else
{
//CCLog("\n\n ---- FT_New_Face with pFontName = %s\n", pFontName);
iError = FT_New_Face( library, pFontName, 0, &face );
if (iError) {
int len = strlen(pFontName) + 11; // 11 = strlen('fonts/.ttf\0')
char *fullPath = (char*)malloc(len);
snprintf(fullPath, len, "fonts/%s.ttf", pFontName);
iError = FT_New_Face( library, fullPath, 0, &face );
free(fullPath);
}
if (iError) {
//no valid font found use default
//CCLog("\n\n ---- no valid font, use default %s\n", pFontName);
iError = FT_New_Face( library, "fonts/arial.ttf", 0, &face );
}
CC_BREAK_IF(iError);
m_fontCache[fontPath] = face;
}
//select utf8 charmap
iError = FT_Select_Charmap(face,FT_ENCODING_UNICODE);
CC_BREAK_IF(iError);
iError = FT_Set_Pixel_Sizes(face, fontSize,fontSize);
CC_BREAK_IF(iError);
iError = divideString(face, text, nWidth, nHeight) ? 0 : 1 ;
//compute the final line width
iMaxLineWidth = MAX(iMaxLineWidth, nWidth);
FT_Pos ascenderPixels = RSHIFT6(face->size->metrics.ascender) ;
FT_Pos descenderPixels = RSHIFT6(face->size->metrics.descender) ;
iMaxLineHeight = ascenderPixels - descenderPixels;
iMaxLineHeight *= vLines.size();
//compute the final line height
iMaxLineHeight = MAX(iMaxLineHeight, nHeight);
uint bitmapSize = iMaxLineWidth * iMaxLineHeight*4 ;
m_pData = new unsigned char[bitmapSize];
memset(m_pData,0, bitmapSize);
const char* pText = text;
iCurYCursor = ascenderPixels;
for (size_t i = 0; i < vLines.size(); i++) {
pText = vLines[i].sLineStr.c_str();
//initialize the origin cursor
iCurXCursor = computeLineStart(face, eAlignMask, *pText, i);
while (*pText != 0) {
int iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, *pText), FT_LOAD_RENDER);
if (iError) {
break;
}
// convert glyph to bitmap with 256 gray
// and get the bitmap
FT_Bitmap & bitmap = face->glyph->bitmap;
FT_Pos horiBearingYPixels = RSHIFT6(face->glyph->metrics.horiBearingY) ;
FT_Pos horiBearingXPixels = RSHIFT6(face->glyph->metrics.horiBearingX) ;
FT_Pos horiAdvancePixels = RSHIFT6(face->glyph->metrics.horiAdvance) ;
for (int i = 0; i < bitmap.rows; ++i) {
iY = iCurYCursor + i - horiBearingYPixels;
if (iY < 0 || iY>=iMaxLineHeight) {
//exceed the height truncate
continue;
}
rowOffset = iY * iMaxLineWidth ;
// if it has gray>0 we set show it as 1, otherwise 0
char cbuf[1024];
for (int j = 0; j < bitmap.width; ++j) {
cTemp = bitmap.buffer[i * bitmap.width + j];
cbuf[j] = cTemp > 64 ? '*' : ' ';
cbuf[j+1] = 0;
if( cTemp )
{
iX = iCurXCursor + j + horiBearingXPixels;
offset = (rowOffset + iX) * 4 ;
assert( (offset + 3) < bitmapSize ) ;
iTemp = cTemp << 24 | cTemp << 16 | cTemp << 8 | cTemp;
*(int*) &m_pData[ offset ] = iTemp ; // ARGB
}
}
}
//step to next glyph
iCurXCursor += horiAdvancePixels + iInterval;
pText++;
}
iCurYCursor += ascenderPixels - descenderPixels ;
}
//clear all lines
vLines.clear();
//success;
if (iError) {
bRet = false;
} else {
bRet = true;
}
}while(0);
return bRet;
}
public:
FT_Library library;
unsigned char *m_pData;
int libError;
vector<TextLine> vLines;
int iInterval;
int iMaxLineWidth;
int iMaxLineHeight;
map<string, FT_Face> m_fontCache;
};
static BitmapDC& sharedBitmapDC()
{
static BitmapDC s_BmpDC;
return s_BmpDC;
}
bool CCImage::initWithString(
const char * pText,
int nWidth/* = 0*/,
int nHeight/* = 0*/,
ETextAlign eAlignMask/* = kAlignCenter*/,
const char * pFontName/* = nil*/,
int nSize/* = 0*/)
{
bool bRet = false;
do
{
CC_BREAK_IF(! pText);
BitmapDC &dc = sharedBitmapDC();
std::string fullFontName = pFontName;
std::string lowerCasePath = fullFontName;
std::transform(lowerCasePath.begin(), lowerCasePath.end(), lowerCasePath.begin(), ::tolower);
if ( lowerCasePath.find(".ttf") != std::string::npos ) {
fullFontName = CCFileUtils::sharedFileUtils()->fullPathForFilename(pFontName);
}
//CCLog("-----pText=%s and Font File is %s nWidth= %d,nHeight=%d",pText,fullFontName.c_str(),nWidth,nHeight);
CC_BREAK_IF(! dc.getBitmap(pText, nWidth, nHeight, eAlignMask, fullFontName.c_str(), nSize));
//CCLog("---- dc.getBitmap is Succesfull... \n");
// assign the dc.m_pData to m_pData in order to save time
m_pData = dc.m_pData;
CC_BREAK_IF(! m_pData);
m_nWidth = (short)dc.iMaxLineWidth;
m_nHeight = (short)dc.iMaxLineHeight;
m_bHasAlpha = true;
m_bPreMulti = true;
m_nBitsPerComponent = 8;
bRet = true;
dc.reset();
} while (0);
return bRet;
}
NS_CC_END

View File

@ -0,0 +1,24 @@
#ifndef __CCPLATFORMDEFINE_H__
#define __CCPLATFORMDEFINE_H__
#include <assert.h>
#define CC_DLL
#define CC_ASSERT(cond) assert(cond)
#define CC_UNUSED_PARAM(unusedparam) (void)unusedparam
/* Define NULL pointer value */
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
#endif /* __CCPLATFORMDEFINE_H__*/

View File

@ -0,0 +1,48 @@
/****************************************************************************
Copyright (c) 2010 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.
****************************************************************************/
#ifndef __CC_STD_C_H__
#define __CC_STD_C_H__
#include "platform/CCPlatformMacros.h"
#include <float.h>
#include <math.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <stdint.h>
#ifndef MIN
#define MIN(x,y) (((x) > (y)) ? (y) : (x))
#endif // MIN
#ifndef MAX
#define MAX(x,y) (((x) < (y)) ? (y) : (x))
#endif // MAX
#endif // __CC_STD_C_H__