Example #1
0
 fzBuffer Data::inflateZIPWithHint(unsigned char *input, unsigned int inLength, unsigned int outLengthHint)
 {
     unsigned int outLength = 0;
     unsigned char* output;
     int err = inflateMemoryWithHint(input, inLength, &output, &outLength, outLengthHint );
     
     if (err != Z_OK || output == NULL) {
         if (err == Z_MEM_ERROR)
             FZLOGERROR("ZIP: Out of memory while decompressing map data.");
         
         else if (err == Z_VERSION_ERROR)
             FZLOGERROR("ZIP: Incompatible zlib version.");
         
         else if (err == Z_DATA_ERROR)
             FZLOGERROR("ZIP: Incorrect zlib compressed data.");
         
         else
             FZLOGERROR("ZIP: Unknown error while decompressing map data.");
         
         delete [] output;
         output = NULL;
         outLength = 0;
     }
     
     return fzBuffer((char*)output, outLength);
 }
Example #2
0
 fzBuffer IO::loadFile(const char *absolutePath)
 {
     FZ_ASSERT(absolutePath, "Absolute path cannot be NULL.");
     if(absolutePath[0] == '\0')
         return fzBuffer::empty();
     
     FILE *f = fopen(absolutePath, "rb");
     if( f == NULL )
         return fzBuffer::empty();
     
     
     fseek(f, 0, SEEK_END);
     size_t size = ftell(f);
     fseek(f, 0, SEEK_SET);
     
     
     char *buffer = new(std::nothrow) char[size+1];
     if(buffer == NULL) {
         fclose(f);
         FZLOGERROR("IO: Impossible to allocate memory.");
         return fzBuffer::empty();
     }
     size_t read = fread(buffer, 1, size, f);
     fclose(f);
     if( read != size ) {
         FZLOGERROR("IO: Abnormal reading error. Probably the path is not a file.");
         delete [] buffer;
         return fzBuffer::empty();
     }
     // NULL TERMINATED
     buffer[size] = '\0';
     
     return fzBuffer(buffer, size+1);
 }
Example #3
0
    bool GLProgram::link()
    {
        glLinkProgram(m_program);
        glValidateProgram(m_program);

        GLint status;
        glGetProgramiv(m_program, GL_LINK_STATUS, &status);

        if (status == GL_FALSE) {
            FZLOGERROR("GLProgram: Error linking program: %i.", m_program);
            FZLOGERROR("%s", getProgramLog().c_str());
            
            fzGLDeleteProgram( m_program );
            m_program = 0;
            return false;
        }

        char uniformName[256];
        GLint nuUniforms = 0;
        glGetProgramiv(m_program, GL_ACTIVE_UNIFORMS, &nuUniforms);

        for(fzInt index = 0; index < nuUniforms; ++index)
        {
            glGetActiveUniform(m_program, index, 256, NULL, NULL, NULL, uniformName);
            m_uniforms.insert(uniformsPair(fzHash(uniformName), glGetUniformLocation(m_program, uniformName)));
        }
        CHECK_GL_ERROR_DEBUG();
        
        setUniform1i("u_texture", 0);

        return true;
    }
Example #4
0
    void Director::applicationLaunched(void *options)
    {
        FZ_ASSERT(m_isInitialized == false, "FORZE was already launched.")
        FZ_ASSERT(p_appdelegate, "FORZE was not initialized properly. App delegate is missing.");
        FZ_ASSERT(OSW::Instance(), "OS wrapper should call Director::applicationLaunching() before.");
        FZLOGINFO("Director: Application launched.");

        if(!m_isInitialized) {
            
            m_isInitialized = true;

            // initialize singletons
            DataStore::Instance();
            DeviceConfig::Instance().logDebugMode();
            DeviceConfig::Instance().logDeviceInfo();
            
            // set default GL values
            setDefaultGLValues();
            
            p_appdelegate->applicationLaunched(options);
            
            if(m_scenesStack.size() == 0)
            {
                FZLOGERROR("Director: A running scene is expected before applicationLaunched() is called.");
                FZLOGERROR("Director: You should call Director::Instance().runWithScene( <YOUR FORZE::SCENE> ).\n");
            }
            startAnimation();
        }
    }
Example #5
0
 fzBuffer Data::inflateCCZ(unsigned char *input, unsigned int inLength)
 {
     // load file into memory
     const CCZHeader *header = reinterpret_cast<const CCZHeader*>(input);
     
     
     // verify header
     if(!(header->sig[0] == 'C' &&
          header->sig[1] == 'C' &&
          header->sig[2] == 'Z' &&
          header->sig[3] == '!')) {
         FZLOGERROR("IO:CCZ: Invalid CCZ file.");
         return fzBuffer::empty();
     }
     
     
     // verify header version
     if( fzBitOrder_int16BigToHost(header->version) > 2 ) {
         FZLOGERROR("IO:CCZ: Unsupported version.");
         return fzBuffer::empty();
     }
     
     
     // verify compression format
     if( fzBitOrder_int16BigToHost(header->compression_type) != CCZ_COMPRESSION_ZLIB ) {
         FZLOGERROR("IO:CCZ: Unsupported compression method.");
         return fzBuffer::empty();
     }
     
     
     uLong fileLen = inLength-1;
     uint32_t expectedLen = fzBitOrder_int32BigToHost( header->len );
     uLongf realLen = expectedLen;
     
     char *contentData = new char[expectedLen];
     uLongf source = (uLongf)input + sizeof(CCZHeader);
     
     
     int ret = uncompress((Bytef*)contentData,
                          &realLen,
                          (Bytef*)source,
                          (uLong)(fileLen - sizeof(CCZHeader))
                          );
             
     if( ret != Z_OK ) {
         FZLOGERROR("IO:CCZ: Failed to uncompress data. Error code: %d.", ret);
         delete [] contentData;
         return fzBuffer::empty();
     }
     FZ_ASSERT(realLen <= expectedLen, "Corrupted .CCZ. The expected uncompressed data length is wrong. Buffer overflow occurred.");
     
     return fzBuffer(contentData, expectedLen);
 }
fzBuffer ResourcesManager::loadResource(const char *filename, fzUInt *outFactor) const
{
    FZ_ASSERT(filename != NULL, "Filename can not be NULL.");
    FZ_ASSERT(outFactor != NULL, "outFactor can not be NULL.");

    // REMOVING FORCED FLAGS
    char *filenameCpy = fzStrcpy(filename);
    IO::removeFileSuffix(filenameCpy);

    // LOOK FOR TEXTURE
    *outFactor = 0;
    char absolutePath[STRING_MAX_SIZE];
    fzUInt factor, priority = 0;

    while (getPath(filenameCpy, priority, absolutePath, &factor))
    {
        fzBuffer buffer = IO::loadFile(absolutePath);
        if(!buffer.isEmpty()) {
            *outFactor = factor;
            delete filenameCpy;
            return buffer;
        }
        ++priority;
    }

    FZLOGERROR("IO: \"%s\" not found.", filename);
    delete filenameCpy;
    return fzBuffer::empty();
}
Example #7
0
void Grabber::grab(Texture2D* texture)
{
    FZ_ASSERT(texture, "Texture can not be NULL");

    FZRETAIN_TEMPLATE(texture, p_texture);

    // generate FBO
    if(m_fbo == 0)
        fzGLGenFramebuffers(1, &m_fbo);

    // cache current framebuffer
    m_oldFBO = fzGLGetFramebuffer();

    // bind FBO
    fzGLBindFramebuffer(m_fbo);

    // associate texture with FBO
    fzGLFramebufferTexture2D(FZ_FRAMEBUFFER, FZ_COLOR_ATTACHMENT0, GL_TEXTURE_2D, p_texture->getName(), 0);

    // check if it worked
    GLuint status = fzGLCheckFramebufferStatus(FZ_FRAMEBUFFER);
    if (status != FZ_FRAMEBUFFER_COMPLETE) {
        FZLOGERROR("Grabber: Could not attach texture to framebuffer. Status: 0x%04X.", status);
    }

    fzGLClearColor(fzColor4F(0,0,0,0));
    glClear(GL_COLOR_BUFFER_BIT);

    fzGLBindFramebuffer(m_oldFBO);
    m_oldFBO = -1;

    CHECK_GL_ERROR_DEBUG();
}
Example #8
0
    void fzMath_mat4PerspectiveProjection(fzFloat fovY, fzFloat aspect,
                                          fzFloat zNear, fzFloat zFar,
                                          float *output)
    {        
        FZ_ASSERT(output != NULL, "Output matrix cannot be NULL.");

        fzFloat r = FZ_DEGREES_TO_RADIANS(fovY / 2);
        fzFloat deltaZ = zFar - zNear;
        fzFloat s = fzMath_sin(r);
        fzFloat cotangent = 0;
        
        if (deltaZ == 0 || s == 0 || aspect == 0) {
            FZLOGERROR("Perpertive impossible.");
            return;
        }
        
        cotangent = fzMath_cos(r) / s;
        
        fzMath_mat4Identity(output);
        output[0] = cotangent / aspect;
        output[5] = cotangent;
        output[10] = -(zFar + zNear) / deltaZ;
        output[11] = -1;
        output[14] = -2 * zNear * zFar / deltaZ;
        output[15] = 0;
    }
Example #9
0
    Texture2D* Director::getScreenshot(int format)
    {
#if 0
        fzSize viewPort = getViewPort();
        fzPixelInfo formatInfo = Texture2D::getPixelInfo((fzPixelFormat)format);
        fzTextureInfo textureInfo = Texture2D::getTextureInfo(formatInfo.textureFormat);
        
        fzUInt bufferSize = (formatInfo.bbp * viewPort.width * viewPort.height)/8;
        unsigned char *pixels = new unsigned char[bufferSize];
        
        glReadPixels(0, 0, viewPort.width, viewPort.height, textureInfo.openGLFormat, formatInfo.dataType, pixels);
        
        
        Texture2D *texture;
        try {
            texture = new Texture2D(pixels, (fzTextureFormat)format,
                                    fzMath_nextPOT(viewPort.width), fzMath_nextPOT(viewPort.height), viewPort);
            
        } catch (std::exception& error) {
            FZLOGERROR("%s", error.what());
            delete [] pixels;
            return NULL;
        }
        return texture;
#endif
        return NULL;
    }
 fzSpriteFrame SpriteFrameCache::getSpriteFrameByKey(const char* key) const
 {
     fzSpriteFrame frame = getSpriteFrameByHash(fzHash(key));
     if(!frame.isValid()) {
         FZLOGERROR("SpriteFrameCache: The fzSpriteFrame was not found for the key \"%s\".", key);
     }
     return frame;
 }
Example #11
0
 string GLShader::getShaderLog() const
 {
     if(!m_shader)
         FZLOGERROR("GLShader: Shader is not compiled yet.");
     else
         return logForOpenGLObject(m_shader, (GLInfoFunction)&glGetShaderiv, (GLLogFunction)&glGetShaderInfoLog);
     
     return string();
 }
Example #12
0
    bool GLShader::compileShader(const char* source)
    {
        FZ_ASSERT(m_shader == 0, "Shader is already compiled");
        
        m_shader = glCreateShader(m_shaderType);
        
        glShaderSource(m_shader, 1, &source, NULL);
        glCompileShader(m_shader);
        
        GLint status;
        glGetShaderiv(m_shader, GL_COMPILE_STATUS, &status);
        
        if(!status) {
            FZLOGERROR("GLShader: Error compiling %s.",shaderTypeToText(m_shaderType));
            FZLOGERROR("%s", getShaderLog().c_str());
        }
        CHECK_GL_ERROR_DEBUG();

        return !!status;
    }
Example #13
0
 bool IO::writeFile(const char *data, const char *absolutePath)
 {
     FZ_ASSERT(data, "Data can not be NULL");
     FZ_ASSERT(absolutePath, "absolutePath can not be NULL");
     
     FILE *f = fopen(absolutePath, "w");
     if( f == NULL ) {
         FZLOGERROR("IO: \"%s\" can not be opened.", absolutePath);
         return false;
     }
     
     int error = fputs(data, f);
     fclose (f);
     
     if(error <= 0) {
         FZLOGERROR("IO: Error writing data. Error code: %d.", error);
         return false;
     }
     return true;
 }
Example #14
0
    Event* EventManager::addEvent(const Event& newEvent)
    {
        FZ_ASSERT(newEvent.getOwner(), "Event owner can not be NULL.");

        if(!(newEvent.getType() & m_flags))
            return NULL;
            
        switch (newEvent.getState())
        {
            case kFZEventState_Began:
#if FORZE_DEBUG > 0
            {
                eventList::const_iterator it(m_events.begin());
                for(; it != m_events.end(); ++it) {
                    if(newEvent.getIdentifier() == it->getIdentifier() &&
                       newEvent.getOwner() == it->getOwner())
                    {
                        FZLOGERROR("EventManager: Event duplicated:");
                        it->log();
                    }
                }
            }
#endif
            case kFZEventState_Indifferent:
            {
                FZ_ASSERT(newEvent.getDelegate() == NULL, "Event delegate should be NULL.");
                m_events.push_back(newEvent);
                return &(m_events.back());
            }
            case kFZEventState_Updated:
            case kFZEventState_Ended:
            case kFZEventState_Cancelled:
            {
                eventList::iterator it(m_events.begin());
                for(; it != m_events.end(); ++it) {
                    Event *e = &(*it);
                    if(newEvent.getIdentifier() == e->getIdentifier() &&
                       newEvent.getOwner() == e->getOwner() &&
                       newEvent.getType() == e->getType())
                    {
                        e->update(newEvent);
                        return e;
                    }
                }
                return NULL;
            }
            default:
            {
                FZ_ASSERT(false, "Invalid event state.");
                return NULL;
            }
        }
    }
fzBuffer ResourcesManager::loadResource(const char *filename) const
{
    FZ_ASSERT(filename != NULL, "Filename can not be NULL.");
    char absolutePath[STRING_MAX_SIZE];
    generateAbsolutePath(filename, 1, absolutePath);

    fzBuffer buffer = IO::loadFile(absolutePath);
    if(buffer.isEmpty())
        FZLOGERROR("IO: \"%s\" not found.", filename);

    return buffer;
}
Example #16
0
    void EventManager::addDelegate(EventDelegate *target, uint16_t flags, fzInt priority, fzEventHandlerMode mode)
    {
        FZ_ASSERT(target != NULL, "Target argument must be non-NULL.");
        
        fzEventHandler *handler = getHandlerForTarget(target);
        if(handler) {
            handler->mode = mode;
            
            if(priority != handler->priority) {
                updateHandlerFlags(handler, 0);
                handler = NULL;
                
            }else if(flags != handler->flags)
                updateHandlerFlags(handler, flags);
        }
        
        if(handler == NULL && flags != 0) {
            fzEventHandler newHandle;
            newHandle.flags = flags;
            newHandle.mode = mode;
            newHandle.priority = priority;
            newHandle.delegate = target;
            m_handlers.insert(indexForPriority(priority), newHandle);
        }
        
#if defined (FORZE_DEBUG) && FORZE_DEBUG > 0
        uint16_t compatibility = checkCompatibility(flags);
        
        if((flags & kFZEventType_Tap) != kFZEventType_Tap) {
            if(compatibility & kFZEventType_Touch)
                FZLOGERROR("EventManager: Touch events are not available in this device.");
            
            if(compatibility & kFZEventType_Mouse)
                FZLOGERROR("EventManager: Mouse events are not available in this device.");
        }
        if(compatibility & kFZEventType_MouseRight)
            FZLOGERROR("EventManager: Mouse right events are not available in this device.");
        if(compatibility & kFZEventType_Keyboard)
            FZLOGERROR("EventManager: Keyboard events are not available in this device.");
        if(compatibility & kFZEventType_Trackpad)
            FZLOGERROR("EventManager: Trackpad events are not available in this device.");
        if(compatibility & kFZEventType_Accelerometer)
            FZLOGERROR("EventManager: Accelerometer events are not available in this device.");
        if(compatibility & kFZEventType_Gyro)
            FZLOGERROR("EventManager: Gyroscope events are not available in this device.");
#endif
        
        updateFlags();
    }
Example #17
0
 fzBuffer Data::B64Decode(const char *input, fzUInt inLength)
 {
     FZ_ASSERT(input, "Input pointer cannot be NULL");
     FZ_ASSERT(inLength > 0, "Input data length cannot be 0.");
     
     //should be enough to store 6-bit buffers in 8-bit buffers
     fzUInt outputSize = Base64decode_len(input);
     char *output = new(std::nothrow) char[outputSize];
     
     if( output ) {
         Base64decode(output, input);
         return fzBuffer(output, outputSize);
         
     }else{
         FZLOGERROR("Base64: error allocating memory.");
         return fzBuffer::empty();
     }
 }
Example #18
0
    Font* FontCache::addFont(const char* filename, fzFloat lineHeight)
    {
        FZ_ASSERT(filename != NULL, "Filename argument must be non-NULL.");
        
        // Make string mutable
        char *filenameCpy = fzStrcpy(filename);
        
        // Remove "-x" suffix
        IO::removeFileSuffix(filenameCpy);
        
        uint32_t hash = fzHash(filenameCpy);
        Font *font = getFontForHash(hash);
        
        if(font != NULL && strcmp(IO::getExtension(filenameCpy), "ttf") == 0) {
            // Rewritting
            FZ_ASSERT(lineHeight > 0, "Line height must me positive.");
            FZLog("NOT IMPLEMENTED");
        }
        
        if(font == NULL) {
            
            try {
                font = new Font(filenameCpy, lineHeight);
                font->retain();
                m_fonts.insert(fontsPair(hash, font));

            } catch(std::exception& error) {
                delete filenameCpy;

                FZLOGERROR("%s", error.what());
                return NULL;
            }
        }
        delete filenameCpy;
        
        return font;
    }
    void SpriteFrameCache::removeSpriteFramesFromFile(const char* plist)
    {
        fzUInt factor;
        fzBuffer data = ResourcesManager::Instance().loadResource(plist, &factor);
        if(data.isEmpty())
            return;
        
        xml_document<> doc;
        doc.parse<parse_fastest>(data.getPointer());
        
        xml_node<> *rootNode, *frameNode;        
        
        // Parse frames
        rootNode = doc.first_node("frames");
        
        if(rootNode == NULL) {
            FZLOGERROR("SpriteFrameCache: <frames> tag wasn't found.");
            data.free();
            return;
        }
        
        for(frameNode = rootNode->first_node(); frameNode; frameNode = frameNode->next_sibling())
        {
            FZ_ASSERT(strncmp(frameNode->name(), "node", frameNode->name_size()) == 0, "XML tag is not \"node\".");

            // NAME
            xml_attribute<> *attribute = frameNode->first_attribute("name");
            if(attribute == NULL) {
                FZ_ASSERT(false, "SpriteFrameCache: <node name> attribute wasn't found.");
                continue;
            }
            
            m_frames.erase(fzHash(attribute->value(), attribute->value_size()));
        }
        data.free();
    }
Example #20
0
 bool fzMath_mat4Invert(const float *m, float *mOut)
 {
     double det;
     int i;
     
     mOut[0] = m[5] * m[10] -
     m[9]  * m[6];
     
     mOut[4] = -m[4] * m[10] +
     m[8]  * m[6];
     
     mOut[8] = m[4] * m[9] -
     m[8]  * m[5];
     
     mOut[12] = -m[4] * m[9] * m[14] +
     m[4]  * m[10] * m[13] +
     m[8]  * m[5] * m[14] -
     m[8]  * m[6] * m[13] -
     m[12] * m[5] * m[10] +
     m[12] * m[6] * m[9];
     
     mOut[1] = -m[1] * m[10] +
     m[9]  * m[2];
     
     mOut[5] = m[0] * m[10] -
     m[8]  * m[2];
     
     mOut[9] = -m[0] * m[9] +
     m[8]  * m[1];
     
     mOut[13] = m[0] * m[9] * m[14] -
     m[0]  * m[10] * m[13] -
     m[8]  * m[1] * m[14] +
     m[8]  * m[2] * m[13] +
     m[12] * m[1] * m[10] -
     m[12] * m[2] * m[9];
     
     mOut[2] = m[1]  * m[6] -
     m[5]  * m[2];
     
     mOut[6] = -m[0]  * m[6] +
     m[4]  * m[2];
     
     mOut[10] = m[0]  * m[5] -
     m[4]  * m[1];
     
     mOut[14] = -m[0]  * m[5] * m[14] +
     m[0]  * m[6] * m[13] +
     m[4]  * m[1] * m[14] -
     m[4]  * m[2] * m[13] -
     m[12] * m[1] * m[6] +
     m[12] * m[2] * m[5];
     
     mOut[3] = 0;
     mOut[7] = 0;
     mOut[11] = 0;
     mOut[15] = 1;
     
     det = m[0] * mOut[0] + m[1] * mOut[4] + m[2] * mOut[8] + m[3] * mOut[12];
     
     if (det == 0) {
         FZLOGERROR("Math: Determinant is zero, imposible to inverse.");
         return false;
     }
     
     det = 1.0 / det;
     
     for (i = 0; i < 15; i++)
         mOut[i] *= det;
     
     return true;
 }
Example #21
0
 ActionInstant* ActionInstant::copy() const
 {
     FZLOGERROR("ActionInstant: Copying is not implemented. Override this method.");
     return NULL;
 }
    void SpriteFrameCache::addSpriteFrames(const char* coordsFilename, Texture2D *texture)
    {        
        fzUInt factor;
        fzBuffer data = ResourcesManager::Instance().loadResource(coordsFilename, &factor);
        if(data.isEmpty())
            return;
        
        xml_document<> doc;
        
        try {
            doc.parse<parse_fastest | parse_validate_closing_tags>(data.getPointer());
            
        } catch(std::exception &error) {
            data.free();
            FZLOGERROR("SpriteFrameCache: Error parsing \"%s\". rapidXML exception: %s", coordsFilename, error.what());
            
            return;
        }
        
        xml_node<> *rootNode, *subNode, *node;

        rootNode = doc.first_node("metadata");
        
        if(texture == NULL) {
            subNode = rootNode->first_node("textureFileName");
            if(subNode) {
                char *filename = fzStrcpy(subNode->value(), subNode->value_size());
                texture = TextureCache::Instance().addImage(filename);
                delete filename;
            }
        }
        
        // Parse metadata
        if(texture == NULL) {
            data.free();
            FZLOGERROR("SpriteFrameCache: Error parsing \"%s\". Error pTexture could not be loaded.", coordsFilename);
            return;
        }
        
        // Parse frames
        rootNode = doc.first_node("frames");
        
        if(rootNode == NULL) {
            data.free();
            FZLOGERROR("SpriteFrameCache: Error parsing \"%s\". <frames> tag wasn't found.", coordsFilename);
            return;
        }
        
        for(subNode = rootNode->first_node(); subNode; subNode = subNode->next_sibling())
        {
            if(strncmp(subNode->name(), "frame", subNode->name_size()) != 0) {
                FZLOGERROR("SpriteFrameCache: Error parsing \"%s\". XML format is not correct.", coordsFilename);
                continue;
            }
            
            fzRect rect;
            fzPoint offset = FZPointZero;
            fzSize originalSize = FZSizeZero;
            bool rotated = false;
            
            // NAME
            xml_attribute<> *attribute = subNode->first_attribute("name");
            if(attribute == NULL) {
                FZLOGERROR("SpriteFrameCache: Error parsing \"%s\". <node name> attribute wasn't found.", coordsFilename);
                continue;
            }
            uint32_t hash = fzHash(attribute->value(), attribute->value_size());
            
            if(getSpriteFrameByHash(hash).isValid())
                continue;
            
            
            // ORIGIN
            node = subNode->first_node("p");
            if(node == NULL) {
                FZLOGERROR("SpriteFrameCache: Error parsing \"%s\". <p> tag wasn't found.", coordsFilename);
                continue;
            }
            attribute = node->first_attribute("x");
            if(attribute == NULL) {
                FZLOGERROR("SpriteFrameCache: Error parsing \"%s\". <p x> attribute wasn't found.", coordsFilename);
                continue;
            }            
            rect.origin.x = atof(attribute->value()) / factor;
            
            attribute = node->first_attribute("y");
            if(attribute == NULL) {
                FZLOGERROR("SpriteFrameCache: Error parsing \"%s\". <p y> attribute wasn't found.", coordsFilename);
                continue;
            } 
            rect.origin.y = atof(attribute->value()) / factor;
            
            
            // SIZE
            node = subNode->first_node("s");
            if(node == NULL) {
                FZLOGERROR("SpriteFrameCache: Error parsing \"%s\". <s> tag wasn't found.", coordsFilename);
                continue;
            }
            
            attribute = node->first_attribute("x");
            if(attribute == NULL) {
                FZLOGERROR("SpriteFrameCache: Error parsing \"%s\". <s x> attribute wasn't found.", coordsFilename);
                continue;
            }            
            rect.size.width = atof(attribute->value()) / factor;
            
            attribute = node->first_attribute("y");
            if(attribute == NULL) {
                FZLOGERROR("SpriteFrameCache: Error parsing \"%s\". <s y> attribute wasn't found.", coordsFilename);
                continue;
            } 
            rect.size.height = atof(attribute->value()) / factor;
            
            
            // OFFSET POSITION
            node = subNode->first_node("o");
            if(node) {
                attribute = node->first_attribute("x");
                if(attribute)
                    offset.x = atof(attribute->value()) / factor;
                
                attribute = node->first_attribute("y");
                if(attribute)
                    offset.y = atof(attribute->value()) / factor;
            } 
            
            
            // UNTRIMMED SIZE (ORIGINAL)
            node = subNode->first_node("u");
            if(node) {
                attribute = node->first_attribute("x");
                if(attribute)
                    originalSize.width = atof(attribute->value()) / factor;
                
                attribute = node->first_attribute("y");
                if(attribute)
                    originalSize.height = atof(attribute->value()) / factor;
            }
            
            
            // IS ROTATED
            node = subNode->last_node("r");
            if(node) {
                attribute = node->first_attribute("x");
                if(attribute)
                    rotated = atoi(attribute->value());
            }
            
            if(originalSize == FZSizeZero)
                originalSize = rect.size;
            
            // create frame
            fzSpriteFrame spriteFrame(texture, rect, offset, originalSize, rotated);
            m_frames.insert(framesPair(hash, spriteFrame));
        }
        data.free();
    }
Example #23
0
 void Font::loadFNTData(char* data)
 {
     if(data == NULL)
         FZ_RAISE("Font:FNT: Imposible to load FNT data. Pointer is NULL.");
     
     int line = 1;
     char word[30];
     bool parsedCommon = false;
     bool parsedPage = false;
     
     while(*data != '\0') {
     
         firstWord(data, word);
         
         switch(fzHash(word)) {
             case "common"_hash:
             {
                 int nuPages = 0;
                 int nu_arg = sscanf(data, "common lineHeight=%f base=%*d scaleW=%*d scaleH=%*d pages=%d", &m_lineHeight, &nuPages);
                 
                 if(nu_arg != 2)
                     FZ_RAISE_STOP("Font:FNT: Line 2. Sintax error. Error parsing FNT common data.");
                 
                 if(nuPages != 1)
                     FZ_RAISE_STOP("Font:FNT: Line 2. Number of pages must be 1.");
                 
                 if(m_lineHeight == 0)
                     FZ_RAISE_STOP("Font:FNT: Line 2. Line height parsing error.");
                 
                 m_lineHeight /= m_factor;
                 parsedCommon = true;
                 
                 break;
             }
             case "page"_hash:
             {
                 char filename[256];
                 int nu_arg = sscanf(data, "page id=%*d file=\"%s\"", filename);
                 
                 if(nu_arg != 1)
                     FZ_RAISE_STOP("Font:FNT: Line 3. Sintax erro. Error parsing FNT page data.");
                 
                 if(filename[0] == '\0')
                     FZ_RAISE_STOP("Font:FNT: Line 3. texture's path is missing.");
                 
                 filename[strlen(filename)-1] = '\0'; // remove last "
                 p_texture = TextureCache::Instance().addImage(filename);
                 if(p_texture == NULL)
                     FZ_RAISE("Font:FNT: Font's texture is missing.");
                 
                 p_texture->retain();
                 parsedPage = true;
                 
                 break;
             }
             case "char"_hash:
             {
                 // CHAR DATA PARSING
                 int charID = 0;
                 fzCharDef temp_char;
                 
                 int nu_arg = sscanf(data, "char id=%d x=%f y=%f width=%f height=%f xoffset=%f yoffset=%f xadvance=%f",
                                 &charID,
                                 &temp_char.x, &temp_char.y,
                                 &temp_char.width, &temp_char.height,
                                 &temp_char.xOffset, &temp_char.yOffset,
                                 &temp_char.xAdvance);
                 
                 temp_char.x         /= m_factor;
                 temp_char.y         /= m_factor;
                 temp_char.width     /= m_factor;
                 temp_char.height    /= m_factor;
                 temp_char.xOffset   /= m_factor;
                 temp_char.yOffset   /= m_factor;
                 temp_char.xAdvance  /= m_factor;
                 
                 if(nu_arg != 8) {
                     FZLOGERROR("Font:FNT: Line %d. Error parsing FNT char data, syntax is not correct.", line);
                     break;
                 }
                 
                 if(charID >= 256) {
                     FZLOGERROR("Font:FNT: Line %d. CharID is out of bounds [0, 255].", line);
                     break;
                 }
                 
                 m_chars[charID] = temp_char;
                 break;
             }
             case "kerning"_hash:
             {
                 // KERNING DATA PARSING
                 int first = 0;
                 int second = 0;
                 fzFloat amount = 0;
                 
                 int nu_arg = sscanf(data, "kerning first=%d second=%d amount=%f",
                                 &first, &second, &amount);
                 
                 if(first < 0 || second < 0 || first > 255 || second > 255) {
                     FZLOGERROR("Font:FNT: Line %d. Invalid indexes.", line);
                     break;
                 }
                 if(nu_arg != 3) {
                     FZLOGERROR("Font:FNT: Line %d. Error parsing FNT kerning data.", line);
                     break;
                 }
                 
                 uint16_t key = generateKey((uint8_t)first, (uint8_t)second);
                 m_kerning.insert(pair<uint16_t, fzFloat>(key, amount));
                 
                 break;
             }
         }
         
         
         while(true) {
             if(*data != '\0') {
                 if(*(data++) == '\n'){
                     ++line;
                     break;
                 }
             }
         }
     }
     if(!parsedCommon)
         FZ_RAISE_STOP("Font:FNT: FNT common data not found.");
     
     if(!parsedPage)
         FZ_RAISE_STOP("Font:FNT: FNT page data not found.");
 }
Example #24
0
 ActionCamera* ActionCamera::copy() const
 {
     FZLOGERROR("NEEDs implementation.");
     return NULL;
 }
Example #25
0
    int inflateMemoryWithHint(unsigned char *input, unsigned int inLength, unsigned char **output, unsigned int *outLength, unsigned int outLenghtHint )
    {        
        unsigned int bufferSize = outLenghtHint;
        
        // ALLOC OUTPUT BUFFER
        *output = new unsigned char[bufferSize];
        if (!*output) {
            FZLOGERROR("ZIP: Memory alloc failed.");
            return Z_MEM_ERROR;
        }
        
        // DESCOMPRESSION STREAM
        z_stream d_stream;
        d_stream.zalloc = (alloc_func)0;
        d_stream.zfree = (free_func)0;
        d_stream.opaque = (voidpf)0;
        d_stream.next_in  = input;
        d_stream.avail_in = inLength;
        d_stream.next_out = *output;
        d_stream.avail_out = bufferSize;
        
        // INIT STREAM
        int status = inflateInit2(&d_stream, 15 + 32);
        if( status != Z_OK )
            return status;
        
        
        // DESCOMPRESS INPUT DATA
        while (true) {
            status = inflate(&d_stream, Z_NO_FLUSH);
            
            if (status == Z_STREAM_END)
                break;
            
            switch (status) {
                case Z_NEED_DICT:
                    status = Z_DATA_ERROR;
                case Z_DATA_ERROR:
                case Z_MEM_ERROR:
                    inflateEnd(&d_stream);
                    return status;
            }
            
            // REALLOC OUTPUT BUFFER
            if (status != Z_STREAM_END) {
                
                unsigned char *tmp = new(std::nothrow) unsigned char[bufferSize * BUFFER_INC_FACTOR];
                if (! tmp ) {
                    FZLOGERROR("ZIP: Memory realloc failed.");
                    inflateEnd(&d_stream);
                    return Z_MEM_ERROR;
                }
                memcpy(tmp, *output, bufferSize * BUFFER_INC_FACTOR);
                *output = tmp;
                
                d_stream.next_out = *output + bufferSize;
                d_stream.avail_out = bufferSize;
                bufferSize *= BUFFER_INC_FACTOR;                
            }
        }
        *outLength = bufferSize - d_stream.avail_out;
        
        // RELEASE UNUSED BUFFER MEMORY
        FZ_ASSERT(bufferSize >= *outLength, "Strange bug");
//        if(bufferSize != *outLength)
//            *output = (unsigned char*)realloc(*output, *outLength);
        
        status = inflateEnd(&d_stream);
        return status;
    }
Example #26
0
    void DataStore::readFromMemory()
    {
        FZ_ASSERT(p_path, "Path cannot be NULL.");
        if(m_dirty)
            return;
        
        fzBuffer buffer = IO::loadFile(p_path);
        
        if(!buffer.isEmpty()) {
            
            xml_document<> doc;
            doc.parse<parse_fastest | parse_validate_closing_tags>(buffer.getPointer());
            
            xml_node<> *node = doc.first_node();
            if(strncmp(node->name(), XML_SIZE_TAG, node->name_size()) != 0)
                FZ_RAISE("DataStore: XML is corrupted.");

            
            // RESERVE CAPACITY
            reserveCapacity(atoi(node->value())+1);
            
            
            // ITERATE XML
            m_num = 0;
            node = node->next_sibling();
            for(; node; node = node->next_sibling())
            {
                if(strncmp(node->name(), XML_ENTRY_TAG, node->name_size()) != 0) {
                    FZLOGERROR("DataStore: XML entry is corrupted.");
                    continue;
                }
                
                fzStoreEntry &entry = p_store[m_num];
                
                // KEY
                xml_attribute<> *attribute = node->first_attribute(XML_KEY_ATTRIBUTE);
                if(attribute == NULL) {
                    FZLOGERROR("DataStore: Key attribute is missing.");
                    continue;
                }
                entry.key = fzStrcpy(attribute->value(), attribute->value_size());
                entry.hash = fzHash(attribute->value(), attribute->value_size());
                
                
                // ENTRY TYPE
                attribute = node->last_attribute(XML_TYPE_ATTRIBUTE);
                if(attribute == NULL) {
                    FZLOGERROR("DataStore: Type attribute is missing.");
                    continue;
                }
                int type = atoi(attribute->value());                
                
                // DATA
                const char *data = node->value();
                if(data) {
                    switch (type) {
                        case kFZData_string:
                        case kFZData_data:
                        {
                            fzBuffer decoded = Data::B64Decode(data, node->value_size());
                            entry.data = decoded;
                            break;
                        }
                        case kFZData_integer:
                            entry.integerValue = atoi(data);
                            break;
                        case kFZData_float:
                            entry.floatValue = atof(data);
                            break;
                        default:
                            FZ_RAISE("DataStore: Entry type is invalid.");
                            break;
                    }
                }
                entry.type = static_cast<unsigned char>(type);

                ++m_num;
            }
            buffer.free();
            
            FZ_ASSERT(m_num <= m_capacity, "Memory overflow.");
        }
    }
Example #27
0
    bool DataStore::save()
    {
        FZ_ASSERT(p_path, "Path cannot be NULL.");

        if(!m_dirty)
            return true;
        
        xml_document<> doc;
        xml_node<>* node;
                
        // XML DECLARATION
        node = doc.allocate_node(node_declaration);
        node->append_attribute(doc.allocate_attribute("version", "1.0"));
        node->append_attribute(doc.allocate_attribute("encoding", "utf-8"));
        doc.append_node(node);
        
        
        // SIZE TAG
        node = doc.allocate_node(node_element, XML_SIZE_TAG, doc.allocate_string(FZT("%d", m_num)));
        doc.append_node(node);

        fzUInt xmlSize = 60;

        // ENTRIES
        for(fzUInt i = 0; i < m_num; ++i) {
          
            char *content = NULL;
            fzStoreEntry& e = p_store[i];
                        
            switch (e.type) {
                case kFZData_string:
                case kFZData_data:
                {
                    fzBuffer enconded = Data::B64Encode(e.data.getPointer(), e.data.getLength());
                    content = doc.allocate_string(enconded.getPointer());
                    enconded.free();
                    break;
                }
                case kFZData_float:
                    content = doc.allocate_string(FZT("%f", e.floatValue));
                    break;
                case kFZData_integer:
                    content = doc.allocate_string(FZT("%d", e.integerValue));
                    break;
                default:
                    FZLOGERROR("DataStore: Invalid data type.");
                    continue;
            }
            
            node = doc.allocate_node(node_element, XML_ENTRY_TAG, content);
            node->append_attribute(doc.allocate_attribute(XML_KEY_ATTRIBUTE, e.key));
            node->append_attribute(doc.allocate_attribute(XML_TYPE_ATTRIBUTE, doc.allocate_string(FZT("%d", e.type))));
            doc.append_node(node);
            
            xmlSize += 25 + strlen(content) + strlen(e.key);
        }
        
        
        // CREATE DIRECTORY (if needed)
        if(!fzDevice_createDirectory(p_path, false)) {
            FZLOGERROR("DataStore: Error creating directory.");
            return false;
        }
        
        
        // PRINTING
        char *buffer = new char[xmlSize];
        char *end = rapidxml::print(buffer, doc, 0);
        *end = '\0'; // NULL TERMINATION
        
        FZ_ASSERT(end < (buffer + xmlSize), "Memory overflow.");
        
        bool success = IO::writeFile(buffer, p_path);
        delete [] buffer;
        
        m_dirty = !success;
        return success;
    }
Example #28
0
 bool EventDelegate::event(Event&)
 {
     FZLOGERROR("EventDelegate: bool event(Event&) should be overwritten.");
     return false;
 }
Example #29
0
    void Label::createFontChars()
    {
        // Get string length
        fzUInt m_stringLen = m_string.size();
    
        Sprite *fontChar = static_cast<Sprite*>(m_children.front());
        if(m_stringLen > 0)
        {
            // Is font available?
            if(p_font == NULL) {
                FZLOGERROR("Label: Impossible to generate label, font config is missing.");
                return;
            }
            
            // Precalculate label size
            fzFloat longestLine = 0;
            fzUInt currentLine = 0;
            char charId = 0, prevId = 0;
            fzFloat lineWidth[100];
            memset(lineWidth, 0, sizeof(fzFloat) * 100);
            
            for(fzUInt i = 0; i < m_stringLen; ++i) {
                charId = m_string.at(i);
                if(charId < 0)
                    FZ_RAISE("Label: CHAR[] doesn't exist. It's negative.");
                
                if( charId == '\n') {
                    longestLine = fzMax(longestLine, lineWidth[currentLine]);
                    ++currentLine;
                }else {
                    lineWidth[currentLine] += p_font->getCharInfo(charId).xAdvance + m_horizontalPadding + p_font->getKerning(prevId, charId);
                    prevId = charId;
                }
            }
            longestLine = fzMax(longestLine, lineWidth[currentLine]);
            
            
            fzFloat lineHeight = p_font->getLineHeight() + m_verticalPadding;
            fzFloat totalHeight = lineHeight * (currentLine+1);
            
            fzInt nextFontPositionY = totalHeight - lineHeight;
            fzInt nextFontPositionX = 0;
            
            prevId = 0; currentLine = 0;
            for(fzUInt i = 0; i < m_stringLen; ++i)
            {
                charId = m_string.at(i);

                // line jump
                if (charId == '\n') {
                    nextFontPositionY -= lineHeight;
                    nextFontPositionX = 0;
                    ++currentLine;
                    continue;
                }
                
                // config line start point
                if (nextFontPositionX == 0)
                {
                    switch (m_alignment) {
                        case kFZLabelAlignment_left:
                            nextFontPositionX = 0;
                            break;
                        case kFZLabelAlignment_right:
                            nextFontPositionX = longestLine - lineWidth[currentLine];
                            //nextFontPositionX = (longestLine - lineWidth[currentLine])/2.0f;
                            break;
                        case kFZLabelAlignment_center:
                            nextFontPositionX = (longestLine - lineWidth[currentLine])/2.0f;
                            break;
                        default:
                            break;
                    }
                }
                
                // get font def
                const fzCharDef& fontDef = p_font->getCharInfo(static_cast<unsigned char>(charId));
                if(fontDef.xAdvance == 0) {
                    char toPrint[3];
                    printChar(toPrint, charId);
                    FZLOGERROR("Label: CHAR[%d] '%s' is not included.", charId, toPrint);
                    nextFontPositionX += p_font->getLineHeight();
                    continue;
                }
                
                // get sprite
                if( fontChar == NULL ) {
                    fontChar = new Sprite();
                    addChild(fontChar);
                    
                }else {
                    // reusing sprites
                    fontChar->setIsVisible(true);
                }
                
                // config sprite
                nextFontPositionX += p_font->getKerning(prevId, charId);
                fzFloat yOffset = p_font->getLineHeight() - fontDef.yOffset;
                fzPoint fontPos = fzPoint(nextFontPositionX + fontDef.xOffset + fontDef.width * 0.5f,
                                          nextFontPositionY + yOffset - fontDef.height * 0.5f );
                
                fontChar->setTextureRect(fontDef.getRect());
                fontChar->setPosition(fontPos);
                fontChar->setColor(m_color);
                
                
                // next sprite
                nextFontPositionX += fontDef.xAdvance + m_horizontalPadding;
                prevId = charId;
                fontChar = static_cast<Sprite*>(fontChar->next());
            }
            
            // new content size
            setContentSize(fzSize(longestLine, totalHeight));
            
        }else{
            
            setContentSize(FZSizeZero);
        }
        
        // make sprites not longer used hidden.
        for(; fontChar; fontChar = static_cast<Sprite*>(fontChar->next()))
            fontChar->setIsVisible(false);
    }
Example #30
0
 Action* Action::copy() const
 {
     FZLOGERROR("Action: Copied action not implemented.");
     return NULL;
 }