Merge branch 'master' into XMLHttpRequest_cchttpclient

# By James Chen (23) and others
# Via James Chen (19) and others
* master: (57 commits)
  Update AUTHORS [ci skip]
  fixed #2151: Commenting a log in CCFileUtils::fullPathForFilename.
  Update AUTHORS [ci skip].
  fixed #2105: Refactoring travis build script.
  Assert statement modifies 'mType'.
  fixed #2151: Custom font can't be loaded correctly if using full path of filename.
  fixed #2150: Updating AUTHORS.
  fixed #2150: Adding tests for this issue and fix compilation error of CCScale9Sprite.
  fixed #2150: Updating ccb and ccbi files.
  Update AUTHORS
  fixed #2105: Updating the URL of 'Building Status' for travis.
  fixed #2105: Adding Travis build support. Moving script to 'tools/travis-script'.
  fixed #2149: "const CCSize& CCScrollView::getContentSize()" --> "const CCSize& CCScrollView::getContentSize() const".
  Update AUTHORS
  Update AUTHORS
  Update AUTHORS
  issue #2103 Add more lua test case(Replace encoding error)
  Added const to CCNode::getChildrenCount()
  Fix for wrong alignment using texture format sizes other than 4 bytes. For example RGBA4444 is 2 bytes per pixel. A texture with width of 1 passes the previous power of 2 test, but the alignment value needs to be 2, not 4.
  issue #2103 Add more lua test case(Add  PerformanceSpriteTest of PerformanceTest)
  ...
This commit is contained in:
Carsten Sandtner 2013-05-13 17:02:17 +02:00
commit b74f1fb161
91 changed files with 6276 additions and 261 deletions

View File

@ -1,17 +1,20 @@
language: cpp
script:
- export NACL_SDK_ROOT=$PWD/nacl_sdk/pepper_canary
- export NACL_SDK_ROOT=$HOME/bin/nacl_sdk/pepper_canary
- export PATH=$PATH:$NACL_SDK_ROOT/toolchain/linux_x86_newlib/bin
- make -j4
install:
- "if [ \"$PLATFORM\" != nacl ]; then ./install-deps-linux.sh; fi"
- "if [ \"$PLATFORM\" = nacl ]; then sudo apt-get update; fi"
- "if [ \"$PLATFORM\" = nacl ]; then sudo apt-get install libc6:i386; fi"
- "if [ \"$PLATFORM\" = nacl ]; then wget http://storage.googleapis.com/nativeclient-mirror/nacl/nacl_sdk/nacl_sdk.zip; fi"
- "if [ \"$PLATFORM\" = nacl ]; then unzip nacl_sdk.zip; fi"
- "if [ \"$PLATFORM\" = nacl ]; then nacl_sdk/naclsdk update --force pepper_canary; fi"
- export NDK_ROOT=$HOME/bin/android-ndk
- ./tools/travis-scripts/run-script.sh
before_install:
- ./tools/travis-scripts/before-install.sh
env:
- PLATFORM=nacl DEBUG=1
- PLATFORM=nacl DEBUG=0
- PLATFORM=linux DEBUG=1
- PLATFORM=linux DEBUG=0
global:
- secure: "XvKfZu6ePLYH6nWwF6YrDMQLCfABOtyzac0JDwgYr7m1f5WH1nYQ7Hgv+pjq\nnJs+A5wdXJ6f6jRvgrgQ1T9UvY0ckR9HIXYmGtg2bd+IjJmDh0gwZMz+OFq4\nQ+Wsj9wxu9LsEAt/CosQvk3r2AoMpIY98a864b0EquZH+zzdzgA="
- secure: "iEFKwSz4IlQ9EfAL8c/1MwU6Ti1IrNtG0YUi3TWdf6sCMglXaRICSJTCY9Hz\nXLYYvp5lPo5FQsqxpMBhkm2Zpitd4zZq+r62P9e2b4P9svAxapOQdYRh9Cjc\nN3eUyQTslMVPE9zsWIJmQbIlDk18X246Izo353UI7mmJ8WRAoNE="
matrix:
# - GEN_JSB=YES
- PLATFORM=linux DEBUG=1
- PLATFORM=nacl DEBUG=1
- PLATFORM=android
branches:
only:
- master

25
AUTHORS
View File

@ -12,6 +12,12 @@ Developers:
Rolando Abarca
Javascript Binding and testjs
silverscania
Pass correct parameter to glPixelStorei when creating a texture
FlagellumDei
Center the window correctly on windows
ggggamer
fixed memory leak of preloadEffect on windows
@ -62,6 +68,7 @@ Developers:
Fix CCUserDefault.cpp compiling on Android.
Fixing CCFileUtils 'createXXXXWithContentsOfFile' path lookup issue.
Add CCDirector::popToSceneStackLevel(int level).
Fixing a bug that custom font can't be loaded correctly if using full path of filename on android.
Waiter
fix an error that OpenSLEngine can't load resources from SD card
@ -115,6 +122,8 @@ Developers:
CCTableView crashes if a CCTableViewDelegate is not provided.
Fixing a bug that _realOpacity isn't assigned in CCLayerColor::initWithColor.
CCScrollView TouchPriority Fix
Add encrypted PVR.CCZ support to ZipUtils + Tests
Fix for broken of ccArrayGetIndexOfObject after merging this commit(076f38c).
Weeds (Andre Rudlaff)
Used fontconfig to enhance font rendering on linux.
@ -369,6 +378,7 @@ Developers:
jotel (Jaroslaw Lewandowski)
Fixing a bug that wrong type of argument signature is used in setAccelerometerIntervalJNI function.
Fix for broken of ccArrayGetIndexOfObject after merging this commit(076f38c).
MarcelBloemendaal
Adding secureTextEntry property to CCTextFieldTTF.
@ -390,6 +400,21 @@ Developers:
coolengineer (Hojin Choi)
Refactoring callback selector for HttpResponse.
djh-
Fixing a bug that displayed color of CCDrawNode is incorrect when VAO is disabled.
acai (beingstudio)
Fix of null pointer access in CCBAnimationManager::getRunningSequenceName.
metalgit92
Adding const qualification to some CCNode's getters
Clarinexus
Fixing a bug that setColor and setOpacity of CCControlButton and CCScale9Sprite are broken.
Xander84
Fixing a bug in CCBValue::getByteValue.
Retired Core Developers:
WenSheng Yang
Author of windows port, CCTextField,

View File

@ -2,8 +2,6 @@
* Touch handler screwed up after TouchesTest? MenuTest? (TestCpp sample)
* Add linkage to libjpeg to get RenderTexture test to work.
* TTF Font rendering is slow and seems to wrap around by a few pixels
horizontally. Need to investigate here, but I suspect the right answer is to
offload font rendering to an offscreen canvas and let the browser handle it.
@ -58,3 +56,5 @@ DONE:
Failed condition: moment > 0.0f
Source:../src/cpBody.c:151
* Add linkage to libjpeg to get RenderTexture test to work.

View File

@ -1,7 +1,7 @@
cocos2d-x
=========
[![Build Status](https://travis-ci.org/sbc100/cocos2d-x.png?branch=travis)](https://travis-ci.org/sbc100/cocos2d-x)
[![Build Status](https://travis-ci.org/cocos2d/cocos2d-x.png?branch=master)](https://travis-ci.org/cocos2d/cocos2d-x)
[cocos2d-x][1] is a multi-platform 2D game framework in C++, branched on
[cocos2d-iphone][2] and licensed under MIT. The master branch on github uses

View File

@ -35,6 +35,7 @@ cocoa/CCSet.cpp \
cocoa/CCString.cpp \
cocoa/CCZone.cpp \
cocoa/CCArray.cpp \
cocoa/CCDataVisitor.cpp \
cocos2d.cpp \
CCDirector.cpp \
draw_nodes/CCDrawingPrimitives.cpp \

View File

@ -326,7 +326,7 @@ CCArray* CCNode::getChildren()
return m_pChildren;
}
unsigned int CCNode::getChildrenCount(void)
unsigned int CCNode::getChildrenCount(void) const
{
return m_pChildren ? m_pChildren->count() : 0;
}
@ -392,7 +392,7 @@ void CCNode::setAnchorPoint(const CCPoint& point)
}
/// contentSize getter
const CCSize& CCNode::getContentSize()
const CCSize& CCNode::getContentSize() const
{
return m_obContentSize;
}
@ -441,7 +441,7 @@ void CCNode::ignoreAnchorPointForPosition(bool newValue)
}
/// tag getter
int CCNode::getTag()
int CCNode::getTag() const
{
return m_nTag;
}

View File

@ -412,7 +412,7 @@ public:
*
* @return The untransformed size of the node.
*/
virtual const CCSize& getContentSize();
virtual const CCSize& getContentSize() const;
/**
@ -608,7 +608,7 @@ public:
*
* @return The amount of children.
*/
unsigned int getChildrenCount(void);
unsigned int getChildrenCount(void) const;
/**
* Sets the parent node
@ -757,7 +757,7 @@ public:
*
* @return A interger that identifies the node.
*/
virtual int getTag();
virtual int getTag() const;
/**
* Changes the tag that is used to identify the node easily.
*

View File

@ -391,4 +391,9 @@ CCObject* CCArray::copyWithZone(CCZone* pZone)
return pArray;
}
void CCArray::acceptVisitor(CCDataVisitor &visitor)
{
visitor.visit(this);
}
NS_CC_END

View File

@ -210,6 +210,9 @@ public:
/* override functions */
virtual CCObject* copyWithZone(CCZone* pZone);
/* override functions */
virtual void acceptVisitor(CCDataVisitor &visitor);
public:
ccArray* data;
CCArray();

View File

@ -50,6 +50,10 @@ public:
}
return pRet;
}
/* override functions */
virtual void acceptVisitor(CCDataVisitor &visitor) { visitor.visit(this); }
private:
bool m_bValue;
};

View File

@ -0,0 +1,227 @@
/****************************************************************************
Copyright (c) 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.
****************************************************************************/
#include "CCObject.h"
#include "CCBool.h"
#include "CCInteger.h"
#include "CCFloat.h"
#include "CCDouble.h"
#include "CCString.h"
#include "CCArray.h"
#include "CCDictionary.h"
#include "CCSet.h"
NS_CC_BEGIN
void CCDataVisitor::visit(const CCBool *value)
{
visitObject(value);
}
void CCDataVisitor::visit(const CCInteger *value)
{
visitObject(value);
}
void CCDataVisitor::visit(const CCFloat *value)
{
visitObject(value);
}
void CCDataVisitor::visit(const CCDouble *value)
{
visitObject(value);
}
void CCDataVisitor::visit(const CCString *value)
{
visitObject(value);
}
void CCDataVisitor::visit(const CCArray *value)
{
visitObject(value);
}
void CCDataVisitor::visit(const CCDictionary *value)
{
visitObject(value);
}
void CCDataVisitor::visit(const CCSet *value)
{
visitObject(value);
}
// CCPrettyPrinter
CCPrettyPrinter::CCPrettyPrinter(int indentLevel/* = 0 */)
{
setIndentLevel(indentLevel);
}
void CCPrettyPrinter::clear()
{
_result.clear();
}
std::string CCPrettyPrinter::getResult()
{
return _result;
}
void CCPrettyPrinter::visitObject(const CCObject *p)
{
char buf[50] = {0};
sprintf(buf, "%p", p);
_result += buf;
}
void CCPrettyPrinter::visit(const CCBool * p)
{
char buf[50] = {0};
sprintf(buf, "%s", p->getValue() ? "true" : "false");
}
void CCPrettyPrinter::visit(const CCInteger *p)
{
char buf[50] = {0};
sprintf(buf, "%d", p->getValue());
_result += buf;
}
void CCPrettyPrinter::visit(const CCFloat *p)
{
char buf[50] = {0};
sprintf(buf, "%f", p->getValue());
_result += buf;
}
void CCPrettyPrinter::visit(const CCDouble *p)
{
char buf[50] = {0};
sprintf(buf, "%lf", p->getValue());
_result += buf;
}
void CCPrettyPrinter::visit(const CCString *p)
{
_result += p->getCString();
}
void CCPrettyPrinter::visit(const CCArray *p)
{
_result += "\n";
_result += _indentStr;
_result += "<array>\n";
setIndentLevel(_indentLevel+1);
CCObject* obj;
int i = 0;
char buf[50] = {0};
CCARRAY_FOREACH(p, obj)
{
if (i > 0) {
_result += "\n";
}
sprintf(buf, "%s%02d: ", _indentStr.c_str(), i);
_result += buf;
CCPrettyPrinter v(_indentLevel);
obj->acceptVisitor(v);
_result += v.getResult();
i++;
}
setIndentLevel(_indentLevel-1);
_result += "\n";
_result += _indentStr;
_result += "</array>";
}
void CCPrettyPrinter::visit(const CCDictionary *p)
{
_result += "\n";
_result += _indentStr;
_result += "<dict>\n";
setIndentLevel(_indentLevel+1);
CCDictElement* element;
bool bFirstElement = true;
char buf[1000] = {0};
CCDICT_FOREACH(p, element)
{
if (!bFirstElement) {
_result += "\n";
}
sprintf(buf, "%s%s: ", _indentStr.c_str(),element->getStrKey());
_result += buf;
CCPrettyPrinter v(_indentLevel);
element->getObject()->acceptVisitor(v);
_result += v.getResult();
bFirstElement = false;
}
setIndentLevel(_indentLevel-1);
_result += "\n";
_result += _indentStr;
_result += "</dict>";
}
void CCPrettyPrinter::visit(const CCSet *p)
{
_result += "\n";
_result += _indentStr;
_result += "<set>\n";
setIndentLevel(_indentLevel+1);
int i = 0;
CCSet* tmp = const_cast<CCSet*>(p);
CCSetIterator it = tmp->begin();
for (; it != tmp->end(); ++it, ++i) {
if (i > 0) {
_result += "\n";
}
_result += _indentStr.c_str();
CCPrettyPrinter v(_indentLevel);
(*it)->acceptVisitor(v);
_result += v.getResult();
}
setIndentLevel(_indentLevel-1);
_result += "\n";
_result += _indentStr;
_result += "</set>\n";
}
void CCPrettyPrinter::setIndentLevel(int indentLevel)
{
_indentLevel = indentLevel;
_indentStr.clear();
for (int i = 0; i < _indentLevel; ++i) {
_indentStr += "\t";
}
}
NS_CC_END

View File

@ -0,0 +1,110 @@
/****************************************************************************
Copyright (c) 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 __CCDATAVISITOR_H__
#define __CCDATAVISITOR_H__
#include "platform/CCPlatformMacros.h"
#include <string>
NS_CC_BEGIN
class CCObject;
class CCBool;
class CCInteger;
class CCFloat;
class CCDouble;
class CCString;
class CCArray;
class CCDictionary;
class CCSet;
/**
* @addtogroup data_structures
* @{
*/
/**
* Visitor that helps to perform action that depends on polymorphic object type
*
* Use cases:
* - data serialization,
* - pretty printing of \a CCObject *
* - safe value reading from \a CCArray, \a CCDictionary, \a CCSet
*
* Usage:
* 1. subclass CCDataVisitor
* 2. overload visit() methods for object that you need to handle
* 3. handle other objects in \a visitObject()
* 4. pass your visitor to \a CCObject::acceptVisitor()
*/
class CC_DLL CCDataVisitor
{
public:
virtual ~CCDataVisitor() {}
/** default method, called from non-overloaded methods and for unrecognized objects */
virtual void visitObject(const CCObject *p) = 0;
virtual void visit(const CCBool *p);
virtual void visit(const CCInteger *p);
virtual void visit(const CCFloat *p);
virtual void visit(const CCDouble *p);
virtual void visit(const CCString *p);
virtual void visit(const CCArray *p);
virtual void visit(const CCDictionary *p);
virtual void visit(const CCSet *p);
};
class CC_DLL CCPrettyPrinter : public CCDataVisitor
{
public:
CCPrettyPrinter(int indentLevel = 0);
virtual void clear();
virtual std::string getResult();
virtual void visitObject(const CCObject *p);
virtual void visit(const CCBool * p);
virtual void visit(const CCInteger *p);
virtual void visit(const CCFloat *p);
virtual void visit(const CCDouble *p);
virtual void visit(const CCString *p);
virtual void visit(const CCArray *p);
virtual void visit(const CCDictionary *p);
virtual void visit(const CCSet *p);
private:
void setIndentLevel(int indentLevel);
int _indentLevel;
std::string _indentStr;
std::string _result;
};
// end of data_structure group
/// @}
NS_CC_END
#endif // __CCDATAVISITOR_H__

View File

@ -408,6 +408,11 @@ CCDictionary* CCDictionary::createWithContentsOfFileThreadSafe(const char *pFile
return CCFileUtils::sharedFileUtils()->createCCDictionaryWithContentsOfFile(pFileName);
}
void CCDictionary::acceptVisitor(CCDataVisitor &visitor)
{
return visitor.visit(this);
}
CCDictionary* CCDictionary::createWithContentsOfFile(const char *pFileName)
{
CCDictionary* pRet = createWithContentsOfFileThreadSafe(pFileName);

View File

@ -382,6 +382,9 @@ public:
*/
static CCDictionary* createWithContentsOfFileThreadSafe(const char *pFileName);
/* override functions */
virtual void acceptVisitor(CCDataVisitor &visitor);
private:
/**
* For internal usage, invoked by setObject.

View File

@ -50,6 +50,10 @@ public:
}
return pRet;
}
/* override functions */
virtual void acceptVisitor(CCDataVisitor &visitor) { visitor.visit(this); }
private:
double m_dValue;
};

View File

@ -50,6 +50,10 @@ public:
}
return pRet;
}
/* override functions */
virtual void acceptVisitor(CCDataVisitor &visitor) { visitor.visit(this); }
private:
float m_fValue;
};

View File

@ -115,4 +115,9 @@ bool CCObject::isEqual(const CCObject *pObject)
return this == pObject;
}
void CCObject::acceptVisitor(CCDataVisitor &visitor)
{
visitor.visitObject(this);
}
NS_CC_END

View File

@ -25,7 +25,7 @@ THE SOFTWARE.
#ifndef __CCOBJECT_H__
#define __CCOBJECT_H__
#include "platform/CCPlatformMacros.h"
#include "CCDataVisitor.h"
#ifdef EMSCRIPTEN
#include <GLES2/gl2.h>
@ -73,6 +73,8 @@ public:
unsigned int retainCount(void) const;
virtual bool isEqual(const CCObject* pObject);
virtual void acceptVisitor(CCDataVisitor &visitor);
virtual void update(float dt) {CC_UNUSED_PARAM(dt);};
friend class CCAutoreleasePool;

View File

@ -56,6 +56,11 @@ CCSet::~CCSet(void)
CC_SAFE_DELETE(m_pSet);
}
void CCSet::acceptVisitor(CCDataVisitor &visitor)
{
visitor.visit(this);
}
CCSet * CCSet::create()
{
CCSet * pRet = new CCSet();

View File

@ -90,6 +90,8 @@ public:
*/
CCObject* anyObject();
virtual void acceptVisitor(CCDataVisitor &visitor);
private:
std::set<CCObject *> *m_pSet;
};

View File

@ -200,4 +200,9 @@ CCString* CCString::createWithContentsOfFile(const char* pszFileName)
return pRet;
}
void CCString::acceptVisitor(CCDataVisitor &visitor)
{
visitor.visit(this);
}
NS_CC_END

View File

@ -109,6 +109,8 @@ public:
*/
static CCString* createWithContentsOfFile(const char* pszFileName);
virtual void acceptVisitor(CCDataVisitor &visitor);
private:
/** only for internal use */

View File

@ -201,7 +201,7 @@ void CCDrawNode::render()
glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, sizeof(ccV2F_C4B_T2F), (GLvoid *)offsetof(ccV2F_C4B_T2F, vertices));
// color
glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_FALSE, sizeof(ccV2F_C4B_T2F), (GLvoid *)offsetof(ccV2F_C4B_T2F, colors));
glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ccV2F_C4B_T2F), (GLvoid *)offsetof(ccV2F_C4B_T2F, colors));
// texcood
glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, sizeof(ccV2F_C4B_T2F), (GLvoid *)offsetof(ccV2F_C4B_T2F, texCoords));

View File

@ -636,8 +636,8 @@ std::string CCFileUtils::fullPathForFilename(const char* pszFileName)
}
}
CCLOG("cocos2d: fullPathForFilename: No file found at %s. Possible missing file.", pszFileName);
//CCLOG("cocos2d: fullPathForFilename: No file found at %s. Possible missing file.", pszFileName);
// The file wasn't found, return the file name passed in.
return pszFileName;
}

View File

@ -24,7 +24,7 @@
#include "platform/CCImage.h"
#include "textures/CCTexture2D.h"
#ifdef __native_client__
#if defined(__native_client__) || defined(EMSCRIPTEN)
// TODO(sbc): I'm pretty sure all platforms should be including
// webph headers in this way.
#include "webp/decode.h"

View File

@ -288,7 +288,12 @@ bool CCImage::_initWithJpgData(void * data, int nSize)
jpeg_mem_src( &cinfo, (unsigned char *) data, nSize );
/* reading the image header which contains image information */
#if (JPEG_LIB_VERSION >= 90)
// libjpeg 0.9 adds stricter types.
jpeg_read_header( &cinfo, TRUE );
#else
jpeg_read_header( &cinfo, true );
#endif
// we only support RGB or grayscale
if (cinfo.jpeg_color_space != JCS_RGB)

View File

@ -28,6 +28,7 @@ THE SOFTWARE.
#include "platform/CCImageCommon_cpp.h"
#include "platform/CCPlatformMacros.h"
#include "platform/CCImage.h"
#include "platform/CCFileUtils.h"
#include "jni/JniHelper.h"
#include <android/log.h>
@ -65,6 +66,17 @@ public:
return false;
}
// Do a full lookup for the font path using CCFileUtils in case the given font name is a relative path to a font file asset,
// or the path has been mapped to a different location in the app package:
std::string fullPathOrFontName = CCFileUtils::sharedFileUtils()->fullPathForFilename(pFontName);
// If the path name returned includes the 'assets' dir then that needs to be removed, because the android.content.Context
// requires this portion of the path to be omitted for assets inside the app package.
if (fullPathOrFontName.find("assets/") == 0)
{
fullPathOrFontName = fullPathOrFontName.substr(strlen("assets/")); // Chop out the 'assets/' portion of the path.
}
/**create bitmap
* this method call Cococs2dx.createBitmap()(java code) to create the bitmap, the java code
* will call Java_org_cocos2dx_lib_Cocos2dxBitmap_nativeInitBitmapDC() to init the width, height
@ -72,7 +84,7 @@ public:
* use this approach to decrease the jni call number
*/
jstring jstrText = methodInfo.env->NewStringUTF(text);
jstring jstrFont = methodInfo.env->NewStringUTF(pFontName);
jstring jstrFont = methodInfo.env->NewStringUTF(fullPathOrFontName.c_str());
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, jstrText,
jstrFont, (int)fontSize, eAlignMask, nWidth, nHeight);

View File

@ -57,7 +57,15 @@ public class Cocos2dxTypefaces {
public static synchronized Typeface get(final Context pContext, final String pAssetName) {
if (!Cocos2dxTypefaces.sTypefaceCache.containsKey(pAssetName)) {
final Typeface typeface = Typeface.createFromAsset(pContext.getAssets(), pAssetName);
Typeface typeface = null;
if (pAssetName.startsWith("/"))
{
typeface = Typeface.createFromFile(pAssetName);
}
else
{
typeface = Typeface.createFromAsset(pContext.getAssets(), pAssetName);
}
Cocos2dxTypefaces.sTypefaceCache.put(pAssetName, typeface);
}

View File

@ -167,8 +167,6 @@ void CCEGLView::release()
m_eglDisplay = EGL_NO_DISPLAY;
}
eglReleaseThread();
m_isGLInitialized = false;
exit(0);

View File

@ -108,7 +108,7 @@ bool OpenGLContext::MakeContextCurrent()
return false;
}
CCLOG("glSetCurrentContextPPAPI: %p", m_graphics3d.pp_resource());
CCLOG("glSetCurrentContextPPAPI: %p", (void*)m_graphics3d.pp_resource());
glSetCurrentContextPPAPI(m_graphics3d.pp_resource());
return true;
}

View File

@ -82,7 +82,7 @@ bool CocosPepperInstance::Init(uint32_t argc, const char* argn[], const char* ar
#ifdef OLD_NACL_MOUNTS
m_runner = new MainThreadRunner(this);
#else
CCLOG("%p %p", pp_instance(), pp::Module::Get()->get_browser_interface());
CCLOG("%p %p", (void*)pp_instance(), (void*)pp::Module::Get()->get_browser_interface());
nacl_io_init_ppapi(pp_instance(), pp::Module::Get()->get_browser_interface());
CCLOG("done nacl_mounts_init_ppapi");

View File

@ -0,0 +1,54 @@
/* jconfig.h. Generated from jconfig.cfg by configure. */
/* jconfig.cfg --- source file edited by configure script */
/* see jconfig.txt for explanations */
#define HAVE_PROTOTYPES 1
#define HAVE_UNSIGNED_CHAR 1
#define HAVE_UNSIGNED_SHORT 1
/* #undef void */
/* #undef const */
/* #undef CHAR_IS_UNSIGNED */
#define HAVE_STDDEF_H 1
#define HAVE_STDLIB_H 1
#define HAVE_LOCALE_H 1
/* #undef NEED_BSD_STRINGS */
/* #undef NEED_SYS_TYPES_H */
/* #undef NEED_FAR_POINTERS */
/* #undef NEED_SHORT_EXTERNAL_NAMES */
/* Define this if you get warnings about undefined structures. */
/* #undef INCOMPLETE_TYPES_BROKEN */
/* Define "boolean" as unsigned char, not int, on Windows systems. */
#ifdef _WIN32
#ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
typedef unsigned char boolean;
#endif
#define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
#endif
#ifdef JPEG_INTERNALS
/* #undef RIGHT_SHIFT_IS_UNSIGNED */
#define INLINE __inline__
/* These are for configuring the JPEG memory manager. */
/* #undef DEFAULT_MAX_MEM */
/* #undef NO_MKTEMP */
#endif /* JPEG_INTERNALS */
#ifdef JPEG_CJPEG_DJPEG
#define BMP_SUPPORTED /* BMP image file format */
#define GIF_SUPPORTED /* GIF image file format */
#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
/* #undef RLE_SUPPORTED */
#define TARGA_SUPPORTED /* Targa image file format */
/* #undef TWO_FILE_COMMANDLINE */
/* #undef NEED_SIGNAL_CATCHER */
/* #undef DONT_USE_B_MODE */
/* Define this if you want percent-done progress reports from cjpeg/djpeg. */
/* #undef PROGRESS_REPORT */
#endif /* JPEG_CJPEG_DJPEG */

View File

@ -0,0 +1,304 @@
/*
* jerror.h
*
* Copyright (C) 1994-1997, Thomas G. Lane.
* Modified 1997-2012 by Guido Vollbeding.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file defines the error and message codes for the JPEG library.
* Edit this file to add new codes, or to translate the message strings to
* some other language.
* A set of error-reporting macros are defined too. Some applications using
* the JPEG library may wish to include this file to get the error codes
* and/or the macros.
*/
/*
* To define the enum list of message codes, include this file without
* defining macro JMESSAGE. To create a message string table, include it
* again with a suitable JMESSAGE definition (see jerror.c for an example).
*/
#ifndef JMESSAGE
#ifndef JERROR_H
/* First time through, define the enum list */
#define JMAKE_ENUM_LIST
#else
/* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
#define JMESSAGE(code,string)
#endif /* JERROR_H */
#endif /* JMESSAGE */
#ifdef JMAKE_ENUM_LIST
typedef enum {
#define JMESSAGE(code,string) code ,
#endif /* JMAKE_ENUM_LIST */
JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
/* For maintenance convenience, list is alphabetical by message code name */
JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
JMESSAGE(JERR_BAD_CROP_SPEC, "Invalid crop request")
JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
JMESSAGE(JERR_BAD_DCTSIZE, "DCT scaled block size %dx%d not supported")
JMESSAGE(JERR_BAD_DROP_SAMPLING,
"Component index %d: mismatching sampling ratio %d:%d, %d:%d, %c")
JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
JMESSAGE(JERR_BAD_LIB_VERSION,
"Wrong JPEG library version: library is %d, caller expects %d")
JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
JMESSAGE(JERR_BAD_PROGRESSION,
"Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
JMESSAGE(JERR_BAD_PROG_SCRIPT,
"Invalid progressive parameters at scan script entry %d")
JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
JMESSAGE(JERR_BAD_STRUCT_SIZE,
"JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
JMESSAGE(JERR_FILE_READ, "Input file read error")
JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
"Cannot transcode due to multiple use of quantization table %d")
JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
JMESSAGE(JERR_NO_ARITH_TABLE, "Arithmetic table 0x%02x was not defined")
JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
JMESSAGE(JERR_QUANT_COMPONENTS,
"Cannot quantize more than %d color components")
JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
JMESSAGE(JERR_SOF_BEFORE, "Invalid JPEG file structure: %s before SOF")
JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
JMESSAGE(JERR_TFILE_WRITE,
"Write failed on temporary file --- out of disk space?")
JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
JMESSAGE(JMSG_VERSION, JVERSION)
JMESSAGE(JTRC_16BIT_TABLES,
"Caution: quantization tables are too coarse for baseline JPEG")
JMESSAGE(JTRC_ADOBE,
"Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
JMESSAGE(JTRC_EOI, "End Of Image")
JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
"Warning: thumbnail image size does not match data length %u")
JMESSAGE(JTRC_JFIF_EXTENSION,
"JFIF extension marker: type 0x%02x, length %u")
JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
JMESSAGE(JTRC_RST, "RST%d")
JMESSAGE(JTRC_SMOOTH_NOTIMPL,
"Smoothing not supported with nonstandard sampling ratios")
JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
JMESSAGE(JTRC_SOI, "Start of Image")
JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
JMESSAGE(JTRC_THUMB_JPEG,
"JFIF extension marker: JPEG-compressed thumbnail image, length %u")
JMESSAGE(JTRC_THUMB_PALETTE,
"JFIF extension marker: palette thumbnail image, length %u")
JMESSAGE(JTRC_THUMB_RGB,
"JFIF extension marker: RGB thumbnail image, length %u")
JMESSAGE(JTRC_UNKNOWN_IDS,
"Unrecognized component IDs %d %d %d, assuming YCbCr")
JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
JMESSAGE(JWRN_ARITH_BAD_CODE, "Corrupt JPEG data: bad arithmetic code")
JMESSAGE(JWRN_BOGUS_PROGRESSION,
"Inconsistent progression sequence for component %d coefficient %d")
JMESSAGE(JWRN_EXTRANEOUS_DATA,
"Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
JMESSAGE(JWRN_MUST_RESYNC,
"Corrupt JPEG data: found marker 0x%02x instead of RST%d")
JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
#ifdef JMAKE_ENUM_LIST
JMSG_LASTMSGCODE
} J_MESSAGE_CODE;
#undef JMAKE_ENUM_LIST
#endif /* JMAKE_ENUM_LIST */
/* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
#undef JMESSAGE
#ifndef JERROR_H
#define JERROR_H
/* Macros to simplify using the error and trace message stuff */
/* The first parameter is either type of cinfo pointer */
/* Fatal errors (print message and exit) */
#define ERREXIT(cinfo,code) \
((cinfo)->err->msg_code = (code), \
(*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
#define ERREXIT1(cinfo,code,p1) \
((cinfo)->err->msg_code = (code), \
(cinfo)->err->msg_parm.i[0] = (p1), \
(*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
#define ERREXIT2(cinfo,code,p1,p2) \
((cinfo)->err->msg_code = (code), \
(cinfo)->err->msg_parm.i[0] = (p1), \
(cinfo)->err->msg_parm.i[1] = (p2), \
(*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
#define ERREXIT3(cinfo,code,p1,p2,p3) \
((cinfo)->err->msg_code = (code), \
(cinfo)->err->msg_parm.i[0] = (p1), \
(cinfo)->err->msg_parm.i[1] = (p2), \
(cinfo)->err->msg_parm.i[2] = (p3), \
(*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
#define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
((cinfo)->err->msg_code = (code), \
(cinfo)->err->msg_parm.i[0] = (p1), \
(cinfo)->err->msg_parm.i[1] = (p2), \
(cinfo)->err->msg_parm.i[2] = (p3), \
(cinfo)->err->msg_parm.i[3] = (p4), \
(*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
#define ERREXIT6(cinfo,code,p1,p2,p3,p4,p5,p6) \
((cinfo)->err->msg_code = (code), \
(cinfo)->err->msg_parm.i[0] = (p1), \
(cinfo)->err->msg_parm.i[1] = (p2), \
(cinfo)->err->msg_parm.i[2] = (p3), \
(cinfo)->err->msg_parm.i[3] = (p4), \
(cinfo)->err->msg_parm.i[4] = (p5), \
(cinfo)->err->msg_parm.i[5] = (p6), \
(*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
#define ERREXITS(cinfo,code,str) \
((cinfo)->err->msg_code = (code), \
strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
(*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
#define MAKESTMT(stuff) do { stuff } while (0)
/* Nonfatal errors (we can keep going, but the data is probably corrupt) */
#define WARNMS(cinfo,code) \
((cinfo)->err->msg_code = (code), \
(*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
#define WARNMS1(cinfo,code,p1) \
((cinfo)->err->msg_code = (code), \
(cinfo)->err->msg_parm.i[0] = (p1), \
(*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
#define WARNMS2(cinfo,code,p1,p2) \
((cinfo)->err->msg_code = (code), \
(cinfo)->err->msg_parm.i[0] = (p1), \
(cinfo)->err->msg_parm.i[1] = (p2), \
(*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
/* Informational/debugging messages */
#define TRACEMS(cinfo,lvl,code) \
((cinfo)->err->msg_code = (code), \
(*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
#define TRACEMS1(cinfo,lvl,code,p1) \
((cinfo)->err->msg_code = (code), \
(cinfo)->err->msg_parm.i[0] = (p1), \
(*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
#define TRACEMS2(cinfo,lvl,code,p1,p2) \
((cinfo)->err->msg_code = (code), \
(cinfo)->err->msg_parm.i[0] = (p1), \
(cinfo)->err->msg_parm.i[1] = (p2), \
(*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
#define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
_mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
(cinfo)->err->msg_code = (code); \
(*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
#define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
_mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
(cinfo)->err->msg_code = (code); \
(*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
#define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
_mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
_mp[4] = (p5); \
(cinfo)->err->msg_code = (code); \
(*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
#define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
_mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
_mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
(cinfo)->err->msg_code = (code); \
(*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
#define TRACEMSS(cinfo,lvl,code,str) \
((cinfo)->err->msg_code = (code), \
strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
(*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
#endif /* JERROR_H */

View File

@ -0,0 +1,390 @@
/*
* jmorecfg.h
*
* Copyright (C) 1991-1997, Thomas G. Lane.
* Modified 1997-2012 by Guido Vollbeding.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains additional configuration options that customize the
* JPEG software for special applications or support machine-dependent
* optimizations. Most users will not need to touch this file.
*/
/*
* Define BITS_IN_JSAMPLE as either
* 8 for 8-bit sample values (the usual setting)
* 12 for 12-bit sample values
* Only 8 and 12 are legal data precisions for lossy JPEG according to the
* JPEG standard, and the IJG code does not support anything else!
* We do not support run-time selection of data precision, sorry.
*/
#define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
/*
* Maximum number of components (color channels) allowed in JPEG image.
* To meet the letter of the JPEG spec, set this to 255. However, darn
* few applications need more than 4 channels (maybe 5 for CMYK + alpha
* mask). We recommend 10 as a reasonable compromise; use 4 if you are
* really short on memory. (Each allowed component costs a hundred or so
* bytes of storage, whether actually used in an image or not.)
*/
#define MAX_COMPONENTS 10 /* maximum number of image components */
/*
* Basic data types.
* You may need to change these if you have a machine with unusual data
* type sizes; for example, "char" not 8 bits, "short" not 16 bits,
* or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
* but it had better be at least 16.
*/
/* Representation of a single sample (pixel element value).
* We frequently allocate large arrays of these, so it's important to keep
* them small. But if you have memory to burn and access to char or short
* arrays is very slow on your hardware, you might want to change these.
*/
#if BITS_IN_JSAMPLE == 8
/* JSAMPLE should be the smallest type that will hold the values 0..255.
* You can use a signed char by having GETJSAMPLE mask it with 0xFF.
*/
#ifdef HAVE_UNSIGNED_CHAR
typedef unsigned char JSAMPLE;
#define GETJSAMPLE(value) ((int) (value))
#else /* not HAVE_UNSIGNED_CHAR */
typedef char JSAMPLE;
#ifdef CHAR_IS_UNSIGNED
#define GETJSAMPLE(value) ((int) (value))
#else
#define GETJSAMPLE(value) ((int) (value) & 0xFF)
#endif /* CHAR_IS_UNSIGNED */
#endif /* HAVE_UNSIGNED_CHAR */
#define MAXJSAMPLE 255
#define CENTERJSAMPLE 128
#endif /* BITS_IN_JSAMPLE == 8 */
#if BITS_IN_JSAMPLE == 12
/* JSAMPLE should be the smallest type that will hold the values 0..4095.
* On nearly all machines "short" will do nicely.
*/
typedef short JSAMPLE;
#define GETJSAMPLE(value) ((int) (value))
#define MAXJSAMPLE 4095
#define CENTERJSAMPLE 2048
#endif /* BITS_IN_JSAMPLE == 12 */
/* Representation of a DCT frequency coefficient.
* This should be a signed value of at least 16 bits; "short" is usually OK.
* Again, we allocate large arrays of these, but you can change to int
* if you have memory to burn and "short" is really slow.
*/
typedef short JCOEF;
/* Compressed datastreams are represented as arrays of JOCTET.
* These must be EXACTLY 8 bits wide, at least once they are written to
* external storage. Note that when using the stdio data source/destination
* managers, this is also the data type passed to fread/fwrite.
*/
#ifdef HAVE_UNSIGNED_CHAR
typedef unsigned char JOCTET;
#define GETJOCTET(value) (value)
#else /* not HAVE_UNSIGNED_CHAR */
typedef char JOCTET;
#ifdef CHAR_IS_UNSIGNED
#define GETJOCTET(value) (value)
#else
#define GETJOCTET(value) ((value) & 0xFF)
#endif /* CHAR_IS_UNSIGNED */
#endif /* HAVE_UNSIGNED_CHAR */
/* These typedefs are used for various table entries and so forth.
* They must be at least as wide as specified; but making them too big
* won't cost a huge amount of memory, so we don't provide special
* extraction code like we did for JSAMPLE. (In other words, these
* typedefs live at a different point on the speed/space tradeoff curve.)
*/
/* UINT8 must hold at least the values 0..255. */
#ifdef HAVE_UNSIGNED_CHAR
typedef unsigned char UINT8;
#else /* not HAVE_UNSIGNED_CHAR */
#ifdef CHAR_IS_UNSIGNED
typedef char UINT8;
#else /* not CHAR_IS_UNSIGNED */
typedef short UINT8;
#endif /* CHAR_IS_UNSIGNED */
#endif /* HAVE_UNSIGNED_CHAR */
/* UINT16 must hold at least the values 0..65535. */
#ifdef HAVE_UNSIGNED_SHORT
typedef unsigned short UINT16;
#else /* not HAVE_UNSIGNED_SHORT */
typedef unsigned int UINT16;
#endif /* HAVE_UNSIGNED_SHORT */
/* INT16 must hold at least the values -32768..32767. */
#ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
typedef short INT16;
#endif
/* INT32 must hold at least signed 32-bit values. */
#ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
#ifndef _BASETSD_H_ /* Microsoft defines it in basetsd.h */
#ifndef _BASETSD_H /* MinGW is slightly different */
#ifndef QGLOBAL_H /* Qt defines it in qglobal.h */
typedef long INT32;
#endif
#endif
#endif
#endif
/* Datatype used for image dimensions. The JPEG standard only supports
* images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
* "unsigned int" is sufficient on all machines. However, if you need to
* handle larger images and you don't mind deviating from the spec, you
* can change this datatype.
*/
typedef unsigned int JDIMENSION;
#define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
/* These macros are used in all function definitions and extern declarations.
* You could modify them if you need to change function linkage conventions;
* in particular, you'll need to do that to make the library a Windows DLL.
* Another application is to make all functions global for use with debuggers
* or code profilers that require it.
*/
/* a function called through method pointers: */
#define METHODDEF(type) static type
/* a function used only in its module: */
#define LOCAL(type) static type
/* a function referenced thru EXTERNs: */
#define GLOBAL(type) type
/* a reference to a GLOBAL function: */
#define EXTERN(type) extern type
/* This macro is used to declare a "method", that is, a function pointer.
* We want to supply prototype parameters if the compiler can cope.
* Note that the arglist parameter must be parenthesized!
* Again, you can customize this if you need special linkage keywords.
*/
#ifdef HAVE_PROTOTYPES
#define JMETHOD(type,methodname,arglist) type (*methodname) arglist
#else
#define JMETHOD(type,methodname,arglist) type (*methodname) ()
#endif
/* The noreturn type identifier is used to declare functions
* which cannot return.
* Compilers can thus create more optimized code and perform
* better checks for warnings and errors.
* Static analyzer tools can make improved inferences about
* execution paths and are prevented from giving false alerts.
*
* Unfortunately, the proposed specifications of corresponding
* extensions in the Dec 2011 ISO C standard revision (C11),
* GCC, MSVC, etc. are not viable.
* Thus we introduce a user defined type to declare noreturn
* functions at least for clarity. A proper compiler would
* have a suitable noreturn type to match in place of void.
*/
#ifndef HAVE_NORETURN_T
typedef void noreturn_t;
#endif
/* Here is the pseudo-keyword for declaring pointers that must be "far"
* on 80x86 machines. Most of the specialized coding for 80x86 is handled
* by just saying "FAR *" where such a pointer is needed. In a few places
* explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
*/
#ifndef FAR
#ifdef NEED_FAR_POINTERS
#define FAR far
#else
#define FAR
#endif
#endif
/*
* On a few systems, type boolean and/or its values FALSE, TRUE may appear
* in standard header files. Or you may have conflicts with application-
* specific header files that you want to include together with these files.
* Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
*/
#ifdef HAVE_BOOLEAN
#ifndef FALSE /* in case these macros already exist */
#define FALSE 0 /* values of boolean */
#endif
#ifndef TRUE
#define TRUE 1
#endif
#else
typedef enum { FALSE = 0, TRUE = 1 } boolean;
#endif
/*
* The remaining options affect code selection within the JPEG library,
* but they don't need to be visible to most applications using the library.
* To minimize application namespace pollution, the symbols won't be
* defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
*/
#ifdef JPEG_INTERNALS
#define JPEG_INTERNAL_OPTIONS
#endif
#ifdef JPEG_INTERNAL_OPTIONS
/*
* These defines indicate whether to include various optional functions.
* Undefining some of these symbols will produce a smaller but less capable
* library. Note that you can leave certain source files out of the
* compilation/linking process if you've #undef'd the corresponding symbols.
* (You may HAVE to do that if your compiler doesn't like null source files.)
*/
/* Capability options common to encoder and decoder: */
#define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
#define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
#define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
/* Encoder capability options: */
#define C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
#define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
#define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
#define DCT_SCALING_SUPPORTED /* Input rescaling via DCT? (Requires DCT_ISLOW)*/
#define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
/* Note: if you selected 12-bit data precision, it is dangerous to turn off
* ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
* precision, so jchuff.c normally uses entropy optimization to compute
* usable tables for higher precision. If you don't want to do optimization,
* you'll have to supply different default Huffman tables.
* The exact same statements apply for progressive JPEG: the default tables
* don't work for progressive mode. (This may get fixed, however.)
*/
#define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
/* Decoder capability options: */
#define D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
#define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
#define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
#define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
#define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
#define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
#undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
#define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
#define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
#define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
/* more capability options later, no doubt */
/*
* Ordering of RGB data in scanlines passed to or from the application.
* If your application wants to deal with data in the order B,G,R, just
* change these macros. You can also deal with formats such as R,G,B,X
* (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
* the offsets will also change the order in which colormap data is organized.
* RESTRICTIONS:
* 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
* 2. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
* is not 3 (they don't understand about dummy color components!). So you
* can't use color quantization if you change that value.
*/
#define RGB_RED 0 /* Offset of Red in an RGB scanline element */
#define RGB_GREEN 1 /* Offset of Green */
#define RGB_BLUE 2 /* Offset of Blue */
#define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
/* Definitions for speed-related optimizations. */
/* If your compiler supports inline functions, define INLINE
* as the inline keyword; otherwise define it as empty.
*/
#ifndef INLINE
#ifdef __GNUC__ /* for instance, GNU C knows about inline */
#define INLINE __inline__
#endif
#ifndef INLINE
#define INLINE /* default is to define it as empty */
#endif
#endif
/* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
* two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
* as short on such a machine. MULTIPLIER must be at least 16 bits wide.
*/
#ifndef MULTIPLIER
#define MULTIPLIER int /* type for fastest integer multiply */
#endif
/* FAST_FLOAT should be either float or double, whichever is done faster
* by your compiler. (Note that this type is only used in the floating point
* DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
* Typically, float is faster in ANSI C compilers, while double is faster in
* pre-ANSI compilers (because they insist on converting to double anyway).
* The code below therefore chooses float if we have ANSI-style prototypes.
*/
#ifndef FAST_FLOAT
#ifdef HAVE_PROTOTYPES
#define FAST_FLOAT float
#else
#define FAST_FLOAT double
#endif
#endif
#endif /* JPEG_INTERNAL_OPTIONS */

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,6 @@
libfreetype.a from Emscripten test-suite
libpng.a from https://github.com/hachque-Emscripten/libpng-1.2.49.git
libz.a from https://github.com/hachque-Emscripten/zlib-1.2.5.git
libxml2.z from https://github.com/kripken/xml.js -- configure flags: emconfigure ./configure --with-http=no --with-ftp=no --prefix=/tmp/lx --with-python=no --with-threads=no
libxml2.a from https://github.com/kripken/xml.js -- configure flags: emconfigure ./configure --with-http=no --with-ftp=no --prefix=/tmp/lx --with-python=no --with-threads=no
libwebp.a from https://code.google.com/p/webp/downloads/detail?name=libwebp-0.3.0.tar.gz -- configure with ./configure --disable-threading --prefix=/tmp/libwebp

View File

@ -0,0 +1 @@
aae3f71d9c2edfe0ea1879a923faf2f656791de1

View File

@ -0,0 +1 @@
1bb3fc4bf9525afd8919ad7493e76dd208f48064

View File

@ -0,0 +1,482 @@
// Copyright 2010 Google Inc. All Rights Reserved.
//
// This code is licensed under the same terms as WebM:
// Software License Agreement: http://www.webmproject.org/license/software/
// Additional IP Rights Grant: http://www.webmproject.org/license/additional/
// -----------------------------------------------------------------------------
//
// Main decoding functions for WebP images.
//
// Author: Skal (pascal.massimino@gmail.com)
#ifndef WEBP_WEBP_DECODE_H_
#define WEBP_WEBP_DECODE_H_
#include "./types.h"
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
#define WEBP_DECODER_ABI_VERSION 0x0201 // MAJOR(8b) + MINOR(8b)
typedef struct WebPRGBABuffer WebPRGBABuffer;
typedef struct WebPYUVABuffer WebPYUVABuffer;
typedef struct WebPDecBuffer WebPDecBuffer;
#if !(defined(__cplusplus) || defined(c_plusplus))
typedef enum VP8StatusCode VP8StatusCode;
typedef enum WEBP_CSP_MODE WEBP_CSP_MODE;
#endif
typedef struct WebPIDecoder WebPIDecoder;
typedef struct WebPBitstreamFeatures WebPBitstreamFeatures;
typedef struct WebPDecoderOptions WebPDecoderOptions;
typedef struct WebPDecoderConfig WebPDecoderConfig;
// Return the decoder's version number, packed in hexadecimal using 8bits for
// each of major/minor/revision. E.g: v2.5.7 is 0x020507.
WEBP_EXTERN(int) WebPGetDecoderVersion(void);
// Retrieve basic header information: width, height.
// This function will also validate the header and return 0 in
// case of formatting error.
// Pointers 'width' and 'height' can be passed NULL if deemed irrelevant.
WEBP_EXTERN(int) WebPGetInfo(const uint8_t* data, size_t data_size,
int* width, int* height);
// Decodes WebP images pointed to by 'data' and returns RGBA samples, along
// with the dimensions in *width and *height. The ordering of samples in
// memory is R, G, B, A, R, G, B, A... in scan order (endian-independent).
// The returned pointer should be deleted calling free().
// Returns NULL in case of error.
WEBP_EXTERN(uint8_t*) WebPDecodeRGBA(const uint8_t* data, size_t data_size,
int* width, int* height);
// Same as WebPDecodeRGBA, but returning A, R, G, B, A, R, G, B... ordered data.
WEBP_EXTERN(uint8_t*) WebPDecodeARGB(const uint8_t* data, size_t data_size,
int* width, int* height);
// Same as WebPDecodeRGBA, but returning B, G, R, A, B, G, R, A... ordered data.
WEBP_EXTERN(uint8_t*) WebPDecodeBGRA(const uint8_t* data, size_t data_size,
int* width, int* height);
// Same as WebPDecodeRGBA, but returning R, G, B, R, G, B... ordered data.
// If the bitstream contains transparency, it is ignored.
WEBP_EXTERN(uint8_t*) WebPDecodeRGB(const uint8_t* data, size_t data_size,
int* width, int* height);
// Same as WebPDecodeRGB, but returning B, G, R, B, G, R... ordered data.
WEBP_EXTERN(uint8_t*) WebPDecodeBGR(const uint8_t* data, size_t data_size,
int* width, int* height);
// Decode WebP images pointed to by 'data' to Y'UV format(*). The pointer
// returned is the Y samples buffer. Upon return, *u and *v will point to
// the U and V chroma data. These U and V buffers need NOT be free()'d,
// unlike the returned Y luma one. The dimension of the U and V planes
// are both (*width + 1) / 2 and (*height + 1)/ 2.
// Upon return, the Y buffer has a stride returned as '*stride', while U and V
// have a common stride returned as '*uv_stride'.
// Return NULL in case of error.
// (*) Also named Y'CbCr. See: http://en.wikipedia.org/wiki/YCbCr
WEBP_EXTERN(uint8_t*) WebPDecodeYUV(const uint8_t* data, size_t data_size,
int* width, int* height,
uint8_t** u, uint8_t** v,
int* stride, int* uv_stride);
// These five functions are variants of the above ones, that decode the image
// directly into a pre-allocated buffer 'output_buffer'. The maximum storage
// available in this buffer is indicated by 'output_buffer_size'. If this
// storage is not sufficient (or an error occurred), NULL is returned.
// Otherwise, output_buffer is returned, for convenience.
// The parameter 'output_stride' specifies the distance (in bytes)
// between scanlines. Hence, output_buffer_size is expected to be at least
// output_stride x picture-height.
WEBP_EXTERN(uint8_t*) WebPDecodeRGBAInto(
const uint8_t* data, size_t data_size,
uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
WEBP_EXTERN(uint8_t*) WebPDecodeARGBInto(
const uint8_t* data, size_t data_size,
uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
WEBP_EXTERN(uint8_t*) WebPDecodeBGRAInto(
const uint8_t* data, size_t data_size,
uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
// RGB and BGR variants. Here too the transparency information, if present,
// will be dropped and ignored.
WEBP_EXTERN(uint8_t*) WebPDecodeRGBInto(
const uint8_t* data, size_t data_size,
uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
WEBP_EXTERN(uint8_t*) WebPDecodeBGRInto(
const uint8_t* data, size_t data_size,
uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
// WebPDecodeYUVInto() is a variant of WebPDecodeYUV() that operates directly
// into pre-allocated luma/chroma plane buffers. This function requires the
// strides to be passed: one for the luma plane and one for each of the
// chroma ones. The size of each plane buffer is passed as 'luma_size',
// 'u_size' and 'v_size' respectively.
// Pointer to the luma plane ('*luma') is returned or NULL if an error occurred
// during decoding (or because some buffers were found to be too small).
WEBP_EXTERN(uint8_t*) WebPDecodeYUVInto(
const uint8_t* data, size_t data_size,
uint8_t* luma, size_t luma_size, int luma_stride,
uint8_t* u, size_t u_size, int u_stride,
uint8_t* v, size_t v_size, int v_stride);
//------------------------------------------------------------------------------
// Output colorspaces and buffer
// Colorspaces
// Note: the naming describes the byte-ordering of packed samples in memory.
// For instance, MODE_BGRA relates to samples ordered as B,G,R,A,B,G,R,A,...
// Non-capital names (e.g.:MODE_Argb) relates to pre-multiplied RGB channels.
// RGBA-4444 and RGB-565 colorspaces are represented by following byte-order:
// RGBA-4444: [r3 r2 r1 r0 g3 g2 g1 g0], [b3 b2 b1 b0 a3 a2 a1 a0], ...
// RGB-565: [r4 r3 r2 r1 r0 g5 g4 g3], [g2 g1 g0 b4 b3 b2 b1 b0], ...
// In the case WEBP_SWAP_16BITS_CSP is defined, the bytes are swapped for
// these two modes:
// RGBA-4444: [b3 b2 b1 b0 a3 a2 a1 a0], [r3 r2 r1 r0 g3 g2 g1 g0], ...
// RGB-565: [g2 g1 g0 b4 b3 b2 b1 b0], [r4 r3 r2 r1 r0 g5 g4 g3], ...
enum WEBP_CSP_MODE {
MODE_RGB = 0, MODE_RGBA = 1,
MODE_BGR = 2, MODE_BGRA = 3,
MODE_ARGB = 4, MODE_RGBA_4444 = 5,
MODE_RGB_565 = 6,
// RGB-premultiplied transparent modes (alpha value is preserved)
MODE_rgbA = 7,
MODE_bgrA = 8,
MODE_Argb = 9,
MODE_rgbA_4444 = 10,
// YUV modes must come after RGB ones.
MODE_YUV = 11, MODE_YUVA = 12, // yuv 4:2:0
MODE_LAST = 13
};
// Some useful macros:
static WEBP_INLINE int WebPIsPremultipliedMode(WEBP_CSP_MODE mode) {
return (mode == MODE_rgbA || mode == MODE_bgrA || mode == MODE_Argb ||
mode == MODE_rgbA_4444);
}
static WEBP_INLINE int WebPIsAlphaMode(WEBP_CSP_MODE mode) {
return (mode == MODE_RGBA || mode == MODE_BGRA || mode == MODE_ARGB ||
mode == MODE_RGBA_4444 || mode == MODE_YUVA ||
WebPIsPremultipliedMode(mode));
}
static WEBP_INLINE int WebPIsRGBMode(WEBP_CSP_MODE mode) {
return (mode < MODE_YUV);
}
//------------------------------------------------------------------------------
// WebPDecBuffer: Generic structure for describing the output sample buffer.
struct WebPRGBABuffer { // view as RGBA
uint8_t* rgba; // pointer to RGBA samples
int stride; // stride in bytes from one scanline to the next.
size_t size; // total size of the *rgba buffer.
};
struct WebPYUVABuffer { // view as YUVA
uint8_t* y, *u, *v, *a; // pointer to luma, chroma U/V, alpha samples
int y_stride; // luma stride
int u_stride, v_stride; // chroma strides
int a_stride; // alpha stride
size_t y_size; // luma plane size
size_t u_size, v_size; // chroma planes size
size_t a_size; // alpha-plane size
};
// Output buffer
struct WebPDecBuffer {
WEBP_CSP_MODE colorspace; // Colorspace.
int width, height; // Dimensions.
int is_external_memory; // If true, 'internal_memory' pointer is not used.
union {
WebPRGBABuffer RGBA;
WebPYUVABuffer YUVA;
} u; // Nameless union of buffer parameters.
uint32_t pad[4]; // padding for later use
uint8_t* private_memory; // Internally allocated memory (only when
// is_external_memory is false). Should not be used
// externally, but accessed via the buffer union.
};
// Internal, version-checked, entry point
WEBP_EXTERN(int) WebPInitDecBufferInternal(WebPDecBuffer*, int);
// Initialize the structure as empty. Must be called before any other use.
// Returns false in case of version mismatch
static WEBP_INLINE int WebPInitDecBuffer(WebPDecBuffer* buffer) {
return WebPInitDecBufferInternal(buffer, WEBP_DECODER_ABI_VERSION);
}
// Free any memory associated with the buffer. Must always be called last.
// Note: doesn't free the 'buffer' structure itself.
WEBP_EXTERN(void) WebPFreeDecBuffer(WebPDecBuffer* buffer);
//------------------------------------------------------------------------------
// Enumeration of the status codes
enum VP8StatusCode {
VP8_STATUS_OK = 0,
VP8_STATUS_OUT_OF_MEMORY,
VP8_STATUS_INVALID_PARAM,
VP8_STATUS_BITSTREAM_ERROR,
VP8_STATUS_UNSUPPORTED_FEATURE,
VP8_STATUS_SUSPENDED,
VP8_STATUS_USER_ABORT,
VP8_STATUS_NOT_ENOUGH_DATA
};
//------------------------------------------------------------------------------
// Incremental decoding
//
// This API allows streamlined decoding of partial data.
// Picture can be incrementally decoded as data become available thanks to the
// WebPIDecoder object. This object can be left in a SUSPENDED state if the
// picture is only partially decoded, pending additional input.
// Code example:
//
// WebPInitDecBuffer(&buffer);
// buffer.colorspace = mode;
// ...
// WebPIDecoder* idec = WebPINewDecoder(&buffer);
// while (has_more_data) {
// // ... (get additional data)
// status = WebPIAppend(idec, new_data, new_data_size);
// if (status != VP8_STATUS_SUSPENDED ||
// break;
// }
//
// // The above call decodes the current available buffer.
// // Part of the image can now be refreshed by calling to
// // WebPIDecGetRGB()/WebPIDecGetYUVA() etc.
// }
// WebPIDelete(idec);
// Creates a new incremental decoder with the supplied buffer parameter.
// This output_buffer can be passed NULL, in which case a default output buffer
// is used (with MODE_RGB). Otherwise, an internal reference to 'output_buffer'
// is kept, which means that the lifespan of 'output_buffer' must be larger than
// that of the returned WebPIDecoder object.
// Returns NULL if the allocation failed.
WEBP_EXTERN(WebPIDecoder*) WebPINewDecoder(WebPDecBuffer* output_buffer);
// This function allocates and initializes an incremental-decoder object, which
// will output the RGB/A samples specified by 'csp' into a preallocated
// buffer 'output_buffer'. The size of this buffer is at least
// 'output_buffer_size' and the stride (distance in bytes between two scanlines)
// is specified by 'output_stride'.
// Additionally, output_buffer can be passed NULL in which case the output
// buffer will be allocated automatically when the decoding starts. The
// colorspace 'csp' is taken into account for allocating this buffer. All other
// parameters are ignored.
// Returns NULL if the allocation failed, or if some parameters are invalid.
WEBP_EXTERN(WebPIDecoder*) WebPINewRGB(
WEBP_CSP_MODE csp,
uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
// This function allocates and initializes an incremental-decoder object, which
// will output the raw luma/chroma samples into a preallocated planes if
// supplied. The luma plane is specified by its pointer 'luma', its size
// 'luma_size' and its stride 'luma_stride'. Similarly, the chroma-u plane
// is specified by the 'u', 'u_size' and 'u_stride' parameters, and the chroma-v
// plane by 'v' and 'v_size'. And same for the alpha-plane. The 'a' pointer
// can be pass NULL in case one is not interested in the transparency plane.
// Conversely, 'luma' can be passed NULL if no preallocated planes are supplied.
// In this case, the output buffer will be automatically allocated (using
// MODE_YUVA) when decoding starts. All parameters are then ignored.
// Returns NULL if the allocation failed or if a parameter is invalid.
WEBP_EXTERN(WebPIDecoder*) WebPINewYUVA(
uint8_t* luma, size_t luma_size, int luma_stride,
uint8_t* u, size_t u_size, int u_stride,
uint8_t* v, size_t v_size, int v_stride,
uint8_t* a, size_t a_size, int a_stride);
// Deprecated version of the above, without the alpha plane.
// Kept for backward compatibility.
WEBP_EXTERN(WebPIDecoder*) WebPINewYUV(
uint8_t* luma, size_t luma_size, int luma_stride,
uint8_t* u, size_t u_size, int u_stride,
uint8_t* v, size_t v_size, int v_stride);
// Deletes the WebPIDecoder object and associated memory. Must always be called
// if WebPINewDecoder, WebPINewRGB or WebPINewYUV succeeded.
WEBP_EXTERN(void) WebPIDelete(WebPIDecoder* idec);
// Copies and decodes the next available data. Returns VP8_STATUS_OK when
// the image is successfully decoded. Returns VP8_STATUS_SUSPENDED when more
// data is expected. Returns error in other cases.
WEBP_EXTERN(VP8StatusCode) WebPIAppend(
WebPIDecoder* idec, const uint8_t* data, size_t data_size);
// A variant of the above function to be used when data buffer contains
// partial data from the beginning. In this case data buffer is not copied
// to the internal memory.
// Note that the value of the 'data' pointer can change between calls to
// WebPIUpdate, for instance when the data buffer is resized to fit larger data.
WEBP_EXTERN(VP8StatusCode) WebPIUpdate(
WebPIDecoder* idec, const uint8_t* data, size_t data_size);
// Returns the RGB/A image decoded so far. Returns NULL if output params
// are not initialized yet. The RGB/A output type corresponds to the colorspace
// specified during call to WebPINewDecoder() or WebPINewRGB().
// *last_y is the index of last decoded row in raster scan order. Some pointers
// (*last_y, *width etc.) can be NULL if corresponding information is not
// needed.
WEBP_EXTERN(uint8_t*) WebPIDecGetRGB(
const WebPIDecoder* idec, int* last_y,
int* width, int* height, int* stride);
// Same as above function to get a YUVA image. Returns pointer to the luma
// plane or NULL in case of error. If there is no alpha information
// the alpha pointer '*a' will be returned NULL.
WEBP_EXTERN(uint8_t*) WebPIDecGetYUVA(
const WebPIDecoder* idec, int* last_y,
uint8_t** u, uint8_t** v, uint8_t** a,
int* width, int* height, int* stride, int* uv_stride, int* a_stride);
// Deprecated alpha-less version of WebPIDecGetYUVA(): it will ignore the
// alpha information (if present). Kept for backward compatibility.
static WEBP_INLINE uint8_t* WebPIDecGetYUV(
const WebPIDecoder* idec, int* last_y, uint8_t** u, uint8_t** v,
int* width, int* height, int* stride, int* uv_stride) {
return WebPIDecGetYUVA(idec, last_y, u, v, NULL, width, height,
stride, uv_stride, NULL);
}
// Generic call to retrieve information about the displayable area.
// If non NULL, the left/right/width/height pointers are filled with the visible
// rectangular area so far.
// Returns NULL in case the incremental decoder object is in an invalid state.
// Otherwise returns the pointer to the internal representation. This structure
// is read-only, tied to WebPIDecoder's lifespan and should not be modified.
WEBP_EXTERN(const WebPDecBuffer*) WebPIDecodedArea(
const WebPIDecoder* idec, int* left, int* top, int* width, int* height);
//------------------------------------------------------------------------------
// Advanced decoding parametrization
//
// Code sample for using the advanced decoding API
/*
// A) Init a configuration object
WebPDecoderConfig config;
CHECK(WebPInitDecoderConfig(&config));
// B) optional: retrieve the bitstream's features.
CHECK(WebPGetFeatures(data, data_size, &config.input) == VP8_STATUS_OK);
// C) Adjust 'config', if needed
config.no_fancy_upsampling = 1;
config.output.colorspace = MODE_BGRA;
// etc.
// Note that you can also make config.output point to an externally
// supplied memory buffer, provided it's big enough to store the decoded
// picture. Otherwise, config.output will just be used to allocate memory
// and store the decoded picture.
// D) Decode!
CHECK(WebPDecode(data, data_size, &config) == VP8_STATUS_OK);
// E) Decoded image is now in config.output (and config.output.u.RGBA)
// F) Reclaim memory allocated in config's object. It's safe to call
// this function even if the memory is external and wasn't allocated
// by WebPDecode().
WebPFreeDecBuffer(&config.output);
*/
// Features gathered from the bitstream
struct WebPBitstreamFeatures {
int width; // Width in pixels, as read from the bitstream.
int height; // Height in pixels, as read from the bitstream.
int has_alpha; // True if the bitstream contains an alpha channel.
int has_animation; // True if the bitstream is an animation.
// Unused for now:
int bitstream_version; // should be 0 for now. TODO(later)
int no_incremental_decoding; // if true, using incremental decoding is not
// recommended.
int rotate; // TODO(later)
int uv_sampling; // should be 0 for now. TODO(later)
uint32_t pad[2]; // padding for later use
};
// Internal, version-checked, entry point
WEBP_EXTERN(VP8StatusCode) WebPGetFeaturesInternal(
const uint8_t*, size_t, WebPBitstreamFeatures*, int);
// Retrieve features from the bitstream. The *features structure is filled
// with information gathered from the bitstream.
// Returns VP8_STATUS_OK when the features are successfully retrieved. Returns
// VP8_STATUS_NOT_ENOUGH_DATA when more data is needed to retrieve the
// features from headers. Returns error in other cases.
static WEBP_INLINE VP8StatusCode WebPGetFeatures(
const uint8_t* data, size_t data_size,
WebPBitstreamFeatures* features) {
return WebPGetFeaturesInternal(data, data_size, features,
WEBP_DECODER_ABI_VERSION);
}
// Decoding options
struct WebPDecoderOptions {
int bypass_filtering; // if true, skip the in-loop filtering
int no_fancy_upsampling; // if true, use faster pointwise upsampler
int use_cropping; // if true, cropping is applied _first_
int crop_left, crop_top; // top-left position for cropping.
// Will be snapped to even values.
int crop_width, crop_height; // dimension of the cropping area
int use_scaling; // if true, scaling is applied _afterward_
int scaled_width, scaled_height; // final resolution
int use_threads; // if true, use multi-threaded decoding
// Unused for now:
int force_rotation; // forced rotation (to be applied _last_)
int no_enhancement; // if true, discard enhancement layer
uint32_t pad[6]; // padding for later use
};
// Main object storing the configuration for advanced decoding.
struct WebPDecoderConfig {
WebPBitstreamFeatures input; // Immutable bitstream features (optional)
WebPDecBuffer output; // Output buffer (can point to external mem)
WebPDecoderOptions options; // Decoding options
};
// Internal, version-checked, entry point
WEBP_EXTERN(int) WebPInitDecoderConfigInternal(WebPDecoderConfig*, int);
// Initialize the configuration as empty. This function must always be
// called first, unless WebPGetFeatures() is to be called.
// Returns false in case of mismatched version.
static WEBP_INLINE int WebPInitDecoderConfig(WebPDecoderConfig* config) {
return WebPInitDecoderConfigInternal(config, WEBP_DECODER_ABI_VERSION);
}
// Instantiate a new incremental decoder object with the requested
// configuration. The bitstream can be passed using 'data' and 'data_size'
// parameter, in which case the features will be parsed and stored into
// config->input. Otherwise, 'data' can be NULL and no parsing will occur.
// Note that 'config' can be NULL too, in which case a default configuration
// is used.
// The return WebPIDecoder object must always be deleted calling WebPIDelete().
// Returns NULL in case of error (and config->status will then reflect
// the error condition).
WEBP_EXTERN(WebPIDecoder*) WebPIDecode(const uint8_t* data, size_t data_size,
WebPDecoderConfig* config);
// Non-incremental version. This version decodes the full data at once, taking
// 'config' into account. Returns decoding status (which should be VP8_STATUS_OK
// if the decoding was successful).
WEBP_EXTERN(VP8StatusCode) WebPDecode(const uint8_t* data, size_t data_size,
WebPDecoderConfig* config);
#if defined(__cplusplus) || defined(c_plusplus)
} // extern "C"
#endif
#endif /* WEBP_WEBP_DECODE_H_ */

View File

@ -0,0 +1,480 @@
// Copyright 2011 Google Inc. All Rights Reserved.
//
// This code is licensed under the same terms as WebM:
// Software License Agreement: http://www.webmproject.org/license/software/
// Additional IP Rights Grant: http://www.webmproject.org/license/additional/
// -----------------------------------------------------------------------------
//
// WebP encoder: main interface
//
// Author: Skal (pascal.massimino@gmail.com)
#ifndef WEBP_WEBP_ENCODE_H_
#define WEBP_WEBP_ENCODE_H_
#include "./types.h"
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
#define WEBP_ENCODER_ABI_VERSION 0x0201 // MAJOR(8b) + MINOR(8b)
#if !(defined(__cplusplus) || defined(c_plusplus))
typedef enum WebPImageHint WebPImageHint;
typedef enum WebPEncCSP WebPEncCSP;
typedef enum WebPPreset WebPPreset;
typedef enum WebPEncodingError WebPEncodingError;
#endif
typedef struct WebPConfig WebPConfig;
typedef struct WebPPicture WebPPicture; // main structure for I/O
typedef struct WebPAuxStats WebPAuxStats;
typedef struct WebPMemoryWriter WebPMemoryWriter;
// Return the encoder's version number, packed in hexadecimal using 8bits for
// each of major/minor/revision. E.g: v2.5.7 is 0x020507.
WEBP_EXTERN(int) WebPGetEncoderVersion(void);
//------------------------------------------------------------------------------
// One-stop-shop call! No questions asked:
// Returns the size of the compressed data (pointed to by *output), or 0 if
// an error occurred. The compressed data must be released by the caller
// using the call 'free(*output)'.
// These functions compress using the lossy format, and the quality_factor
// can go from 0 (smaller output, lower quality) to 100 (best quality,
// larger output).
WEBP_EXTERN(size_t) WebPEncodeRGB(const uint8_t* rgb,
int width, int height, int stride,
float quality_factor, uint8_t** output);
WEBP_EXTERN(size_t) WebPEncodeBGR(const uint8_t* bgr,
int width, int height, int stride,
float quality_factor, uint8_t** output);
WEBP_EXTERN(size_t) WebPEncodeRGBA(const uint8_t* rgba,
int width, int height, int stride,
float quality_factor, uint8_t** output);
WEBP_EXTERN(size_t) WebPEncodeBGRA(const uint8_t* bgra,
int width, int height, int stride,
float quality_factor, uint8_t** output);
// These functions are the equivalent of the above, but compressing in a
// lossless manner. Files are usually larger than lossy format, but will
// not suffer any compression loss.
WEBP_EXTERN(size_t) WebPEncodeLosslessRGB(const uint8_t* rgb,
int width, int height, int stride,
uint8_t** output);
WEBP_EXTERN(size_t) WebPEncodeLosslessBGR(const uint8_t* bgr,
int width, int height, int stride,
uint8_t** output);
WEBP_EXTERN(size_t) WebPEncodeLosslessRGBA(const uint8_t* rgba,
int width, int height, int stride,
uint8_t** output);
WEBP_EXTERN(size_t) WebPEncodeLosslessBGRA(const uint8_t* bgra,
int width, int height, int stride,
uint8_t** output);
//------------------------------------------------------------------------------
// Coding parameters
// Image characteristics hint for the underlying encoder.
enum WebPImageHint {
WEBP_HINT_DEFAULT = 0, // default preset.
WEBP_HINT_PICTURE, // digital picture, like portrait, inner shot
WEBP_HINT_PHOTO, // outdoor photograph, with natural lighting
WEBP_HINT_GRAPH, // Discrete tone image (graph, map-tile etc).
WEBP_HINT_LAST
};
// Compression parameters.
struct WebPConfig {
int lossless; // Lossless encoding (0=lossy(default), 1=lossless).
float quality; // between 0 (smallest file) and 100 (biggest)
int method; // quality/speed trade-off (0=fast, 6=slower-better)
WebPImageHint image_hint; // Hint for image type (lossless only for now).
// Parameters related to lossy compression only:
int target_size; // if non-zero, set the desired target size in bytes.
// Takes precedence over the 'compression' parameter.
float target_PSNR; // if non-zero, specifies the minimal distortion to
// try to achieve. Takes precedence over target_size.
int segments; // maximum number of segments to use, in [1..4]
int sns_strength; // Spatial Noise Shaping. 0=off, 100=maximum.
int filter_strength; // range: [0 = off .. 100 = strongest]
int filter_sharpness; // range: [0 = off .. 7 = least sharp]
int filter_type; // filtering type: 0 = simple, 1 = strong (only used
// if filter_strength > 0 or autofilter > 0)
int autofilter; // Auto adjust filter's strength [0 = off, 1 = on]
int alpha_compression; // Algorithm for encoding the alpha plane (0 = none,
// 1 = compressed with WebP lossless). Default is 1.
int alpha_filtering; // Predictive filtering method for alpha plane.
// 0: none, 1: fast, 2: best. Default if 1.
int alpha_quality; // Between 0 (smallest size) and 100 (lossless).
// Default is 100.
int pass; // number of entropy-analysis passes (in [1..10]).
int show_compressed; // if true, export the compressed picture back.
// In-loop filtering is not applied.
int preprocessing; // preprocessing filter (0=none, 1=segment-smooth)
int partitions; // log2(number of token partitions) in [0..3]. Default
// is set to 0 for easier progressive decoding.
int partition_limit; // quality degradation allowed to fit the 512k limit
// on prediction modes coding (0: no degradation,
// 100: maximum possible degradation).
int emulate_jpeg_size; // If true, compression parameters will be remapped
// to better match the expected output size from
// JPEG compression. Generally, the output size will
// be similar but the degradation will be lower.
int thread_level; // If non-zero, try and use multi-threaded encoding.
int low_memory; // If set, reduce memory usage (but increase CPU use).
uint32_t pad[5]; // padding for later use
};
// Enumerate some predefined settings for WebPConfig, depending on the type
// of source picture. These presets are used when calling WebPConfigPreset().
enum WebPPreset {
WEBP_PRESET_DEFAULT = 0, // default preset.
WEBP_PRESET_PICTURE, // digital picture, like portrait, inner shot
WEBP_PRESET_PHOTO, // outdoor photograph, with natural lighting
WEBP_PRESET_DRAWING, // hand or line drawing, with high-contrast details
WEBP_PRESET_ICON, // small-sized colorful images
WEBP_PRESET_TEXT // text-like
};
// Internal, version-checked, entry point
WEBP_EXTERN(int) WebPConfigInitInternal(WebPConfig*, WebPPreset, float, int);
// Should always be called, to initialize a fresh WebPConfig structure before
// modification. Returns false in case of version mismatch. WebPConfigInit()
// must have succeeded before using the 'config' object.
// Note that the default values are lossless=0 and quality=75.
static WEBP_INLINE int WebPConfigInit(WebPConfig* config) {
return WebPConfigInitInternal(config, WEBP_PRESET_DEFAULT, 75.f,
WEBP_ENCODER_ABI_VERSION);
}
// This function will initialize the configuration according to a predefined
// set of parameters (referred to by 'preset') and a given quality factor.
// This function can be called as a replacement to WebPConfigInit(). Will
// return false in case of error.
static WEBP_INLINE int WebPConfigPreset(WebPConfig* config,
WebPPreset preset, float quality) {
return WebPConfigInitInternal(config, preset, quality,
WEBP_ENCODER_ABI_VERSION);
}
// Returns true if 'config' is non-NULL and all configuration parameters are
// within their valid ranges.
WEBP_EXTERN(int) WebPValidateConfig(const WebPConfig* config);
//------------------------------------------------------------------------------
// Input / Output
// Structure for storing auxiliary statistics (mostly for lossy encoding).
struct WebPAuxStats {
int coded_size; // final size
float PSNR[5]; // peak-signal-to-noise ratio for Y/U/V/All/Alpha
int block_count[3]; // number of intra4/intra16/skipped macroblocks
int header_bytes[2]; // approximate number of bytes spent for header
// and mode-partition #0
int residual_bytes[3][4]; // approximate number of bytes spent for
// DC/AC/uv coefficients for each (0..3) segments.
int segment_size[4]; // number of macroblocks in each segments
int segment_quant[4]; // quantizer values for each segments
int segment_level[4]; // filtering strength for each segments [0..63]
int alpha_data_size; // size of the transparency data
int layer_data_size; // size of the enhancement layer data
// lossless encoder statistics
uint32_t lossless_features; // bit0:predictor bit1:cross-color transform
// bit2:subtract-green bit3:color indexing
int histogram_bits; // number of precision bits of histogram
int transform_bits; // precision bits for transform
int cache_bits; // number of bits for color cache lookup
int palette_size; // number of color in palette, if used
int lossless_size; // final lossless size
uint32_t pad[4]; // padding for later use
};
// Signature for output function. Should return true if writing was successful.
// data/data_size is the segment of data to write, and 'picture' is for
// reference (and so one can make use of picture->custom_ptr).
typedef int (*WebPWriterFunction)(const uint8_t* data, size_t data_size,
const WebPPicture* picture);
// WebPMemoryWrite: a special WebPWriterFunction that writes to memory using
// the following WebPMemoryWriter object (to be set as a custom_ptr).
struct WebPMemoryWriter {
uint8_t* mem; // final buffer (of size 'max_size', larger than 'size').
size_t size; // final size
size_t max_size; // total capacity
uint32_t pad[1]; // padding for later use
};
// The following must be called first before any use.
WEBP_EXTERN(void) WebPMemoryWriterInit(WebPMemoryWriter* writer);
// The custom writer to be used with WebPMemoryWriter as custom_ptr. Upon
// completion, writer.mem and writer.size will hold the coded data.
// writer.mem must be freed using the call 'free(writer.mem)'.
WEBP_EXTERN(int) WebPMemoryWrite(const uint8_t* data, size_t data_size,
const WebPPicture* picture);
// Progress hook, called from time to time to report progress. It can return
// false to request an abort of the encoding process, or true otherwise if
// everything is OK.
typedef int (*WebPProgressHook)(int percent, const WebPPicture* picture);
// Color spaces.
enum WebPEncCSP {
// chroma sampling
WEBP_YUV420 = 0, // 4:2:0
WEBP_YUV422 = 1, // 4:2:2
WEBP_YUV444 = 2, // 4:4:4
WEBP_YUV400 = 3, // grayscale
WEBP_CSP_UV_MASK = 3, // bit-mask to get the UV sampling factors
// alpha channel variants
WEBP_YUV420A = 4,
WEBP_YUV422A = 5,
WEBP_YUV444A = 6,
WEBP_YUV400A = 7, // grayscale + alpha
WEBP_CSP_ALPHA_BIT = 4 // bit that is set if alpha is present
};
// Encoding error conditions.
enum WebPEncodingError {
VP8_ENC_OK = 0,
VP8_ENC_ERROR_OUT_OF_MEMORY, // memory error allocating objects
VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY, // memory error while flushing bits
VP8_ENC_ERROR_NULL_PARAMETER, // a pointer parameter is NULL
VP8_ENC_ERROR_INVALID_CONFIGURATION, // configuration is invalid
VP8_ENC_ERROR_BAD_DIMENSION, // picture has invalid width/height
VP8_ENC_ERROR_PARTITION0_OVERFLOW, // partition is bigger than 512k
VP8_ENC_ERROR_PARTITION_OVERFLOW, // partition is bigger than 16M
VP8_ENC_ERROR_BAD_WRITE, // error while flushing bytes
VP8_ENC_ERROR_FILE_TOO_BIG, // file is bigger than 4G
VP8_ENC_ERROR_USER_ABORT, // abort request by user
VP8_ENC_ERROR_LAST // list terminator. always last.
};
// maximum width/height allowed (inclusive), in pixels
#define WEBP_MAX_DIMENSION 16383
// Main exchange structure (input samples, output bytes, statistics)
struct WebPPicture {
// INPUT
//////////////
// Main flag for encoder selecting between ARGB or YUV input.
// It is recommended to use ARGB input (*argb, argb_stride) for lossless
// compression, and YUV input (*y, *u, *v, etc.) for lossy compression
// since these are the respective native colorspace for these formats.
int use_argb;
// YUV input (mostly used for input to lossy compression)
WebPEncCSP colorspace; // colorspace: should be YUV420 for now (=Y'CbCr).
int width, height; // dimensions (less or equal to WEBP_MAX_DIMENSION)
uint8_t *y, *u, *v; // pointers to luma/chroma planes.
int y_stride, uv_stride; // luma/chroma strides.
uint8_t* a; // pointer to the alpha plane
int a_stride; // stride of the alpha plane
uint32_t pad1[2]; // padding for later use
// ARGB input (mostly used for input to lossless compression)
uint32_t* argb; // Pointer to argb (32 bit) plane.
int argb_stride; // This is stride in pixels units, not bytes.
uint32_t pad2[3]; // padding for later use
// OUTPUT
///////////////
// Byte-emission hook, to store compressed bytes as they are ready.
WebPWriterFunction writer; // can be NULL
void* custom_ptr; // can be used by the writer.
// map for extra information (only for lossy compression mode)
int extra_info_type; // 1: intra type, 2: segment, 3: quant
// 4: intra-16 prediction mode,
// 5: chroma prediction mode,
// 6: bit cost, 7: distortion
uint8_t* extra_info; // if not NULL, points to an array of size
// ((width + 15) / 16) * ((height + 15) / 16) that
// will be filled with a macroblock map, depending
// on extra_info_type.
// STATS AND REPORTS
///////////////////////////
// Pointer to side statistics (updated only if not NULL)
WebPAuxStats* stats;
// Error code for the latest error encountered during encoding
WebPEncodingError error_code;
// If not NULL, report progress during encoding.
WebPProgressHook progress_hook;
void* user_data; // this field is free to be set to any value and
// used during callbacks (like progress-report e.g.).
uint32_t pad3[3]; // padding for later use
// Unused for now: original samples (for non-YUV420 modes)
uint8_t *u0, *v0;
int uv0_stride;
uint32_t pad4[7]; // padding for later use
// PRIVATE FIELDS
////////////////////
void* memory_; // row chunk of memory for yuva planes
void* memory_argb_; // and for argb too.
void* pad5[2]; // padding for later use
};
// Internal, version-checked, entry point
WEBP_EXTERN(int) WebPPictureInitInternal(WebPPicture*, int);
// Should always be called, to initialize the structure. Returns false in case
// of version mismatch. WebPPictureInit() must have succeeded before using the
// 'picture' object.
// Note that, by default, use_argb is false and colorspace is WEBP_YUV420.
static WEBP_INLINE int WebPPictureInit(WebPPicture* picture) {
return WebPPictureInitInternal(picture, WEBP_ENCODER_ABI_VERSION);
}
//------------------------------------------------------------------------------
// WebPPicture utils
// Convenience allocation / deallocation based on picture->width/height:
// Allocate y/u/v buffers as per colorspace/width/height specification.
// Note! This function will free the previous buffer if needed.
// Returns false in case of memory error.
WEBP_EXTERN(int) WebPPictureAlloc(WebPPicture* picture);
// Release the memory allocated by WebPPictureAlloc() or WebPPictureImport*().
// Note that this function does _not_ free the memory used by the 'picture'
// object itself.
// Besides memory (which is reclaimed) all other fields of 'picture' are
// preserved.
WEBP_EXTERN(void) WebPPictureFree(WebPPicture* picture);
// Copy the pixels of *src into *dst, using WebPPictureAlloc. Upon return,
// *dst will fully own the copied pixels (this is not a view).
// Returns false in case of memory allocation error.
WEBP_EXTERN(int) WebPPictureCopy(const WebPPicture* src, WebPPicture* dst);
// Compute PSNR, SSIM or LSIM distortion metric between two pictures.
// Result is in dB, stores in result[] in the Y/U/V/Alpha/All order.
// Returns false in case of error (src and ref don't have same dimension, ...)
// Warning: this function is rather CPU-intensive.
WEBP_EXTERN(int) WebPPictureDistortion(
const WebPPicture* src, const WebPPicture* ref,
int metric_type, // 0 = PSNR, 1 = SSIM, 2 = LSIM
float result[5]);
// self-crops a picture to the rectangle defined by top/left/width/height.
// Returns false in case of memory allocation error, or if the rectangle is
// outside of the source picture.
// The rectangle for the view is defined by the top-left corner pixel
// coordinates (left, top) as well as its width and height. This rectangle
// must be fully be comprised inside the 'src' source picture. If the source
// picture uses the YUV420 colorspace, the top and left coordinates will be
// snapped to even values.
WEBP_EXTERN(int) WebPPictureCrop(WebPPicture* picture,
int left, int top, int width, int height);
// Extracts a view from 'src' picture into 'dst'. The rectangle for the view
// is defined by the top-left corner pixel coordinates (left, top) as well
// as its width and height. This rectangle must be fully be comprised inside
// the 'src' source picture. If the source picture uses the YUV420 colorspace,
// the top and left coordinates will be snapped to even values.
// Picture 'src' must out-live 'dst' picture. Self-extraction of view is allowed
// ('src' equal to 'dst') as a mean of fast-cropping (but note that doing so,
// the original dimension will be lost).
// Returns false in case of memory allocation error or invalid parameters.
WEBP_EXTERN(int) WebPPictureView(const WebPPicture* src,
int left, int top, int width, int height,
WebPPicture* dst);
// Returns true if the 'picture' is actually a view and therefore does
// not own the memory for pixels.
WEBP_EXTERN(int) WebPPictureIsView(const WebPPicture* picture);
// Rescale a picture to new dimension width x height.
// Now gamma correction is applied.
// Returns false in case of error (invalid parameter or insufficient memory).
WEBP_EXTERN(int) WebPPictureRescale(WebPPicture* pic, int width, int height);
// Colorspace conversion function to import RGB samples.
// Previous buffer will be free'd, if any.
// *rgb buffer should have a size of at least height * rgb_stride.
// Returns false in case of memory error.
WEBP_EXTERN(int) WebPPictureImportRGB(
WebPPicture* picture, const uint8_t* rgb, int rgb_stride);
// Same, but for RGBA buffer.
WEBP_EXTERN(int) WebPPictureImportRGBA(
WebPPicture* picture, const uint8_t* rgba, int rgba_stride);
// Same, but for RGBA buffer. Imports the RGB direct from the 32-bit format
// input buffer ignoring the alpha channel. Avoids needing to copy the data
// to a temporary 24-bit RGB buffer to import the RGB only.
WEBP_EXTERN(int) WebPPictureImportRGBX(
WebPPicture* picture, const uint8_t* rgbx, int rgbx_stride);
// Variants of the above, but taking BGR(A|X) input.
WEBP_EXTERN(int) WebPPictureImportBGR(
WebPPicture* picture, const uint8_t* bgr, int bgr_stride);
WEBP_EXTERN(int) WebPPictureImportBGRA(
WebPPicture* picture, const uint8_t* bgra, int bgra_stride);
WEBP_EXTERN(int) WebPPictureImportBGRX(
WebPPicture* picture, const uint8_t* bgrx, int bgrx_stride);
// Converts picture->argb data to the YUVA format specified by 'colorspace'.
// Upon return, picture->use_argb is set to false. The presence of real
// non-opaque transparent values is detected, and 'colorspace' will be
// adjusted accordingly. Note that this method is lossy.
// Returns false in case of error.
WEBP_EXTERN(int) WebPPictureARGBToYUVA(WebPPicture* picture,
WebPEncCSP colorspace);
// Converts picture->yuv to picture->argb and sets picture->use_argb to true.
// The input format must be YUV_420 or YUV_420A.
// Note that the use of this method is discouraged if one has access to the
// raw ARGB samples, since using YUV420 is comparatively lossy. Also, the
// conversion from YUV420 to ARGB incurs a small loss too.
// Returns false in case of error.
WEBP_EXTERN(int) WebPPictureYUVAToARGB(WebPPicture* picture);
// Helper function: given a width x height plane of YUV(A) samples
// (with stride 'stride'), clean-up the YUV samples under fully transparent
// area, to help compressibility (no guarantee, though).
WEBP_EXTERN(void) WebPCleanupTransparentArea(WebPPicture* picture);
// Scan the picture 'picture' for the presence of non fully opaque alpha values.
// Returns true in such case. Otherwise returns false (indicating that the
// alpha plane can be ignored altogether e.g.).
WEBP_EXTERN(int) WebPPictureHasTransparency(const WebPPicture* picture);
//------------------------------------------------------------------------------
// Main call
// Main encoding call, after config and picture have been initialized.
// 'picture' must be less than 16384x16384 in dimension (cf WEBP_MAX_DIMENSION),
// and the 'config' object must be a valid one.
// Returns false in case of error, true otherwise.
// In case of error, picture->error_code is updated accordingly.
// 'picture' can hold the source samples in both YUV(A) or ARGB input, depending
// on the value of 'picture->use_argb'. It is highly recommended to use
// the former for lossy encoding, and the latter for lossless encoding
// (when config.lossless is true). Automatic conversion from one format to
// another is provided but they both incur some loss.
WEBP_EXTERN(int) WebPEncode(const WebPConfig* config, WebPPicture* picture);
//------------------------------------------------------------------------------
#if defined(__cplusplus) || defined(c_plusplus)
} // extern "C"
#endif
#endif /* WEBP_WEBP_ENCODE_H_ */

View File

@ -0,0 +1,45 @@
// Copyright 2010 Google Inc. All Rights Reserved.
//
// This code is licensed under the same terms as WebM:
// Software License Agreement: http://www.webmproject.org/license/software/
// Additional IP Rights Grant: http://www.webmproject.org/license/additional/
// -----------------------------------------------------------------------------
//
// Common types
//
// Author: Skal (pascal.massimino@gmail.com)
#ifndef WEBP_WEBP_TYPES_H_
#define WEBP_WEBP_TYPES_H_
#include <stddef.h> // for size_t
#ifndef _MSC_VER
#include <inttypes.h>
#ifdef __STRICT_ANSI__
#define WEBP_INLINE
#else /* __STRICT_ANSI__ */
#define WEBP_INLINE inline
#endif
#else
typedef signed char int8_t;
typedef unsigned char uint8_t;
typedef signed short int16_t;
typedef unsigned short uint16_t;
typedef signed int int32_t;
typedef unsigned int uint32_t;
typedef unsigned long long int uint64_t;
typedef long long int int64_t;
#define WEBP_INLINE __forceinline
#endif /* _MSC_VER */
#ifndef WEBP_EXTERN
// This explicitly marks library functions and allows for changing the
// signature for e.g., Windows DLL builds.
#define WEBP_EXTERN(type) extern type
#endif /* WEBP_EXTERN */
// Macro to check ABI compatibility (same major revision number)
#define WEBP_ABI_IS_INCOMPATIBLE(a, b) (((a) >> 8) != ((b) >> 8))
#endif /* WEBP_WEBP_TYPES_H_ */

View File

@ -693,9 +693,9 @@ void CCEGLView::centerWindow()
}
GetWindowRect(m_hWnd, &rcWindow);
int offsetX = (rcDesktop.right - rcDesktop.left - (rcWindow.right - rcWindow.left)) / 2;
int offsetX = rcDesktop.left + (rcDesktop.right - rcDesktop.left - (rcWindow.right - rcWindow.left)) / 2;
offsetX = (offsetX > 0) ? offsetX : rcDesktop.left;
int offsetY = (rcDesktop.bottom - rcDesktop.top - (rcWindow.bottom - rcWindow.top)) / 2;
int offsetY = rcDesktop.top + (rcDesktop.bottom - rcDesktop.top - (rcWindow.bottom - rcWindow.top)) / 2;
offsetY = (offsetY > 0) ? offsetY : rcDesktop.top;
SetWindowPos(m_hWnd, 0, offsetX, offsetY, 0, 0, SWP_NOCOPYBITS | SWP_NOSIZE | SWP_NOOWNERZORDER | SWP_NOZORDER);

View File

@ -38,6 +38,7 @@ SOURCES = ../actions/CCAction.cpp \
../cocoa/CCArray.cpp \
../cocoa/CCDictionary.cpp \
../cocoa/CCString.cpp \
../cocoa/CCDataVisitor.cpp \
../draw_nodes/CCDrawingPrimitives.cpp \
../draw_nodes/CCDrawNode.cpp \
../effects/CCGrabber.cpp \

View File

@ -35,8 +35,8 @@ INCLUDES += \
-I$(COCOS_SRC)/platform/third_party/emscripten/libz \
-I$(COCOS_SRC)/platform/third_party/emscripten/libfreetype2 \
-I$(COCOS_SRC)/platform/third_party/emscripten/libtiff/include \
-I$(COCOS_SRC)/platform/third_party/linux/libjpeg \
-I$(COCOS_SRC)/platform/third_party/linux/libwebp
-I$(COCOS_SRC)/platform/third_party/emscripten/libjpeg \
-I$(COCOS_SRC)/platform/third_party/emscripten/libwebp
LBITS := $(shell getconf LONG_BIT)
INCLUDES += -I$(COCOS_SRC)/platform/third_party/linux
@ -49,8 +49,8 @@ OBJ_DIR := $(OBJ_DIR)/debug
LIB_DIR := $(LIB_DIR)/debug
BIN_DIR := $(BIN_DIR)/debug
else
CCFLAGS += -O2 --jcache -s GL_UNSAFE_OPTS=0
CXXFLAGS += -O2 --jcache -s GL_UNSAFE_OPTS=0
CCFLAGS += -O2 --jcache -s GL_UNSAFE_OPTS=0 -s ASM_JS=1
CXXFLAGS += -O2 --jcache -s GL_UNSAFE_OPTS=0 -s ASM_JS=1
DEFINES += -DNDEBUG -DCP_USE_DOUBLES=0
OBJ_DIR := $(OBJ_DIR)/release
LIB_DIR := $(LIB_DIR)/release
@ -77,7 +77,7 @@ STATICLIBS_DIR = $(COCOS_SRC)/platform/third_party/emscripten/libraries
STATICLIBS = $(STATICLIBS_DIR)/libfreetype.a \
$(STATICLIBS_DIR)/libpng.a \
$(STATICLIBS_DIR)/zlib.a \
$(STATICLIBS_DIR)/libtiff.a #\
$(STATICLIBS_DIR)/libtiff.a \
$(STATICLIBS_DIR)/libjpeg.a \
$(STATICLIBS_DIR)/libwebp.a

View File

@ -1 +1 @@
ab1a108831dfdc88ca340350536987da48bccfdc
89741f647de6b40616d5c45625fcd3c2d8e9d20a

View File

@ -34,6 +34,7 @@ SOURCES = ../actions/CCAction.cpp \
../cocoa/CCArray.cpp \
../cocoa/CCDictionary.cpp \
../cocoa/CCString.cpp \
../cocoa/CCDataVisitor.cpp \
../draw_nodes/CCDrawingPrimitives.cpp \
../draw_nodes/CCDrawNode.cpp \
../effects/CCGrabber.cpp \

View File

@ -1 +1 @@
593eeddbb616c30af1167e9add361f1cd8e7996e
703f1f571cf577296708f26a90de6288773b8db5

View File

@ -34,6 +34,7 @@ SOURCES = ../actions/CCAction.cpp \
../cocoa/CCArray.cpp \
../cocoa/CCDictionary.cpp \
../cocoa/CCString.cpp \
../cocoa/CCDataVisitor.cpp \
../draw_nodes/CCDrawingPrimitives.cpp \
../draw_nodes/CCDrawNode.cpp \
../effects/CCGrabber.cpp \

View File

@ -144,6 +144,7 @@ xcopy /Y /Q "$(ProjectDir)..\platform\third_party\win32\libraries\*.*" "$(OutDir
<ClCompile Include="..\cocoa\CCAffineTransform.cpp" />
<ClCompile Include="..\cocoa\CCArray.cpp" />
<ClCompile Include="..\cocoa\CCAutoreleasePool.cpp" />
<ClCompile Include="..\cocoa\CCDataVisitor.cpp" />
<ClCompile Include="..\cocoa\CCDictionary.cpp" />
<ClCompile Include="..\cocoa\CCGeometry.cpp" />
<ClCompile Include="..\cocoa\CCNS.cpp" />
@ -268,7 +269,11 @@ xcopy /Y /Q "$(ProjectDir)..\platform\third_party\win32\libraries\*.*" "$(OutDir
<ClInclude Include="..\cocoa\CCAffineTransform.h" />
<ClInclude Include="..\cocoa\CCArray.h" />
<ClInclude Include="..\cocoa\CCAutoreleasePool.h" />
<ClInclude Include="..\cocoa\CCBool.h" />
<ClInclude Include="..\cocoa\CCDataVisitor.h" />
<ClInclude Include="..\cocoa\CCDictionary.h" />
<ClInclude Include="..\cocoa\CCDouble.h" />
<ClInclude Include="..\cocoa\CCFloat.h" />
<ClInclude Include="..\cocoa\CCGeometry.h" />
<ClInclude Include="..\cocoa\CCInteger.h" />
<ClInclude Include="..\cocoa\CCNS.h" />

View File

@ -458,6 +458,9 @@
<ClCompile Include="..\support\tinyxml2\tinyxml2.cpp">
<Filter>support\tinyxml2</Filter>
</ClCompile>
<ClCompile Include="..\cocoa\CCDataVisitor.cpp">
<Filter>cocoa</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\base_nodes\CCAtlasNode.h">
@ -914,5 +917,17 @@
<ClInclude Include="..\support\tinyxml2\tinyxml2.h">
<Filter>support\tinyxml2</Filter>
</ClInclude>
<ClInclude Include="..\cocoa\CCDataVisitor.h">
<Filter>cocoa</Filter>
</ClInclude>
<ClInclude Include="..\cocoa\CCBool.h">
<Filter>cocoa</Filter>
</ClInclude>
<ClInclude Include="..\cocoa\CCDouble.h">
<Filter>cocoa</Filter>
</ClInclude>
<ClInclude Include="..\cocoa\CCFloat.h">
<Filter>cocoa</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -101,12 +101,12 @@ void ccArrayShrink(ccArray *arr)
unsigned int ccArrayGetIndexOfObject(ccArray *arr, CCObject* object)
{
const unsigned int arrNum = arr->num;
const CCObject* ptr = arr->arr[0];
CCObject** ptr = arr->arr;
for(unsigned int i = 0; i < arrNum; ++i, ++ptr)
{
if( ptr == object ) return i;
if( *ptr == object ) return i;
}
return CC_INVALID_INDEX;
}

View File

@ -1,26 +1,26 @@
/****************************************************************************
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.
****************************************************************************/
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 <zlib.h>
#include <assert.h>
#include <stdlib.h>
@ -33,8 +33,96 @@ THE SOFTWARE.
NS_CC_BEGIN
unsigned int ZipUtils::s_uEncryptedPvrKeyParts[4] = {0,0,0,0};
unsigned int ZipUtils::s_uEncryptionKey[1024];
bool ZipUtils::s_bEncryptionKeyIsValid = false;
// --------------------- ZipUtils ---------------------
inline void ZipUtils::ccDecodeEncodedPvr(unsigned int *data, int len)
{
const int enclen = 1024;
const int securelen = 512;
const int distance = 64;
// check if key was set
// make sure to call caw_setkey_part() for all 4 key parts
CCAssert(s_uEncryptedPvrKeyParts[0] != 0, "Cocos2D: CCZ file is encrypted but key part 0 is not set. Did you call ZipUtils::ccSetPvrEncryptionKeyPart(...)?");
CCAssert(s_uEncryptedPvrKeyParts[1] != 0, "Cocos2D: CCZ file is encrypted but key part 1 is not set. Did you call ZipUtils::ccSetPvrEncryptionKeyPart(...)?");
CCAssert(s_uEncryptedPvrKeyParts[2] != 0, "Cocos2D: CCZ file is encrypted but key part 2 is not set. Did you call ZipUtils::ccSetPvrEncryptionKeyPart(...)?");
CCAssert(s_uEncryptedPvrKeyParts[3] != 0, "Cocos2D: CCZ file is encrypted but key part 3 is not set. Did you call ZipUtils::ccSetPvrEncryptionKeyPart(...)?");
// create long key
if(!s_bEncryptionKeyIsValid)
{
unsigned int y, p, e;
unsigned int rounds = 6;
unsigned int sum = 0;
unsigned int z = s_uEncryptionKey[enclen-1];
do
{
#define DELTA 0x9e3779b9
#define MX (((z>>5^y<<2) + (y>>3^z<<4)) ^ ((sum^y) + (s_uEncryptedPvrKeyParts[(p&3)^e] ^ z)))
sum += DELTA;
e = (sum >> 2) & 3;
for (p = 0; p < enclen - 1; p++)
{
y = s_uEncryptionKey[p + 1];
z = s_uEncryptionKey[p] += MX;
}
y = s_uEncryptionKey[0];
z = s_uEncryptionKey[enclen - 1] += MX;
} while (--rounds);
s_bEncryptionKeyIsValid = true;
}
int b = 0;
int i = 0;
// encrypt first part completely
for(; i < len && i < securelen; i++)
{
data[i] ^= s_uEncryptionKey[b++];
if(b >= enclen)
{
b = 0;
}
}
// encrypt second section partially
for(; i < len; i += distance)
{
data[i] ^= s_uEncryptionKey[b++];
if(b >= enclen)
{
b = 0;
}
}
}
inline unsigned int ZipUtils::ccChecksumPvr(const unsigned int *data, int len)
{
unsigned int cs = 0;
const int cslen = 128;
len = (len < cslen) ? len : cslen;
for(int i = 0; i < len; i++)
{
cs = cs ^ data[i];
}
return cs;
}
// memory in iPhone is precious
// Should buffer factor be 1.5 instead of 2 ?
#define BUFFER_INC_FACTOR (2)
@ -43,63 +131,63 @@ int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength,
{
/* ret value */
int err = Z_OK;
int bufferSize = outLenghtHint;
*out = new unsigned char[bufferSize];
z_stream d_stream; /* decompression stream */
z_stream d_stream; /* decompression stream */
d_stream.zalloc = (alloc_func)0;
d_stream.zfree = (free_func)0;
d_stream.opaque = (voidpf)0;
d_stream.next_in = in;
d_stream.avail_in = inLength;
d_stream.next_out = *out;
d_stream.avail_out = bufferSize;
/* window size to hold 256k */
if( (err = inflateInit2(&d_stream, 15 + 32)) != Z_OK )
return err;
for (;;)
for (;;)
{
err = inflate(&d_stream, Z_NO_FLUSH);
if (err == Z_STREAM_END)
{
break;
}
switch (err)
switch (err)
{
case Z_NEED_DICT:
err = Z_DATA_ERROR;
case Z_DATA_ERROR:
case Z_MEM_ERROR:
inflateEnd(&d_stream);
return err;
case Z_NEED_DICT:
err = Z_DATA_ERROR;
case Z_DATA_ERROR:
case Z_MEM_ERROR:
inflateEnd(&d_stream);
return err;
}
// not enough memory ?
if (err != Z_STREAM_END)
if (err != Z_STREAM_END)
{
delete [] *out;
*out = new unsigned char[bufferSize * BUFFER_INC_FACTOR];
/* not enough memory, ouch */
if (! *out )
if (! *out )
{
CCLOG("cocos2d: ZipUtils: realloc failed");
inflateEnd(&d_stream);
return Z_MEM_ERROR;
}
d_stream.next_out = *out + bufferSize;
d_stream.avail_out = bufferSize;
bufferSize *= BUFFER_INC_FACTOR;
}
}
*outLength = bufferSize - d_stream.avail_out;
err = inflateEnd(&d_stream);
return err;
@ -109,30 +197,30 @@ int ZipUtils::ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength,
{
unsigned int outLength = 0;
int err = ccInflateMemoryWithHint(in, inLength, out, &outLength, outLengthHint);
if (err != Z_OK || *out == NULL) {
if (err == Z_MEM_ERROR)
{
CCLOG("cocos2d: ZipUtils: Out of memory while decompressing map data!");
} else
if (err == Z_VERSION_ERROR)
{
CCLOG("cocos2d: ZipUtils: Incompatible zlib version!");
} else
if (err == Z_DATA_ERROR)
{
CCLOG("cocos2d: ZipUtils: Incorrect zlib compressed data!");
}
else
{
CCLOG("cocos2d: ZipUtils: Unknown error while decompressing map data!");
}
} else
if (err == Z_VERSION_ERROR)
{
CCLOG("cocos2d: ZipUtils: Incompatible zlib version!");
} else
if (err == Z_DATA_ERROR)
{
CCLOG("cocos2d: ZipUtils: Incorrect zlib compressed data!");
}
else
{
CCLOG("cocos2d: ZipUtils: Unknown error while decompressing map data!");
}
delete[] *out;
*out = NULL;
outLength = 0;
}
return outLength;
}
@ -146,30 +234,30 @@ int ZipUtils::ccInflateGZipFile(const char *path, unsigned char **out)
{
int len;
unsigned int offset = 0;
CCAssert(out, "");
CCAssert(&*out, "");
gzFile inFile = gzopen(path, "rb");
if( inFile == NULL ) {
CCLOG("cocos2d: ZipUtils: error open gzip file: %s", path);
return -1;
}
/* 512k initial decompress buffer */
unsigned int bufferSize = 512 * 1024;
unsigned int totalBufferSize = bufferSize;
*out = (unsigned char*)malloc( bufferSize );
if( ! out )
if( ! out )
{
CCLOG("cocos2d: ZipUtils: out of memory");
return -1;
}
for (;;) {
len = gzread(inFile, *out + offset, bufferSize);
if (len < 0)
if (len < 0)
{
CCLOG("cocos2d: ZipUtils: error in gzread");
free( *out );
@ -180,108 +268,170 @@ int ZipUtils::ccInflateGZipFile(const char *path, unsigned char **out)
{
break;
}
offset += len;
// finish reading the file
if( (unsigned int)len < bufferSize )
{
break;
}
bufferSize *= BUFFER_INC_FACTOR;
totalBufferSize += bufferSize;
unsigned char *tmp = (unsigned char*)realloc(*out, totalBufferSize );
if( ! tmp )
if( ! tmp )
{
CCLOG("cocos2d: ZipUtils: out of memory");
free( *out );
*out = NULL;
return -1;
}
*out = tmp;
}
if (gzclose(inFile) != Z_OK)
{
CCLOG("cocos2d: ZipUtils: gzclose failed");
}
return offset;
}
int ZipUtils::ccInflateCCZFile(const char *path, unsigned char **out)
{
CCAssert(out, "");
CCAssert(&*out, "");
// load file into memory
unsigned char* compressed = NULL;
CCAssert(out, "");
CCAssert(&*out, "");
unsigned long fileLen = 0;
compressed = CCFileUtils::sharedFileUtils()->getFileData(path, "rb", &fileLen);
// load file into memory
unsigned char* compressed = NULL;
unsigned long fileLen = 0;
compressed = CCFileUtils::sharedFileUtils()->getFileData(path, "rb", &fileLen);
if(NULL == compressed || 0 == fileLen)
{
CCLOG("cocos2d: Error loading CCZ compressed file");
return -1;
}
struct CCZHeader *header = (struct CCZHeader*) compressed;
// verify header
if( header->sig[0] == 'C' && header->sig[1] == 'C' && header->sig[2] == 'Z' && header->sig[3] == '!' )
{
// verify header version
unsigned int version = CC_SWAP_INT16_BIG_TO_HOST( header->version );
if( version > 2 )
{
CCLOG("cocos2d: Unsupported CCZ header format");
delete [] compressed;
return -1;
}
// verify compression format
if( CC_SWAP_INT16_BIG_TO_HOST(header->compression_type) != CCZ_COMPRESSION_ZLIB )
{
CCLOG("cocos2d: CCZ Unsupported compression method");
delete [] compressed;
return -1;
}
}
else if( header->sig[0] == 'C' && header->sig[1] == 'C' && header->sig[2] == 'Z' && header->sig[3] == 'p' )
{
// encrypted ccz file
header = (struct CCZHeader*) compressed;
// verify header version
unsigned int version = CC_SWAP_INT16_BIG_TO_HOST( header->version );
if( version > 0 )
{
CCLOG("cocos2d: Unsupported CCZ header format");
delete [] compressed;
return -1;
}
// verify compression format
if( CC_SWAP_INT16_BIG_TO_HOST(header->compression_type) != CCZ_COMPRESSION_ZLIB )
{
CCLOG("cocos2d: CCZ Unsupported compression method");
delete [] compressed;
return -1;
}
// decrypt
unsigned int* ints = (unsigned int*)(compressed+12);
int enclen = (fileLen-12)/4;
ccDecodeEncodedPvr(ints, enclen);
#if COCOS2D_DEBUG > 0
// verify checksum in debug mode
unsigned int calculated = ccChecksumPvr(ints, enclen);
unsigned int required = CC_SWAP_INT32_BIG_TO_HOST( header->reserved );
if(calculated != required)
{
CCLOG("cocos2d: Can't decrypt image file. Is the decryption key valid?");
delete [] compressed;
return -1;
}
#endif
}
else
{
CCLOG("cocos2d: Invalid CCZ file");
delete [] compressed;
return -1;
}
unsigned int len = CC_SWAP_INT32_BIG_TO_HOST( header->len );
*out = (unsigned char*)malloc( len );
if(! *out )
{
CCLOG("cocos2d: CCZ: Failed to allocate memory for texture");
delete [] compressed;
return -1;
}
unsigned long destlen = len;
unsigned long source = (unsigned long) compressed + sizeof(*header);
int ret = uncompress(*out, &destlen, (Bytef*)source, fileLen - sizeof(*header) );
delete [] compressed;
if( ret != Z_OK )
{
CCLOG("cocos2d: CCZ: Failed to uncompress data");
free( *out );
*out = NULL;
return -1;
}
return len;
}
if(NULL == compressed || 0 == fileLen)
{
CCLOG("cocos2d: Error loading CCZ compressed file");
return -1;
}
void ZipUtils::ccSetPvrEncryptionKeyPart(int index, unsigned int value)
{
CCAssert(index >= 0, "Cocos2d: key part index cannot be less than 0");
CCAssert(index <= 3, "Cocos2d: key part index cannot be greater than 3");
if(s_uEncryptedPvrKeyParts[index] != value)
{
s_uEncryptedPvrKeyParts[index] = value;
s_bEncryptionKeyIsValid = false;
}
}
struct CCZHeader *header = (struct CCZHeader*) compressed;
// verify header
if( header->sig[0] != 'C' || header->sig[1] != 'C' || header->sig[2] != 'Z' || header->sig[3] != '!' )
{
CCLOG("cocos2d: Invalid CCZ file");
delete [] compressed;
return -1;
}
// verify header version
unsigned int version = CC_SWAP_INT16_BIG_TO_HOST( header->version );
if( version > 2 )
{
CCLOG("cocos2d: Unsupported CCZ header format");
delete [] compressed;
return -1;
}
// verify compression format
if( CC_SWAP_INT16_BIG_TO_HOST(header->compression_type) != CCZ_COMPRESSION_ZLIB )
{
CCLOG("cocos2d: CCZ Unsupported compression method");
delete [] compressed;
return -1;
}
unsigned int len = CC_SWAP_INT32_BIG_TO_HOST( header->len );
*out = (unsigned char*)malloc( len );
if(! *out )
{
CCLOG("cocos2d: CCZ: Failed to allocate memory for texture");
delete [] compressed;
return -1;
}
unsigned long destlen = len;
unsigned long source = (unsigned long) compressed + sizeof(*header);
int ret = uncompress(*out, &destlen, (Bytef*)source, fileLen - sizeof(*header) );
delete [] compressed;
if( ret != Z_OK )
{
CCLOG("cocos2d: CCZ: Failed to uncompress data");
free( *out );
*out = NULL;
return -1;
}
return len;
void ZipUtils::ccSetPvrEncryptionKey(unsigned int keyPart1, unsigned int keyPart2, unsigned int keyPart3, unsigned int keyPart4)
{
ccSetPvrEncryptionKeyPart(0, keyPart1);
ccSetPvrEncryptionKeyPart(1, keyPart2);
ccSetPvrEncryptionKeyPart(2, keyPart3);
ccSetPvrEncryptionKeyPart(3, keyPart4);
}
// --------------------- ZipFile ---------------------
@ -298,14 +448,14 @@ class ZipFilePrivate
{
public:
unzFile zipFile;
// std::unordered_map is faster if available on the platform
typedef std::map<std::string, struct ZipEntryInfo> FileListContainer;
FileListContainer fileList;
};
ZipFile::ZipFile(const std::string &zipFile, const std::string &filter)
: m_data(new ZipFilePrivate)
: m_data(new ZipFilePrivate)
{
m_data->zipFile = unzOpen(zipFile.c_str());
if (m_data->zipFile)
@ -330,17 +480,17 @@ bool ZipFile::setFilter(const std::string &filter)
{
CC_BREAK_IF(!m_data);
CC_BREAK_IF(!m_data->zipFile);
// clear existing file list
m_data->fileList.clear();
// UNZ_MAXFILENAMEINZIP + 1 - it is done so in unzLocateFile
char szCurrentFileName[UNZ_MAXFILENAMEINZIP + 1];
unz_file_info64 fileInfo;
// go through all files and store position information about the required files
int err = unzGoToFirstFile64(m_data->zipFile, &fileInfo,
szCurrentFileName, sizeof(szCurrentFileName) - 1);
szCurrentFileName, sizeof(szCurrentFileName) - 1);
while (err == UNZ_OK)
{
unz_file_pos posInfo;
@ -360,12 +510,12 @@ bool ZipFile::setFilter(const std::string &filter)
}
// next file - also get the information about it
err = unzGoToNextFile64(m_data->zipFile, &fileInfo,
szCurrentFileName, sizeof(szCurrentFileName) - 1);
szCurrentFileName, sizeof(szCurrentFileName) - 1);
}
ret = true;
} while(false);
return ret;
}
@ -375,10 +525,10 @@ bool ZipFile::fileExists(const std::string &fileName) const
do
{
CC_BREAK_IF(!m_data);
ret = m_data->fileList.find(fileName) != m_data->fileList.end();
} while(false);
return ret;
}
@ -389,34 +539,34 @@ unsigned char *ZipFile::getFileData(const std::string &fileName, unsigned long *
{
*pSize = 0;
}
do
{
CC_BREAK_IF(!m_data->zipFile);
CC_BREAK_IF(fileName.empty());
ZipFilePrivate::FileListContainer::const_iterator it = m_data->fileList.find(fileName);
CC_BREAK_IF(it == m_data->fileList.end());
ZipEntryInfo fileInfo = it->second;
int nRet = unzGoToFilePos(m_data->zipFile, &fileInfo.pos);
CC_BREAK_IF(UNZ_OK != nRet);
nRet = unzOpenCurrentFile(m_data->zipFile);
CC_BREAK_IF(UNZ_OK != nRet);
pBuffer = new unsigned char[fileInfo.uncompressed_size];
int CC_UNUSED nSize = unzReadCurrentFile(m_data->zipFile, pBuffer, fileInfo.uncompressed_size);
CCAssert(nSize == 0 || nSize == (int)fileInfo.uncompressed_size, "the file size is wrong");
if (pSize)
{
*pSize = fileInfo.uncompressed_size;
}
unzCloseCurrentFile(m_data->zipFile);
} while (0);
return pBuffer;
}

View File

@ -25,6 +25,7 @@ THE SOFTWARE.
#define __SUPPORT_ZIPUTILS_H__
#include <string>
#include "CCPlatformDefine.h"
namespace cocos2d
{
@ -32,21 +33,21 @@ namespace cocos2d
/** @struct CCZHeader
*/
struct CCZHeader {
unsigned char sig[4]; // signature. Should be 'CCZ!' 4 bytes
unsigned short compression_type; // should 0
unsigned short version; // should be 2 (although version type==1 is also supported)
unsigned int reserved; // Reserved for users.
unsigned int len; // size of the uncompressed file
unsigned char sig[4]; // signature. Should be 'CCZ!' 4 bytes
unsigned short compression_type; // should 0
unsigned short version; // should be 2 (although version type==1 is also supported)
unsigned int reserved; // Reserved for users.
unsigned int len; // size of the uncompressed file
};
enum {
CCZ_COMPRESSION_ZLIB, // zlib format.
CCZ_COMPRESSION_BZIP2, // bzip2 format (not supported yet)
CCZ_COMPRESSION_GZIP, // gzip format (not supported yet)
CCZ_COMPRESSION_NONE, // plain (not supported yet)
CCZ_COMPRESSION_ZLIB, // zlib format.
CCZ_COMPRESSION_BZIP2, // bzip2 format (not supported yet)
CCZ_COMPRESSION_GZIP, // gzip format (not supported yet)
CCZ_COMPRESSION_NONE, // plain (not supported yet)
};
class ZipUtils
class CC_DLL ZipUtils
{
public:
/**
@ -88,9 +89,67 @@ namespace cocos2d
*/
static int ccInflateCCZFile(const char *filename, unsigned char **out);
/** Sets the pvr.ccz encryption key parts separately for added
* security.
*
* Example: If the key used to encrypt the pvr.ccz file is
* 0xaaaaaaaabbbbbbbbccccccccdddddddd you will call this function 4
* different times, preferably from 4 different source files, as follows
*
* ZipUtils::ccSetPvrEncryptionKeyPart(0, 0xaaaaaaaa);
* ZipUtils::ccSetPvrEncryptionKeyPart(1, 0xbbbbbbbb);
* ZipUtils::ccSetPvrEncryptionKeyPart(2, 0xcccccccc);
* ZipUtils::ccSetPvrEncryptionKeyPart(3, 0xdddddddd);
*
* Splitting the key into 4 parts and calling the function
* from 4 different source files increases the difficulty to
* reverse engineer the encryption key. Be aware that encrpytion
* is *never* 100% secure and the key code can be cracked by
* knowledgable persons.
*
* IMPORTANT: Be sure to call ccSetPvrEncryptionKey or
* ccSetPvrEncryptionKeyPart with all of the key parts *before* loading
* the spritesheet or decryption will fail and the spritesheet
* will fail to load.
*
* @param index part of the key [0..3]
* @param value value of the key part
*/
static void ccSetPvrEncryptionKeyPart(int index, unsigned int value);
/** Sets the pvr.ccz encryption key.
*
* Example: If the key used to encrypt the pvr.ccz file is
* 0xaaaaaaaabbbbbbbbccccccccdddddddd you will call this function with
* the key split into 4 parts as follows
*
* ZipUtils::ccSetPvrEncryptionKey(0xaaaaaaaa, 0xbbbbbbbb, 0xcccccccc, 0xdddddddd);
*
* Note that using this function makes it easier to reverse engineer and
* discover the complete key because the key parts are present in one
* function call.
*
* IMPORTANT: Be sure to call ccSetPvrEncryptionKey or
* ccSetPvrEncryptionKeyPart with all of the key parts *before* loading
* the spritesheet or decryption will fail and the spritesheet
* will fail to load.
*
* @param keyPart1 the key value part 1.
* @param keyPart2 the key value part 2.
* @param keyPart3 the key value part 3.
* @param keyPart4 the key value part 4.
*/
static void ccSetPvrEncryptionKey(unsigned int keyPart1, unsigned int keyPart2, unsigned int keyPart3, unsigned int keyPart4);
private:
static int ccInflateMemoryWithHint(unsigned char *in, unsigned int inLength, unsigned char **out, unsigned int *outLength,
unsigned int outLenghtHint);
unsigned int outLenghtHint);
static inline void ccDecodeEncodedPvr (unsigned int *data, int len);
static inline unsigned int ccChecksumPvr(const unsigned int *data, int len);
static unsigned int s_uEncryptedPvrKeyParts[4];
static unsigned int s_uEncryptionKey[1024];
static bool s_bEncryptionKeyIsValid;
};
// forward declaration

View File

@ -174,14 +174,23 @@ bool CCTexture2D::hasPremultipliedAlpha()
bool CCTexture2D::initWithData(const void *data, CCTexture2DPixelFormat pixelFormat, unsigned int pixelsWide, unsigned int pixelsHigh, const CCSize& contentSize)
{
// XXX: 32 bits or POT textures uses UNPACK of 4 (is this correct ??? )
if( pixelFormat == kCCTexture2DPixelFormat_RGBA8888 || ( ccNextPOT(pixelsWide)==pixelsWide && ccNextPOT(pixelsHigh)==pixelsHigh) )
unsigned int bytesPerRow = pixelsWide * bitsPerPixelForFormat(pixelFormat) / 8;
if(bytesPerRow % 8 == 0)
{
glPixelStorei(GL_UNPACK_ALIGNMENT,4);
glPixelStorei(GL_UNPACK_ALIGNMENT, 8);
}
else if(bytesPerRow % 4 == 0)
{
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
}
else if(bytesPerRow % 2 == 0)
{
glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
}
else
{
glPixelStorei(GL_UNPACK_ALIGNMENT,1);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
}
glGenTextures(1, &m_uName);

View File

@ -69,6 +69,10 @@ static pthread_cond_t s_SleepCondition;
static pthread_mutex_t s_asyncStructQueueMutex;
static pthread_mutex_t s_ImageInfoMutex;
#ifdef EMSCRIPTEN
// Hack to get ASM.JS validation (no undefined symbols allowed).
#define pthread_cond_signal(_)
#endif // EMSCRIPTEN
static unsigned long s_nAsyncRefCount = 0;
@ -233,6 +237,11 @@ CCDictionary* CCTextureCache::snapshotTextures()
void CCTextureCache::addImageAsync(const char *path, CCObject *target, SEL_CallFuncO selector)
{
#ifdef EMSCRIPTEN
CCLOGWARN("Cannot load image %s asynchronously in Emscripten builds.", path);
return;
#endif // EMSCRIPTEN
CCAssert(path != NULL, "TextureCache: fileimage MUST not be NULL");
CCTexture2D *texture = NULL;

View File

@ -443,7 +443,7 @@ bool CCTexturePVR::unpackPVRv3Data(unsigned char* dataPointer, unsigned int data
// unsupported / bad pixel format
if (! infoValid)
{
CCLOG("cocos2d: WARNING: unsupported pvr pixelformat: %lx", pixelFormat );
CCLOG("cocos2d: WARNING: unsupported pvr pixelformat: %lx", (unsigned long)pixelFormat );
return false;
}

View File

@ -185,7 +185,11 @@ void CCBAnimationManager::setDelegate(CCBAnimationManagerDelegate *pDelegate)
const char* CCBAnimationManager::getRunningSequenceName()
{
return mRunningSequence->getName();
if (mRunningSequence)
{
return mRunningSequence->getName();
}
return NULL;
}
const CCSize& CCBAnimationManager::getContainerSize(CCNode *pNode)

View File

@ -131,7 +131,7 @@ bool CCBValue::getBoolValue()
unsigned char CCBValue::getByteValue()
{
assert(mType = kUnsignedCharValue);
assert(mType == kUnsignedCharValue);
return (unsigned char)(mValue.nValue);
}

View File

@ -721,6 +721,23 @@ GLubyte CCControlButton::getOpacity()
return _realOpacity;
}
void CCControlButton::setColor(const ccColor3B & color)
{
CCControl::setColor(color);
CCDictElement * item = NULL;
CCDICT_FOREACH(m_backgroundSpriteDispatchTable, item)
{
CCScale9Sprite* sprite = (CCScale9Sprite*)item->getObject();
sprite->setColor(color);
}
}
const ccColor3B& CCControlButton::getColor()
{
return _realColor;
}
void CCControlButton::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent)
{
m_isPushed = false;

View File

@ -93,6 +93,8 @@ protected:
/* Override setter to affect a background sprite too */
virtual GLubyte getOpacity(void);
virtual void setOpacity(GLubyte var);
virtual const ccColor3B& getColor(void);
virtual void setColor(const ccColor3B&);
/** Flag to know if the button is currently pushed. */
protected:

View File

@ -805,6 +805,11 @@ void CCScale9Sprite::setColor(const ccColor3B& color)
}
}
const ccColor3B& CCScale9Sprite::getColor()
{
return _color;
}
void CCScale9Sprite::setOpacity(GLubyte opacity)
{
_opacity = opacity;
@ -821,4 +826,9 @@ void CCScale9Sprite::setOpacity(GLubyte opacity)
}
}
GLubyte CCScale9Sprite::getOpacity()
{
return _opacity;
}
NS_CC_EXT_END

View File

@ -308,7 +308,9 @@ public:
*/
virtual bool isOpacityModifyRGB(void);
virtual void setOpacity(GLubyte opacity);
virtual GLubyte getOpacity();
virtual void setColor(const ccColor3B& color);
virtual const ccColor3B& getColor();
virtual bool updateWithBatchNode(CCSpriteBatchNode* batchnode, CCRect rect, bool rotated, CCRect capInsets);

View File

@ -436,7 +436,7 @@ void CCScrollView::performedAnimatedScroll(float dt)
}
const CCSize& CCScrollView::getContentSize()
const CCSize& CCScrollView::getContentSize() const
{
return m_pContainer->getContentSize();
}

View File

@ -187,7 +187,7 @@ public:
virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent);
virtual void setContentSize(const CCSize & size);
virtual const CCSize& getContentSize();
virtual const CCSize& getContentSize() const;
void updateInset();
/**

View File

@ -85,6 +85,7 @@ Classes/SpineTest/SpineTest.cpp \
Classes/SpriteTest/SpriteTest.cpp \
Classes/TextureCacheTest/TextureCacheTest.cpp \
Classes/Texture2dTest/Texture2dTest.cpp \
Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp \
Classes/TileMapTest/TileMapTest.cpp \
Classes/TouchesTest/Ball.cpp \
Classes/TouchesTest/Paddle.cpp \
@ -93,6 +94,7 @@ Classes/TransitionsTest/TransitionsTest.cpp \
Classes/UserDefaultTest/UserDefaultTest.cpp \
Classes/ZwoptexTest/ZwoptexTest.cpp \
Classes/FileUtilsTest/FileUtilsTest.cpp \
Classes/DataVisitorTest/DataVisitorTest.cpp \
Classes/controller.cpp \
Classes/testBasic.cpp \
Classes/AppDelegate.cpp \

View File

@ -0,0 +1,86 @@
#include "DataVisitorTest.h"
#include "../testResource.h"
std::string PrettyPrinterDemo::title()
{
return "PrettyPrinter Test";
}
std::string PrettyPrinterDemo::subtitle()
{
return "Please see log!";
}
void PrettyPrinterDemo::addSprite()
{
// create sprites
CCSprite *s1 = CCSprite::create("Images/grossini.png");
CCSprite *s2 = CCSprite::create("Images/grossini_dance_01.png");
CCSprite *s3 = CCSprite::create("Images/grossini_dance_02.png");
CCSprite *s4 = CCSprite::create("Images/grossini_dance_03.png");
CCSprite *s5 = CCSprite::create("Images/grossini_dance_04.png");
s1->setPosition(ccp(50, 50));
s2->setPosition(ccp(60, 50));
s3->setPosition(ccp(70, 50));
s4->setPosition(ccp(80, 50));
s5->setPosition(ccp(90, 50));
this->addChild(s1);
this->addChild(s2);
this->addChild(s3);
this->addChild(s4);
this->addChild(s5);
}
void PrettyPrinterDemo::onEnter()
{
CCLayer::onEnter();
CCSize s = CCDirector::sharedDirector()->getWinSize();
CCLabelTTF* label = CCLabelTTF::create(title().c_str(), "Arial", 28);
label->setPosition( ccp(s.width/2, s.height * 4/5) );
this->addChild(label, 1);
std::string strSubtitle = subtitle();
if(strSubtitle.empty() == false)
{
CCLabelTTF* subLabel = CCLabelTTF::create(strSubtitle.c_str(), "Thonburi", 16);
subLabel->setPosition( ccp(s.width/2, s.height * 3/5) );
this->addChild(subLabel, 1);
}
// Test code
CCPrettyPrinter vistor;
// print dictionary
CCDictionary* pDict = CCDictionary::createWithContentsOfFile("animations/animations.plist");
pDict->acceptVisitor(vistor);
CCLog("%s", vistor.getResult().c_str());
CCLog("-------------------------------");
CCSet myset;
for (int i = 0; i < 30; ++i) {
myset.addObject(CCString::createWithFormat("str: %d", i));
}
vistor.clear();
myset.acceptVisitor(vistor);
CCLog("%s", vistor.getResult().c_str());
CCLog("-------------------------------");
vistor.clear();
addSprite();
pDict = CCTextureCache::sharedTextureCache()->snapshotTextures();
pDict->acceptVisitor(vistor);
CCLog("%s", vistor.getResult().c_str());
}
void DataVisitorTestScene::runThisTest()
{
CCLayer *layer = new PrettyPrinterDemo();
layer->autorelease();
addChild(layer);
CCDirector::sharedDirector()->replaceScene(this);
}

View File

@ -0,0 +1,27 @@
#ifndef __DATAVISITOR_TEST_H__
#define __DATAVISITOR_TEST_H__
#include "../testBasic.h"
#include <string>
class PrettyPrinterDemo : public CCLayer
{
public:
virtual std::string title();
virtual std::string subtitle();
virtual void onEnter();
void addSprite();
protected:
std::string m_strTitle;
};
class DataVisitorTestScene : public TestScene
{
public:
virtual void runThisTest();
CREATE_FUNC(DataVisitorTestScene);
};
#endif // __DATAVISITOR_TEST_H__

View File

@ -46,17 +46,35 @@ bool CCControlButtonTest_HelloVariableSize::init()
// For each title in the array
CCObject* pObj = NULL;
int i = 0;
CCARRAY_FOREACH(stringArray, pObj)
{
CCString* title = (CCString*)pObj;
// Creates a button with this string as title
CCControlButton *button = standardButtonWithTitle(title->getCString());
if (i == 0)
{
button->setOpacity(50);
button->setColor(ccc3(0, 255, 0));
}
else if (i == 1)
{
button->setOpacity(200);
button->setColor(ccc3(0, 255, 0));
}
else if (i == 2)
{
button->setOpacity(100);
button->setColor(ccc3(0, 0, 255));
}
button->setPosition(ccp (total_width + button->getContentSize().width / 2, button->getContentSize().height / 2));
layer->addChild(button);
// Compute the size of the layer
height = button->getContentSize().height;
total_width += button->getContentSize().width;
i++;
}
layer->setAnchorPoint(ccp (0.5, 0.5));
@ -86,7 +104,7 @@ CCControlButton *CCControlButtonTest_HelloVariableSize::standardButtonWithTitle(
CCControlButton *button = CCControlButton::create(titleButton, backgroundButton);
button->setBackgroundSpriteForState(backgroundHighlightedButton, CCControlStateHighlighted);
button->setTitleColorForState(ccWHITE, CCControlStateHighlighted);
return button;
}

View File

@ -3,7 +3,9 @@
#include "NotificationCenterTest/NotificationCenterTest.h"
#include "ControlExtensionTest/CCControlSceneManager.h"
#include "CocosBuilderTest/CocosBuilderTest.h"
#if (CC_TARGET_PLATFORM != CC_PLATFORM_EMSCRIPTEN)
#include "NetworkTest/HttpClientTest.h"
#endif
#include "TableViewTest/TableViewTestScene.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
@ -34,7 +36,9 @@ static const std::string testsName[TEST_MAX_COUNT] =
"NotificationCenterTest",
"CCControlButtonTest",
"CocosBuilderTest",
#if (CC_TARGET_PLATFORM != CC_PLATFORM_EMSCRIPTEN)
"HttpClientTest",
#endif
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
"EditBoxTest",
#endif
@ -98,7 +102,7 @@ void ExtensionsMainLayer::menuCallback(CCObject* pSender)
}
}
break;
#if (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE && CC_TARGET_PLATFORM != CC_PLATFORM_NACL)
#if (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE && CC_TARGET_PLATFORM != CC_PLATFORM_NACL && CC_TARGET_PLATFORM != CC_PLATFORM_EMSCRIPTEN)
case TEST_HTTPCLIENT:
{
runHttpClientTest();

View File

@ -0,0 +1,82 @@
#include "TextureAtlasEncryptionTest.h"
#include "../testResource.h"
#include "support/zip_support/ZipUtils.h"
std::string TextureAtlasEncryptionDemo::title()
{
return "Texture Atlas Encryption";
}
std::string TextureAtlasEncryptionDemo::subtitle()
{
return "";
}
void TextureAtlasEncryptionDemo::onEnter()
{
CCLayer::onEnter();
CCSize s = CCDirector::sharedDirector()->getWinSize();
CCLabelTTF* label = CCLabelTTF::create(title().c_str(), "Arial", 28);
label->setPosition( ccp(s.width/2, s.height * 0.75f) );
this->addChild(label, 1);
std::string strSubtitle = subtitle();
if(strSubtitle.empty() == false)
{
CCLabelTTF* subLabel = CCLabelTTF::create(strSubtitle.c_str(), "Thonburi", 16);
subLabel->setPosition( ccp(s.width/2, s.height-80) );
this->addChild(subLabel, 1);
}
// Load the non-encrypted atlas
CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("Images/nonencryptedAtlas.plist", "Images/nonencryptedAtlas.pvr.ccz");
// Create a sprite from the non-encrypted atlas
CCSprite *nonencryptedSprite = CCSprite::createWithSpriteFrameName("Icon.png");
nonencryptedSprite->setPosition(ccp(s.width * 0.25f, s.height * 0.5f));
this->addChild(nonencryptedSprite);
CCLabelTTF* nonencryptedSpriteLabel = CCLabelTTF::create("non-encrypted", "Arial", 28);
nonencryptedSpriteLabel->setPosition(ccp(s.width * 0.25f, nonencryptedSprite->boundingBox().getMinY() - nonencryptedSprite->getContentSize().height/2));
this->addChild(nonencryptedSpriteLabel, 1);
// Load the encrypted atlas
// 1) Set the encryption keys or step 2 will fail
// In this case the encryption key 0xaaaaaaaabbbbbbbbccccccccdddddddd is
// split into four parts. See the header docs for more information.
ZipUtils::ccSetPvrEncryptionKeyPart(0, 0xaaaaaaaa);
ZipUtils::ccSetPvrEncryptionKeyPart(1, 0xbbbbbbbb);
ZipUtils::ccSetPvrEncryptionKeyPart(2, 0xcccccccc);
ZipUtils::ccSetPvrEncryptionKeyPart(3, 0xdddddddd);
// Alternatively, you can call the function that accepts the key in a single
// function call.
// This is slightly less secure because the entire key is more easily
// found in the compiled source. See the header docs for more information.
// ZipUtils::ccSetPvrEncryptionKey(0xaaaaaaaa, 0xbbbbbbbb, 0xcccccccc, 0xdddddddd);
// 2) Load the encrypted atlas
CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("Images/encryptedAtlas.plist", "Images/encryptedAtlas.pvr.ccz");
// 3) Create a sprite from the encrypted atlas
CCSprite *encryptedSprite = CCSprite::createWithSpriteFrameName("powered.png");
encryptedSprite->setPosition(ccp(s.width * 0.75f, s.height * 0.5f));
this->addChild(encryptedSprite);
CCLabelTTF* encryptedSpriteLabel = CCLabelTTF::create("encrypted", "Arial", 28);
encryptedSpriteLabel->setPosition(ccp(s.width * 0.75f, encryptedSprite->boundingBox().getMinY() - encryptedSpriteLabel->getContentSize().height/2));
this->addChild(encryptedSpriteLabel, 1);
}
void TextureAtlasEncryptionTestScene::runThisTest()
{
CCLayer *layer = new TextureAtlasEncryptionDemo;
layer->autorelease();
addChild(layer);
CCDirector::sharedDirector()->replaceScene(this);
}

View File

@ -0,0 +1,25 @@
#ifndef _TextureAtlasEncryption_TEST_H_
#define _TextureAtlasEncryption_TEST_H_
#include "cocos2d.h"
#include "../testBasic.h"
#include <string>
class TextureAtlasEncryptionDemo : public CCLayer
{
public:
virtual std::string title();
virtual std::string subtitle();
virtual void onEnter();
protected:
std::string m_strTitle;
};
class TextureAtlasEncryptionTestScene : public TestScene
{
public:
virtual void runThisTest();
};
#endif

View File

@ -122,6 +122,12 @@ static TestScene* CreateTestScene(int nIdx)
case TEST_SPINE:
pScene = new SpineTestScene();
break;
case TEST_TEXTUREPACKER_ENCRYPTION:
pScene = new TextureAtlasEncryptionTestScene();
break;
case TEST_DATAVISTOR:
pScene = new DataVisitorTestScene();
break;
default:
break;
}

View File

@ -56,6 +56,8 @@
#endif
#include "FileUtilsTest/FileUtilsTest.h"
#include "SpineTest/SpineTest.h"
#include "TexturePackerEncryptionTest/TextureAtlasEncryptionTest.h"
#include "DataVisitorTest/DataVisitorTest.h"
enum
{
@ -113,6 +115,8 @@ enum
#endif
TEST_FILEUTILS,
TEST_SPINE,
TEST_TEXTUREPACKER_ENCRYPTION,
TEST_DATAVISTOR,
TESTS_COUNT,
};
@ -172,7 +176,9 @@ const std::string g_aTestNames[TESTS_COUNT] = {
"ClippingNodeTest",
#endif
"FileUtilsTest",
"SpineTest"
"SpineTest",
"TexturePackerEncryption",
"DataVistorTest"
};
#endif

View File

@ -83,6 +83,7 @@ SOURCES = ../Classes/AccelerometerTest/AccelerometerTest.cpp \
../Classes/UserDefaultTest/UserDefaultTest.cpp \
../Classes/ZwoptexTest/ZwoptexTest.cpp \
../Classes/FileUtilsTest/FileUtilsTest.cpp \
../Classes/DataVisitorTest/DataVisitorTest.cpp \
../Classes/controller.cpp \
../Classes/testBasic.cpp \
../Classes/AppDelegate.cpp \

View File

@ -1 +1 @@
f4a587eb683fe30c950bf226a756c77d25c06468
6b5e473d37f1653e3e4098f7a69cd6be2b4bc4b4

View File

@ -75,6 +75,7 @@ SOURCES = ../Classes/AccelerometerTest/AccelerometerTest.cpp \
../Classes/SpriteTest/SpriteTest.cpp \
../Classes/TextInputTest/TextInputTest.cpp \
../Classes/Texture2dTest/Texture2dTest.cpp \
../Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp \
../Classes/TextureCacheTest/TextureCacheTest.cpp \
../Classes/TileMapTest/TileMapTest.cpp \
../Classes/TouchesTest/Ball.cpp \
@ -85,6 +86,7 @@ SOURCES = ../Classes/AccelerometerTest/AccelerometerTest.cpp \
../Classes/ZwoptexTest/ZwoptexTest.cpp \
../Classes/FileUtilsTest/FileUtilsTest.cpp \
../Classes/SpineTest/SpineTest.cpp \
../Classes/DataVisitorTest/DataVisitorTest.cpp \
../Classes/controller.cpp \
../Classes/testBasic.cpp \
../Classes/AppDelegate.cpp \

View File

@ -1 +1 @@
ff7a1763f32d0d088fa1e219e5737fdc9cc2c1c8
90d267b6c461f771978ca8a8d23c6e688cfa7077

View File

@ -432,6 +432,11 @@ files
TextureCacheTest.cpp
TextureCacheTest.h
[Test/TexturePackerEncryptionTest]
[../Classes/TexturePackerEncryptionTest]
TexturePackerEncryptionTest.cpp
TexturePackerEncryptionTest.h
[Test/TileMapTest]
(../Classes/TileMapTest)
TileMapTest.cpp
@ -470,6 +475,11 @@ files
(../Classes/SpineTest)
SpineTest.cpp
SpineTest.h
[Test/DataVisitorTest]
(../Classes/DataVisitorTest)
DataVisitorTest.cpp
DataVisitorTest.h
}

View File

@ -82,6 +82,7 @@ SOURCES = ../Classes/AccelerometerTest/AccelerometerTest.cpp \
../Classes/TextInputTest/TextInputTest.cpp \
../Classes/Texture2dTest/Texture2dTest.cpp \
../Classes/TextureCacheTest/TextureCacheTest.cpp \
../Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp \
../Classes/TileMapTest/TileMapTest.cpp \
../Classes/TouchesTest/Ball.cpp \
../Classes/TouchesTest/Paddle.cpp \
@ -90,6 +91,7 @@ SOURCES = ../Classes/AccelerometerTest/AccelerometerTest.cpp \
../Classes/UserDefaultTest/UserDefaultTest.cpp \
../Classes/ZwoptexTest/ZwoptexTest.cpp \
../Classes/SpineTest/SpineTest.cpp \
../Classes/DataVisitorTest/DataVisitorTest.cpp \
../Classes/controller.cpp \
../Classes/testBasic.cpp \
../Classes/AppDelegate.cpp \

View File

@ -121,6 +121,7 @@
<ItemGroup>
<ClCompile Include="..\Classes\ChipmunkTest\ChipmunkTest.cpp" />
<ClCompile Include="..\Classes\ClippingNodeTest\ClippingNodeTest.cpp" />
<ClCompile Include="..\Classes\DataVisitorTest\DataVisitorTest.cpp" />
<ClCompile Include="..\Classes\ExtensionsTest\CocosBuilderTest\AnimationsTest\AnimationsTestLayer.cpp" />
<ClCompile Include="..\Classes\ExtensionsTest\CocosBuilderTest\TimelineCallbackTest\TimelineCallbackTestLayer.cpp" />
<ClCompile Include="..\Classes\ExtensionsTest\ControlExtensionTest\CCControlPotentiometerTest\CCControlPotentiometerTest.cpp" />
@ -131,6 +132,7 @@
<ClCompile Include="..\Classes\ExtensionsTest\TableViewTest\TableViewTestScene.cpp" />
<ClCompile Include="..\Classes\FileUtilsTest\FileUtilsTest.cpp" />
<ClCompile Include="..\Classes\SpineTest\SpineTest.cpp" />
<ClCompile Include="..\Classes\TexturePackerEncryptionTest\TextureAtlasEncryptionTest.cpp" />
<ClCompile Include="..\Classes\VisibleRect.cpp" />
<ClCompile Include="main.cpp" />
<ClCompile Include="..\Classes\AppDelegate.cpp" />
@ -214,6 +216,7 @@
<ItemGroup>
<ClInclude Include="..\Classes\ChipmunkTest\ChipmunkTest.h" />
<ClInclude Include="..\Classes\ClippingNodeTest\ClippingNodeTest.h" />
<ClInclude Include="..\Classes\DataVisitorTest\DataVisitorTest.h" />
<ClInclude Include="..\Classes\ExtensionsTest\CocosBuilderTest\AnimationsTest\AnimationsLayerLoader.h" />
<ClInclude Include="..\Classes\ExtensionsTest\CocosBuilderTest\AnimationsTest\AnimationsTestLayer.h" />
<ClInclude Include="..\Classes\ExtensionsTest\CocosBuilderTest\TimelineCallbackTest\TimelineCallbackLayerLoader.h" />
@ -226,6 +229,7 @@
<ClInclude Include="..\Classes\ExtensionsTest\TableViewTest\TableViewTestScene.h" />
<ClInclude Include="..\Classes\FileUtilsTest\FileUtilsTest.h" />
<ClInclude Include="..\Classes\SpineTest\SpineTest.h" />
<ClInclude Include="..\Classes\TexturePackerEncryptionTest\TextureAtlasEncryptionTest.h" />
<ClInclude Include="..\Classes\VisibleRect.h" />
<ClInclude Include="main.h" />
<ClInclude Include="..\Classes\AppDelegate.h" />

View File

@ -217,6 +217,12 @@
<Filter Include="Classes\SpineTest">
<UniqueIdentifier>{60df7835-5770-44bb-b5c7-24c9aa34da88}</UniqueIdentifier>
</Filter>
<Filter Include="Classes\TexturePackerEncryptionTest">
<UniqueIdentifier>{4031c3bb-97f8-4b43-91e5-48dd94ca2d24}</UniqueIdentifier>
</Filter>
<Filter Include="Classes\DataVisitorTest">
<UniqueIdentifier>{8049d378-12f7-46ba-ba96-091f3c0a4600}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="main.cpp">
@ -492,6 +498,12 @@
<ClCompile Include="..\Classes\SpineTest\SpineTest.cpp">
<Filter>Classes\SpineTest</Filter>
</ClCompile>
<ClCompile Include="..\Classes\TexturePackerEncryptionTest\TextureAtlasEncryptionTest.cpp">
<Filter>Classes\TexturePackerEncryptionTest</Filter>
</ClCompile>
<ClCompile Include="..\Classes\DataVisitorTest\DataVisitorTest.cpp">
<Filter>Classes\DataVisitorTest</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="main.h">
@ -947,5 +959,11 @@
<ClInclude Include="..\Classes\SpineTest\SpineTest.h">
<Filter>Classes\SpineTest</Filter>
</ClInclude>
<ClInclude Include="..\Classes\TexturePackerEncryptionTest\TextureAtlasEncryptionTest.h">
<Filter>Classes\TexturePackerEncryptionTest</Filter>
</ClInclude>
<ClInclude Include="..\Classes\DataVisitorTest\DataVisitorTest.h">
<Filter>Classes\DataVisitorTest</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -75,7 +75,7 @@ local _allTests = {
{ isSupported = false, name = "Accelerometer" , create_func= AccelerometerMain },
{ isSupported = false, name = "KeypadTest" , create_func= KeypadTestMain },
{ isSupported = true, name = "CocosDenshionTest" , create_func = CocosDenshionTestMain },
{ isSupported = false, name = "PerformanceTest" , create_func= PerformanceTestMain },
{ isSupported = true, name = "PerformanceTest" , create_func= PerformanceTestMain },
{ isSupported = true, name = "ZwoptexTest" , create_func = ZwoptexTestMain },
{ isSupported = false, name = "CurlTest" , create_func= CurlTestMain },
{ isSupported = true, name = "UserDefaultTest" , create_func= UserDefaultTestMain },

View File

@ -1,7 +1,11 @@
jsbcc stands for JavasSript Byte Code Compiler.
it compiles javascript files to SpiderMonkey byte code files
It compiles javascript files to SpiderMonkey byte code files. It supports Mac and win32 now.
Usage:
jsbcc input_js_file [byte_code_file]
Note: it also supports pipeline, so you can use it like this:
Note: it also supports pipeline on Mac, so you can use it like this:
ls *.js | jsbcc
Furthermore, 2 scripts supplied to help: "jsbcc.sh" on Mac and "jsbcc.bat" on win32
jsbcc.sh/jsbcc.bat js_root_dir
js_root_dir is the root directory of js source files. The scripts search and compile js source files recrusively.

View File

@ -0,0 +1,97 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{BD6738AE-6468-4881-B32B-5749DCF95511}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>jsbcc</RootNamespace>
<ProjectName>jsbcc</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;XP_WIN;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\..\scripting\javascript\spidermonkey-win32\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>..\..\scripting\javascript\spidermonkey-win32\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>Ws2_32.lib;mozjs.lib</AdditionalDependencies>
</Link>
<PostBuildEvent>
<Command>copy "$(ProjectDir)..\..\scripting\javascript\spidermonkey-win32\lib\mozjs.dll" "$(TargetDir)"
copy "$(ProjectDir)src\jsbcc.bat" "$(TargetDir)"</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;XP_WIN;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\..\scripting\javascript\spidermonkey-win32\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalLibraryDirectories>..\..\scripting\javascript\spidermonkey-win32\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>Ws2_32.lib;mozjs.lib</AdditionalDependencies>
</Link>
<PostBuildEvent>
<Command>copy "$(ProjectDir)..\..\scripting\javascript\spidermonkey-win32\lib\mozjs.dll" "$(TargetDir)"
copy "$(ProjectDir)src\jsbcc.bat" "$(TargetDir)"</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="src\main.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="src\main.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1 @@
for /f %%f in ('dir %1\*.js /s/b') do jsbcc.exe %%f

View File

@ -9,15 +9,25 @@
#include <iostream>
#include <sstream>
#include <sys/select.h>
#include <stdio.h>
#ifdef WIN32
#include <Winsock2.h>
#define STDIN_FILENO 0
#else
#include <unistd.h>
#include <sys/select.h>
#endif
#include "jsapi.h"
#ifdef WIN32
const char *USAGE = "Usage: jsbcc input_js_file [byte_code_file]";
#else
const char *USAGE = "Usage: jsbcc input_js_file [byte_code_file]\n"\
" Or\n"\
" ls *.js | jsbcc -p";
#endif
const char *BYTE_CODE_FILE_EXT = ".jsc";
enum ErrorCode {
@ -84,7 +94,6 @@ bool CompileFile(const std::string &inputFilePath, const std::string &outputFile
JS::CompileOptions options(context);
options.setUTF8(true);
options.setSourcePolicy(JS::CompileOptions::NO_SOURCE);
js::RootedObject rootedObject(context, global);
std::cout << "Compiling ..." << std::endl;
JSScript *script = JS::Compile(context, rootedObject, options, inputFilePath.c_str());
@ -102,7 +111,6 @@ bool CompileFile(const std::string &inputFilePath, const std::string &outputFile
}
}
Exit:
if (context) {
JS_DestroyContext(context);
context = NULL;

View File

@ -0,0 +1,58 @@
#!/bin/bash
# exit this script if any commmand fails
set -e
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
COCOS2DX_ROOT="$DIR"/../..
mkdir -p $HOME/bin
pushd $HOME/bin
install_android_ndk()
{
# Download android ndk
echo "Download android ndk ..."
curl -O http://dl.google.com/android/ndk/android-ndk-r8e-linux-x86_64.tar.bz2
echo "Decompress android-ndk-r8e-linux-x86_64.tar.bz2 ..."
tar xjf android-ndk-r8e-linux-x86_64.tar.bz2
# Rename ndk
mv android-ndk-r8e android-ndk
}
if [ "$GEN_JSB"x = "YES"x ]; then
if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then
exit 0
fi
install_android_ndk
# Download llvm3.1
echo "Download llvm3.1 ..."
curl -O http://llvm.org/releases/3.1/clang+llvm-3.1-x86_64-linux-ubuntu_12.04.tar.gz
echo "Decompress android-ndk-r8e-linux-x86_64.tar.bz2 ..."
tar xzf clang+llvm-3.1-x86_64-linux-ubuntu_12.04.tar.gz
# Rename llvm
mv clang+llvm-3.1-x86_64-linux-ubuntu_12.04 clang+llvm-3.1
fi
if [ "$PLATFORM"x = "linux"x ]; then
bash $COCOS2DX_ROOT/install-deps-linux.sh
fi
if [ "$PLATFORM"x = "nacl"x ]; then
sudo apt-get update
sudo apt-get install libc6:i386
echo "Download nacl_sdk ..."
wget http://storage.googleapis.com/nativeclient-mirror/nacl/nacl_sdk/nacl_sdk.zip
echo "Decompress nacl_sdk.zip"
unzip nacl_sdk.zip
nacl_sdk/naclsdk update --force pepper_canary
fi
if [ "$PLATFORM"x = "android"x ]; then
install_android_ndk
fi
popd

View File

@ -0,0 +1,198 @@
#!/bin/bash
# Generate JS bindings for Cocos2D-X
# ... using Android NDK system headers
# ... and automatically update submodule references
# ... and push these changes to remote repos
# Dependencies
#
# For bindings generator:
# (see ../../../tojs/genbindings.sh
# ... for the defaults used if the environment is not customized)
#
# * $PYTHON_BIN
# * $CLANG_ROOT
# * $NDK_ROOT
#
# For automatically pushing changes:
#
# * REMOTE_AUTOGEN_BINDINGS_REPOSITORY
# * REMOTE_COCOS2DX_REPOSITORY
# * Note : Ensure you have commit access to above repositories
# * COCOS2DX_PULL_BASE
# * hub
# * see http://defunkt.io/hub/
# * Ensure that hub has an OAuth token to REMOTE_COCOS2DX_REPOSITORY
# * see http://defunkt.io/hub/hub.1.html#CONFIGURATION
#Set git user
git config --global user.email "CocosRobot@gmail.com"
git config --global user.name "CocosRobot"
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
COCOS2DX_ROOT="$DIR"/../..
TOJS_ROOT=$COCOS2DX_ROOT/tools/tojs
GENERATED_WORKTREE="$COCOS2DX_ROOT"/scripting/javascript/bindings/generated
REMOTE_AUTOGEN_BINDINGS_REPOSITORY="https://github.com/angeltown/cocos2dx-autogen-bindings.git"
REMOTE_COCOS2DX_REPOSITORY="https://github.com/angeltown/cocos2d-x.git"
COCOS2DX_PULL_BASE="dumganhar/cocos2d-x:travis"
sudo apt-get --force-yes --yes install python-yaml python-cheetah
# Update cocos2d-x repo
# It needs to be updated in Jenkins command before executing this script.
#pushd "$COCOS2DX_ROOT"
#git checkout -f
#git checkout gles20
#git pull upstream gles20
#rm -rf "$GENERATED_WORKTREE"
#git submodule update --init
#popd
# Update submodule of auto-gen JSBinding repo.
pushd "$GENERATED_WORKTREE"
git checkout -B master
#Set remotes
git remote add upstream https://${GH_TOKEN}@github.com/angeltown/cocos2dx-autogen-bindings.git 2> /dev/null > /dev/null
echo "Delete all directories and files except '.git' and 'README'."
ls -a | grep -E -v ^\[.\]\{1,2\}$ | grep -E -v ^\.git$ | grep -E -v ^README$ | xargs -I{} rm -rf {}
echo "Show files in scripting/javascript/bindings/generated folder."
ls -a
popd
# Exit on error
set -e
# 1. Generate JS bindings
pushd "$TOJS_ROOT"
./genbindings.sh
popd
echo
echo Bindings generated successfully
echo
if [ -z "${REMOTE_AUTOGEN_BINDINGS_REPOSITORY+aaa}" ]; then
echo
echo Environment variable must be set REMOTE_AUTOGEN_BINDINGS_REPOSITORY
echo This script expects to automatically push changes
echo to this repo
echo example
echo REMOTE_AUTOGEN_BINDINGS_REPOSITORY=\"git@github.com:folecr/cocos2dx-autogen-bindings.git\"
echo REMOTE_AUTOGEN_BINDINGS_REPOSITORY=\"\$HOME/test/cocos2dx-autogen-bindings\"
echo
echo Exiting with failure.
echo
exit 1
fi
if [ -z "${COMMITTAG+aaa}" ]; then
# ... if COMMITTAG is not set, use this machine's hostname
COMMITTAG=`hostname -s`
fi
echo
echo Using "'$COMMITTAG'" in the commit messages
echo
ELAPSEDSECS=`date +%s`
echo Using "$ELAPSEDSECS" in the branch names for pseudo-uniqueness
GENERATED_BRANCH=autogeneratedbindings_"$ELAPSEDSECS"
# 2. In JSBindings repo, Check if there are any files that are different from the index
pushd "$GENERATED_WORKTREE"
# Run status to record the output in the log
git status
echo
echo Comparing with HEAD ...
echo
# Don't exit on non-zero return value
set +e
git diff --stat --exit-code
DIFF_RETVAL=$?
if [ $DIFF_RETVAL -eq 0 ]
then
echo
echo "No differences in generated files"
echo "Exiting with success."
echo
exit 0
else
echo
echo "Generated files differ from HEAD. Continuing."
echo
fi
# Exit on error
set -e
# 3. In JSBindings repo, Check out a branch named "autogeneratedbindings" and commit the auto generated bindings to it
git checkout -b "$GENERATED_BRANCH"
git add --verbose .
git add --verbose -u .
git commit --verbose -m "$COMMITTAG : autogenerated bindings"
# 4. In JSBindings repo, Push the commit with generated bindings to "master" of the auto generated bindings repository
git push -fq upstream "$GENERATED_BRANCH":master 2> /dev/null
popd
if [ -z "${REMOTE_COCOS2DX_REPOSITORY+aaa}" ]; then
echo
echo Environment variable is not set REMOTE_COCOS2DX_REPOSITORY
echo This script will NOT automatically push changes
echo unless this variable is set.
echo example
echo REMOTE_COCOS2DX_REPOSITORY=\"git@github.com:cocos2d/cocos2d-x.git\"
echo REMOTE_COCOS2DX_REPOSITORY=\"\$HOME/test/cocos2d-x\"
echo
echo Exiting with success.
echo
exit 0
fi
COCOS_BRANCH=updategeneratedsubmodule_"$ELAPSEDSECS"
pushd "${DIR}"
# 5. In Cocos2D-X repo, Checkout a branch named "updategeneratedsubmodule" Update the submodule reference to point to the commit with generated bindings
cd "${COCOS2DX_ROOT}"
git add scripting/javascript/bindings/generated
git checkout -b "$COCOS_BRANCH"
git commit -m "$COMMITTAG : updating submodule reference to latest autogenerated bindings"
#Set remotes
git remote add upstream https://${GH_TOKEN}@github.com/angeltown/cocos2d-x.git 2> /dev/null > /dev/null
# 6. In Cocos2D-X repo, Push the commit with updated submodule to "master" of the cocos2d-x repository
git push -fq upstream "$COCOS_BRANCH" 2> /dev/null
if [ -z "${COCOS2DX_PULL_BASE+aaa}" ]; then
echo
echo Environment variable is not set COCOS2DX_PULL_BASE
echo This script will NOT automatically generate pull requests
echo unless this variable is set.
echo example
echo COCOS2DX_PULL_BASE=\"cocos2d/cocos2d-x:master\"
echo COCOS2DX_PULL_BASE=\"username/repository:branch\"
echo
echo Exiting with success.
echo
exit 0
fi
# 7.
curl --user "angeltown:$GH_PASSWORD" --request POST --data "{ \"title\": \"$COMMITTAG : updating submodule reference to latest autogenerated bindings\", \"body\": \"\", \"head\": \"angeltown:${COCOS_BRANCH}\", \"base\": \"travis\"}" https://api.github.com/repos/dumganhar/cocos2d-x/pulls 2> /dev/null > /dev/null
# ${HUB} pull-request "$COMMITTAG : updating submodule reference to latest autogenerated bindings" -b "$COCOS2DX_PULL_BASE" -h "$COCOS_BRANCH"
popd

View File

@ -0,0 +1,37 @@
#!/bin/bash
# exit this script if any commmand fails
set -e
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
COCOS2DX_ROOT="$DIR"/../..
if [ "$GEN_JSB"x = "YES"x ]; then
if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then
exit 0
fi
cd $COCOS2DX_ROOT/tools/travis-scripts
./generate-jsbindings.sh
fi
build_android()
{
cd $COCOS2DX_ROOT/samples/$1/$2/proj.android
./build_native.sh
}
if [ "$PLATFORM"x = "android"x ]; then
build_android Cpp HelloCpp
build_android Javascript TestJavascript
build_android Lua TestLua
fi
if [ "$PLATFORM"x = "nacl"x ]; then
cd $COCOS2DX_ROOT
make -j4
fi
if [ "$PLATFORM"x = "linux"x ]; then
cd $COCOS2DX_ROOT
make -j4
fi