From b2079db22271ca004546e2823cddfbc27d9c33bc Mon Sep 17 00:00:00 2001 From: dborth Date: Tue, 7 Apr 2009 02:54:44 +0000 Subject: [PATCH] --- source/ngc/FreeTypeGX.cpp | 718 ++++++++++++++++++++++++++ source/ngc/FreeTypeGX.h | 286 +++++++++++ source/ngc/menudraw.cpp | 1000 ------------------------------------- source/ngc/menudraw.h | 44 -- source/ngc/oggplayer.c | 354 +++++++++++++ source/ngc/oggplayer.h | 174 +++++++ 6 files changed, 1532 insertions(+), 1044 deletions(-) create mode 100644 source/ngc/FreeTypeGX.cpp create mode 100644 source/ngc/FreeTypeGX.h delete mode 100644 source/ngc/menudraw.cpp delete mode 100644 source/ngc/menudraw.h create mode 100644 source/ngc/oggplayer.c create mode 100644 source/ngc/oggplayer.h diff --git a/source/ngc/FreeTypeGX.cpp b/source/ngc/FreeTypeGX.cpp new file mode 100644 index 0000000..0cbab38 --- /dev/null +++ b/source/ngc/FreeTypeGX.cpp @@ -0,0 +1,718 @@ +/* + * FreeTypeGX is a wrapper class for libFreeType which renders a compiled + * FreeType parsable font into a GX texture for Wii homebrew development. + * Copyright (C) 2008 Armin Tamzarian + * Modified by Tantric, 2009 + * + * This file is part of FreeTypeGX. + * + * FreeTypeGX is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * FreeTypeGX is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with FreeTypeGX. If not, see . + */ + +#include "FreeTypeGX.h" + +/** + * Default constructor for the FreeTypeGX class. + * + * @param textureFormat Optional format (GX_TF_*) of the texture as defined by the libogc gx.h header file. If not specified default value is GX_TF_RGBA8. + * @param vertexIndex Optional vertex format index (GX_VTXFMT*) of the glyph textures as defined by the libogc gx.h header file. If not specified default value is GX_VTXFMT1. + */ +FreeTypeGX::FreeTypeGX(uint8_t textureFormat, uint8_t vertexIndex) { + FT_Init_FreeType(&this->ftLibrary); + + this->textureFormat = textureFormat; + this->setVertexFormat(vertexIndex); + this->setCompatibilityMode(FTGX_COMPATIBILITY_NONE); +} + +/** + * Default destructor for the FreeTypeGX class. + */ +FreeTypeGX::~FreeTypeGX() { + this->unloadFont(); +} + +/** + * Convert a short char sctring to a wide char string. + * + * This routine converts a supplied shot character string into a wide character string. + * Note that it is the user's responsibility to clear the returned buffer once it is no longer needed. + * + * @param strChar Character string to be converted. + * @return Wide character representation of supplied character string. + */ +wchar_t* FreeTypeGX::charToWideChar(char* strChar) { + wchar_t *strWChar; + strWChar = new wchar_t[strlen(strChar) + 1]; + + char *tempSrc = strChar; + wchar_t *tempDest = strWChar; + while((*tempDest++ = *tempSrc++)); + + return strWChar; +} + +/** + * + * \overload + */ +wchar_t* FreeTypeGX::charToWideChar(const char* strChar) { + return FreeTypeGX::charToWideChar((char*) strChar); +} + +/** + * Setup the vertex attribute formats for the glyph textures. + * + * This function sets up the vertex format for the glyph texture on the specified vertex format index. + * Note that this function should not need to be called except if the vertex formats are cleared or the specified + * vertex format index is modified. + * + * @param vertexIndex Vertex format index (GX_VTXFMT*) of the glyph textures as defined by the libogc gx.h header file. +*/ +void FreeTypeGX::setVertexFormat(uint8_t vertexIndex) { + this->vertexIndex = vertexIndex; + + GX_SetVtxAttrFmt(this->vertexIndex, GX_VA_POS, GX_POS_XY, GX_S16, 0); + GX_SetVtxAttrFmt(this->vertexIndex, GX_VA_TEX0, GX_TEX_ST, GX_F32, 0); + GX_SetVtxAttrFmt(this->vertexIndex, GX_VA_CLR0, GX_CLR_RGBA, GX_RGBA8, 0); +} + +/** + * Sets the TEV and VTX rendering compatibility requirements for the class. + * + * This sets up the default TEV opertion and VTX descriptions rendering values for the class. This ensures that FreeTypeGX + * can remain compatible with external liraries or project code. Certain external libraries or code by design or lack of + * foresight assume that the TEV opertion and VTX descriptions values will remain constant or are always returned to a + * certain value. This will enable compatibility with those libraries and any other code which cannot or will not be changed. + * + * @param compatibilityMode Compatibility descritor (FTGX_COMPATIBILITY_*) as defined in FreeTypeGX.h +*/ +void FreeTypeGX::setCompatibilityMode(uint32_t compatibilityMode) { + this->compatibilityMode = compatibilityMode; +} + +/** + * Sets the TEV operation and VTX descriptor values after texture rendering it complete. + * + * This function calls the GX_SetTevOp and GX_SetVtxDesc functions with the compatibility parameters specified + * in setCompatibilityMode. + */ +void FreeTypeGX::setDefaultMode() { + if(this->compatibilityMode) { + switch(this->compatibilityMode & 0x00FF) { + case FTGX_COMPATIBILITY_DEFAULT_TEVOP_GX_MODULATE: + GX_SetTevOp(GX_TEVSTAGE0, GX_MODULATE); + break; + case FTGX_COMPATIBILITY_DEFAULT_TEVOP_GX_DECAL: + GX_SetTevOp(GX_TEVSTAGE0, GX_DECAL); + break; + case FTGX_COMPATIBILITY_DEFAULT_TEVOP_GX_BLEND: + GX_SetTevOp(GX_TEVSTAGE0, GX_BLEND); + break; + case FTGX_COMPATIBILITY_DEFAULT_TEVOP_GX_REPLACE: + GX_SetTevOp(GX_TEVSTAGE0, GX_REPLACE); + break; + case FTGX_COMPATIBILITY_DEFAULT_TEVOP_GX_PASSCLR: + GX_SetTevOp(GX_TEVSTAGE0, GX_PASSCLR); + break; + default: + break; + } + + switch(this->compatibilityMode & 0xFF00) { + case FTGX_COMPATIBILITY_DEFAULT_VTXDESC_GX_NONE: + GX_SetVtxDesc(GX_VA_TEX0, GX_NONE); + break; + case FTGX_COMPATIBILITY_DEFAULT_VTXDESC_GX_DIRECT: + GX_SetVtxDesc(GX_VA_TEX0, GX_DIRECT); + break; + case FTGX_COMPATIBILITY_DEFAULT_VTXDESC_GX_INDEX8: + GX_SetVtxDesc(GX_VA_TEX0, GX_INDEX8); + break; + case FTGX_COMPATIBILITY_DEFAULT_VTXDESC_GX_INDEX16: + GX_SetVtxDesc(GX_VA_TEX0, GX_INDEX16); + break; + default: + break; + } + } +} + +/** + * Loads and processes a specified true type font buffer to a specific point size. + * + * This routine takes a precompiled true type font buffer and loads the necessary processed data into memory. This routine should be called before drawText will succeed. + * + * @param fontBuffer A pointer in memory to a precompiled true type font buffer. + * @param bufferSize Size of the true type font buffer in bytes. + * @param pointSize The desired point size this wrapper's configured font face. + * @param cacheAll Optional flag to specify if all font characters should be cached when the class object is created. If specified as false the characters only become cached the first time they are used. If not specified default value is false. + */ +uint16_t FreeTypeGX::loadFont(uint8_t* fontBuffer, FT_Long bufferSize, FT_UInt pointSize, bool cacheAll) { + this->unloadFont(); + this->ftPointSize = pointSize; + + FT_New_Memory_Face(this->ftLibrary, (FT_Byte *)fontBuffer, bufferSize, 0, &this->ftFace); + + if(this->ftPointSize > 0) + FT_Set_Pixel_Sizes(this->ftFace, 0, this->ftPointSize); + + this->ftSlot = this->ftFace->glyph; + this->ftKerningEnabled = FT_HAS_KERNING(this->ftFace); + + if (cacheAll) { + return this->cacheGlyphDataComplete(); + } + + return 0; +} + +/** + * + * \overload + */ +uint16_t FreeTypeGX::loadFont(const uint8_t* fontBuffer, FT_Long bufferSize, FT_UInt pointSize, bool cacheAll) { + return this->loadFont((uint8_t *)fontBuffer, bufferSize, pointSize, cacheAll); +} + +/** + * Clears all loaded font glyph data. + * + * This routine clears all members of the font map structure and frees all allocated memory back to the system. + */ +void FreeTypeGX::unloadFont() { + if(this->fontData.size() == 0) + return; + + GX_DrawDone(); + GX_Flush(); + + for( std::map::iterator i = this->fontData.begin(); i != this->fontData.end(); i++) { + free(i->second.glyphDataTexture); + } + + this->fontData.clear(); +} + +void FreeTypeGX::changeSize(FT_UInt pointSize) { + this->unloadFont(); + this->ftPointSize = pointSize; + FT_Set_Pixel_Sizes(this->ftFace, 0, this->ftPointSize); +} + +/** + * Adjusts the texture data buffer to necessary width for a given texture format. + * + * This routine determines adjusts the given texture width into the required width to hold the necessary texture data for proper alignment. + * + * @param textureWidth The initial guess for the texture width. + * @param textureFormat The texture format to which the data is to be converted. + * @return The correctly adjusted texture width. + */ +uint16_t FreeTypeGX::adjustTextureWidth(uint16_t textureWidth, uint8_t textureFormat) { + uint16_t alignment; + + switch(textureFormat) { + case GX_TF_I4: /* 8x8 Tiles - 4-bit Intensity */ + case GX_TF_I8: /* 8x4 Tiles - 8-bit Intensity */ + case GX_TF_IA4: /* 8x4 Tiles - 4-bit Intensity, , 4-bit Alpha */ + alignment = 8; + break; + + case GX_TF_IA8: /* 4x4 Tiles - 8-bit Intensity, 8-bit Alpha */ + case GX_TF_RGB565: /* 4x4 Tiles - RGB565 Format */ + case GX_TF_RGB5A3: /* 4x4 Tiles - RGB5A3 Format */ + case GX_TF_RGBA8: /* 4x4 Tiles - RGBA8 Dual Cache Line Format */ + default: + alignment = 4; + break; + } + return textureWidth % alignment == 0 ? textureWidth : alignment + textureWidth - (textureWidth % alignment); + +} + +/** + * Adjusts the texture data buffer to necessary height for a given texture format. + * + * This routine determines adjusts the given texture height into the required height to hold the necessary texture data for proper alignment. + * + * @param textureHeight The initial guess for the texture height. + * @param textureFormat The texture format to which the data is to be converted. + * @return The correctly adjusted texture height. + */ +uint16_t FreeTypeGX::adjustTextureHeight(uint16_t textureHeight, uint8_t textureFormat) { + uint16_t alignment; + + switch(textureFormat) { + case GX_TF_I4: /* 8x8 Tiles - 4-bit Intensity */ + alignment = 8; + break; + + case GX_TF_I8: /* 8x4 Tiles - 8-bit Intensity */ + case GX_TF_IA4: /* 8x4 Tiles - 4-bit Intensity, , 4-bit Alpha */ + case GX_TF_IA8: /* 4x4 Tiles - 8-bit Intensity, 8-bit Alpha */ + case GX_TF_RGB565: /* 4x4 Tiles - RGB565 Format */ + case GX_TF_RGB5A3: /* 4x4 Tiles - RGB5A3 Format */ + case GX_TF_RGBA8: /* 4x4 Tiles - RGBA8 Dual Cache Line Format */ + default: + alignment = 4; + break; + } + return textureHeight % alignment == 0 ? textureHeight : alignment + textureHeight - (textureHeight % alignment); + +} + +/** + * Caches the given font glyph in the instance font texture buffer. + * + * This routine renders and stores the requested glyph's bitmap and relevant information into its own quickly addressible + * structure within an instance-specific map. + * + * @param charCode The requested glyph's character code. + * @return A pointer to the allocated font structure. + */ +ftgxCharData *FreeTypeGX::cacheGlyphData(wchar_t charCode) { + FT_UInt gIndex; + uint16_t textureWidth = 0, textureHeight = 0; + + gIndex = FT_Get_Char_Index( this->ftFace, charCode ); + if (!FT_Load_Glyph(this->ftFace, gIndex, FT_LOAD_DEFAULT )) { + FT_Render_Glyph( this->ftSlot, FT_RENDER_MODE_NORMAL ); + + if(this->ftSlot->format == FT_GLYPH_FORMAT_BITMAP) { + FT_Bitmap *glyphBitmap = &this->ftSlot->bitmap; + + textureWidth = adjustTextureWidth(glyphBitmap->width, this->textureFormat); + textureHeight = adjustTextureHeight(glyphBitmap->rows, this->textureFormat); + + this->fontData[charCode] = (ftgxCharData){ + this->ftSlot->advance.x >> 6, + gIndex, + textureWidth, + textureHeight, + this->ftSlot->bitmap_top, + this->ftSlot->bitmap_top, + textureHeight - this->ftSlot->bitmap_top, + NULL + }; + this->loadGlyphData(glyphBitmap, &this->fontData[charCode]); + + return &this->fontData[charCode]; + } + } + + return NULL; +} + +/** + * Locates each character in this wrapper's configured font face and proccess them. + * + * This routine locates each character in the configured font face and renders the glyph's bitmap. + * Each bitmap and relevant information is loaded into its own quickly addressible structure within an instance-specific map. + */ +uint16_t FreeTypeGX::cacheGlyphDataComplete() { + uint16_t i = 0; + FT_UInt gIndex; + FT_ULong charCode = FT_Get_First_Char( this->ftFace, &gIndex ); + while ( gIndex != 0 ) { + + if(this->cacheGlyphData(charCode) != NULL) { + i++; + } + + charCode = FT_Get_Next_Char( this->ftFace, charCode, &gIndex ); + } + + return i; +} + +/** + * Loads the rendered bitmap into the relevant structure's data buffer. + * + * This routine does a simple byte-wise copy of the glyph's rendered 8-bit grayscale bitmap into the structure's buffer. + * Each byte is converted from the bitmap's intensity value into the a uint32_t RGBA value. + * + * @param bmp A pointer to the most recently rendered glyph's bitmap. + * @param charData A pointer to an allocated ftgxCharData structure whose data represent that of the last rendered glyph. + */ +void FreeTypeGX::loadGlyphData(FT_Bitmap *bmp, ftgxCharData *charData) { + + uint32_t *glyphData = (uint32_t *)memalign(32, charData->textureWidth * charData->textureHeight * 4); + memset(glyphData, 0x00, charData->textureWidth * charData->textureHeight * 4); + + for (uint16_t imagePosY = 0; imagePosY < bmp->rows; imagePosY++) { + for (uint16_t imagePosX = 0; imagePosX < bmp->width; imagePosX++) { + uint32_t pixel = (uint32_t) bmp->buffer[imagePosY * bmp->width + imagePosX]; + glyphData[imagePosY * charData->textureWidth + imagePosX] = 0x00000000 | (pixel << 24) | (pixel << 16) | (pixel << 8) | pixel; + } + } + + switch(this->textureFormat) { + case GX_TF_I4: + charData->glyphDataTexture = Metaphrasis::convertBufferToI4(glyphData, charData->textureWidth, charData->textureHeight); + break; + case GX_TF_I8: + charData->glyphDataTexture = Metaphrasis::convertBufferToI8(glyphData, charData->textureWidth, charData->textureHeight); + break; + case GX_TF_IA4: + charData->glyphDataTexture = Metaphrasis::convertBufferToIA4(glyphData, charData->textureWidth, charData->textureHeight); + break; + case GX_TF_IA8: + charData->glyphDataTexture = Metaphrasis::convertBufferToIA8(glyphData, charData->textureWidth, charData->textureHeight); + break; + case GX_TF_RGB565: + charData->glyphDataTexture = Metaphrasis::convertBufferToRGB565(glyphData, charData->textureWidth, charData->textureHeight); + break; + case GX_TF_RGB5A3: + charData->glyphDataTexture = Metaphrasis::convertBufferToRGB5A3(glyphData, charData->textureWidth, charData->textureHeight); + break; + case GX_TF_RGBA8: + default: + charData->glyphDataTexture = Metaphrasis::convertBufferToRGBA8(glyphData, charData->textureWidth, charData->textureHeight); + break; + } + + free(glyphData); +} + +/** + * Determines the x offset of the rendered string. + * + * This routine calculates the x offset of the rendered string based off of a supplied positional format parameter. + * + * @param width Current pixel width of the string. + * @param format Positional format of the string. + */ +uint16_t FreeTypeGX::getStyleOffsetWidth(uint16_t width, uint16_t format) { + + if (format & FTGX_JUSTIFY_LEFT ) { + return 0; + } + else if (format & FTGX_JUSTIFY_CENTER ) { + return width >> 1; + } + else if (format & FTGX_JUSTIFY_RIGHT ) { + return width; + } + + return 0; +} + +/** + * Determines the y offset of the rendered string. + * + * This routine calculates the y offset of the rendered string based off of a supplied positional format parameter. + * + * @param offset Current pixel offset data of the string. + * @param format Positional format of the string. + */ +uint16_t FreeTypeGX::getStyleOffsetHeight(ftgxDataOffset offset, uint16_t format) { + if (format & FTGX_ALIGN_TOP ) { + return -offset.max; + } + else if (format & FTGX_ALIGN_MIDDLE ) { + return -offset.max; + } + else if (format & FTGX_ALIGN_BOTTOM ) { + return offset.min; + } + + return 0; +} + +/** + * Processes the supplied text string and prints the results at the specified coordinates. + * + * This routine processes each character of the supplied text string, loads the relevant preprocessed bitmap buffer, + * a texture from said buffer, and loads the resultant texture into the EFB. + * + * @param x Screen X coordinate at which to output the text. + * @param y Screen Y coordinate at which to output the text. Note that this value corresponds to the text string origin and not the top or bottom of the glyphs. + * @param text NULL terminated string to output. + * @param color Optional color to apply to the text characters. If not specified default value is ftgxWhite: (GXColor){0xff, 0xff, 0xff, 0xff} + * @param textStyle Flags which specify any styling which should be applied to the rendered string. + * @return The number of characters printed. + */ +uint16_t FreeTypeGX::drawText(int16_t x, int16_t y, wchar_t *text, GXColor color, uint16_t textStyle) { + uint16_t strLength = wcslen(text); + uint16_t x_pos = x, printed = 0; + uint16_t x_offset = 0, y_offset = 0; + GXTexObj glyphTexture; + FT_Vector pairDelta; + + if(textStyle & 0x000F) { + x_offset = this->getStyleOffsetWidth(this->getWidth(text), textStyle); + } + if(textStyle & 0x00F0) { + y_offset = this->getStyleOffsetHeight(this->getOffset(text), textStyle); + } + + for (uint16_t i = 0; i < strLength; i++) { + + ftgxCharData* glyphData = NULL; + if( this->fontData.find(text[i]) != this->fontData.end() ) { + glyphData = &this->fontData[text[i]]; + } + else { + glyphData = this->cacheGlyphData(text[i]); + } + + if(glyphData != NULL) { + + if(this->ftKerningEnabled && i) { + FT_Get_Kerning( this->ftFace, this->fontData[text[i - 1]].glyphIndex, glyphData->glyphIndex, FT_KERNING_DEFAULT, &pairDelta ); + x_pos += pairDelta.x >> 6; + } + + GX_InitTexObj(&glyphTexture, glyphData->glyphDataTexture, glyphData->textureWidth, glyphData->textureHeight, this->textureFormat, GX_CLAMP, GX_CLAMP, GX_FALSE); + this->copyTextureToFramebuffer(&glyphTexture, glyphData->textureWidth, glyphData->textureHeight, x_pos - x_offset, y - glyphData->renderOffsetY - y_offset, color); + + x_pos += glyphData->glyphAdvanceX; + printed++; + } + } + + if(textStyle & 0x0F00) { + this->drawTextFeature(x - x_offset, y, this->getWidth(text), this->getOffset(text), textStyle, color); + } + + return printed; +} + +/** + * \overload + */ +uint16_t FreeTypeGX::drawText(int16_t x, int16_t y, wchar_t const *text, GXColor color, uint16_t textStyle) { + return this->drawText(x, y, (wchar_t *)text, color, textStyle); +} + +void FreeTypeGX::drawTextFeature(int16_t x, int16_t y, uint16_t width, ftgxDataOffset offsetData, uint16_t format, GXColor color) { + uint16_t featureHeight = this->ftPointSize >> 4 > 0 ? this->ftPointSize >> 4 : 1; + + if (format & FTGX_STYLE_UNDERLINE ) { + switch(format & 0x00F0) { + case FTGX_ALIGN_TOP: + this->copyFeatureToFramebuffer(width, featureHeight, x, y + offsetData.max + 1, color); + break; + case FTGX_ALIGN_MIDDLE: + this->copyFeatureToFramebuffer(width, featureHeight, x, y + ((offsetData.max - offsetData.min) >> 1) + 1, color); + break; + case FTGX_ALIGN_BOTTOM: + this->copyFeatureToFramebuffer(width, featureHeight, x, y - offsetData.min, color); + break; + default: + this->copyFeatureToFramebuffer(width, featureHeight, x, y + 1, color); + break; + } + } + + if (format & FTGX_STYLE_STRIKE ) { + switch(format & 0x00F0) { + case FTGX_ALIGN_TOP: + this->copyFeatureToFramebuffer(width, featureHeight, x, y + ((offsetData.max + offsetData.min) >> 1), color); + break; + case FTGX_ALIGN_MIDDLE: + this->copyFeatureToFramebuffer(width, featureHeight, x, y, color); + break; + case FTGX_ALIGN_BOTTOM: + this->copyFeatureToFramebuffer(width, featureHeight, x, y - ((offsetData.max + offsetData.min) >> 1), color); + break; + default: + this->copyFeatureToFramebuffer(width, featureHeight, x, y - ((offsetData.max - offsetData.min) >> 1), color); + break; + } + } +} + +/** + * Processes the supplied string and return the width of the string in pixels. + * + * This routine processes each character of the supplied text string and calculates the width of the entire string. + * Note that if precaching of the entire font set is not enabled any uncached glyph will be cached after the call to this function. + * + * @param text NULL terminated string to calculate. + * @return The width of the text string in pixels. + */ +uint16_t FreeTypeGX::getWidth(wchar_t *text) { + uint16_t strLength = wcslen(text); + uint16_t strWidth = 0; + FT_Vector pairDelta; + + for (uint16_t i = 0; i < strLength; i++) { + + ftgxCharData* glyphData = NULL; + if( this->fontData.find(text[i]) != this->fontData.end() ) { + glyphData = &this->fontData[text[i]]; + } + else { + glyphData = this->cacheGlyphData(text[i]); + } + + if(glyphData != NULL) { + if(this->ftKerningEnabled && (i > 0)) { + FT_Get_Kerning( this->ftFace, this->fontData[text[i - 1]].glyphIndex, glyphData->glyphIndex, FT_KERNING_DEFAULT, &pairDelta ); + strWidth += pairDelta.x >> 6; + } + + strWidth += glyphData->glyphAdvanceX; + } + } + + return strWidth; +} + +/** + * + * \overload + */ +uint16_t FreeTypeGX::getWidth(wchar_t const *text) { + return this->getWidth((wchar_t *)text); +} + +/** + * Processes the supplied string and return the height of the string in pixels. + * + * This routine processes each character of the supplied text string and calculates the height of the entire string. + * Note that if precaching of the entire font set is not enabled any uncached glyph will be cached after the call to this function. + * + * @param text NULL terminated string to calculate. + * @return The height of the text string in pixels. + */ +uint16_t FreeTypeGX::getHeight(wchar_t *text) { + ftgxDataOffset offset = this->getOffset(text); + + return offset.max + offset.min; +} + +/** + * + * \overload + */ +uint16_t FreeTypeGX::getHeight(wchar_t const *text) { + return this->getHeight((wchar_t *)text); +} + +/** + * Get the maximum offset above and minimum offset below the font origin line. + * + * This function calculates the maximum pixel height above the font origin line and the minimum + * pixel height below the font origin line and returns the values in an addressible structure. + * + * @param text NULL terminated string to calculate. + * @return The max and min values above and below the font origin line. + */ +ftgxDataOffset FreeTypeGX::getOffset(wchar_t *text) { + uint16_t strLength = wcslen(text); + uint16_t strMax = 0, strMin = 0; + + for (uint16_t i = 0; i < strLength; i++) { + + ftgxCharData* glyphData = NULL; + if( this->fontData.find(text[i]) != this->fontData.end() ) { + glyphData = &this->fontData[text[i]]; + } + else { + glyphData = this->cacheGlyphData(text[i]); + } + + if(glyphData != NULL) { + strMax = glyphData->renderOffsetMax > strMax ? glyphData->renderOffsetMax : strMax; + strMin = glyphData->renderOffsetMin > strMin ? glyphData->renderOffsetMin : strMin; + } + } + + return (ftgxDataOffset){strMax, strMin}; +} + +/** + * + * \overload + */ +ftgxDataOffset FreeTypeGX::getOffset(wchar_t const *text) { + return this->getOffset(text); +} + +/** + * Copies the supplied texture quad to the EFB. + * + * This routine uses the in-built GX quad builder functions to define the texture bounds and location on the EFB target. + * + * @param texObj A pointer to the glyph's initialized texture object. + * @param texWidth The pixel width of the texture object. + * @param texHeight The pixel height of the texture object. + * @param screenX The screen X coordinate at which to output the rendered texture. + * @param screenY The screen Y coordinate at which to output the rendered texture. + * @param color Color to apply to the texture. + */ +void FreeTypeGX::copyTextureToFramebuffer(GXTexObj *texObj, f32 texWidth, f32 texHeight, int16_t screenX, int16_t screenY, GXColor color) { + + GX_LoadTexObj(texObj, GX_TEXMAP0); + GX_InvalidateTexAll(); + + GX_SetTevOp (GX_TEVSTAGE0, GX_MODULATE); + GX_SetVtxDesc (GX_VA_TEX0, GX_DIRECT); + + GX_Begin(GX_QUADS, this->vertexIndex, 4); + GX_Position2s16(screenX, screenY); + GX_Color4u8(color.r, color.g, color.b, color.a); + GX_TexCoord2f32(0.0f, 0.0f); + + GX_Position2s16(texWidth + screenX, screenY); + GX_Color4u8(color.r, color.g, color.b, color.a); + GX_TexCoord2f32(1.0f, 0.0f); + + GX_Position2s16(texWidth + screenX, texHeight + screenY); + GX_Color4u8(color.r, color.g, color.b, color.a); + GX_TexCoord2f32(1.0f, 1.0f); + + GX_Position2s16(screenX, texHeight + screenY); + GX_Color4u8(color.r, color.g, color.b, color.a); + GX_TexCoord2f32(0.0f, 1.0f); + GX_End(); + + this->setDefaultMode(); +} + +/** + * Creates a feature quad to the EFB. + * + * This function creates a simple quad for displaying underline or strikeout text styling. + * + * @param featureWidth The pixel width of the quad. + * @param featureHeight The pixel height of the quad. + * @param screenX The screen X coordinate at which to output the quad. + * @param screenY The screen Y coordinate at which to output the quad. + * @param color Color to apply to the texture. + */ +void FreeTypeGX::copyFeatureToFramebuffer(f32 featureWidth, f32 featureHeight, int16_t screenX, int16_t screenY, GXColor color) { + + GX_SetTevOp (GX_TEVSTAGE0, GX_PASSCLR); + GX_SetVtxDesc (GX_VA_TEX0, GX_NONE); + + GX_Begin(GX_QUADS, this->vertexIndex, 4); + GX_Position2s16(screenX, screenY); + GX_Color4u8(color.r, color.g, color.b, color.a); + + GX_Position2s16(featureWidth + screenX, screenY); + GX_Color4u8(color.r, color.g, color.b, color.a); + + GX_Position2s16(featureWidth + screenX, featureHeight + screenY); + GX_Color4u8(color.r, color.g, color.b, color.a); + + GX_Position2s16(screenX, featureHeight + screenY); + GX_Color4u8(color.r, color.g, color.b, color.a); + GX_End(); + + this->setDefaultMode(); +} diff --git a/source/ngc/FreeTypeGX.h b/source/ngc/FreeTypeGX.h new file mode 100644 index 0000000..935cd7d --- /dev/null +++ b/source/ngc/FreeTypeGX.h @@ -0,0 +1,286 @@ +/* + * FreeTypeGX is a wrapper class for libFreeType which renders a compiled + * FreeType parsable font into a GX texture for Wii homebrew development. + * Copyright (C) 2008 Armin Tamzarian + * Modified by Tantric, 2009 + * + * This file is part of FreeTypeGX. + * + * FreeTypeGX is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * FreeTypeGX is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with FreeTypeGX. If not, see . + */ + +/** \mainpage FreeTypeGX + * + * \section sec_intro Introduction + * + * FreeTypeGX is a wrapper class for libFreeType which renders a compiled FreeType parsable font into a GX texture for Wii homebrew development. + *
+ * FreeTypeGX is written in C++ and makes use of a selectable pre-buffered or buffer-on-demand methodology to allow fast and efficient printing of text to the EFB. + *

+ * This library was developed in-full by Armin Tamzarian with the support of developers in \#wiibrew on EFnet. + * + * \section sec_installation_source Installation (Source Code) + * + * -# Ensure that you have the libFreeType Wii library installed in your development environment with the library added to your Makefile where appropriate. + * -# Ensure that you have the Metaphrasis library installed in your development environment with the library added to your Makefile where appropriate. + * -# Extract the FreeTypeGX archive. + * -# Copy the contents of the src directory into your project's development path. + * -# Include the FreeTypeGX header file in your code using syntax such as the following: + * \code + * #include "FreeTypeGX.h" + * \endcode + * + * \section sec_installation_library Installation (Library) + * + * -# Ensure that you have the libFreeType Wii library installed in your development environment with the library added to your Makefile where appropriate. + * -# Ensure that you have the Metaphrasis library installed in your development environment with the library added to your Makefile where appropriate. + * -# Extract the FreeTypeGX archive. + * -# Copy the contents of the lib directory into your devKitPro/libogc directory. + * -# Include the FreeTypeGX header file in your code using syntax such as the following: + * \code + * #include "FreeTypeGX.h" + * \endcode + * + * \section sec_freetypegx_prerequisites FreeTypeGX Prerequisites + * + * Before you begin using FreeTypeGX in your project you must ensure that the desired font in compiled into your project. For this example I will assume you are building your project with a Makefile using devKitPro evironment and are attempting to include a font whose filename is rursus_compact_mono.ttf. + * + * -# Copy the font into a directory which will be processed by the project's Makefile. If you are unsure about where you should place your font just copy the it into your project's source directory. + * \n\n + * -# Modify the Makefile to convert the font into an object file: + * \code + * %.ttf.o : %.ttf + * @echo $(notdir $<) + * $(bin2o) + * \endcode + * \n + * -# Include the font object's generated header file in your source code: + * \code + * #include "rursus_compact_mono_ttf.h" + * \endcode + * This header file defines the two variables that you will need for use within your project: + * \code + * extern const u8 rursus_compact_mono_ttf[]; A pointer to the font buffer within the compiled project. + * extern const u32 rursus_compact_mono_ttf_size; The size of the font's buffer in bytes. + * \endcode + * + * \section sec_freetypegx_usage FreeTypeGX Usage + * + * -# Within the file you included the FreeTypeGX.h header create an instance object of the FreeTypeGX class: + * \code + * FreeTypeGX *freeTypeGX = new FreeTypeGX(); + * \endcode + * Alternately you can specify a texture format to which you would like to render the font characters. Note that the default value for this parameter is GX_TF_RGBA8. + * \code + * FreeTypeGX *freeTypeGX = new FreeTypeGX(GX_TF_RGB565); + * \endcode + * Furthermore, you can also specify a vertex format index to avoid conflicts with concurrent libraries or other systems. Note that the default value for this parameter is GX_VTXFMT1. + * \code + * FreeTypeGX *freeTypeGX = new FreeTypeGX(GX_TF_RGB565, GX_VTXFMT1); + * \endcode + * \n + * Currently supported textures are: + * \li GX_TF_I4 + * \li GX_TF_I8 + * \li GX_TF_IA4 + * \li GX_TF_IA8 + * \li GX_TF_RGB565 + * \li GX_TF_RGB5A3 + * \li GX_TF_RGBA8 + * + * \n + * -# Using the allocated FreeTypeGX instance object call the loadFont function to load the font from the compiled buffer and specify the desired point size. Note that this function can be called multiple times to load a new: + * \code + * freeTypeGX->loadFont(rursus_compact_mono_ttf, rursus_compact_mono_ttf_size, 64); + * \endcode + * Alternately you can specify a flag which will load and cache all available font glyphs immidiately. Note that on large font sets enabling this feature could take a significant amount of time. + * \code + * freeTypeGX->loadFont(rursus_compact_mono_ttf, rursus_compact_mono_ttf_size, 64, true); + * \endcode + * \n + * -# If necessary you can enable compatibility modes with concurrent libraries or systems. For more information on this feature see the documentation for setCompatibilityMode: + * \code + * freeTypeGX->setCompatibilityMode(FTGX_COMPATIBILITY_GRRLIB); + * \endcode + * -# Using the allocated FreeTypeGX instance object call the drawText function to print a string at the specified screen X and Y coordinates to the current EFB: + * \code + * freeTypeGX->drawText(10, 25, _TEXT("FreeTypeGX Rocks!")); + * \endcode + * Alternately you can specify a GXColor object you would like to apply to the printed characters: + * \code + * freeTypeGX->drawText(10, 25, _TEXT("FreeTypeGX Rocks!"), + * (GXColor){0xff, 0xee, 0xaa, 0xff}); + * \endcode + * Furthermore you can also specify a group of styling parameters which will modify the positioning or style of the text: + * \code + * freeTypeGX->drawText(10, 25, _TEXT("FreeTypeGX Rocks!"), + * (GXColor){0xff, 0xee, 0xaa, 0xff}, + * FTGX_JUSTIFY_CENTER | FTGX_ALIGN_BOTTOM | FTGX_STYLE_UNDERLINE); + * \endcode + * \n + * Currently style parameters are: + * \li FTGX_JUSTIFY_LEFT + * \li FTGX_JUSTIFY_CENTER + * \li FTGX_JUSTIFY_RIGHT + * \li FTGX_ALIGN_TOP + * \li FTGX_ALIGN_MIDDLE + * \li FTGX_ALIGN_BOTTOM + * \li FTGX_STYLE_UNDERLINE + * \li FTGX_STYLE_STRIKE + * + * \section sec_license License + * + * FreeTypeGX is distributed under the GNU Lesser General Public License. + * + * \section sec_contact Contact + * + * If you have any suggestions, questions, or comments regarding this library feel free to e-mail me at tamzarian1989 [at] gmail [dawt] com. + */ + +#ifndef FREETYPEGX_H_ +#define FREETYPEGX_H_ + +#include +#include +#include FT_FREETYPE_H +#include FT_BITMAP_H +#include + +#include +#include +#include + +/*! \struct ftgxCharData_ + * + * Font face character glyph relevant data structure. + */ +typedef struct ftgxCharData_ { + uint16_t glyphAdvanceX; /**< Character glyph X coordinate advance in pixels. */ + uint16_t glyphIndex; /**< Charachter glyph index in the font face. */ + + uint16_t textureWidth; /**< Texture width in pixels/bytes. */ + uint16_t textureHeight; /**< Texture glyph height in pixels/bytes. */ + + uint16_t renderOffsetY; /**< Texture Y axis bearing offset. */ + uint16_t renderOffsetMax; /**< Texture Y axis bearing maximum value. */ + uint16_t renderOffsetMin; /**< Texture Y axis bearing minimum value. */ + + uint32_t* glyphDataTexture; /**< Glyph texture bitmap data buffer. */ +} ftgxCharData; + +/*! \struct ftgxDataOffset_ + * + * Offset structure which hold both a maximum and minimum value. + */ +typedef struct ftgxDataOffset_ { + int16_t max; /**< Maximum data offset. */ + int16_t min; /**< Minimum data offset. */ +} ftgxDataOffset; + +#define _TEXT(t) L ## t /**< Unicode helper macro. */ + +#define FTGX_NULL 0x0000 +#define FTGX_JUSTIFY_LEFT 0x0001 +#define FTGX_JUSTIFY_CENTER 0x0002 +#define FTGX_JUSTIFY_RIGHT 0x0004 + +#define FTGX_ALIGN_TOP 0x0010 +#define FTGX_ALIGN_MIDDLE 0x0020 +#define FTGX_ALIGN_BOTTOM 0x0040 + +#define FTGX_STYLE_UNDERLINE 0x0100 +#define FTGX_STYLE_STRIKE 0x0200 + +#define FTGX_COMPATIBILITY_DEFAULT_TEVOP_GX_MODULATE 0X0001 +#define FTGX_COMPATIBILITY_DEFAULT_TEVOP_GX_DECAL 0X0002 +#define FTGX_COMPATIBILITY_DEFAULT_TEVOP_GX_BLEND 0X0004 +#define FTGX_COMPATIBILITY_DEFAULT_TEVOP_GX_REPLACE 0X0008 +#define FTGX_COMPATIBILITY_DEFAULT_TEVOP_GX_PASSCLR 0X0010 + +#define FTGX_COMPATIBILITY_DEFAULT_VTXDESC_GX_NONE 0X0100 +#define FTGX_COMPATIBILITY_DEFAULT_VTXDESC_GX_DIRECT 0X0200 +#define FTGX_COMPATIBILITY_DEFAULT_VTXDESC_GX_INDEX8 0X0400 +#define FTGX_COMPATIBILITY_DEFAULT_VTXDESC_GX_INDEX16 0X0800 + +#define FTGX_COMPATIBILITY_NONE 0x0000 +#define FTGX_COMPATIBILITY_GRRLIB FTGX_COMPATIBILITY_DEFAULT_TEVOP_GX_PASSCLR | FTGX_COMPATIBILITY_DEFAULT_VTXDESC_GX_NONE +#define FTGX_COMPATIBILITY_LIBWIISPRITE FTGX_COMPATIBILITY_DEFAULT_TEVOP_GX_MODULATE | FTGX_COMPATIBILITY_DEFAULT_VTXDESC_GX_DIRECT + +const GXColor ftgxWhite = (GXColor){0xff, 0xff, 0xff, 0xff}; /**< Constant color value used only to sanitize Doxygen documentation. */ + +/*! \class FreeTypeGX + * \brief Wrapper class for the libFreeType library with GX rendering. + * \author Armin Tamzarian + * \version 0.2.4 + * + * FreeTypeGX acts as a wrapper class for the libFreeType library. It supports precaching of transformed glyph data into + * a specified texture format. Rendering of the data to the EFB is accomplished through the application of high performance + * GX texture functions resulting in high throughput of string rendering. + */ +class FreeTypeGX { + + private: + FT_Library ftLibrary; /**< FreeType FT_Library instance. */ + FT_Face ftFace; /**< FreeType reusable FT_Face typographic object. */ + FT_GlyphSlot ftSlot; /**< FreeType reusable FT_GlyphSlot glyph container object. */ + FT_UInt ftPointSize; /**< Requested size of the rendered font. */ + bool ftKerningEnabled; /**< Flag indicating the availability of font kerning data. */ + + uint8_t textureFormat; /**< Defined texture format of the target EFB. */ + uint8_t vertexIndex; /**< Vertex format descriptor index. */ + uint32_t compatibilityMode; /**< Compatibility mode for default tev operations and vertex descriptors. */ + std::map fontData; /**< Map which holds the glyph data structures for the corresponding characters. */ + + static uint16_t adjustTextureWidth(uint16_t textureWidth, uint8_t textureFormat); + static uint16_t adjustTextureHeight(uint16_t textureHeight, uint8_t textureFormat); + + static uint16_t getStyleOffsetWidth(uint16_t width, uint16_t format); + static uint16_t getStyleOffsetHeight(ftgxDataOffset offset, uint16_t format); + + void unloadFont(); + ftgxCharData *cacheGlyphData(wchar_t charCode); + uint16_t cacheGlyphDataComplete(); + void loadGlyphData(FT_Bitmap *bmp, ftgxCharData *charData); + + void setDefaultMode(); + + void drawTextFeature(int16_t x, int16_t y, uint16_t width, ftgxDataOffset offsetData, uint16_t format, GXColor color); + void copyTextureToFramebuffer(GXTexObj *texObj, f32 texWidth, f32 texHeight, int16_t screenX, int16_t screenY, GXColor color); + void copyFeatureToFramebuffer(f32 featureWidth, f32 featureHeight, int16_t screenX, int16_t screenY, GXColor color); + + public: + FreeTypeGX(uint8_t textureFormat = GX_TF_RGBA8, uint8_t vertexIndex = GX_VTXFMT1); + ~FreeTypeGX(); + + static wchar_t* charToWideChar(char* p); + static wchar_t* charToWideChar(const char* p); + void setVertexFormat(uint8_t vertexIndex); + void setCompatibilityMode(uint32_t compatibilityMode); + + uint16_t loadFont(uint8_t* fontBuffer, FT_Long bufferSize, FT_UInt pointSize, bool cacheAll = false); + uint16_t loadFont(const uint8_t* fontBuffer, FT_Long bufferSize, FT_UInt pointSize, bool cacheAll = false); + void changeSize(FT_UInt pointSize); + + uint16_t drawText(int16_t x, int16_t y, wchar_t *text, GXColor color = ftgxWhite, uint16_t textStyling = FTGX_NULL); + uint16_t drawText(int16_t x, int16_t y, wchar_t const *text, GXColor color = ftgxWhite, uint16_t textStyling = FTGX_NULL); + + uint16_t getWidth(wchar_t *text); + uint16_t getWidth(wchar_t const *text); + uint16_t getHeight(wchar_t *text); + uint16_t getHeight(wchar_t const *text); + ftgxDataOffset getOffset(wchar_t *text); + ftgxDataOffset getOffset(wchar_t const *text); +}; + +#endif /* FREETYPEGX_H_ */ diff --git a/source/ngc/menudraw.cpp b/source/ngc/menudraw.cpp deleted file mode 100644 index a71943e..0000000 --- a/source/ngc/menudraw.cpp +++ /dev/null @@ -1,1000 +0,0 @@ -/**************************************************************************** - * Visual Boy Advance GX - * - * Tantric September 2008 - * - * menudraw.cpp - * - * Menu drawing routines - ***************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include FT_FREETYPE_H - -#include "video.h" -#include "menudraw.h" -#include "vba.h" -#include "filesel.h" -#include "dvd.h" -#include "input.h" -#include "networkop.h" -#include "wiiusbsupport.h" -#include "filelist.h" - -/*** Globals ***/ -static FT_Library ftlibrary; -static FT_Face face; -static FT_GlyphSlot slot; -static unsigned int fonthi, fontlo; - -extern int screenheight; -extern unsigned int *xfb[2]; -extern int whichfb; - -unsigned int getcolour (u8 r1, u8 g1, u8 b1); -void DrawLineFast( int startx, int endx, int y, u8 r, u8 g, u8 b ); -u32 getrgb( u32 ycbr, u32 low ); - -/**************************************************************************** - * Initialisation of libfreetype - ***************************************************************************/ -int -FT_Init () -{ - - int err; - - err = FT_Init_FreeType (&ftlibrary); - if (err) - return 1; - - err = - FT_New_Memory_Face (ftlibrary, (FT_Byte *) font_ttf, font_ttf_size, 0, &face); - if (err) - return 1; - - setfontsize (16); - setfontcolour (0xff, 0xff, 0xff); - - slot = face->glyph; - - return 0; - -} - -/**************************************************************************** - * setfontsize - * - * Set the screen font size in pixels - ***************************************************************************/ -void -setfontsize (int pixelsize) -{ - int err; - - err = FT_Set_Pixel_Sizes (face, 0, pixelsize); - - if (err) - printf ("Error setting pixel sizes!"); -} - -/**************************************************************************** - * DrawCharacter - * Draws a single character on the screen - ***************************************************************************/ -static void -DrawCharacter (FT_Bitmap * bmp, FT_Int x, FT_Int y) -{ - FT_Int i, j, p, q; - FT_Int x_max = x + bmp->width; - FT_Int y_max = y + bmp->rows; - int spos; - unsigned int pixel; - int c; - - for (i = x, p = 0; i < x_max; i++, p++) - { - for (j = y, q = 0; j < y_max; j++, q++) - { - if (i < 0 || j < 0 || i >= 640 || j >= screenheight) - continue; - - /*** Convert pixel position to GC int sizes ***/ - spos = (j * 320) + (i >> 1); - - pixel = xfb[whichfb][spos]; - c = bmp->buffer[q * bmp->width + p]; - - /*** Cool Anti-Aliasing doesn't work too well at hires on GC ***/ - if (c > 128) - { - if (i & 1) - pixel = (pixel & 0xffff0000) | fontlo; - else - pixel = ((pixel & 0xffff) | fonthi); - - xfb[whichfb][spos] = pixel; - } - } - } -} - -/**************************************************************************** - * DrawText - * - * Place the font bitmap on the screen - ***************************************************************************/ -void -DrawText (int x, int y, const char *text) -{ - int px, n; - int i; - int err; - int value, count; - - n = strlen (text); - if (n == 0) - return; - - setfontcolour (0x00, 0x00, 0x00); - - /*** x == -1, auto centre ***/ - if (x == -1) - { - value = 0; - px = 0; - } - else - { - value = 1; - px = x; - } - - for (count = value; count < 2; count++) - { - /*** Draw the string ***/ - for (i = 0; i < n; i++) - { - err = FT_Load_Char (face, text[i], FT_LOAD_RENDER); - - if (err) - { - printf ("Error %c %d\n", text[i], err); - continue; /*** Skip unprintable characters ***/ - } - - if (count) - DrawCharacter (&slot->bitmap, px + slot->bitmap_left, - y - slot->bitmap_top); - - px += slot->advance.x >> 6; - } - - px = (640 - px) >> 1; - - } -} - -/**************************************************************************** - * setfontcolour - * - * Uses RGB triple values. - ***************************************************************************/ -void -setfontcolour (u8 r, u8 g, u8 b) -{ - u32 fontcolour; - - fontcolour = getcolour (r, g, b); - fonthi = fontcolour & 0xffff0000; - fontlo = fontcolour & 0xffff; -} - -/**************************************************************************** - * Draws Version # on screen - ***************************************************************************/ - -void DrawVersion() -{ - setfontsize (12); - setfontcolour (0,0,0); - char versionText[50]; - sprintf(versionText, "%s %s", APPNAME, APPVERSION); - DrawText (115, screenheight - 34, versionText); -} - -/**************************************************************************** - * Display credits, legal copyright and licence - * - * THIS MUST NOT BE REMOVED IN ANY DERIVATIVE WORK. - ***************************************************************************/ -void -Credits () -{ - clearscreen (); - - setfontcolour (0x00, 0x00, 0x00); - - setfontsize (26); - DrawText (-1, 150, "Credits"); - - int ypos = 110; - - if (screenheight == 480) - ypos += 52; - else - ypos += 32; - - setfontsize (14); - - DrawText (-1, ypos += 18, "Official Site: http://code.google.com/p/vba-wii/"); - - DrawText (90, ypos += 36, "Visual Boy Advance GX"); - DrawText (380, ypos, "Tantric, Carl Kenner"); - DrawText (90, ypos += 18, "GameCube/Wii Port Improvements"); - DrawText (380, ypos, "emukidid"); - DrawText (90, ypos += 18, "Original GameCube Port"); - DrawText (380, ypos, "SoftDev"); - DrawText (90, ypos += 18, "Visual Boy Advance - M"); - DrawText (380, ypos, "VBA-M Team"); - DrawText (90, ypos += 18, "Visual Boy Advance 1.7.2"); - DrawText (380, ypos, "Forgotten"); - DrawText (90, ypos += 18, "libogc"); - DrawText (380, ypos, "Shagkur & wintermute"); - DrawText (90, ypos += 18, "Testing"); - DrawText (380, ypos, "tehskeen users"); - - DrawText (-1, ypos += 36, "And many others who have contributed over the years!"); - - setfontsize (12); - DrawText (-1, ypos += 30, "This software is open source and may be copied,"); - DrawText (-1, ypos += 15, "distributed, or modified under the terms of"); - DrawText (-1, ypos += 15, "the GNU General Public License (GPL) Version 2."); - - DrawVersion(); - updateRumbleFrame(); - showscreen (); -} - - - -/**************************************************************************** - * getcolour - * - * Simply converts RGB to Y1CbY2Cr format - * - * I got this from a pastebin, so thanks to whoever originally wrote it! - ***************************************************************************/ - -unsigned int -getcolour (u8 r1, u8 g1, u8 b1) -{ - int y1, cb1, cr1, y2, cb2, cr2, cb, cr; - u8 r2, g2, b2; - - r2 = r1; - g2 = g1; - b2 = b1; - - y1 = (299 * r1 + 587 * g1 + 114 * b1) / 1000; - cb1 = (-16874 * r1 - 33126 * g1 + 50000 * b1 + 12800000) / 100000; - cr1 = (50000 * r1 - 41869 * g1 - 8131 * b1 + 12800000) / 100000; - - y2 = (299 * r2 + 587 * g2 + 114 * b2) / 1000; - cb2 = (-16874 * r2 - 33126 * g2 + 50000 * b2 + 12800000) / 100000; - cr2 = (50000 * r2 - 41869 * g2 - 8131 * b2 + 12800000) / 100000; - - cb = (cb1 + cb2) >> 1; - cr = (cr1 + cr2) >> 1; - - return ((y1 << 24) | (cb << 16) | (y2 << 8) | cr); -} - -/**************************************************************************** - * Wait for user to press A - ***************************************************************************/ -void -WaitButtonA () -{ -#ifdef HW_RVL - while ( (PAD_ButtonsDown (0) & PAD_BUTTON_A) - || (WPAD_ButtonsDown(0) & (WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A)) - || (DownUsbKeys[KB_ENTER])) { - updateRumbleFrame(); - VIDEO_WaitVSync(); - } - while (!(PAD_ButtonsDown (0) & PAD_BUTTON_A) - && !(WPAD_ButtonsDown(0) & (WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A)) - && !(DownUsbKeys[KB_ENTER])) { - updateRumbleFrame(); - VIDEO_WaitVSync(); - } -#else - while ( PAD_ButtonsDown (0) & PAD_BUTTON_A ) { - updateRumbleFrame(); - VIDEO_WaitVSync(); - } - while (!(PAD_ButtonsDown (0) & PAD_BUTTON_A) ) { - updateRumbleFrame(); - VIDEO_WaitVSync(); - } -#endif -} - -/**************************************************************************** - * Wait for user to press A or B. Returns 0 = B; 1 = A - ***************************************************************************/ - -int -WaitButtonAB () -{ -#ifdef HW_RVL - u32 gc_btns, wm_btns; - - while ( (PAD_ButtonsDown (0) & (PAD_BUTTON_A | PAD_BUTTON_B)) - || (WPAD_ButtonsDown(0) & (WPAD_BUTTON_A | WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_A | WPAD_CLASSIC_BUTTON_B)) - || (DownUsbKeys[KB_ENTER]) || (DownUsbKeys[KB_ESC]) - ) { - updateRumbleFrame(); - VIDEO_WaitVSync(); - } - - while ( TRUE ) - { - gc_btns = PAD_ButtonsDown (0); - wm_btns = WPAD_ButtonsDown (0); - if ( (gc_btns & PAD_BUTTON_A) || (wm_btns & (WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A)) - || (DownUsbKeys[KB_ENTER]) - ) - return 1; - else if ( (gc_btns & PAD_BUTTON_B) || (wm_btns & (WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B)) - || (DownUsbKeys[KB_ESC]) - ) - return 0; - } -#else - u32 gc_btns; - - while ( (PAD_ButtonsDown (0) & (PAD_BUTTON_A | PAD_BUTTON_B)) ) { - updateRumbleFrame(); - VIDEO_WaitVSync(); - } - - while ( TRUE ) - { - gc_btns = PAD_ButtonsDown (0); - if ( gc_btns & PAD_BUTTON_A ) - return 1; - else if ( gc_btns & PAD_BUTTON_B ) - return 0; - } -#endif -} - -/**************************************************************************** - * Show a prompt - ***************************************************************************/ -void -WaitPrompt (const char *msg) -{ - int ypos = (screenheight - 64) >> 1; - - if (screenheight == 480) - ypos += 52; - else - ypos += 32; - - clearscreen (); - setfontsize(16); - DrawText (-1, ypos, msg); - ypos += 30; - DrawText (-1, ypos, "Press A to continue"); - - DrawVersion(); - showscreen (); - WaitButtonA (); -} - -/**************************************************************************** - * Show a prompt with choice of two options. Returns 1 if A button was pressed - and 0 if B button was pressed. - ***************************************************************************/ -int -WaitPromptChoice (const char *msg, const char *bmsg, const char *amsg) -{ - int ypos = (screenheight - 64) >> 1; - - if (screenheight == 480) - ypos += 37; - else - ypos += 17; - - clearscreen (); - setfontsize(20); - DrawText (-1, ypos, msg); - ypos += 60; - char txt[80]; - sprintf (txt, "B = %s : A = %s", bmsg, amsg); - DrawText (-1, ypos, txt); - - DrawVersion(); - showscreen (); - return WaitButtonAB (); -} - -/**************************************************************************** - * Show an action in progress - ***************************************************************************/ -void -ShowAction (const char *msg) -{ - int ypos = (screenheight - 30) >> 1; - - if (screenheight == 480) - ypos += 52; - else - ypos += 32; - - clearscreen (); - setfontsize(20); - DrawText (-1, ypos, msg); - - DrawVersion(); - showscreen (); -} - -/**************************************************************************** - * Generic Menu Routines - ***************************************************************************/ -void -DrawMenu (char items[][50], const char *title, int maxitems, int selected, int fontsize, int x) -{ - int i, w = 0; - int ypos = 0; - int n = 1; - int line_height; - - ypos = 105; - - if (screenheight == 480) - ypos += 52; - else - ypos += 42; - - clearscreen (); - - setfontcolour (0, 0, 0); - - if (title != NULL) - { - setfontsize (26); - DrawText (-1, 150, title); - } - - // Draw menu items - - setfontsize (fontsize); // set font size - - line_height = (fontsize + 8); - - for (i = 0; i < maxitems; i++) - { - if(strlen(items[i]) > 0) - { - if ( items[i] == NULL ) - ypos -= line_height; - else if (i == selected) - { - for( w = 0; w < line_height; w++ ) - DrawLineFast( 77, 575, n * line_height + (ypos-line_height+6) + w, 0x00, 0x00, 0x00 ); - - //setfontcolour (0xff, 0xff, 0xff); - DrawText (x, n * line_height + ypos, items[i]); - //setfontcolour (0x00, 0x00, 0x00); - } - else - { - DrawText (x, n * line_height + ypos, items[i]); - } - n++; - } - } - - DrawVersion(); - showscreen (); -} - -/**************************************************************************** - * FindMenuItem - * - * Help function to find the next visible menu item on the list - * Supports menu wrap-around - ***************************************************************************/ - -int FindMenuItem(char items[][50], int maxitems, int currentItem, int direction) -{ - int nextItem = currentItem + direction; - - if(nextItem < 0) - nextItem = maxitems-1; - else if(nextItem >= maxitems) - nextItem = 0; - - if(strlen(items[nextItem]) > 0) - return nextItem; - else - return FindMenuItem(&items[0], maxitems, nextItem, direction); -} - -/**************************************************************************** - * RunMenu - * - * Call this with the menu array defined in menu.cpp - * It's here to keep all the font / interface stuff together. - ***************************************************************************/ -int menu = 0; - -int -RunMenu (char items[][50], int maxitems, const char *title, int fontsize, int x) -{ - int redraw = 1; - int quit = 0; - int ret = 0; - - u32 p = 0; - u32 wp = 0; - signed char gc_ay = 0; - signed char wm_ay = 0; - - while (quit == 0) - { - #ifdef HW_RVL - if(updateFound) - { - updateFound = WaitPromptChoice("An update is available!", "Update later", "Update now"); - if(updateFound) - if(DownloadUpdate()) - ExitToLoader(); - } - - if(ShutdownRequested) - ShutdownWii(); - #endif - - if (redraw) - { - DrawMenu (&items[0], title, maxitems, menu, fontsize); - redraw = 0; - } - - gc_ay = PAD_StickY (0); - p = PAD_ButtonsDown (0); -#ifdef HW_RVL - wm_ay = WPAD_Stick (0,0,1); - wp = WPAD_ButtonsDown (0); -#endif - - updateRumbleFrame(); - VIDEO_WaitVSync(); // slow things down a bit so we don't overread the pads - - /*** Look for up ***/ - if ( (p & PAD_BUTTON_UP) || (wp & (WPAD_BUTTON_UP | WPAD_CLASSIC_BUTTON_UP)) || - (gc_ay > PADCAL) || (wm_ay > PADCAL) -#ifdef HW_RVL - || DownUsbKeys[KB_UP] -#endif - ) - { - redraw = 1; - menu = FindMenuItem(&items[0], maxitems, menu, -1); - } - - /*** Look for down ***/ - if ( (p & PAD_BUTTON_DOWN) || (wp & (WPAD_BUTTON_DOWN | WPAD_CLASSIC_BUTTON_DOWN)) || - (gc_ay < -PADCAL) || (wm_ay < -PADCAL) -#ifdef HW_RVL - || DownUsbKeys[KB_DOWN] -#endif - ) - { - redraw = 1; - menu = FindMenuItem(&items[0], maxitems, menu, +1); - } - - if ((p & PAD_BUTTON_A) || (wp & (WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A)) -#ifdef HW_RVL - || DownUsbKeys[KB_ENTER] -#endif - ) - { - quit = 1; - ret = menu; - } - - if ((p & PAD_BUTTON_B) || (wp & (WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B)) -#ifdef HW_RVL - || DownUsbKeys[KB_ESC] -#endif - ) - { - quit = -1; - ret = -1; - } - } - - /*** Wait for B button to be released before proceeding ***/ - while ( (PAD_ButtonsDown(0) & PAD_BUTTON_B) -#ifdef HW_RVL - || (WPAD_ButtonsDown(0) & (WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B)) - || DownUsbKeys[KB_ESC] -#endif - ) - { - ret = -1; - updateRumbleFrame(); - VIDEO_WaitVSync(); - } - - return ret; - -} - -/**************************************************************************** - * Showfile screen - * - * Display the file selection to the user - ***************************************************************************/ - -void -ShowFiles (BROWSERENTRY * browserList, int maxfiles, int offset, int selection) -{ - int i, j; - char text[MAXPATHLEN]; - int ypos; - int w; - - clearscreen (); - - setfontsize (26); - DrawText (-1, 150, "Choose Game"); - - setfontsize(18); - - ypos = (screenheight - ((PAGESIZE - 1) * 20)) >> 1; - - if (screenheight == 480) - ypos += 24; - else - ypos += 10; - - ypos += 30; - - j = 0; - for (i = offset; i < (offset + PAGESIZE) && (i < maxfiles); i++) - { - if (browserList[i].isdir) // if a dir - { - strcpy (text, "["); - strcat (text, browserList[i].displayname); - strcat (text, "]"); - } - else - { - sprintf(text, browserList[i].displayname); - } - if (j == (selection - offset)) - { - /*** Highlighted text entry ***/ - for ( w = 0; w < 20; w++ ) - DrawLineFast( 77, 575, ( j * 20 ) + (ypos-16) + w, 0x00, 0x00, 0x00 ); - DrawText (100, (j * 20) + ypos, text); - } - else - { - /*** Normal entry ***/ - DrawText (100, (j * 20) + ypos, text); - } - j++; - } - - DrawVersion(); - showscreen (); -} - -/**************************************************************************** - * Cheats screen - * - * Displays a scrollable list of cheats to the user - ***************************************************************************/ - -void -ShowCheats (char items[][50], char itemvalues[][50], int maxitems, int offset, int selection) -{ - int i, j = 0; - int ypos; - int w; - - clearscreen (); - - setfontsize (26); - DrawText (-1, 150, "Cheats"); - - setfontsize(18); - - ypos = (screenheight - ((PAGESIZE - 1) * 20)) >> 1; - - if (screenheight == 480) - ypos += 24; - else - ypos += 10; - - for (i = offset; i < (offset + PAGESIZE) && (i < maxitems); i++) - { - if (i == selection) - { - /*** Highlighted text entry ***/ - for ( w = 0; w < 20; w++ ) - DrawLineFast( 30, 610, ( j * 20 ) + (ypos-16) + w, 0x80, 0x80, 0x80 ); - - DrawText (150, (j * 20) + ypos, items[i]); - DrawText (400, (j * 20) + ypos, itemvalues[i]); - } - else - { - /*** Normal entry ***/ - DrawText (150, (j * 20) + ypos, items[i]); - DrawText (400, (j * 20) + ypos, itemvalues[i]); - } - j++; - } - - DrawVersion(); - showscreen (); -} - - -/**************************************************************************** - * DrawLine - * - * Quick'n'Dirty Bresenham line drawing routine. - ***************************************************************************/ -#define SIGN(x) ((x<0)?-1:((x>0)?1:0)) - -void -DrawLine (int x1, int y1, int x2, int y2, u8 r, u8 g, u8 b) -{ - u32 colour, pixel; - u32 colourhi, colourlo; - int i, dx, dy, sdx, sdy, dxabs, dyabs, x, y, px, py; - int sp; - - colour = getcolour (r, g, b); - colourhi = colour & 0xffff0000; - colourlo = colour & 0xffff; - - dx = x2 - x1; /*** Horizontal distance ***/ - dy = y2 - y1; /*** Vertical distance ***/ - - dxabs = abs (dx); - dyabs = abs (dy); - sdx = SIGN (dx); - sdy = SIGN (dy); - x = dyabs >> 1; - y = dxabs >> 1; - px = x1; - py = y1; - - sp = (py * 320) + (px >> 1); - pixel = xfb[whichfb][sp]; - /*** Plot this pixel ***/ - if (px & 1) - xfb[whichfb][sp] = (pixel & 0xffff0000) | colourlo; - else - xfb[whichfb][sp] = (pixel & 0xffff) | colourhi; - - if (dxabs >= dyabs) /*** Mostly horizontal ***/ - { - for (i = 0; i < dxabs; i++) - { - y += dyabs; - if (y >= dxabs) - { - y -= dxabs; - py += sdy; - } - - px += sdx; - - sp = (py * 320) + (px >> 1); - pixel = xfb[whichfb][sp]; - - if (px & 1) - xfb[whichfb][sp] = (pixel & 0xffff0000) | colourlo; - else - xfb[whichfb][sp] = (pixel & 0xffff) | colourhi; - } - } - else - { - for (i = 0; i < dyabs; i++) - { - x += dxabs; - if (x >= dyabs) - { - x -= dyabs; - px += sdx; - } - - py += sdy; - - sp = (py * 320) + (px >> 1); - pixel = xfb[whichfb][sp]; - - if (px & 1) - xfb[whichfb][sp] = (pixel & 0xffff0000) | colourlo; - else - xfb[whichfb][sp] = (pixel & 0xffff) | colourhi; - } - } -} - -/**************************************************************************** - * Progress Bar - * - * Show the user what's happening - ***************************************************************************/ -void -ShowProgress (const char *msg, int done, int total) -{ - if(total <= 0) // division by 0 is bad! - return; - else if(done > total) // this shouldn't happen - done = total; - else if(total < (256*1024)) // don't bother showing progress for small files - return; - - int xpos, ypos; - int i; - - if(done < 5000) // we just started! - { - ypos = (screenheight - 30) >> 1; - - if (screenheight == 480) - ypos += 52; - else - ypos += 32; - - clearscreen (); - setfontsize(20); - DrawText (-1, ypos, msg); - - /*** Draw a white outline box ***/ - for (i = 380; i < 401; i++) - DrawLine (100, i, 540, i, 0xff, 0xff, 0xff); - } - - /*** Show progess ***/ - xpos = (int) (((float) done / (float) total) * 438); - - for (i = 381; i < 400; i++) - DrawLine (101, i, 101 + xpos, i, 0x00, 0x00, 0x80); - - if(done < 5000) // we just started! - { - DrawVersion(); - showscreen (); - } -} - -/**************************************************************************** - * DrawPolygon - ***************************************************************************/ -void -DrawPolygon (int vertices, int varray[], u8 r, u8 g, u8 b) -{ - int i; - - for (i = 0; i < vertices - 1; i++) - { - DrawLine (varray[(i << 1)], varray[(i << 1) + 1], varray[(i << 1) + 2], - varray[(i << 1) + 3], r, g, b); - } - - DrawLine (varray[0], varray[1], varray[(vertices << 1) - 2], - varray[(vertices << 1) - 1], r, g, b); -} - -/**************************************************************************** - * Draw Line Fast - * - * This routine requires that start and endx are 32bit aligned. - * It tries to perform a semi-transparency over the existing image. - ***************************************************************************/ - -#define SRCWEIGHT 0.7f -#define DSTWEIGHT (1.0f - SRCWEIGHT) - -static inline u8 c_adjust( u8 c , float weight ) -{ - return (u8)((float)c * weight); -} - -void DrawLineFast( int startx, int endx, int y, u8 r, u8 g, u8 b ) -{ - int width; - u32 offset; - int i; - u32 colour, clo, chi; - u32 lo,hi; - u8 *s, *d; - - //colour = getcolour(r, g, b); - colour = ( r << 16 | g << 8 | b ); - d = (u8 *)&colour; - d[1] = c_adjust(d[1], DSTWEIGHT); - d[2] = c_adjust(d[2], DSTWEIGHT); - d[3] = c_adjust(d[3], DSTWEIGHT); - - width = ( endx - startx ) >> 1; - offset = ( y << 8 ) + ( y << 6 ) + ( startx >> 1 ); - - for ( i = 0; i < width; i++ ) - { - lo = getrgb(xfb[whichfb][offset], 0); - hi = getrgb(xfb[whichfb][offset], 1); - - s = (u8 *)&hi; - s[1] = ( ( c_adjust(s[1],SRCWEIGHT) ) + d[1] ); - s[2] = ( ( c_adjust(s[2],SRCWEIGHT) ) + d[2] ); - s[3] = ( ( c_adjust(s[3],SRCWEIGHT) ) + d[3] ); - - s = (u8 *)&lo; - s[1] = ( ( c_adjust(s[1],SRCWEIGHT) ) + d[1] ); - s[2] = ( ( c_adjust(s[2],SRCWEIGHT) ) + d[2] ); - s[3] = ( ( c_adjust(s[3],SRCWEIGHT) ) + d[3] ); - - clo = getcolour( s[1], s[2], s[3] ); - s = (u8 *)&hi; - chi = getcolour( s[1], s[2], s[3] ); - - xfb[whichfb][offset++] = (chi & 0xffff0000 ) | ( clo & 0xffff) ; - } -} - -/**************************************************************************** - * Ok, I'm useless with Y1CBY2CR colour. - * So convert back to RGB so I can work with it -;) - ***************************************************************************/ -u32 getrgb( u32 ycbr, u32 low ) -{ - u8 r,g,b; - u32 y; - s8 cb,cr; - - if ( low ) - y = ( ycbr & 0xff00 ) >> 8; - else - y = ( ycbr & 0xff000000 ) >> 24; - - cr = ycbr & 0xff; - cb = ( ycbr & 0xff0000 ) >> 16; - - cr -= 128; - cb -= 128; - - r = (u8)((float)y + 1.371 * (float)cr); - g = (u8)((float)y - 0.698 * (float)cr - 0.336 * (float)cb); - b = (u8)((float)y + 1.732 * (float)cb); - - return (u32)( r << 16 | g << 8 | b ); - -} diff --git a/source/ngc/menudraw.h b/source/ngc/menudraw.h deleted file mode 100644 index 473c0b2..0000000 --- a/source/ngc/menudraw.h +++ /dev/null @@ -1,44 +0,0 @@ -/**************************************************************************** - * Visual Boy Advance GX - * - * Tantric September 2008 - * - * menudraw.h - * - * Menu drawing routines - * - * Uses libfreetype 2.2.1 compiled for GC with TTF support only. - * TTF only reduces the library by some 900k bytes! - * - * **WARNING*** - * - * ONLY USE GUARANTEED PATENT FREE FONTS. - ***************************************************************************/ -#ifndef _NGCMENUDRAW_ -#define _NGCMENUDRAW_ - -#include -#include "filesel.h" - -#define PAGESIZE 13 // max item listing on a screen - -int FT_Init (); -void setfontsize (int pixelsize); -void setfontcolour (u8 r, u8 g, u8 b); -void unpackbackdrop (); -void Credits (); -void RomInfo (); -void WaitButtonA (); -int RunMenu (char items[][50], int maxitems, const char *title, int fontsize = 20, int x = -1); -void DrawMenu (char items[][50], const char *title, int maxitems, int selected, int fontsize = 20, int x = -1); -void ShowCheats (char items[][50], char itemvalues[][50], int maxitems, int offset, int selection); -void ShowFiles (BROWSERENTRY * browserList, int maxfiles, int offset, int selection); - -void WaitPrompt (const char *msg); -int WaitPromptChoice (const char *msg, const char* bmsg, const char* amsg); -void ShowAction (const char *msg); -void ShowProgress (const char *msg, int done, int total); -void DrawPolygon (int vertices, int *varray, u8 r, u8 g, u8 b); -void DrawLineFast( int startx, int endx, int y, u8 r, u8 g, u8 b ); - -#endif diff --git a/source/ngc/oggplayer.c b/source/ngc/oggplayer.c new file mode 100644 index 0000000..e22039f --- /dev/null +++ b/source/ngc/oggplayer.c @@ -0,0 +1,354 @@ +/* + Copyright (c) 2008 Francisco Muņoz 'Hermes' + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are + permitted provided that the following conditions are met: + + - Redistributions of source code must retain the above copyright notice, this list of + conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright notice, this list + of conditions and the following disclaimer in the documentation and/or other + materials provided with the distribution. + - The names of the contributors may not be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef NO_SOUND + +#include "oggplayer.h" +#include + +/* OGG control */ + +#define READ_SAMPLES 4096 // samples that it must read before to send +#define MAX_PCMOUT 4096 // minimum size to read ogg samples +typedef struct +{ + OggVorbis_File vf; + vorbis_info *vi; + int current_section; + + // OGG file operation + int fd; + int mode; + int eof; + int flag; + int volume; + int seek_time; + + /* OGG buffer control */ + short pcmout[2][READ_SAMPLES + MAX_PCMOUT * 2]; /* take 4k out of the data segment, not the stack */ + int pcmout_pos; + int pcm_indx; + +} private_data_ogg; + +static private_data_ogg private_ogg; + +// OGG thread control + +#define STACKSIZE 8192 + +static u8 oggplayer_stack[STACKSIZE]; +static lwpq_t oggplayer_queue; +static lwp_t h_oggplayer; +static int ogg_thread_running = 0; + +static void ogg_add_callback(int voice) +{ + if (ogg_thread_running <= 0) + { + SND_StopVoice(0); + return; + } + + if (private_ogg.flag & 128) + return; // Ogg is paused + + if (private_ogg.pcm_indx >= READ_SAMPLES) + { + if (SND_AddVoice(0, + (void *) private_ogg.pcmout[private_ogg.pcmout_pos], + private_ogg.pcm_indx << 1) == 0) + { + private_ogg.pcmout_pos ^= 1; + private_ogg.pcm_indx = 0; + private_ogg.flag = 0; + LWP_ThreadSignal(oggplayer_queue); + } + } + else + { + if (private_ogg.flag & 64) + { + private_ogg.flag &= ~64; + LWP_ThreadSignal(oggplayer_queue); + } + } +} + +static void * ogg_player_thread(private_data_ogg * priv) +{ + int first_time = 1; + + ogg_thread_running = 0; + //init + LWP_InitQueue(&oggplayer_queue); + + priv[0].vi = ov_info(&priv[0].vf, -1); + + SND_Pause(0); + + priv[0].pcm_indx = 0; + priv[0].pcmout_pos = 0; + priv[0].eof = 0; + priv[0].flag = 0; + priv[0].current_section = 0; + + ogg_thread_running = 1; + + while (!priv[0].eof) + { + long ret; + if (ogg_thread_running <= 0) + break; + + if (priv[0].flag) + LWP_ThreadSleep(oggplayer_queue); // wait only when i have samples to send + + if (ogg_thread_running <= 0) + break; + + if (priv[0].flag == 0) // wait to all samples are sended + { + if (SND_TestPointer(0, priv[0].pcmout[priv[0].pcmout_pos]) + && SND_StatusVoice(0) != SND_UNUSED) + { + priv[0].flag |= 64; + continue; + } + if (priv[0].pcm_indx < READ_SAMPLES) + { + priv[0].flag = 3; + + if (priv[0].seek_time >= 0) + { + ov_time_seek(&priv[0].vf, priv[0].seek_time); + priv[0].seek_time = -1; + } + + ret + = ov_read( + &priv[0].vf, + (void *) &priv[0].pcmout[priv[0].pcmout_pos][priv[0].pcm_indx], + MAX_PCMOUT,/*0,2,1,*/&priv[0].current_section); + priv[0].flag &= 192; + if (ret == 0) + { + /* EOF */ + if (priv[0].mode & 1) + ov_time_seek(&priv[0].vf, 0); // repeat + else + priv[0].eof = 1; // stops + // + } + else if (ret < 0) + { + /* error in the stream. Not a problem, just reporting it in + case we (the app) cares. In this case, we don't. */ + if (ret != OV_HOLE) + { + if (priv[0].mode & 1) + ov_time_seek(&priv[0].vf, 0); // repeat + else + priv[0].eof = 1; // stops + } + } + else + { + /* we don't bother dealing with sample rate changes, etc, but + you'll have to*/ + priv[0].pcm_indx += ret >> 1; //get 16 bits samples + } + } + else + priv[0].flag = 1; + } + + if (priv[0].flag == 1) + { + if (SND_StatusVoice(0) == SND_UNUSED || first_time) + { + first_time = 0; + if (priv[0].vi->channels == 2) + { + SND_SetVoice(0, VOICE_STEREO_16BIT, priv[0].vi->rate, 0, + (void *) priv[0].pcmout[priv[0].pcmout_pos], + priv[0].pcm_indx << 1, priv[0].volume, + priv[0].volume, ogg_add_callback); + priv[0].pcmout_pos ^= 1; + priv[0].pcm_indx = 0; + priv[0].flag = 0; + } + else + { + SND_SetVoice(0, VOICE_MONO_16BIT, priv[0].vi->rate, 0, + (void *) priv[0].pcmout[priv[0].pcmout_pos], + priv[0].pcm_indx << 1, priv[0].volume, + priv[0].volume, ogg_add_callback); + priv[0].pcmout_pos ^= 1; + priv[0].pcm_indx = 0; + priv[0].flag = 0; + } + } + else + { + // if(priv[0].pcm_indx==0) priv[0].flag=0; // all samples sended + } + + } + + } + ov_clear(&priv[0].vf); + priv[0].fd = -1; + priv[0].pcm_indx = 0; + ogg_thread_running = 0; + + return 0; +} + +void StopOgg() +{ + SND_StopVoice(0); + if (ogg_thread_running > 0) + { + ogg_thread_running = -2; + LWP_ThreadSignal(oggplayer_queue); + LWP_JoinThread(h_oggplayer, NULL); + + while (((volatile int) ogg_thread_running) != 0) + { + ;;; + } + } +} + +int PlayOgg(int fd, int time_pos, int mode) +{ + StopOgg(); + + ogg_thread_running = 0; + + private_ogg.fd = fd; + private_ogg.mode = mode; + private_ogg.eof = 0; + private_ogg.volume = 127; + private_ogg.flag = 0; + private_ogg.seek_time = -1; + + if (time_pos > 0) + private_ogg.seek_time = time_pos; + + if (fd < 0) + { + private_ogg.fd = -1; + return -1; + } + if (ov_open((void *) &private_ogg.fd, &private_ogg.vf, NULL, 0) < 0) + { + mem_close(private_ogg.fd); // mem_close() can too close files from devices + private_ogg.fd = -1; + ogg_thread_running = -1; + return -1; + } + + if (LWP_CreateThread(&h_oggplayer, (void *) ogg_player_thread, + &private_ogg, oggplayer_stack, STACKSIZE, 80) == -1) + { + ogg_thread_running = -1; + ov_clear(&private_ogg.vf); + private_ogg.fd = -1; + return -1; + } + LWP_ThreadSignal(oggplayer_queue); + while (((volatile int) ogg_thread_running) == 0) + { + ;;; + } + return 0; +} + +void PauseOgg(int pause) +{ + if (pause) + { + private_ogg.flag |= 128; + } + else + { + if (private_ogg.flag & 128) + { + private_ogg.flag |= 64; + private_ogg.flag &= ~128; + if (ogg_thread_running > 0) + { + LWP_ThreadSignal(oggplayer_queue); + // while(((volatile int )private_ogg.flag)!=1 && ((volatile int )ogg_thread_running)>0) {;;;} + } + } + + } +} + +int StatusOgg() +{ + if (ogg_thread_running <= 0) + return -1; // Error + + if (private_ogg.eof) + return 255; // EOF + + if (private_ogg.flag & 128) + return 2; // paused + return 1; // running +} + +void SetVolumeOgg(int volume) +{ + private_ogg.volume = volume; + + SND_ChangeVolumeVoice(0, volume, volume); +} + +s32 GetTimeOgg() +{ + int ret; + if (ogg_thread_running <= 0) + return 0; + if (private_ogg.fd < 0) + return 0; + ret = ((s32) ov_time_tell(&private_ogg.vf)); + if (ret < 0) + ret = 0; + + return ret; +} + +void SetTimeOgg(s32 time_pos) +{ + if (time_pos >= 0) + private_ogg.seek_time = time_pos; +} + +#endif diff --git a/source/ngc/oggplayer.h b/source/ngc/oggplayer.h new file mode 100644 index 0000000..cb14adc --- /dev/null +++ b/source/ngc/oggplayer.h @@ -0,0 +1,174 @@ +/* + Copyright (c) 2008 Francisco Muņoz 'Hermes' + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are + permitted provided that the following conditions are met: + + - Redistributions of source code must retain the above copyright notice, this list of + conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright notice, this list + of conditions and the following disclaimer in the documentation and/or other + materials provided with the distribution. + - The names of the contributors may not be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef NO_SOUND + +#ifndef __OGGPLAYER_H__ +#define __OGGPLAYER_H__ + +#include +#include "tremor/ivorbiscodec.h" +#include "tremor/ivorbisfile.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +#define OGG_ONE_TIME 0 +#define OGG_INFINITE_TIME 1 + +#define OGG_STATUS_RUNNING 1 +#define OGG_STATUS_ERR -1 +#define OGG_STATUS_PAUSED 2 +#define OGG_STATUS_EOF 255 + +/*------------------------------------------------------------------------------------------------------------------------------------------------------*/ +/* Player OGG functions */ +/*------------------------------------------------------------------------------------------------------------------------------------------------------*/ + +/* int PlayOgg(int fd, int time_pos, int mode); + + Play an Ogg file. This file can be loaded from memory (mem_open(void *ogg, int size_ogg)) or from device with open("device:file.ogg",O_RDONLY,0); + + NOTE: The file is closed by the player when you call PlayOgg(), StopOgg() or if it fail. + + -- Params --- + + fd: file descriptor from open() or mem_open() + + time_pos: initial time position in the file (in milliseconds). For example, use 30000 to advance 30 seconds + + mode: Use OGG_ONE_TIME or OGG_INFINITE_TIME. When you use OGG_ONE_TIME the sound stops and StatusOgg() return OGG_STATUS_EOF + + return: 0- Ok, -1 Error + + */ + +int PlayOgg(int fd, int time_pos, int mode); + +/*------------------------------------------------------------------------------------------------------------------------------------------------------*/ + +/* void StopOgg(); + + Stop an Ogg file. + + NOTE: The file is closed and the player thread is released + + -- Params --- + + + */ + +void StopOgg(); + +/*------------------------------------------------------------------------------------------------------------------------------------------------------*/ + +/* void PauseOgg(int pause); + + Pause an Ogg file. + + -- Params --- + + pause: 0 -> continue, 1-> pause + + */ + +void PauseOgg(int pause); + +/*------------------------------------------------------------------------------------------------------------------------------------------------------*/ + +/* int StatusOgg(); + + Return the Ogg status + + -- Params --- + + + return: OGG_STATUS_RUNNING + OGG_STATUS_ERR -> not initialized? + OGG_STATUS_PAUSED + OGG_STATUS_EOF -> player stopped by End Of File + + */ + +int StatusOgg(); + +/*------------------------------------------------------------------------------------------------------------------------------------------------------*/ + +/* void SetVolumeOgg(int volume); + + Set the Ogg playing volume. + NOTE: it change the volume of voice 0 (used for the Ogg player) + + -- Params --- + + volume: 0 to 255 (max) + + */ + +void SetVolumeOgg(int volume); + +/*------------------------------------------------------------------------------------------------------------------------------------------------------*/ + +/* s32 GetTimeOgg(); + + Return the Ogg time from the starts of the file + + -- Params --- + + return: 0 -> Ok or error condition (you must ignore this value) + >0 -> time in milliseconds from the starts + + */ + +s32 GetTimeOgg(); + +/*------------------------------------------------------------------------------------------------------------------------------------------------------*/ + +/* void SetTimeOgg(s32 time_pos); + + Set the time position + + NOTE: The file is closed by the player when you call PlayOgg(), StopOgg() or if it fail. + + -- Params --- + + time_pos: time position in the file (in milliseconds). For example, use 30000 to advance 30 seconds + + */ + +void SetTimeOgg(s32 time_pos); + +/*------------------------------------------------------------------------------------------------------------------------------------------------------*/ + +#ifdef __cplusplus +} +#endif + +#endif + +#endif