bool Checkbox::init( const String& name, const Vector2& position, const String& enableImage, const String& disabledImage ) { m_name = name.ToCString(); m_position = position; m_enabledImage = ResourceManager::Instance().LoadImage( enableImage.ToCString() ); m_disabledImage = ResourceManager::Instance().LoadImage( disabledImage.ToCString() ); m_size = Vector2( (float)m_enabledImage->GetWidth(), (float)m_enabledImage->GetHeight() ); return m_enabledImage && m_disabledImage; }
CEntity * CEntityFactory::CreateEntity(EntityId id){ String buffer = String::Read(m_entitiesInfo); //Analizamos el XML xml_document<> doc; doc.parse<0>((char*)buffer.ToCString()); //Dependiendo del id buscamos la entidad adecuada String entityName; switch (id){ case EDREADNOUGHT: entityName = "dreadnought"; break; case EAVATAR: entityName = "avatar"; break; case EDREADNOUGHTSHOT1: entityName = "dreadnoughtshot1"; break; case EDREADNOUGHTSHOT2: entityName = "dreadnoughtshot2"; break; case EAVATARSHOT1: entityName = "avatarshot1"; break; case EAVATARTRACTOR: entityName = "avatartractor"; break; case EFIGHTERSHOT: entityName = "fightershot"; break; } //Accedemos al nodo de la entidad xml_node<>* entityNode = doc.first_node()->first_node(entityName.ToCString()); CEntity * entity = new CEntity(id); //Accedemos al nodo componentes xml_node<>* componentsNode = entityNode->first_node("components"); //Accedemos al primer componente xml_node<>* componentNode = componentsNode->first_node(); //Buscamos todas las componentes while (componentNode != nullptr){ String name = componentNode->name(); //Creamos el nuevo componente Component * component = NewComponent(name, entity, entityName); //Lo añadimos a la entidad if (component){ entity->AddComponent(component); } componentNode = componentNode->next_sibling(); } m_entities.Add(entity); return entity; }
StringList Include::Evaluate(EvaluationContext& context) { // check include depth size_t includeDepth = context.IncludeDepth(); if (includeDepth >= util::kIncludeDepthLimit) { std::stringstream message; message << "Reached include depth limit (" << util::kIncludeDepthLimit << ")"; throw EvaluationException(message.str()); } context.SetIncludeDepth(includeDepth + 1); StringList fileNames = fFileNames->Evaluate(context); if (!fileNames.IsEmpty()) { // Only the file referred to by the first element is included. // bind the target data::Target* target = context.Targets().LookupOrCreate(fileNames.ElementAt(0)); String filePath; data::FileStatus fileStatus; data::TargetBinder::Bind(*context.GlobalVariables(), target, filePath, fileStatus); // open the file std::ifstream file(filePath.ToCString()); if (file.fail()) { if (target->IsIgnoreIfMissing()) return StringList::False(); throw EvaluationException( std::string("include: Failed to open file \"") + filePath.ToCString() + "\""); } // parse and evaluate it parser::Parser parser; parser.SetFileName(filePath.ToStlString()); util::Reference<code::Block> block(parser.Parse(file), true); block->Evaluate(context); if (context.GetJumpCondition() == JUMP_CONDITION_JUMP_TO_EOF) context.SetJumpCondition(JUMP_CONDITION_NONE); } // reset include depth context.SetIncludeDepth(includeDepth); return StringList::False(); }
CollisionPixelData::CollisionPixelData(const String &filename) { int imgW, imgH, comp; this->filename = filename; unsigned char* buffer = stbi_load(filename.ToCString(), &imgW, &imgH, &comp, 4); if (buffer) { width = (uint16)imgW; height = (uint16)imgH; data = new bool[width * height]; for ( uint32 j = 0; j < height; j++ ) for ( uint32 i = 0; i < width; i++ ) { if (buffer[(j * width + i) * 4 + 3] == 0) data[(j * width) + i] = false; else data[(j * width) + i] = true; } stbi_image_free(buffer); } }
CollisionPixelData::CollisionPixelData(const String & filename) { m_filename = filename; int width32 = 0; int height32 = 0; int * ptrComp = NULL; uint8 * buffer = stbi_load(filename.ToCString(), &width32, &height32, ptrComp, 4); uint8 * ptrBuffer = buffer; m_width = width32; m_height = height32; uint32 numPixels = m_width * m_height; bool * bufferBool = (bool *)malloc(numPixels); m_data = bufferBool; for (uint32 i = 0; i < numPixels; i++) { if (*((uint32 *)(ptrBuffer)) == 0xff000000) *bufferBool = true; else *bufferBool = false; bufferBool++; ptrBuffer+=4; } if (buffer) stbi_image_free(buffer); }
kt_bool StringHelper::FromString(const String& rStringValue, Quaternion& rValue) { kt_size_t index = rStringValue.FindFirstOf(" "); if (index != -1) { std::stringstream converter; converter.str(rStringValue.ToCString()); kt_double valueX = 0.0; kt_double valueY = 0.0; kt_double valueZ = 0.0; kt_double valueW = 0.0; converter >> valueX; converter >> valueY; converter >> valueZ; converter >> valueW; rValue.SetX(valueX); rValue.SetY(valueY); rValue.SetZ(valueZ); rValue.SetW(valueW); return true; }
String::String(const String& str) { if (&str!=NULL) mvar_ImpAcc=(StringImp *)new StringImp(str.ToCString()); else mvar_ImpAcc=(StringImp *)new StringImp(""); }
void BuildGameThread::run() { bool ok = false; String output = ""; String cmd = ""; cmd += "uic Assets/Engine/EditorWindow.ui > src/View/EditorWindowAutoGenerated.h"; cmd += " && qmake \"BUILD_MODE=GAME\" && make -j8"; SystemUtils::System(cmd.ToCString(), &output, &ok); if (!ok) { Debug_Error(output); } else { Debug_Log("Game has been built!"); } if (ok && runGameAfterBuild) { String output = ""; Debug_Log("Running Game..."); SystemUtils::SystemBackground("./Game.exe"); Debug_Log("Game is running!"); } }
Font::Font(const String& filename) : Image(filename, 16, 16) { int widthImage = 0; int heightImage = 0; int nComponents = 4; unsigned int nFrames = 16 * 16; uint16 widthFrame = GetWidth(); uint16 heightFrame = GetHeight(); uint16 nLine = -1; unsigned char* pixels = stbi_load( filename.ToCString(), &widthImage, &heightImage, &nComponents, nComponents); for(unsigned int n = 0; n < (unsigned int)nFrames; n++) { Glyph glyph(0, 0, widthFrame, heightFrame); uint16 row = n / 16; uint16 column = n % 16; for(unsigned int posY = (unsigned int) (row * heightFrame); posY < (unsigned int) ((row + 1) * heightFrame) ; posY++ ) { for(unsigned int posX = (unsigned int)( column * widthFrame ); posX < (unsigned int)( (column + 1) * widthFrame ); posX++) { unsigned char pixelR = pixels[(posY * widthImage + posX) * 4 + 0]; unsigned char pixelG = pixels[(posY * widthImage + posX) * 4 + 1]; unsigned char pixelB = pixels[(posY * widthImage + posX) * 4 + 2]; unsigned char* pixelA = &pixels[(posY * widthImage + posX) * 4 + 3]; if( Glyph::IsYellow( pixelR, pixelG, pixelB)) { glyph.SetInitialCoordinates(posX, posY); *pixelA = 0; } else if( Glyph::IsRed( pixelR, pixelG, pixelB)) { glyph.SetFinalCoordinates(posX, posY); *pixelA = 0; } else if( Glyph::IsBlack( pixelR, pixelG, pixelB)) { *pixelA = 0; } } } glyphs.Add(glyph); } glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, widthImage, heightImage, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); stbi_image_free(pixels); }
Image::Image(const String &filename, uint16 hframes, uint16 vframes) { this->filename = filename; this->hframes = hframes; this->vframes = vframes; width = 0; height = 0; handlex = 0; handley = 0; gltex = 0; lastU = 1.0; lastV = 1.0; // TAREA: Cargar el buffer de la imagen int bWidth=0; int bHeight=0; unsigned char* buffer = stbi_load(filename.ToCString(),&bWidth,&bHeight,NULL,4); unsigned char* buffer1 = NULL; width=(uint16)bWidth; height=(uint16)bHeight; int width1=(int)pow(2,ceil(Log2(width))); int height1=(int)pow(2,ceil(Log2(height))); if ((width1!=width)||(height1!=height)) { bWidth = width1; bHeight = height1; buffer1=new unsigned char[bWidth*bHeight*4]; for (int i=0; i<(height);i++) { for (int j=0; j<(width); j++) { for (int k=0; k<4;k++) { buffer1[(j*width1+i)*4 + k]=buffer[(j*width+i)*4 + k]; } } } lastU=(double)width/width1; lastV=(double)height/height1; } // Generamos la textura if ( buffer ) { // TAREA: Generar la textura de OpenGL glGenTextures(1, &gltex); Bind(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_NEAREST); if (buffer1) glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,bWidth,bHeight,0,GL_RGBA,GL_UNSIGNED_BYTE,buffer1); else glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,bWidth,bHeight,0,GL_RGBA,GL_UNSIGNED_BYTE,buffer); stbi_image_free(buffer); delete[] buffer1; } }
Font::Font(const String &filename) : Image(filename, 16, 16) { m_x = 0; m_y = 0; m_speedX = 0; m_speedY = 0; for (unsigned short int f = 0; f < GetNumFrames(); f++) glyphs.Add(Glyph(0, 0, GetWidth(), GetHeight())); int width32 = 0; int height32 = 0; int *ptrComp = nullptr; uint8 * const buffer = stbi_load(filename.ToCString(), &width32, &height32, ptrComp, 4); //this pointer should never be missing if (buffer) { uint8 *ptrBuffer = buffer; //0x<A><B><G><R> const uint32 red = 0xff0000ff; const uint32 yellow = 0xff00ffff; const uint32 black = 0xff000000; const uint32 transparent = 0x00000000; unsigned short int i, j; uint16 row = 0; uint16 col = 0; for (unsigned short int frame = 0; frame < GetNumFrames(); frame++) { row = frame / GetHFrames(); col = frame % GetHFrames(); ptrBuffer = buffer + ((GetWidth() * col) * 4) + (row * GetHeight() * GetWidth() * GetHFrames() * 4); for (j = 0; j < GetHeight(); j++) { for (i = 0; i < GetWidth(); i++) { //inside each frame if (*((uint32 *)(ptrBuffer)) == black) memset(ptrBuffer, transparent, 4); else if (*((uint32 *)(ptrBuffer)) == yellow) { glyphs[frame].SetOrigX(i); glyphs[frame].SetOrigY(j); memset(ptrBuffer, transparent, 4); } else if (*((uint32 *)(ptrBuffer)) == red) { glyphs[frame].SetEndX(i); glyphs[frame].SetEndY(j); memset(ptrBuffer, transparent, 4); } ptrBuffer += 4; } ptrBuffer += ((GetHFrames() * GetWidth()) - GetWidth()) * 4; } } Renderer::Instance().GenFontImage(buffer, width32, height32); delete buffer; } }
uint32 Font::GetTextWidth(const String & text) const { uint32 toRet = 0; const char * str = text.ToCString(); //glyphs[*str] -> frame position corresponds to char ASCII code while (*str != '\0') { toRet += glyphs[*str].GetEndX() - glyphs[*str].GetOrigX(); str++; } return toRet; }
kt_bool StringHelper::FromString(const String& rStringValue, kt_double& rValue) { int precision = std::numeric_limits<double>::digits10; std::stringstream converter; converter.precision(precision); converter.str(rStringValue.ToCString()); converter >> rValue; return true; }
Map::Map(const String &filename, uint16 firstColId) { m_filename = filename; m_firstColId = firstColId; m_valid = false; String buffer = String::Read(filename); if (buffer != "") { xml_document<> doc; doc.parse<0>((char *)buffer.ToCString()); xml_node<> * rootNode = doc.first_node("map"); m_width = String(rootNode->first_attribute("width")->value()).ToInt(); m_height = atof(rootNode->first_attribute("height")->value()); m_tileWidth = atof(rootNode->first_attribute("tilewidth")->value()); m_tileHeight = atof(rootNode->first_attribute("tileheight")->value()); xml_node<> * tilesetNode = rootNode->first_node("tileset"); //ignoring other tilesets if any, only getting the first one int firstGID = String(tilesetNode->first_attribute("firstgid")->value()).ToInt(); int tileWidth = String(tilesetNode->first_attribute("tilewidth")->value()).ToInt(); int tileHeight = String(tilesetNode->first_attribute("tileheight")->value()).ToInt(); int tileOffsetX = 0; int tileOffsetY = 0; if (tilesetNode->first_node("tileoffset")) { tileOffsetX = String(tilesetNode->first_node("tileoffset")->first_attribute("x")->value()).ToInt(); tileOffsetY = String(tilesetNode->first_node("tileoffset")->first_attribute("y")->value()).ToInt(); } xml_node<> * imageNode = tilesetNode->first_node("image"); m_imageFile = String(imageNode->first_attribute("source")->value()).StripDir(); int imageWidth = String(imageNode->first_attribute("width")->value()).ToInt(); int imageHeight = String(imageNode->first_attribute("height")->value()).ToInt(); //delete imageNode; xml_node<> * dataNode = rootNode->first_node("layer")->first_node("data"); if (!dataNode->first_attribute("encoding") && !dataNode->first_attribute("compression")) { xml_node<> * tileNode = dataNode->first_node("tile"); while (tileNode != NULL) { int32 tileId = String(tileNode->first_attribute("gid")->value()).ToInt() - firstGID; m_tileIds.Add(tileId); tileNode = tileNode->next_sibling("tile"); } String tilesetFile = filename.ExtractDir() + "/" + m_imageFile; m_image = ResourceManager::Instance().LoadImage(tilesetFile, imageWidth / tileWidth, imageHeight / tileHeight); m_image->SetHandle(tileOffsetX, tileOffsetY); m_valid = true; } } }
uint32 Font::GetTextHeight(const String & text) const { uint32 toRet = 0; uint32 height; const char * str = text.ToCString(); while (*str != '\0') { height = glyphs[*str].GetEndY() - glyphs[*str].GetOrigY(); if (height > toRet) toRet = height; str++; } return toRet; }
AudioStream::AudioStream(const String & filename, AudioSource * source) { buffers[0] = buffers[1] = 0; AudioStream::source = source; stream = stb_vorbis_open_filename(filename.ToCString(), nullptr, nullptr); if (!stream) return; info = stb_vorbis_get_info(stream); samplesLeft = stb_vorbis_stream_length_in_samples(stream) * info.channels; alGenBuffers(2, buffers); Stream(buffers[0]); Stream(buffers[1]); alSourceQueueBuffers(AudioStream::source->GetID(), 2, buffers); streams.Add(this); }
IsometricMap::IsometricMap(const String& filename, uint16 firstColId ) : Map( filename, firstColId ) { String content = String::Read( filename.ToCString() ); xml_document<> file; file.parse<0>( (char*) content.ToCString() ); xml_node<>* map = file.first_node( "map" ); xml_node<>* tileSet = map->first_node( "tileset" ); int firstgid = atoi( tileSet->first_attribute( "firstgid" )->value() ); xml_node<>* layer = map->first_node( "layer" ); layer = layer->next_sibling( "layer" ); xml_node<>* data = layer->first_node( "data" ); if( data->first_attribute( "encoding" ) || data->first_attribute( "compression" ) ) { return; } xml_node<>* tile = data->first_node( "tile" ); while( tile ) { int gid = atoi( tile->first_attribute( "gid" )->value() ); topLayerIds.Add( gid - firstgid ); tile = tile->next_sibling( "tile" ); } int handleX = GetImage()->GetHandleX() + GetTileWidth(); int handleY = GetImage()->GetHeight() - GetImage()->GetHandleY() - GetTileHeight(); GetImage()->SetHandle( handleX, handleY ); }
Map::Map(const String &filename, uint16 firstColId) { valid = false; this->filename = filename; this->firstColId = firstColId; width = height = tileWidth = tileHeight = 0; // Analizamos el XML String buffer = String::Read(filename); xml_document<> doc; doc.parse<0>((char*)buffer.ToCString()); // Obtenemos informacion de cabecera xml_node<>* mapNode = doc.first_node("map"); width = atoi(mapNode->first_attribute("width")->value()); height = atoi(mapNode->first_attribute("height")->value()); tileWidth = atoi(mapNode->first_attribute("tilewidth")->value()); tileHeight = atoi(mapNode->first_attribute("tileheight")->value()); // Obtenemos informacion del tileset ("source" no esta soportado) xml_node<>* tilesetNode = mapNode->first_node("tileset"); int firstGid = atoi(tilesetNode->first_attribute("firstgid")->value()); uint16 tilesetTileWidth = atoi(tilesetNode->first_attribute("tilewidth")->value()); uint16 tilesetTileHeight = atoi(tilesetNode->first_attribute("tileheight")->value()); int offsetX = 0, offsetY = 0; if ( tilesetNode->first_node("tileoffset") ) { offsetX = atoi(tilesetNode->first_node("tileoffset")->first_attribute("x")->value()); offsetY = atoi(tilesetNode->first_node("tileoffset")->first_attribute("y")->value()); } imageFile = String(tilesetNode->first_node("image")->first_attribute("source")->value()).StripDir(); int imageWidth = atoi(tilesetNode->first_node("image")->first_attribute("width")->value()); int imageHeight = atoi(tilesetNode->first_node("image")->first_attribute("height")->value()); // Leemos el primer layer, sin codificacion ni compresion (los demas son ignorados) xml_node<>* dataNode = mapNode->first_node("layer")->first_node("data"); if ( dataNode->first_attribute("encoding") || dataNode->first_attribute("compression") ) return; xml_node<>* tileNode = dataNode->first_node("tile"); while ( tileNode ) { tileIds.Add(atoi(tileNode->first_attribute("gid")->value()) - firstGid); tileNode = tileNode->next_sibling("tile"); } // Cargamos la imagen image = ResourceManager::Instance().LoadImage(filename.ExtractDir() + "/" + imageFile, imageWidth/tilesetTileWidth, imageHeight/tilesetTileHeight); image->SetHandle(offsetX, offsetY); valid = true; }
Image::Image(const String &filename, uint16 hframes, uint16 vframes) { this->filename = filename; this->hframes = hframes; this->vframes = vframes; width = 0; height = 0; handlex = 0; handley = 0; gltex = 0; lastU = 1.0; lastV = 1.0; unsigned char *buffer; int comp; // TAREA: Cargar el buffer de la imagen buffer = stbi_load(filename.ToCString(), reinterpret_cast<int *>(&width), reinterpret_cast<int *>(&height), &comp, 4); // Generamos la textura if ( buffer ) { newWidth = static_cast<uint16>(pow(2, ceil(Log2(width)))); newHeight = static_cast<uint16>(pow(2, ceil(Log2(height)))); // TAREA: Generar la textura de OpenGL if (newWidth != width || newHeight != height) { unsigned char *newBuffer = static_cast<unsigned char*>(malloc(newWidth*newHeight*4)); // 65536 int fullNewWidth = newWidth * 4; int fullOldWidth = width * 4; for (unsigned int i = 0; i < height; i++) { // newBuffer[i] = buffer[i]; memcpy(&newBuffer[fullNewWidth * i], &buffer[fullOldWidth * i], fullOldWidth); } lastU = static_cast<double>(width) / static_cast<double>(newWidth); lastV = static_cast<double>(height) / static_cast<double>(newHeight); gltex = Renderer::Instance().GenImage(newBuffer, newWidth, newHeight); } else { gltex = Renderer::Instance().GenImage(buffer, width, height); } } }
void Font::Render(const String & text, double x, double y) const{ /* ASCII * 32 = (space) * 48 = 0 * 64 = @ * 65 = A * 126 = ~ <- last */ const char * str = text.ToCString(); unsigned short int offset = 0; while (*str != '\0') { Renderer::Instance().DrawImage(this, x + offset, y, *str, GetHeight(), GetWidth(), 0); offset += glyphs[*str].GetEndX() - glyphs[*str].GetOrigX(); str++; } }
CollisionPixelData::CollisionPixelData(const String & filename) { this->filename = filename; // Cargar el buffer de la imagen int w, h; uint8 * buffer = stbi_load(filename.ToCString(), &w, &h, NULL, 4); // RGBA --> 4 if (buffer) { width = static_cast<uint16>(w); height = static_cast<uint16>(h); data = static_cast<bool *>(malloc(w*h*sizeof(bool))); for (uint32 i = 3; i < w * h * 4; i += 4) { if (buffer[i]) data[i / 4] = true; else data[i / 4] = false; } stbi_image_free(buffer); } }
IsometricMap::IsometricMap(const String & filename, uint16 firstColId) : Map(filename, firstColId) { String content = String::Read(filename); xml_document<> doc; doc.parse<0>(const_cast<char*>(content.ToCString())); xml_node<> * node = doc.first_node("map"); xml_node<> * tileset = node->first_node("tileset"); int firstgid = String(tileset->first_attribute("firstgid")->value()).ToInt(); int tilewidth = String(tileset->first_attribute("tilewidth")->value()).ToInt(); int tileheight = String(tileset->first_attribute("tileheight")->value()).ToInt(); xml_node<>* data = node->first_node("layer")->next_sibling("layer")->first_node("data"); if (data->first_attribute("encoding") || data->first_attribute("compression")) { return; } xml_node<>* tile = data->first_node("tile"); while (tile) { topLayerIds.Add(String(tile->first_attribute("gid")->value()).ToInt() - firstgid); tile = tile->next_sibling("tile"); } GetImage()->SetHandle(GetImage()->GetHandleX() + tilewidth / 2, GetImage()->GetHeight() - GetImage()->GetHandleY() - tileheight); }
//------------------------------------- // //------------------------------------- TError BaseScene::Init() { TError error = OK; String content = String::Read( m_sceneInfo->ToCString() ); rapidjson::Document document; document.Parse<0>( (char*) content.ToCString() ); if( document.HasParseError() ) return ERROR; if( !document.HasMember("Image") || !document.HasMember("Entities") ) error = ERROR; String pathImage = String( document["Image"].GetString() ); Image* image = ResourceManager::Instance().LoadImage( pathImage ); m_scene = NEW( Scene,( image )); const rapidjson::Value& entities = document["Entities"]; for( unsigned int i = 0; i < entities.Size(); i++ ) { IEntity* newEntity = IEntityFactory::Instance().GetEntity( &entities[i], error ); if( error == OK ) { newEntity->SetParentScene( this ); newEntity->Init(); m_entities.Add( newEntity ); } else { IEntityFactory::Instance().RemoveEntity( newEntity ); } } return error; }
void Screen::SetTitle(const String &title) { glfwSetWindowTitle(title.ToCString()); }
Font::Font(const String& filename) : Image(filename, 16, 16) { _glyphs = Array<Glyph>(); Glyph myGlyph = Glyph(); // Cargamos el buffer con la imagen int iWidth; int iHeight; unsigned char* buffer = stbi_load(filename.ToCString(), &iWidth, &iHeight, NULL, nElemPixel); // Calculamos las dimensiones de cada frame bool dimX = false; for (int i = 1; i < iWidth / nElemPixel && !dimX; i++) { uint8 r = buffer[i * nElemPixel]; uint8 g = buffer[i * nElemPixel + 1]; uint8 b = buffer[i * nElemPixel + 2]; if (IsColor(r, g, b, 255, 255, 0)) { _dimFrameX = i; dimX = true; } } bool dimY = false; for (int i = 1; i < iHeight / nElemPixel && !dimY; i++) { uint8 r = buffer[i * iWidth * nElemPixel]; uint8 g = buffer[i * iWidth * nElemPixel + 1]; uint8 b = buffer[i * iWidth * nElemPixel + 2]; if (IsColor(r, g, b, 255, 255, 0)) { _dimFrameY = i; dimY = true; } } // Tratamos los pixeles dentro de cada frame if ( buffer ) { if (dimX && dimY) { for (int j = 0; j < nFrameY; j++) { for (int i = 0; i < nFrameX; i++) { // Accedemos al frame[i,j] for (int k = 0; k < _dimFrameX; k++) { for (int l = 0; l < _dimFrameY; l++) { // Accedemos al pixel[k,l] del frame[i,j] uint8 r = buffer[IndexFrom(i, j, k, l, iWidth, 0)]; uint8 g = buffer[IndexFrom(i, j, k, l, iWidth, 1)]; uint8 b = buffer[IndexFrom(i, j, k, l, iWidth, 2)]; if (IsColor(r, g, b, 255, 255, 0)) { myGlyph.SetIni(i * _dimFrameX + k, j * _dimFrameY + l); buffer[IndexFrom(i, j, k, l, iWidth, 3)] = 0; } else if (IsColor(r, g, b, 255, 0, 0)) { myGlyph.SetFin(i * _dimFrameX + k, j * _dimFrameY + l); buffer[IndexFrom(i, j, k, l, iWidth, 3)] = 0; } else if (IsColor(r, g, b, 0, 0, 0)) { buffer[IndexFrom(i, j, k, l, iWidth, 3)] = 0; } } } if (myGlyph.GetIniX() != 0 || myGlyph.GetIniY() != 0 || myGlyph.GetFinX() != 0 || myGlyph.GetFinY() != 0) _glyphs.Add(myGlyph); } } glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, iWidth, iHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); } free(buffer); } }
Map::Map(const String &filename, uint16 firstColId) { // TAREA: Implementar constructor this->filename = filename; this->firstColId = firstColId; valid = false; String file = String::Read(filename); xml_document<> xmlparser; xmlparser.parse<0>((char *)file.ToCString()); //guardamos los datos del mapa xml_node<>* nodeMap = xmlparser.first_node("map"); width = atoi(nodeMap->first_attribute("width")->value()); height = atoi(nodeMap->first_attribute("height")->value()); tileWidth = atoi(nodeMap->first_attribute("tilewidth")->value()); tileHeight = atoi(nodeMap->first_attribute("tileheight")->value()); //guardamos los datos del tileset xml_node<>* nodeTileset = nodeMap->first_node("tileset"); uint16 firstgid = atoi(nodeTileset->first_attribute("firstgid")->value()); uint16 tWidth = atoi(nodeTileset->first_attribute("tilewidth")->value()); uint16 tHeight = atoi(nodeTileset->first_attribute("tileheight")->value()); uint16 offsX,offsY; offsX = offsY = 0; //guardamos el offset xml_node<>* nodeOffset = nodeTileset->first_node("tileoffset"); if (nodeOffset) { offsX = atoi(nodeOffset->first_attribute("x")->value()); offsY = atoi(nodeOffset->first_attribute("y")->value()); } //guardamos los datos del fichero de imagen xml_node<>* nodeImg = nodeTileset->first_node("image"); this->imageFile = String( (char *)nodeImg->first_attribute("source")->value() ); uint16 imgWidth = atoi(nodeImg->first_attribute("width")->value()); uint16 imgHeight = atoi(nodeImg->first_attribute("height")->value()); //gestionamos solo la primera capa de tiles xml_node<>* nodeData = nodeMap->first_node("layer")->first_node("data"); //comprobamos que no haya codificacion en "data" y en tal caso salimos con valid=false xml_attribute<>* eleEnc = nodeData->first_attribute("enconding"); xml_attribute<>* eleComp = nodeData->first_attribute("compresion"); if (eleEnc || eleComp) return; //guardamos los tiles xml_node<>* nodeTile = nodeData->first_node("tile"); while (nodeTile) { //cogemos el id del tile y le restamos el valor firstgid int16 tid = atoi(nodeTile->first_attribute("gid")->value()); tid -= firstgid; this->tileIds.Add(tid); nodeTile = nodeTile->next_sibling("tile"); } this->imageFile = filename.ExtractDir() + "/" + this->imageFile; //el numero de frames lo obtenemos dividiendo el ancho/alto de la imagen por el ancho/alto del tile this->image = ResourceManager::Instance().LoadImage(imageFile, imgWidth / tWidth, imgHeight / tHeight ); this->image->SetHandle(offsX, offsY); tileBuffer = new bool[tileWidth * tileHeight]; collisionMode = Sprite::CollisionMode::COLLISION_RECT; valid = true; }
Entity * EntityFactory::CreatePlayerOne(World * world) { Entity * entity; Image * ship = nullptr; Document document; String string; const char * json; float life, energy, eneryRegeneration; /*Retive spaceshipdata*/ switch (LevelManager::Instance().GetPLayerOneSpaceShip()) { case LevelManager::AVATAR: string = String::Read("../data/spaceships/avatar/data.cfg"); json = string.ToCString(); document.Parse(json); ship = ResourceStore::Instance().GetAvatarImage(); break; case LevelManager::DREADNOUGH: string = String::Read("../data/spaceships/dreadnought/data.cfg"); json = string.ToCString(); document.Parse(json); ship = ResourceStore::Instance().GetDreadnoughtImage(); break; } entity = new Entity(0, 0, ship->GetWidth(), ship->GetHeight(), 0);//create entity /*Set spaceship control*/ switch (LevelManager::Instance().GetPLayerOneType()) { float linearVel, angularVel; case LevelManager::HUMAN: { string = String::Read("../data/config/keybindings.cfg"); json = string.ToCString(); Document keybindings; keybindings.Parse(json); assert(keybindings.HasMember("Player1")); assert(keybindings["Player1"].IsObject()); assert(document.HasMember("LinearVelocity")); assert(document["LinearVelocity"].IsNumber()); assert(document["LinearVelocity"].IsFloat()); linearVel = document["LinearVelocity"].GetFloat(); assert(document.HasMember("AngularVelocity")); assert(document["AngularVelocity"].IsNumber()); assert(document["AngularVelocity"].IsFloat()); angularVel = document["AngularVelocity"].GetFloat(); ComponentPlayerController * playerController = new ComponentPlayerController(linearVel, angularVel); playerController->BinKeys( static_cast<inputs>(keybindings["Player1"]["UP"].GetInt()), static_cast<inputs>(keybindings["Player1"]["DOWN"].GetInt()), static_cast<inputs>(keybindings["Player1"]["RLEFT"].GetInt()), static_cast<inputs>(keybindings["Player1"]["RRIGHT"].GetInt()), static_cast<inputs>(keybindings["Player1"]["FIREMAIN"].GetInt()), static_cast<inputs>(keybindings["Player1"]["FIRESECONDARY"].GetInt()) ); entity->AddComponent(playerController); } break; case LevelManager::EASY: ComponentBehaviour *EasyIA= new ComponentBehaviour(new DroneBehaviouralTree(entity)); break; } life = document["Life"].GetFloat(); energy = document["Energy"].GetFloat(); eneryRegeneration = document["EnergyRegeneration"].GetFloat(); ComponentStats * stats = new ComponentStats(life, energy, eneryRegeneration); entity->AddComponent(stats); ComponentRenderer * renderer = new ComponentRenderer(ship); entity->AddComponent(renderer); ComponentCircleCollision * collider = new ComponentCircleCollision(1000, false); entity->AddComponent(collider); ComponentShipExplosion * explosion = new ComponentShipExplosion(this); entity->AddComponent(explosion); assert(document.HasMember("PrimaryWeapon")); assert(document["PrimaryWeapon"].IsObject()); assert(document["PrimaryWeapon"].HasMember("Type")); assert(document["PrimaryWeapon"]["Type"].IsString()); string = document["PrimaryWeapon"]["Type"].GetString(); if(string==String("LASER")){ ComponentLaserWeapon * weapon = new ComponentLaserWeapon(world,WT_MAIN, document["PrimaryWeapon"]["Cooldown"].GetDouble(), document["PrimaryWeapon"]["Damage"].GetDouble(), document["PrimaryWeapon"]["EnergyConsumption"].GetDouble(), document["PrimaryWeapon"]["Range"].GetDouble()); entity->AddComponent(weapon); }else if (string == String("MISSILE")) { ComponentBalisticWeapon * weapon = new ComponentBalisticWeapon(world, this,WT_MAIN, document["PrimaryWeapon"]["Cooldown"].GetDouble(), document["PrimaryWeapon"]["Damage"].GetDouble(), document["PrimaryWeapon"]["EnergyConsumption"].GetDouble(), document["PrimaryWeapon"]["Speed"].GetDouble()); entity->AddComponent(weapon); } entityStore.Add(entity); return entity; }
// Loads the platform specific dynamic library bool WindowsDynamicLibrary::LoadDynamicLibrary(String libraryName) { AppendWindowsExtension(&libraryName); m_Handle = LoadLibrary(libraryName.ToCString()); return m_Handle != Detail::WINDOWS_NO_MODULE; }
AudioBuffer::AudioBuffer(const String &filename) { if (filename.ExtractExt() == "wav") { m_alBuffer = 0; File * file = new File(filename, FILE_READ); int32 chunkId = file->ReadInt(); int32 riffChunkSize = file->ReadInt(); int32 format = file->ReadInt(); int32 subChunkId = file->ReadInt(); int32 fmtChunkSize = file->ReadInt(); int16 audioFormat = file->ReadInt16(); int16 channels = file->ReadInt16(); int32 sampleRate = file->ReadInt(); int32 byteRate = file->ReadInt(); int16 blockAlign = file->ReadInt16(); int16 bitsPerSample = file->ReadInt16(); if (fmtChunkSize > 16) { int16 extraParamsSize = file->ReadInt16(); file->Seek(file->Pos() + extraParamsSize); } char text[5] = ""; file->ReadBytes(text, 4); while (String(text) != "data" && !file->Eof()) { file->ReadBytes(text, 4); if (String(text) == "data") break; file->Seek(file->Pos() + 4); } int32 dataSize = file->ReadInt(); uint32 * data = (uint32 *)malloc(dataSize); file->ReadBytes(data, dataSize); ALenum bufferFormat; if (bitsPerSample == 8) { if (channels == 1) bufferFormat = AL_FORMAT_MONO8; else bufferFormat = AL_FORMAT_STEREO8; } else { if (channels == 1) bufferFormat = AL_FORMAT_MONO16; else bufferFormat = AL_FORMAT_STEREO16; } alGenBuffers(1, &m_alBuffer); alBufferData(m_alBuffer, bufferFormat, data, dataSize, sampleRate); delete file; free(data); } else if (filename.ExtractExt() == "ogg") { stb_vorbis * file = stb_vorbis_open_filename(filename.ToCString(), nullptr, nullptr); if (file) { stb_vorbis_info info = stb_vorbis_get_info(file); uint32 size = stb_vorbis_stream_length_in_samples(file) * info.channels; int16 * buffer = (int16 *)malloc(size * sizeof(int16)); stb_vorbis_get_samples_short_interleaved(file, info.channels, buffer, size); alGenBuffers(1, &m_alBuffer); ALenum bufferFormat; if (info.channels == 1) bufferFormat = AL_FORMAT_MONO16; else bufferFormat = AL_FORMAT_STEREO16; alBufferData(m_alBuffer, bufferFormat, buffer, size, info.sample_rate); stb_vorbis_close(file); free(buffer); } } }
AudioBuffer::AudioBuffer(const String & filename):alBuffer(0) { if (filename.ExtractExt() == "wav") { alGenBuffers(1, &alBuffer); File file(filename, FILE_READ); file.Seek(16); uint32 fmtChunkSize; file.ReadBytes(&fmtChunkSize, 4); uint16 audioFormat; file.ReadBytes(&audioFormat, 2); uint16 channels; file.ReadBytes(&channels, 2); file.Seek(24); uint32 sampleRate; file.ReadBytes(&sampleRate, 4); file.Seek(34); uint16 bitsPerSample; file.ReadBytes(&bitsPerSample, 2); uint16 extraParamSize; if (fmtChunkSize != 16) { file.ReadBytes(&extraParamSize, 2); file.Seek(38 + extraParamSize); } char texto[5]; texto[4] = '\0'; while (String(texto) != "data") { file.ReadBytes(texto, 4); } uint32 dataSize; uint32* data; file.ReadBytes(&dataSize, 4); data = (uint32*)malloc(dataSize); file.ReadBytes(data, dataSize); ALenum format; if (bitsPerSample == 8) { if (channels == 1) { format = AL_FORMAT_MONO8; } else { format = AL_FORMAT_STEREO8; } } if (bitsPerSample == 16) { if (channels == 1) { format = AL_FORMAT_MONO16; } else { format = AL_FORMAT_STEREO16; } } alBufferData(alBuffer, format, data, dataSize, sampleRate); free(data); } else if (filename.ExtractExt() == "ogg") { stb_vorbis* stb_vorbis; stb_vorbis = stb_vorbis_open_filename(filename.ToCString(), nullptr, nullptr); if (stb_vorbis == nullptr) return; stb_vorbis_info info = stb_vorbis_get_info(stb_vorbis); uint32 dataSize = stb_vorbis_stream_length_in_samples(stb_vorbis) * info.channels; int16* buffer = (int16*)malloc(dataSize * sizeof(uint16)); stb_vorbis_get_samples_short_interleaved(stb_vorbis, info.channels,(short *) buffer, dataSize); alGenBuffers(1, &alBuffer); ALenum format; if (info.channels == 1) { format = AL_FORMAT_MONO16; } else { format = AL_FORMAT_STEREO16; } alBufferData(alBuffer, format, buffer, dataSize * sizeof(int16), info.sample_rate); free(buffer); stb_vorbis_close(stb_vorbis); } }