void initialize() { GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 }; GLfloat mat_shininess[] = { 10.0 }; GLfloat white_light[] = { 1.0, 1.0, 1.0, 1.0 }; GLfloat grey_light[] = { 0.6, 0.6, 0.6, 1.0 }; glClearColor(0.0, 0.0, 0.0, 0.0); glShadeModel(GL_SMOOTH); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light); glLightfv(GL_LIGHT0, GL_SPECULAR, white_light); GLfloat blue_light[] = { 0.0, 0.0, 1.0, 1.0 }; glLightfv(GL_LIGHT1, GL_DIFFUSE, blue_light); glLightfv(GL_LIGHT1, GL_SPECULAR, blue_light); glLightf(GL_LIGHT1, GL_SPOT_CUTOFF, 60.0); glLightf(GL_LIGHT1, GL_SPOT_EXPONENT, 3.3); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, grey_light); glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE); glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_LIGHT1); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_TEXTURE_2D); if (!texture.loadFromFile("earth.jpg")) { printf("Could not load texture"); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); }
void AnimatedSphere::create(sf::Texture& tex, float radius, const sf::Time& time) { circle.setTexture(&tex); tex.setRepeated(true); if(radius < 0) throw std::logic_error{ "Circle's radius cannot be negative! Radius = " + std::to_string(radius) }; float diam = 2 * radius; texRect = { 0, 0, (int)diam, (int)diam }; circle.setRadius(radius); passed = sf::Time::Zero; animTime = time; texRect = { 0, 0, 2 * (int)radius, 2 * (int)radius }; circle.setTextureRect(texRect); }
void Animation::LoadContent(std::string text, sf::Texture image, sf::Vector2f position) { this->preText = text; this->image = image; this->position = position; alpha = 1.0f; textColor = sf::Color(114, 77, 255); if(image.getSize().y > 0) { sprite.setTexture(image); } this->text.setString(text); active = false; }
Button::Button(const sf::Font& font, const sf::Texture& texture) : m_texture (texture), m_text ("", font, 30u), m_toggleButton (false) { sf::IntRect subrect({ 0, 0 }, sf::Vector2i(texture.getSize())); subrect.height /= State::Count; for (auto i = 0; i < State::Count; ++i) { m_subRects.push_back(subrect); subrect.top += subrect.height; } m_sprite.setTexture(m_texture); m_sprite.setTextureRect(m_subRects[State::Normal]); auto bounds = m_sprite.getLocalBounds(); m_text.setPosition(bounds.width / 2.f, bounds.height / 2.f); }
Background(sf::RenderWindow &window) { background.loadFromFile("res/fondo1_baja.jpg"); sprite.setTexture(background); width = 1; height = 1; actualAnimation = 0; timeBetweenAnimations = 1; timeSinceLastAnimation = 0.0; animationWidth = sprite.getGlobalBounds().width/width; animationHeight = sprite.getGlobalBounds().height/height; if(window.getSize().y/animationHeight < window.getSize().x/animationWidth) sprite.scale(2*window.getSize().y/animationHeight,2*window.getSize().y/animationHeight); else sprite.scale(2*window.getSize().x/animationWidth,2*window.getSize().x/animationWidth); //sprite.setOrigin(sf::Vector2f(animationWidth/2, animationHeight/2)); sprite.setPosition(window.getSize().x/2, window.getSize().y/2.0); }
void Animation::setSimpleReels(const sf::Texture& Spritesheet, int framex, int framey, int framespersec, int spool) { frame.setTexture(Spritesheet); int i; sheetSize = Spritesheet.getSize(); numberOfFrames = framex; numberOfTapes = framey; xsize = sheetSize.x/framex; ysize = sheetSize.y/framey; for(i=0; i<framex; i++) { addReel(i*xsize,0,xsize,ysize,framey,boost::lexical_cast<string>(i)); } activeReel = 0; if(ysize < ((float)sheetSize.y/framey)) {buffer = 1;} fps = framespersec; if(fps>=1) { spf = 1.0/fps; } else { spf = 0; } runtime = ( (float) framey)/framespersec; current_spool = framex; current_frame = framey; framebox = reels[activeReel].getRect(); frame.setTextureRect(framebox); frame.setOrigin(0.5*xsize,0.5*ysize); return; }
void Animation::LoadContent(sf::String string, sf::Texture &texture, sf::Vector2f position) { if(!font.loadFromFile("../Fonts/Dead Kansas.ttf")) { // error... } text.setFont(font); this->text = text; this->string = string; this->texture = texture; this->position = position; alpha = 1.0f; textColour = sf::Color(114, 66, 161); if(texture.getSize().y > 0); { sprite.setTexture(this->texture); } this->text = text; this->string = string; active = false; }
bool TextureHandler::loadFromFile(const typeAssetID assetID, sf::Texture& asset) { // Start with a return result of false bool succLoad = false; // Retrieve the filename for this asset std::string filename = assetID; // Was a valid filename found? then attempt to load the asset from anFilename if(filename.length() > 0) { // Load the asset from a file succLoad = asset.loadFromFile(filename); } else { ELOG() << "TextureHandler::LoadFromFile(" << assetID << ") No filename provided!" << std::endl; } // Return anResult of true if successful, false otherwise return succLoad; }
int main() { //check if top and bottom flipped sf::RenderWindow window = sf::RenderWindow(sf::VideoMode(640, 640, 32), "Perlin Noise", sf::Style::Titlebar | sf::Style::Close); sf::RenderTexture renderTexture; glewExperimental = GL_TRUE; glewInit(); srand(time(NULL)); texture.create(640,640); const float PERSISTENCE = .5; float i = 0; int count = 0; for( i = 2; i < 129; i /= PERSISTENCE){ std::cout << i; sf::Vector2f** gradients; gradients = new sf::Vector2f* [1 + (int)i]; for(int j = 0; j < (int)i + 1; j++){ gradients[j] = new sf::Vector2f[(int)i + 1]; } genRandom(gradients, i, 1 / i); drawNoise(window, gradients, i, 1 / i); for(int j = 0; j < (int)i + 1; j++){ delete[] gradients[j]; } delete[] gradients; //std::cin.get(); } display(window); std::cout << "draw"; window.display(); std::cin.get(); return 0; }
Selector::Selector(const sf::Texture& t) : m_texture (t), m_currentIndex (0), m_target (0.f) { sf::Vector2f texSize(t.getSize()); m_topButton.width = texSize.x / 2.f; m_topButton.height = texSize.y / 3.f; m_bottomButton = m_topButton; m_bottomButton.top = m_bottomButton.height * 2.f; m_vertices[0].texCoords.x = m_topButton.width; m_vertices[0].position.y = m_topButton.height; m_vertices[1].texCoords.x = texSize.x; m_vertices[1].position = { m_topButton.width, m_topButton.height }; m_vertices[2].texCoords = { texSize.x, m_topButton.height }; m_vertices[2].position = { m_topButton.width, m_topButton.height * 2.f }; m_vertices[3].texCoords = { m_topButton.width, m_topButton.height }; m_vertices[3].position.y = m_topButton.height * 2.f; m_vertices[5].texCoords.x = m_topButton.width; m_vertices[5].position.x = m_topButton.width; m_vertices[6].texCoords = { m_topButton.width, texSize.y }; m_vertices[6].position = m_vertices[6].texCoords; m_vertices[7].texCoords.y = texSize.y; m_vertices[7].position.y = texSize.y; m_localBounds.width = m_topButton.width; m_localBounds.height = texSize.y; }
//int row the row of the tilesheet sprite sprite //int col the col of the tilesheet for sprite Entity::Entity(sf::Texture& texture, Level* level, int row, int col) { source.x = 0; source.y = 0; kills = 0; log_message = new sf::Text(); sprite.setTexture(texture); this->current_level = level; list = NULL; m_Font = NULL; // Clear cFont pointer m_MIL = NULL; // Clear MIL pointer m_MSL = NULL; // Clear MSL pointer int single_sprite_width = int(texture.getSize().x / NUM_SPRITES_IN_ROW); //TODO Assumming there are 4 frames int single_sprite_height = int(sprite.getGlobalBounds().height / NUM_SPRITES_IN_COL); sprite.setTextureRect(sf::Rect<int>(0, 0, single_sprite_width, single_sprite_height)); //m_thisParent = NULL; // Clear this list //m_Numthiss = 0; //m_definitioninitionFile[0] = 0; // Clear definition filename //m_NumMeshes = 0; // Clear mesh data //m_Meshes = NULL; //m_TexturePath[0] = 0; //m_NumAnimations = 0; // Clear animation data //m_Animations = NULL; //m_SpellController = NULL; // Clear spell controller selectSpriteSet(row, col); setMessageTimer(1000); }
int log_setup_1(){ //Load Font if( PTSANS_loaded == false ){ if (!PTSANS.loadFromFile("PTN57F.ttf")) return -1; PTSANS_loaded = true; } texture_3.loadFromFile( "Temp_log.png" ); //Setup Strings log_string.setFont( PTSANS ); log_string.setCharacterSize(24); log_string.setColor( sf::Color(255, 255, 255) ); log_string.setPosition(90.f, 600.f); log_name.setFont( PTSANS ); log_name.setCharacterSize(40); log_name.setColor( sf::Color(255, 255, 255) ); log_name.setPosition(90.f, 535.f); log_back.setTexture( texture_3, false ); log_back.setPosition( 0.f, 580.f ); }
void Actor::createRobotArm(sf::RenderWindow &window, b2World *world, b2FixtureDef &fixture, sf::Texture &texture, sf::Texture &robot_body_texture, int current_index, int body_type, int shape_type) { this->robot_arm = new Object( window, world, fixture, texture, current_index, body_type, shape_type ); this->robot_arm->getSprite()->setOrigin( texture.getSize().x / 2.0, 0 ); sf::Vector2f arm_position; arm_position.x = this->robot_body->getSprite()->getPosition().x; arm_position.y = this->robot_body->getSprite()->getPosition().y; this->robot_arm->getSprite()->setPosition( arm_position ); /* //arm to body joint b2RevoluteJointDef revolute_joint_def; revolute_joint_def.bodyA = this->robot_arm->getBody(); revolute_joint_def.localAnchorA.Set( 0, 1.0 ); //top middle revolute_joint_def.bodyB = this->robot_body->getBody(); revolute_joint_def.localAnchorB.Set( 0.05, 0.6 ); //upper middle of body revolute_joint_def.collideConnected = false; world->CreateJoint( &revolute_joint_def ); */ }
JointPlatform::JointPlatform(sf::Texture& texture, sf::Texture& jointTexture, float initX, float initY, float rotation) { _sprite.setTexture( texture ); _sprite.setOrigin( texture.getSize().x / 2.f, texture.getSize().y / 2.f); _sprite.setRotation( rotation ); _bodyDef.position.Set( MathHelper::ToUnit( initX ), MathHelper::ToUnit( initY ) ); _bodyDef.angle = MathHelper::DegreeToRadian( rotation ); _bodyDef.type = b2_dynamicBody; _bodyShape.SetAsBox( MathHelper::ToUnit( texture.getSize().x / 2.f ), MathHelper::ToUnit( texture.getSize().y / 2.f ) ); cout << "(" << _bodyDef.position.x << "," << _bodyDef.position.y << ")" << endl; _fixtureDef.shape = &_bodyShape; _fixtureDef.density = 10.f; _fixtureDef.friction = 0.5f; _fixtureDef.restitution = 0.5f; //texture for the acnhor or joint _jointBodySprite.setTexture( jointTexture ); _jointBodySprite.setOrigin( jointTexture.getSize().x / 2.f, jointTexture.getSize().y / 2.f); _jointBodySprite.setRotation( 0.0f ); //setup joint body _jointBodyDef.type = b2_staticBody; _jointBodyDef.position.Set( MathHelper::ToUnit( initX ), MathHelper::ToUnit( initY ) ); _jointBodyShape.m_radius = MathHelper::ToUnit( jointTexture.getSize().x / 2.f ); _jointFixtureDef.density = 1.f; _jointFixtureDef.shape = &_jointBodyShape; //set up joint _jointDef.enableMotor = true; _jointDef.maxMotorTorque = 15; _jointDef.motorSpeed = MathHelper::DegreeToRadian( 360 ); _jointDef.collideConnected = false; }
gun::Sprite::Sprite(const sf::Texture& texture) : sprite_(sf::Sprite(texture)), draw_order_(0), is_visible_(true) { sprite_.setOrigin((float)(texture.getSize().x / 2), (float)(texture.getSize().y / 2)); }
//iterate function draw sf::Sprite& update() { graphTx.update(graph); graphSpr.rotate(rotation * 180. / pi); return graphSpr; }
sf::Vector2f Fonction::centerCorner(const sf::Texture& texture) { return H_VECTOR2F(texture.getSize()); }
sf::Vector2f Fonction::bottomLeftCorner(const sf::Texture& texture) { return sf::Vector2f(0, texture.getSize().y); }
sf::Vector2f Fonction::bottomRightCorner(const sf::Texture& texture) { return VECTOR2F(texture.getSize()); }
sf::Vector2f Fonction::topRightCorner(const sf::Texture& texture) { return sf::Vector2f(texture.getSize().x, 0); }
void FeVideoImp::preload() { { sf::Lock l( image_swap_mutex ); if (rgba_buffer[0]) av_freep(&rgba_buffer[0]); int ret = av_image_alloc(rgba_buffer, rgba_linesize, disptex_width, disptex_height, AV_PIX_FMT_RGBA, 1); if (ret < 0) { std::cerr << "Error allocating image during preload" << std::endl; return; } } bool keep_going = true; while ( keep_going ) { AVPacket *packet = pop_packet(); if ( packet == NULL ) { if ( !m_parent->end_of_file() ) m_parent->read_packet(); else keep_going = false; } else { // // decompress packet and put it in our frame queue // int got_frame = 0; #if (LIBAVCODEC_VERSION_INT >= AV_VERSION_INT( 55, 45, 0 )) AVFrame *raw_frame = av_frame_alloc(); codec_ctx->refcounted_frames = 1; #else AVFrame *raw_frame = avcodec_alloc_frame(); #endif int len = avcodec_decode_video2( codec_ctx, raw_frame, &got_frame, packet ); if ( len < 0 ) { std::cerr << "Error decoding video" << std::endl; keep_going=false; } if ( got_frame ) { if ( (codec_ctx->width & 0x7) || (codec_ctx->height & 0x7) ) sws_flags |= SWS_ACCURATE_RND; sws_ctx = sws_getCachedContext( NULL, codec_ctx->width, codec_ctx->height, codec_ctx->pix_fmt, disptex_width, disptex_height, AV_PIX_FMT_RGBA, sws_flags, NULL, NULL, NULL ); if ( !sws_ctx ) { std::cerr << "Error allocating SwsContext during preload" << std::endl; free_frame( raw_frame ); free_packet( packet ); return; } sf::Lock l( image_swap_mutex ); sws_scale( sws_ctx, raw_frame->data, raw_frame->linesize, 0, codec_ctx->height, rgba_buffer, rgba_linesize ); display_texture->update( rgba_buffer[0] ); keep_going = false; } free_frame( raw_frame ); free_packet( packet ); } } }
std::map<std::string, sf::IntRect> makeGuardAnimation(Video::Render::Animation &animation) { static sf::Texture texture; if(!texture.loadFromFile("assets/dummy_guard_spritesheet.png")) { throw std::runtime_error("Error loading guard animation texture"); } Video::Render::AnimatedSprite idleSequence(texture); Video::Render::AnimatedSprite fallSequence(texture); Video::Render::AnimatedSprite slashSequence(texture); Video::Render::AnimatedSprite runSequence(texture); Video::Render::AnimatedSprite hurtSequence(texture); Video::Render::AnimatedSprite jumpSequence(texture); Video::Render::Sprite::Frame frameBuffer[15]; std::map<std::string, sf::IntRect> seq_solids; //idle frameBuffer[0].setTextureSegment(sf::IntRect(9, 8, 67, 92)); frameBuffer[1].setTextureSegment(sf::IntRect(89, 8, 67, 92)); frameBuffer[2].setTextureSegment(sf::IntRect(169, 8, 67, 92)); frameBuffer[3].setTextureSegment(sf::IntRect(249, 8, 67, 92)); frameBuffer[4].setTextureSegment(sf::IntRect(329, 8, 67, 92)); seq_solids.insert(std::pair<std::string, sf::IntRect>("idle", sf::IntRect(12, 10, 40, 82))); //fall frameBuffer[5].setTextureSegment(sf::IntRect(17, 133, 64, 90)); seq_solids.insert(std::pair<std::string, sf::IntRect>("fall", sf::IntRect(2, 10, 40, 78))); //slash frameBuffer[6].setTextureSegment(sf::IntRect(123, 135, 100, 92)); frameBuffer[7].setTextureSegment(sf::IntRect(220, 135, 100, 92)); seq_solids.insert(std::pair<std::string, sf::IntRect>("slash", sf::IntRect(25, 12, 40, 79))); //run frameBuffer[8].setTextureSegment(sf::IntRect(132, 271, 75, 92)); frameBuffer[9].setTextureSegment(sf::IntRect(216, 271, 75, 92)); frameBuffer[10].setTextureSegment(sf::IntRect(292, 271, 75, 92)); frameBuffer[11].setTextureSegment(sf::IntRect(372, 271, 75, 92)); seq_solids.insert(std::pair<std::string, sf::IntRect>("run", sf::IntRect(20, 10, 40, 82))); //hurt frameBuffer[12].setTextureSegment(sf::IntRect(8, 281, 68, 89)); seq_solids.insert(std::pair<std::string, sf::IntRect>("hurt", sf::IntRect(16, 7, 40, 82))); //jump frameBuffer[13].setTextureSegment(sf::IntRect(22, 395, 56, 96)); frameBuffer[14].setTextureSegment(sf::IntRect(107, 395, 56, 96)); seq_solids.insert(std::pair<std::string, sf::IntRect>("jump", sf::IntRect(14, 8, 40, 85))); for(int i = 0; i < 15; ++i) { frameBuffer[i].setDuration(sf::seconds(1.0f/15.0f)); } int famt[] = {5, 1, 2, 4, 1, 2}; Video::Render::AnimatedSprite *seq[] = {&idleSequence, &fallSequence, &slashSequence, &runSequence, &hurtSequence, &jumpSequence}; for(int i = 0, j = 0; i < 6; ++i) { for(int k = 0; k < famt[i]; ++k) { seq[i]->insertFrame(frameBuffer[j]); j += 1; } } animation.addSequence("idle", idleSequence, true); animation.addSequence("fall", fallSequence, true); animation.addSequence("slash", slashSequence, true); animation.addSequence("run", runSequence, true); animation.addSequence("hurt", hurtSequence, true); animation.addSequence("jump", jumpSequence, true); return seq_solids; }
sf::IntRect getFullRect(const sf::Texture& texture) { return sf::IntRect(0, 0, texture.getSize().x, texture.getSize().y); }
void chargerTexture(sf::Texture& Texture, std::string filePath) { Texture.setSmooth(false); if(!Texture.loadFromFile(filePath)) std::cerr << "Erreur durant chargement de la texture " << filePath << std::endl; }
void AnimatedDrawable::setTexture(const sf::Texture& t) { m_sprite.setTexture(t); m_textureSize = t.getSize(); }
bool Level::LoadFromFile(std::string filename) { TiXmlDocument levelFile(filename.c_str()); // Загружаем XML-карту if(!levelFile.LoadFile()) { std::cout << "Loading level \"" << filename << "\" failed." << std::endl; return false; } // Работаем с контейнером map TiXmlElement *map; map = levelFile.FirstChildElement("map"); // Пример карты: <map version="1.0" orientation="orthogonal" // width="10" height="10" tilewidth="34" tileheight="34"> width = atoi(map->Attribute("width")); height = atoi(map->Attribute("height")); tileWidth = atoi(map->Attribute("tilewidth")); tileHeight = atoi(map->Attribute("tileheight")); // Берем описание тайлсета и идентификатор первого тайла TiXmlElement *tilesetElement; tilesetElement = map->FirstChildElement("tileset"); firstTileID = atoi(tilesetElement->Attribute("firstgid")); // source - путь до картинки в контейнере image TiXmlElement *image; image = tilesetElement->FirstChildElement("image"); std::string imagepath = image->Attribute("source"); // Пытаемся загрузить тайлсет sf::Image img; if(!img.loadFromFile(imagepath)) { std::cout << "Failed to load tile sheet." << std::endl; return false; } img.createMaskFromColor(sf::Color(255, 255, 255)); tilesetImage.loadFromImage(img); tilesetImage.setSmooth(false); // Получаем количество столбцов и строк тайлсета int columns = tilesetImage.getSize().x / tileWidth; int rows = tilesetImage.getSize().y / tileHeight; // Вектор из прямоугольников изображений (TextureRect) std::vector<sf::Rect<int>> subRects; for(int y = 0; y < rows; y++) for(int x = 0; x < columns; x++) { sf::Rect<int> rect; rect.top = y * tileHeight; rect.height = tileHeight; rect.left = x * tileWidth; rect.width = tileWidth; subRects.push_back(rect); } // Работа со слоями TiXmlElement *layerElement; layerElement = map->FirstChildElement("layer"); while(layerElement) { Layer layer; // Если присутствует opacity, то задаем прозрачность слоя, иначе он полностью непрозрачен if (layerElement->Attribute("opacity") != NULL) { float opacity = strtod(layerElement->Attribute("opacity"), NULL); layer.opacity = 255 * opacity; } else { layer.opacity = 255; } // Контейнер <data> TiXmlElement *layerDataElement; layerDataElement = layerElement->FirstChildElement("data"); if(layerDataElement == NULL) { std::cout << "Bad map. No layer information found." << std::endl; } // Контейнер <tile> - описание тайлов каждого слоя TiXmlElement *tileElement; tileElement = layerDataElement->FirstChildElement("tile"); if(tileElement == NULL) { std::cout << "Bad map. No tile information found." << std::endl; return false; } int x = 0; int y = 0; while(tileElement) { int tileGID = atoi(tileElement->Attribute("gid")); int subRectToUse = tileGID - firstTileID; // Устанавливаем TextureRect каждого тайла if (subRectToUse >= 0) { sf::Sprite sprite; sprite.setTexture(tilesetImage); sprite.setTextureRect(subRects[subRectToUse]); sprite.setPosition(x * tileWidth, y * tileHeight); sprite.setColor(sf::Color(255, 255, 255, layer.opacity)); layer.tiles.push_back(sprite); } tileElement = tileElement->NextSiblingElement("tile"); x++; if (x >= width) { x = 0; y++; if(y >= height) y = 0; } } layers.push_back(layer); layerElement = layerElement->NextSiblingElement("layer"); } // Работа с объектами TiXmlElement *objectGroupElement; // Если есть слои объектов if (map->FirstChildElement("objectgroup") != NULL) { objectGroupElement = map->FirstChildElement("objectgroup"); while (objectGroupElement) { // Контейнер <object> TiXmlElement *objectElement; objectElement = objectGroupElement->FirstChildElement("object"); while(objectElement) { // Получаем все данные - тип, имя, позиция, etc std::string objectType; if (objectElement->Attribute("type") != NULL) { objectType = objectElement->Attribute("type"); } std::string objectName; if (objectElement->Attribute("name") != NULL) { objectName = objectElement->Attribute("name"); } int x = atoi(objectElement->Attribute("x")); int y = atoi(objectElement->Attribute("y")); int width, height; sf::Sprite sprite; sprite.setTexture(tilesetImage); sprite.setTextureRect(sf::Rect<int>(0,0,0,0)); sprite.setPosition(x, y); if (objectElement->Attribute("width") != NULL) { width = atoi(objectElement->Attribute("width")); height = atoi(objectElement->Attribute("height")); } else { width = subRects[atoi(objectElement->Attribute("gid")) - firstTileID].width; height = subRects[atoi(objectElement->Attribute("gid")) - firstTileID].height; sprite.setTextureRect(subRects[atoi(objectElement->Attribute("gid")) - firstTileID]); } // Экземпляр объекта Object object; object.name = objectName; object.type = objectType; object.sprite = sprite; sf::Rect <float> objectRect; objectRect.top = y; objectRect.left = x; objectRect.height = height; objectRect.width = width; object.rect = objectRect; // "Переменные" объекта TiXmlElement *properties; properties = objectElement->FirstChildElement("properties"); if (properties != NULL) { TiXmlElement *prop; prop = properties->FirstChildElement("property"); if (prop != NULL) { while(prop) { std::string propertyName = prop->Attribute("name"); std::string propertyValue = prop->Attribute("value"); object.properties[propertyName] = propertyValue; prop = prop->NextSiblingElement("property"); } } } objects.push_back(object); objectElement = objectElement->NextSiblingElement("object"); } objectGroupElement = objectGroupElement->NextSiblingElement("objectgroup"); } } else { std::cout << "No object layers found..." << std::endl; } return true; }
std::map<std::string, sf::IntRect> makePlayerAnimation(Video::Render::Animation &animation) { static sf::Texture texture; if(!texture.loadFromFile("assets/dummy_player_spritesheet.png")) { throw std::runtime_error("Error loading player animation texture"); } Video::Render::AnimatedSprite idleSequence(texture); Video::Render::AnimatedSprite fallSequence(texture); Video::Render::AnimatedSprite slashSequence(texture); Video::Render::AnimatedSprite castSequence(texture); Video::Render::AnimatedSprite runSequence(texture); Video::Render::AnimatedSprite airSlashSequence(texture); Video::Render::AnimatedSprite hurtSequence(texture); Video::Render::AnimatedSprite jumpSequence(texture); Video::Render::Sprite::Frame frameBuffer[21]; std::map<std::string, sf::IntRect> seq_solids; //everything was offset by 1px (5->6, 0->1, 55->54, 70->69...). why? //idle frameBuffer[0].setTextureSegment(sf::IntRect(5, 6, 55, 70)); frameBuffer[1].setTextureSegment(sf::IntRect(85, 6, 55, 70)); frameBuffer[2].setTextureSegment(sf::IntRect(165, 6, 55, 70)); frameBuffer[3].setTextureSegment(sf::IntRect(245, 6, 55, 70)); seq_solids.insert(std::pair<std::string, sf::IntRect>("idle", sf::IntRect(10, 2, 30, 68))); //fall frameBuffer[4].setTextureSegment(sf::IntRect(343, 6, 48, 69)); seq_solids.insert(std::pair<std::string, sf::IntRect>("fall", sf::IntRect(13, 2, 30, 64))); //slash frameBuffer[5].setTextureSegment(sf::IntRect(3, 100, 79, 68)); frameBuffer[6].setTextureSegment(sf::IntRect(82, 100, 79, 68)); seq_solids.insert(std::pair<std::string, sf::IntRect>("slash", sf::IntRect(12, 2, 30, 66))); //cast frameBuffer[7].setTextureSegment(sf::IntRect(188, 101, 78, 68)); frameBuffer[8].setTextureSegment(sf::IntRect(268, 101, 78, 68)); frameBuffer[9].setTextureSegment(sf::IntRect(348, 101, 78, 68)); frameBuffer[10].setTextureSegment(sf::IntRect(428, 101, 78, 68)); seq_solids.insert(std::pair<std::string, sf::IntRect>("cast", sf::IntRect(10, 1, 30, 67))); //run frameBuffer[11].setTextureSegment(sf::IntRect(0, 202, 69, 55)); frameBuffer[12].setTextureSegment(sf::IntRect(74, 202, 69, 55)); frameBuffer[13].setTextureSegment(sf::IntRect(154, 202, 69, 55)); seq_solids.insert(std::pair<std::string, sf::IntRect>("run", sf::IntRect(19, 2, 40, 53))); //air slash frameBuffer[14].setTextureSegment(sf::IntRect(257, 193, 79, 63)); frameBuffer[15].setTextureSegment(sf::IntRect(336, 193, 79, 63)); seq_solids.insert(std::pair<std::string, sf::IntRect>("air", sf::IntRect(19, 2, 30, 61))); //hurt frameBuffer[16].setTextureSegment(sf::IntRect(4, 288, 50, 67)); seq_solids.insert(std::pair<std::string, sf::IntRect>("hurt", sf::IntRect(8, 4, 40, 60))); //having one solid here is problematic, because first two frames are crouching, so shorter... //jump frameBuffer[17].setTextureSegment(sf::IntRect(96, 280, 67, 70)); frameBuffer[18].setTextureSegment(sf::IntRect(174, 280, 67, 70)); frameBuffer[19].setTextureSegment(sf::IntRect(250, 280, 67, 70)); frameBuffer[20].setTextureSegment(sf::IntRect(341, 280, 67, 70)); seq_solids.insert(std::pair<std::string, sf::IntRect>("jump", sf::IntRect(19, 1, 30, 68))); for(int i = 0; i < 21; ++i) { frameBuffer[i].setDuration(sf::seconds(1.0f/15.0f)); } // last one should be actually four but for now lets skip this frame int famt[] = {4, 1, 2, 4, 3, 2, 1, 3}; Video::Render::AnimatedSprite *seq[] = {&idleSequence, &fallSequence, &slashSequence, &castSequence, &runSequence, &airSlashSequence, &hurtSequence, &jumpSequence}; for(int i = 0, j = 0; i < 8; ++i) { for(int k = 0; k < famt[i]; ++k) { seq[i]->insertFrame(frameBuffer[j]); j += 1; } } animation.addSequence("idle", idleSequence, true); animation.addSequence("fall", fallSequence, true); animation.addSequence("slash", slashSequence, true); animation.addSequence("cast", castSequence, true); animation.addSequence("run", runSequence, true); animation.addSequence("air", airSlashSequence, true); animation.addSequence("hurt", hurtSequence, true); animation.addSequence("jump", jumpSequence, true); return seq_solids; }
rectangle::rectangle(const sf::Texture& texture) : top(0), left(0), right(texture.getSize().x), bottom(texture.getSize().y) {}
void display(sf::RenderWindow* window, std::string pathImage){ open = true; t.loadFromFile(pathImage); s = sf::Sprite(); s.setTexture(t); s.scale(window->getSize().y/s.getGlobalBounds().height,window->getSize().y/s.getGlobalBounds().height); s.setPosition(window->getSize().x/2 - s.getGlobalBounds().width/2, 0); while(open){ sf::Event event; while (window->pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window->close(); break; case sf::Event::KeyPressed: if (event.key.code == sf::Keyboard::Escape) window->close(); break; case sf::Event::MouseButtonPressed: if (event.mouseButton.button == sf::Mouse::Left) { open = false; } break; default: break; } if( event.type == sf::Event::KeyPressed || event.type == sf::Event::MouseButtonPressed|| event.type == sf::Event::TouchEnded ) open = false; } window->clear(); window->draw(s); window->display(); } sf::Clock timer; sf::Sprite dark; sf::Texture text; bool closing = true; text.loadFromFile("res/pics/black.png"); dark.setTexture(text); dark.setOrigin(dark.getLocalBounds().width/2,dark.getLocalBounds().height/2); dark.setPosition(window->getSize().x/2,window->getSize().y/2); float scale = 1/dark.getGlobalBounds().width;; float time = 0; while(closing and wantAnimation){ dark.setScale(scale,scale); time += timer.restart().asSeconds(); if(time > 0.1){ scale *= 1.5; time = 0; } window->clear(); window->draw(s); window->draw(dark); window->display(); if(dark.getGlobalBounds().width > window->getSize().x) closing = false; } //clean events sf::Event e; while (window->pollEvent(e)) { } }
namespace VN { class _Log; int log_index = 0; float char_width[256]; const float log_width = 1100; sf::Texture texture_1; //person_2 sf::Texture texture_2; //person_1 sf::Texture texture_3; //log_background sf::Sprite person_1; sf::Sprite person_2; sf::Sprite log_back; vector<_Log> logs; sf::Font PTSANS; bool PTSANS_loaded = false; sf::Text log_string; sf::Text log_name; int log_setup_1(){ //Load Font if( PTSANS_loaded == false ){ if (!PTSANS.loadFromFile("PTN57F.ttf")) return -1; PTSANS_loaded = true; } texture_3.loadFromFile( "Temp_log.png" ); //Setup Strings log_string.setFont( PTSANS ); log_string.setCharacterSize(24); log_string.setColor( sf::Color(255, 255, 255) ); log_string.setPosition(90.f, 600.f); log_name.setFont( PTSANS ); log_name.setCharacterSize(40); log_name.setColor( sf::Color(255, 255, 255) ); log_name.setPosition(90.f, 535.f); log_back.setTexture( texture_3, false ); log_back.setPosition( 0.f, 580.f ); } //============================= LOG CLASS ============================= class _Log { public: _Log() : image_loaded(0) {} ~_Log(){ clean(); } string name; string text; string image_path; string sound_path; int align; //cleaned during loading void clean(); void clear(); //delete all data void draw_text( sf::RenderWindow& App ); void draw_image( sf::RenderWindow& App ); void load_image(); private: bool image_loaded; sf::Sprite Sprite; void clean_name(); void clean_log_text(); void clean_image_path(); void clean_sound_path(); void clean_path( string& input ); }; void _Log::clean(){ clean_name(); clean_log_text(); clean_image_path(); clean_sound_path(); } void _Log::clean_name(){ int check_index = 0; int write_index = 0; //search for the first characters which is not a space check_index = name.find_first_not_of(' '); if( check_index == -1 ){ //there is no need to clean if all the characters are spaces name.clear(); return; } //Clean double or more spaces together while( check_index < name.length() ) { if( name[check_index] == ' ' ) { while( name[check_index] == ' ' && check_index < name.length() ) check_index++; check_index--; } if( write_index != check_index ) name[ write_index ] = name[ check_index ]; write_index++; check_index++; } //Clean the last spaces if( name[write_index-1] == ' ' ) { name.resize( write_index-1 ); } else { name.resize( write_index ); } if( tolower( name ) == "narator" ) name = tolower( name ); } void _Log::clean_log_text(){ int check_index = 0; int write_index = 0; if( name != "narator" ) { //name has already been cleaned //search for the first characters which is not a space check_index = text.find_first_not_of(' '); if( check_index == -1 ) { //there is no need to clean if there is not a single space in the sentence text.insert( text.begin(), '\"' ); text.insert( text.end(), '\"' ); goto cleaned; } else if( check_index == 0 ){ text.insert( text.begin(), '\"' ); } else { text[ write_index ] = '\"'; write_index++; } //Clean double or more spaces together while( check_index < text.length() ){ if( text[check_index] == ' ' ){ while( text[check_index] == ' ' && check_index < text.length() ) check_index++; check_index--; } if( write_index != check_index ) text[ write_index ] = text[ check_index ]; write_index++; check_index++; } //add quotation mark add the end of the sentence if( write_index == text.length() ){ text.insert( text.end(), '\"' ); }else{ if( text[ write_index - 1 ] == ' ' ) { text[ write_index - 1 ] = '\"'; text.resize( write_index ); } else { text[ write_index ] = '\"'; text.resize( write_index + 1 ); } } } else { //search for the first characters which is not a space check_index = text.find_first_not_of(' '); //there is no need to clean if there is not a single space in the sentence if( check_index == -1 ) goto cleaned; //Clean doublxe or more spaces together while( check_index < text.length() ) { if( text[check_index] == ' ' ) { while( text[check_index] == ' ' && check_index < text.length() ) check_index++; check_index--; } if( write_index != check_index ) text[ write_index ] = text[ check_index ]; write_index++; check_index++; } //Clean the last spaces if( text[write_index-1] == ' ' ) { text.resize( write_index-1 ); } else { text.resize( write_index ); } } cleaned: //word wrapping int i, temp = 0, temp2, temp_i; for( i = 0; i < text.length(); ++i ){ temp_i = i; temp2 = 0; for( ; text[i] != ' ' && i < text.length() ; ++i ){ temp2 += char_width[ text[i] ]; } temp2 += char_width[' ']; if( temp + temp2 >= log_width ){ text.insert( text.begin() + temp_i, '\n' ); temp = temp2; } else { temp = temp + temp2; } } return; } void _Log::clean_path( string& input ){ if( input.length() == 0 ) return; //remove all spaces int check_index = input.find_first_not_of(' '); int write_index = 0; int temp_index; if( check_index == -1 ){ input.clear(); return; } while( check_index < input.length() ){ if( input[check_index] != ' ' ){ temp_index = check_index; } if( input[check_index] == '\\' ){ check_index = input.find_first_not_of( '\\', check_index ); if( check_index != -1 ){ check_index--; } else { check_index = input.find_last_of( '\\' ); } } input[write_index] = input[check_index]; write_index++; check_index++; } input.resize( temp_index + 1 ); } void _Log::clean_image_path(){ clean_path( image_path ); } void _Log::clean_sound_path(){ clean_path( sound_path ); } void _Log::clear(){ name.clear(); text.clear(); image_path.clear(); sound_path.clear(); align = 0; } void _Log::draw_text( sf::RenderWindow& App ) { if( name != "narator" ){ log_string.setString( text ); App.draw( log_string ); log_name.setString( name ); App.draw( log_name ); }else{ log_string.setString( text ); App.draw( log_string); } } void _Log::draw_image( sf::RenderWindow& App ) { if( !image_loaded ) load_image(); App.draw( Sprite ); } void _Log::load_image(){ if( image_loaded == false && image_path.length() != 0 ) { texture_1.loadFromFile( image_path ); Sprite.setTexture( texture_1, false ); sf::IntRect spr_data = Sprite.getTextureRect(); float x,y = WINDOW_HEIGHT - spr_data.height; switch( align ){ case 1: x = 0.f; break; case 2: x = WINDOW_WIDTH * 0.25 - spr_data.width /2; break; case 3: x = WINDOW_WIDTH * 0.5 - spr_data.width /2; break; case 4: x = WINDOW_WIDTH * 0.75 - spr_data.width /2; break; case 5: x = WINDOW_WIDTH - spr_data.width; break; } Sprite.setPosition( x, y ); cout << x << " " << y << endl; image_loaded = true; } } // ============================= END ============================= // ============================= FILE OPERATION ============================= void load_text_file( vector<_Log>& logs, string filename ){ logs.clear(); ifstream textfile; char c; string temp_string; int linenum = 0; textfile.open( filename.c_str() ); while( textfile.good() ) { logs.push_back( _Log() ); goto skip2; skip: logs[linenum].clear(); skip2: // ================================= // FIRST PARAMETER : image_path // ================================= c = textfile.get(); while ( textfile.good() && c != '|' ) { if( c == '\n' ) goto skip; logs[linenum].image_path += c; c = textfile.get(); } // ===================================== // SECOND PARAMETER : image_alignment // ===================================== c = textfile.get(); temp_string.clear(); while( textfile.good() && c != '|' ){ if( c == '\n' ) goto skip; temp_string += c; c = textfile.get(); } logs[linenum].align = parseInt( temp_string ); // ===================================== // THIRD PARAMETER : sound_path // ===================================== c = textfile.get(); while ( textfile.good() && c != '|' ) { if( c == '\n' ) goto skip; logs[linenum].sound_path += c; c = textfile.get(); } // ===================================== // FOURTH PARAMETER : name // ===================================== c = textfile.get(); while ( textfile.good() && c != ':' ) { if( c == '\n' ) goto skip; logs[linenum].name += c; c = textfile.get(); } // ===================================== // FIFTH PARAMETER : log_text // ===================================== c = textfile.get(); while ( textfile.good() && c != '\n' ) { logs[linenum].text += c; c = textfile.get(); } logs[linenum].clean(); linenum++; } textfile.close(); } // ============================= END ============================= // ============================= INIT OPERATION ============================= void init_char_width(){ if (!PTSANS.loadFromFile("PTN57F.ttf" )) return; PTSANS_loaded = true; string tq; int tmp = log_string.getPosition().x; for( int i = 255; i--; ){ tq = (char) i; log_string.setString( tq ); char_width[i] = log_string.findCharacterPos( 1 ).x - tmp; } } void init( string filename ){ log_setup_1(); init_char_width(); load_text_file( logs, filename ); } // ============================= END ============================= void print_log(){ //print logs for debugging for( int i = 0; i < logs.size() ; ++ i ){ cout << logs[i].image_path << endl; cout << logs[i].sound_path << endl; cout << logs[i].name << endl; cout << logs[i].text << endl; cin.get(); } } void Draw( sf::RenderWindow& App ) { logs[ log_index ].draw_image( App ); App.draw( log_back ); logs[ log_index ].draw_text( App ); } //Call this to move on to the next log void Next(){ if( log_index+1 < logs.size() ) { log_index++; } } }