// IWYU pragma: no_include #include "credits.h" #include // Para SDL_RenderFillRect, SDL_RenderTexture, SDL_SetRenderTarget, SDL_SetRenderDrawColor, SDL_CreateTexture, SDL_DestroyTexture, SDL_GetTicks, SDL_GetRenderTarget, SDL_PixelFormat, SDL_PollEvent, SDL_RenderClear, SDL_RenderRect, SDL_SetTextureBlendMode, SDL_TextureAccess, SDL_BLENDMODE_BLEND, SDL_Event #include // Para max, min, clamp #include // Para array #include // Para runtime_error #include // Para basic_string, string #include // Para string_view #include // Para vector #include "audio.h" // Para Audio #include "balloon_manager.h" // Para BalloonManager #include "color.h" // Para Zone, Colors::SHADOW_TEXT, Colors::NO_COLOR_MOD, Color #include "fade.h" // Para Fade, FadeType, FadeMode #include "global_events.h" // Para check #include "global_inputs.h" // Para check #include "input.h" // Para Input, Input::ALLOW_REPEAT #include "lang.h" // Para getText #include "param.h" // Para Param, param, ParamGame, ParamFade #include "player.h" // Para Player, PlayerState #include "resource.h" // Para Resource #include "screen.h" // Para Screen #include "section.hpp" // Para Name, name #include "sprite.h" // Para Sprite #include "text.h" // Para Text, Text::CENTER, Text::SHADOW #include "texture.h" // Para Texture #include "tiled_bg.h" // Para TiledBG, TiledBGMode #include "ui/service_menu.h" // Para ServiceMenu #include "utils.h" // Textos constexpr std::string_view TEXT_COPYRIGHT = "@2020,2025 JailDesigner"; // Constructor Credits::Credits() : balloon_manager_(std::make_unique(nullptr)), tiled_bg_(std::make_unique(param.game.game_area.rect, TiledBGMode::DIAGONAL)), fade_in_(std::make_unique()), fade_out_(std::make_unique()), text_texture_(SDL_CreateTexture(Screen::get()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, static_cast(param.game.width), static_cast(param.game.height))), canvas_(SDL_CreateTexture(Screen::get()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, static_cast(param.game.width), static_cast(param.game.height))) { if (text_texture_ == nullptr) { throw std::runtime_error("Failed to create SDL texture for text."); } Section::name = Section::Name::CREDITS; balloon_manager_->setPlayArea(play_area_); fade_in_->setColor(param.fade.color); fade_in_->setType(Fade::Type::FULLSCREEN); fade_in_->setPostDuration(static_cast(50 * (1000.0f / 60.0f))); // 50 frames = ~833ms fade_in_->setMode(Fade::Mode::IN); fade_in_->activate(); fade_out_->setColor(0, 0, 0); fade_out_->setType(Fade::Type::FULLSCREEN); fade_out_->setPostDuration(static_cast(400 * (1000.0f / 60.0f))); // 400 frames = ~6667ms updateRedRect(); tiled_bg_->setColor(Color(255, 96, 96)); tiled_bg_->setSpeed(60.0F); initPlayers(); SDL_SetTextureBlendMode(text_texture_, SDL_BLENDMODE_BLEND); fillTextTexture(); steps_ = static_cast(std::abs((top_black_rect_.h - param.game.game_area.center_y - 1) + ((left_black_rect_.w - param.game.game_area.center_x) / 4))); } // Destructor Credits::~Credits() { SDL_DestroyTexture(text_texture_); SDL_DestroyTexture(canvas_); resetVolume(); Audio::get()->stopMusic(); // Desregistra los jugadores de Options Options::keyboard.clearPlayers(); Options::gamepad_manager.clearPlayers(); } // Calcula el deltatime auto Credits::calculateDeltaTime() -> float { const Uint64 current_time = SDL_GetTicks(); const float delta_time = static_cast(current_time - last_time_) / 1000.0f; // Convertir ms a segundos last_time_ = current_time; return delta_time; } // Bucle principal void Credits::run() { last_time_ = SDL_GetTicks(); while (Section::name == Section::Name::CREDITS) { checkInput(); const float delta_time = calculateDeltaTime(); update(delta_time); checkEvents(); // Tiene que ir antes del render render(); } } // Actualiza las variables (time-based) void Credits::update(float deltaTime) { const float multiplier = want_to_pass_ ? 4.0f : 1.0f; const float adjusted_delta_time = deltaTime * multiplier; static auto *const SCREEN = Screen::get(); SCREEN->update(deltaTime); // Actualiza el objeto screen Audio::update(); // Actualiza el objeto audio tiled_bg_->update(adjusted_delta_time); cycleColors(); balloon_manager_->update(adjusted_delta_time); updateTextureDstRects(adjusted_delta_time); throwBalloons(adjusted_delta_time); updatePlayers(adjusted_delta_time); updateAllFades(adjusted_delta_time); // Convertir deltaTime a equivalente de frames (60fps) const float frameFactor = adjusted_delta_time * 60.0f; counter_ += frameFactor; fillCanvas(); } // Dibuja Credits::en patalla void Credits::render() { static auto *const SCREEN = Screen::get(); SCREEN->start(); // Prepara para empezar a dibujar en la textura de juego SDL_RenderTexture(SCREEN->getRenderer(), canvas_, nullptr, nullptr); // Copia la textura con la zona de juego a la pantalla SCREEN->render(); // Vuelca el contenido del renderizador en pantalla } // Comprueba el manejador de eventos void Credits::checkEvents() { SDL_Event event; while (SDL_PollEvent(&event)) { GlobalEvents::handle(event); } } // Comprueba las entradas void Credits::checkInput() { Input::get()->update(); if (!ServiceMenu::get()->isEnabled()) { // Comprueba si se ha pulsado cualquier botón (de los usados para jugar) if (Input::get()->checkAnyButton(Input::ALLOW_REPEAT)) { want_to_pass_ = true; fading_ = mini_logo_on_position_; } else { want_to_pass_ = false; } } // Comprueba los inputs que se pueden introducir en cualquier sección del juego GlobalInputs::check(); } // Crea la textura con el texto void Credits::fillTextTexture() { auto text = Resource::get()->getText("smb2"); auto text_grad = Resource::get()->getText("smb2_grad"); SDL_SetRenderTarget(Screen::get()->getRenderer(), text_texture_); SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0, 0, 0, 0); SDL_RenderClear(Screen::get()->getRenderer()); const std::array TEXTS = { Lang::getText("[CREDITS] PROGRAMMED_AND_DESIGNED_BY"), Lang::getText("[CREDITS] PIXELART_DRAWN_BY"), Lang::getText("[CREDITS] MUSIC_COMPOSED_BY"), Lang::getText("[CREDITS] SOUND_EFFECTS"), "JAILDESIGNER", "JAILDOCTOR", "ERIC MATYAS (SOUNDIMAGE.ORG)", "WWW.THEMOTIONMONKEY.CO.UK", "WWW.KENNEY.NL", "JAILDOCTOR", "JAILDESIGNER"}; const int SPACE_POST_TITLE = 3 + text->getCharacterSize(); const int SPACE_PRE_TITLE = text->getCharacterSize() * 4; const int TEXTS_HEIGHT = (1 * text->getCharacterSize()) + (8 * SPACE_POST_TITLE) + (3 * SPACE_PRE_TITLE); const int POS_X = static_cast(param.game.game_area.center_x); credits_rect_dst_.h = credits_rect_src_.h = static_cast(TEXTS_HEIGHT); auto text_style = Text::Style(Text::CENTER | Text::SHADOW, Colors::NO_COLOR_MOD, Colors::SHADOW_TEXT); // PROGRAMMED_AND_DESIGNED_BY int y = 0; text_grad->writeStyle(POS_X, y, TEXTS.at(0), text_style); y += SPACE_POST_TITLE; text->writeStyle(POS_X, y, TEXTS.at(4), text_style); // PIXELART_DRAWN_BY y += SPACE_PRE_TITLE; text_grad->writeStyle(POS_X, y, TEXTS.at(1), text_style); y += SPACE_POST_TITLE; text->writeStyle(POS_X, y, TEXTS.at(4), text_style); // MUSIC_COMPOSED_BY y += SPACE_PRE_TITLE; text_grad->writeStyle(POS_X, y, TEXTS.at(2), text_style); y += SPACE_POST_TITLE; text->writeStyle(POS_X, y, TEXTS.at(5), text_style); y += SPACE_POST_TITLE; text->writeStyle(POS_X, y, TEXTS.at(6), text_style); // SOUND_EFFECTS y += SPACE_PRE_TITLE; text_grad->writeStyle(POS_X, y, TEXTS.at(3), text_style); y += SPACE_POST_TITLE; text->writeStyle(POS_X, y, TEXTS.at(7), text_style); y += SPACE_POST_TITLE; text->writeStyle(POS_X, y, TEXTS.at(8), text_style); y += SPACE_POST_TITLE; text->writeStyle(POS_X, y, TEXTS.at(9), text_style); y += SPACE_POST_TITLE; text->writeStyle(POS_X, y, TEXTS.at(10), text_style); // Mini logo y += SPACE_PRE_TITLE; mini_logo_rect_src_.y = static_cast(y); auto mini_logo_sprite = std::make_unique(Resource::get()->getTexture("logo_jailgames_mini.png")); mini_logo_sprite->setPosition(1 + POS_X - (mini_logo_sprite->getWidth() / 2), 1 + y); Resource::get()->getTexture("logo_jailgames_mini.png")->setColor(Colors::SHADOW_TEXT.r, Colors::SHADOW_TEXT.g, Colors::SHADOW_TEXT.b); mini_logo_sprite->render(); mini_logo_sprite->setPosition(POS_X - (mini_logo_sprite->getWidth() / 2), y); Resource::get()->getTexture("logo_jailgames_mini.png")->setColor(255, 255, 255); mini_logo_sprite->render(); // Texto con el copyright y += mini_logo_sprite->getHeight() + 3; text->writeDX(Text::CENTER | Text::SHADOW, POS_X, y, std::string(TEXT_COPYRIGHT), 1, Colors::NO_COLOR_MOD, 1, Colors::SHADOW_TEXT); // Resetea el renderizador SDL_SetRenderTarget(Screen::get()->getRenderer(), nullptr); // Actualiza las variables mini_logo_rect_dst_.h = mini_logo_rect_src_.h = mini_logo_sprite->getHeight() + 3 + text->getCharacterSize(); credits_rect_dst_.y = param.game.game_area.rect.h; mini_logo_rect_dst_.y = credits_rect_dst_.y + credits_rect_dst_.h + 30; mini_logo_final_pos_ = param.game.game_area.center_y - mini_logo_rect_src_.h / 2; } // Dibuja todos los sprites en la textura void Credits::fillCanvas() { // Cambia el destino del renderizador auto *temp = SDL_GetRenderTarget(Screen::get()->getRenderer()); SDL_SetRenderTarget(Screen::get()->getRenderer(), canvas_); // Dibuja el fondo, los globos y los jugadores tiled_bg_->render(); balloon_manager_->render(); renderPlayers(); // Dibuja los titulos de credito SDL_RenderTexture(Screen::get()->getRenderer(), text_texture_, &credits_rect_src_, &credits_rect_dst_); // Dibuja el mini_logo SDL_RenderTexture(Screen::get()->getRenderer(), text_texture_, &mini_logo_rect_src_, &mini_logo_rect_dst_); // Dibuja los rectangulos negros SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0, 0, 0, 0xFF); SDL_RenderFillRect(Screen::get()->getRenderer(), &top_black_rect_); SDL_RenderFillRect(Screen::get()->getRenderer(), &bottom_black_rect_); SDL_RenderFillRect(Screen::get()->getRenderer(), &left_black_rect_); SDL_RenderFillRect(Screen::get()->getRenderer(), &right_black_rect_); // Dibuja el rectangulo rojo const Color COLOR = color_.LIGHTEN(); SDL_SetRenderDrawColor(Screen::get()->getRenderer(), COLOR.r, COLOR.g, COLOR.b, 0xFF); SDL_RenderRect(Screen::get()->getRenderer(), &border_rect_); // Si el mini_logo está en su destino, lo dibuja encima de lo anterior if (mini_logo_on_position_) { SDL_RenderTexture(Screen::get()->getRenderer(), text_texture_, &mini_logo_rect_src_, &mini_logo_rect_dst_); } // Dibuja el fade sobre el resto de elementos fade_in_->render(); fade_out_->render(); // Deja el renderizador apuntando donde estaba SDL_SetRenderTarget(Screen::get()->getRenderer(), temp); } // Actualiza el destino de los rectangulos de las texturas (time-based) void Credits::updateTextureDstRects(float deltaTime) { constexpr float TEXTURE_UPDATE_INTERVAL_S = 10.0f / 60.0f; // ~0.167s (cada 10 frames) static float texture_accumulator = 0.0f; texture_accumulator += deltaTime; if (texture_accumulator >= TEXTURE_UPDATE_INTERVAL_S) { texture_accumulator -= TEXTURE_UPDATE_INTERVAL_S; // Comprueba la posición de la textura con los titulos de credito if (credits_rect_dst_.y + credits_rect_dst_.h > play_area_.y) { --credits_rect_dst_.y; } // Comprueba la posición de la textura con el mini_logo if (mini_logo_rect_dst_.y == mini_logo_final_pos_) { mini_logo_on_position_ = true; // Si el jugador quiere pasar los titulos de credito, el fade se inicia solo if (want_to_pass_) { fading_ = true; } // Se activa el contador para evitar que la sección sea infinita if (counter_prevent_endless_ == 1000) { fading_ = true; } else { ++counter_prevent_endless_; } } else { --mini_logo_rect_dst_.y; } } } // Tira globos al escenario (time-based) void Credits::throwBalloons(float deltaTime) { constexpr int SPEED = 200; const std::vector SETS = {0, 63, 25, 67, 17, 75, 13, 50}; constexpr float BALLOON_INTERVAL_S = SPEED / 60.0f; // ~3.33s (cada 200 frames) constexpr float POWERBALL_INTERVAL_S = (SPEED * 4) / 60.0f; // ~13.33s (cada 800 frames) if (counter_ > ((SETS.size() - 1) * SPEED) * 3) { return; } static float balloon_accumulator = 0.0f; static float powerball_accumulator = 0.0f; balloon_accumulator += deltaTime; powerball_accumulator += deltaTime; if (balloon_accumulator >= BALLOON_INTERVAL_S) { balloon_accumulator -= BALLOON_INTERVAL_S; const int INDEX = (static_cast(counter_ / SPEED)) % SETS.size(); balloon_manager_->deployFormation(SETS.at(INDEX), -60); } if (powerball_accumulator >= POWERBALL_INTERVAL_S && counter_ > 0) { powerball_accumulator -= POWERBALL_INTERVAL_S; balloon_manager_->createPowerBall(); } } // Inicializa los jugadores void Credits::initPlayers() { std::vector>> player_textures; // Vector con todas las texturas de los jugadores; std::vector> player_animations; // Vector con las animaciones del jugador // Texturas - Player1 std::vector> player1_textures; player1_textures.emplace_back(Resource::get()->getTexture("player1_pal0")); player1_textures.emplace_back(Resource::get()->getTexture("player1_pal1")); player1_textures.emplace_back(Resource::get()->getTexture("player1_pal2")); player1_textures.emplace_back(Resource::get()->getTexture("player1_pal3")); player1_textures.emplace_back(Resource::get()->getTexture("player1_power.png")); player_textures.push_back(player1_textures); // Texturas - Player2 std::vector> player2_textures; player2_textures.emplace_back(Resource::get()->getTexture("player2_pal0")); player2_textures.emplace_back(Resource::get()->getTexture("player2_pal1")); player2_textures.emplace_back(Resource::get()->getTexture("player2_pal2")); player2_textures.emplace_back(Resource::get()->getTexture("player2_pal3")); player2_textures.emplace_back(Resource::get()->getTexture("player2_power.png")); player_textures.push_back(player2_textures); // Animaciones -- Jugador player_animations.emplace_back(Resource::get()->getAnimation("player.ani")); player_animations.emplace_back(Resource::get()->getAnimation("player_power.ani")); // Crea los dos jugadores const int Y = play_area_.y + play_area_.h - Player::WIDTH; constexpr bool DEMO = false; constexpr int AWAY_DISTANCE = 700; Player::Config config_player1; config_player1.id = Player::Id::PLAYER1; config_player1.x = play_area_.x - AWAY_DISTANCE - Player::WIDTH; config_player1.y = Y; config_player1.demo = DEMO; config_player1.play_area = &play_area_; config_player1.texture = player_textures.at(0); config_player1.animations = player_animations; config_player1.hi_score_table = &Options::settings.hi_score_table; config_player1.glowing_entry = &Options::settings.glowing_entries.at(static_cast(Player::Id::PLAYER1) - 1); players_.emplace_back(std::make_unique(config_player1)); players_.back()->setWalkingState(Player::State::WALKING_RIGHT); players_.back()->setPlayingState(Player::State::CREDITS); Player::Config config_player2; config_player2.id = Player::Id::PLAYER2; config_player2.x = play_area_.x + play_area_.w + AWAY_DISTANCE; config_player2.y = Y; config_player2.demo = DEMO; config_player2.play_area = &play_area_; config_player2.texture = player_textures.at(1); config_player2.animations = player_animations; config_player2.hi_score_table = &Options::settings.hi_score_table; config_player2.glowing_entry = &Options::settings.glowing_entries.at(static_cast(Player::Id::PLAYER2) - 1); players_.emplace_back(std::make_unique(config_player2)); players_.back()->setWalkingState(Player::State::WALKING_LEFT); players_.back()->setPlayingState(Player::State::CREDITS); // Registra los jugadores en Options for (const auto &player : players_) { Options::keyboard.addPlayer(player); Options::gamepad_manager.addPlayer(player); } } // Actualiza los rectangulos negros (time-based) void Credits::updateBlackRects(float deltaTime) { static float current_step_ = static_cast(steps_); constexpr float BLACK_RECT_INTERVAL_S = 4.0f / 60.0f; // ~0.067s (cada 4 frames) static float black_rect_accumulator = 0.0f; if (top_black_rect_.h != param.game.game_area.center_y - 1 && bottom_black_rect_.y != param.game.game_area.center_y + 1) { // Si los rectangulos superior e inferior no han llegado al centro black_rect_accumulator += deltaTime; if (black_rect_accumulator >= BLACK_RECT_INTERVAL_S) { black_rect_accumulator -= BLACK_RECT_INTERVAL_S; // Incrementa la altura del rectangulo superior top_black_rect_.h = std::min(top_black_rect_.h + 1, param.game.game_area.center_y - 1); // Incrementa la altura y modifica la posición del rectangulo inferior ++bottom_black_rect_.h; bottom_black_rect_.y = std::max(bottom_black_rect_.y - 1, param.game.game_area.center_y + 1); --current_step_; setVolume(static_cast(initial_volume_ * current_step_ / steps_)); } } else { // Si los rectangulos superior e inferior han llegado al centro if (left_black_rect_.w != param.game.game_area.center_x && right_black_rect_.x != param.game.game_area.center_x) { constexpr int SPEED = 2; // Si los rectangulos izquierdo y derecho no han llegado al centro // Incrementa la anchura del rectangulo situado a la izquierda left_black_rect_.w = std::min(left_black_rect_.w + SPEED, param.game.game_area.center_x); // Incrementa la anchura y modifica la posición del rectangulo situado a la derecha right_black_rect_.w += SPEED; right_black_rect_.x = std::max(right_black_rect_.x - SPEED, param.game.game_area.center_x); --current_step_; setVolume(static_cast(initial_volume_ * current_step_ / steps_)); } else { // Si los rectangulos izquierdo y derecho han llegado al centro setVolume(0); Audio::get()->stopMusic(); if (counter_pre_fade_ == 400) { fade_out_->activate(); } else { // Convertir deltaTime a equivalente de frames const float frameFactor = deltaTime * 60.0f; counter_pre_fade_ += frameFactor; } } } } // Actualiza el rectangulo rojo void Credits::updateRedRect() { border_rect_.x = left_black_rect_.x + left_black_rect_.w; border_rect_.y = top_black_rect_.y + top_black_rect_.h - 1; border_rect_.w = right_black_rect_.x - border_rect_.x; border_rect_.h = bottom_black_rect_.y - border_rect_.y + 1; } // Actualiza el estado de fade (time-based) void Credits::updateAllFades(float deltaTime) { if (fading_) { updateBlackRects(deltaTime); updateRedRect(); } fade_in_->update(); // Fade ya usa tiempo interno if (fade_in_->hasEnded()) { Audio::get()->playMusic("credits.ogg"); } fade_out_->update(); // Fade ya usa tiempo interno if (fade_out_->hasEnded()) { Section::name = Section::Name::HI_SCORE_TABLE; } } // Establece el nivel de volumen void Credits::setVolume(int amount) { Options::audio.music.volume = std::clamp(amount, 0, 100); Audio::get()->setMusicVolume(Options::audio.music.volume); } // Reestablece el nivel de volumen void Credits::resetVolume() const { Options::audio.music.volume = initial_volume_; Audio::get()->setMusicVolume(Options::audio.music.volume); } // Cambia el color del fondo void Credits::cycleColors() { constexpr int UPPER_LIMIT = 140; // Límite superior constexpr int LOWER_LIMIT = 30; // Límite inferior static auto r_ = static_cast(UPPER_LIMIT); static auto g_ = static_cast(LOWER_LIMIT); static auto b_ = static_cast(LOWER_LIMIT); static float step_r_ = -0.5F; // Paso flotante para transiciones suaves static float step_g_ = 0.3F; static float step_b_ = 0.1F; // Ajustar valores de R r_ += step_r_; if (r_ >= UPPER_LIMIT || r_ <= LOWER_LIMIT) { step_r_ = -step_r_; // Cambia de dirección al alcanzar los límites } // Ajustar valores de G g_ += step_g_; if (g_ >= UPPER_LIMIT || g_ <= LOWER_LIMIT) { step_g_ = -step_g_; // Cambia de dirección al alcanzar los límites } // Ajustar valores de B b_ += step_b_; if (b_ >= UPPER_LIMIT || b_ <= LOWER_LIMIT) { step_b_ = -step_b_; // Cambia de dirección al alcanzar los límites } // Aplicar el color, redondeando a enteros antes de usar color_ = Color(static_cast(r_), static_cast(g_), static_cast(b_)); tiled_bg_->setColor(color_); } // Actualza los jugadores (time-based) void Credits::updatePlayers(float deltaTime) { for (auto &player : players_) { player->update(deltaTime); } } // Renderiza los jugadores void Credits::renderPlayers() { for (auto const &player : players_) { player->render(); } }