Compare commits

...

15 Commits

Author SHA1 Message Date
acc1b0e8a1 canvis de paleta amb L i R del mando 2026-04-13 21:05:52 +02:00
49fb895984 fix: no restaurava la pantalla en emscripten al eixir de fullscreen 2026-04-13 20:42:40 +02:00
9047bd7d1f tone a commitar pa provar el canvi de pantalla en emscripten 2026-04-13 20:09:18 +02:00
9b8820ffa3 pantalla de carrega no bloquejant
streaming de audio per evitar precárrega i descompresió a memoria
2026-04-13 19:29:05 +02:00
585c93054e commit per a provar les coses rares de la pantalla en wasm 2026-04-13 18:31:16 +02:00
8bfc32de40 emscripten: no anava back en game 2026-04-13 18:06:54 +02:00
40766ad122 fix: en console faltava SCENE DEMO 2026-04-13 18:02:04 +02:00
e67aeb10fe fix: controls en el mando 2026-04-13 17:57:13 +02:00
5f293cbddf reordenades les layers del overlay
consola ara tanca i obri per temps en lloc de velocitat
2026-04-13 14:03:45 +02:00
7f470361cc soport de gamepad per a wasm 2026-04-13 13:20:50 +02:00
d9c41f420b fix: arrancar amb el borde desactivat feia crash al activarlo 2026-04-13 11:57:01 +02:00
023bbb224b arreglat el cuelgue de la precàrrega en wasm i afegit nom del recurs en curs
- CMakeLists.txt (Emscripten): afegit -fexceptions (compile + link) perquè
  fkyaml i altres throws ara es capturen pels try/catch enlloc de cridar
  abort(). També -sASSERTIONS=1 per veure missatges clars d'error en el
  runtime de Emscripten.
- resource_cache: abans de carregar cada recurs, desa el seu nom en
  current_loading_name_ i (en wasm/debug) el repinta immediatament sobre la
  barra de progrés. Ara, si la càrrega es penja en un fitxer concret, el
  nom queda visible en pantalla i ajuda a diagnosticar el problema.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 09:52:28 +02:00
70cfe5245d afegit suport Emscripten/WebAssembly al build system
- CMakeLists.txt: branca EMSCRIPTEN amb SDL3 via FetchContent, preload de data/
  config/ i gamecontrollerdb.txt, WebGL2, EMSCRIPTEN_BUILD define i sortida .html.
  Exclou sdl3gpu_shader (no soportat a WebGL2) i el pack_tool en wasm.
- Makefile: target wasm via Docker emscripten/emsdk, build a build/wasm i
  sortida a dist/wasm (.html .js .wasm .data).
- director.cpp: createSystemFolder utilitza MEMFS en wasm (sense pwd.h/unistd.h),
  executable_path buit, dev-mode forçat (filesystem preload, no pack), windowed.
- screen.cpp: initShaders és no-op en wasm (SDL3 GPU no suportat a WebGL2).
- global_inputs.cpp: handleQuit és no-op en wasm (no es pot eixir del joc).
- Director::handleEvent ignora SDL_EVENT_QUIT en wasm.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 09:02:00 +02:00
c32a880b6a refactor: migració a l'arquitectura SDL3 Callback API
Substitueix el bucle blocant main() → Director::run() → escena::run() per
SDL_AppInit/Iterate/Event/Quit. Cada escena implementa ara iterate() (un frame)
i handleEvent() (un event) sota una interfície base Scene.

- Director gestiona l'escena activa i les transicions via switchToActiveScene()
- Setup/cleanup que estava al voltant del while de run() mogut a ctor/dtor
  (música de Game/Ending/Ending2, volum de LoadingScreen)
- GlobalEvents ja no processa SDL_EVENT_QUIT (ho fa Director::handleEvent)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 08:49:19 +02:00
714de067c8 corregit makefile per a windows 2026-04-05 18:27:51 +02:00
45 changed files with 1436 additions and 763 deletions

View File

@@ -87,6 +87,7 @@ set(APP_SOURCES
source/game/gameplay/tilemap_renderer.cpp
# Game - Scenes
source/game/scenes/boot_loader.cpp
source/game/scenes/credits.cpp
source/game/scenes/ending.cpp
source/game/scenes/ending2.cpp
@@ -127,11 +128,27 @@ set(DEBUG_SOURCES
)
# Configuración de SDL3
find_package(SDL3 REQUIRED CONFIG REQUIRED COMPONENTS SDL3)
message(STATUS "SDL3 encontrado: ${SDL3_INCLUDE_DIRS}")
if(EMSCRIPTEN)
# En Emscripten, SDL3 se compila desde source con FetchContent
include(FetchContent)
FetchContent_Declare(
SDL3
GIT_REPOSITORY https://github.com/libsdl-org/SDL.git
GIT_TAG release-3.2.12
GIT_SHALLOW TRUE
)
set(SDL_SHARED OFF CACHE BOOL "" FORCE)
set(SDL_STATIC ON CACHE BOOL "" FORCE)
set(SDL_TEST_LIBRARY OFF CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(SDL3)
message(STATUS "SDL3 compilado desde source para Emscripten")
else()
find_package(SDL3 REQUIRED CONFIG REQUIRED COMPONENTS SDL3)
message(STATUS "SDL3 encontrado: ${SDL3_INCLUDE_DIRS}")
endif()
# --- SHADER COMPILATION (Linux/Windows only - macOS uses Metal) ---
if(NOT APPLE)
# --- SHADER COMPILATION (Linux/Windows only - macOS usa Metal, Emscripten no els necessita) ---
if(NOT APPLE AND NOT EMSCRIPTEN)
find_program(GLSLC_EXE NAMES glslc)
set(SHADERS_DIR "${CMAKE_SOURCE_DIR}/data/shaders")
@@ -196,10 +213,15 @@ else()
endif()
# --- 2. AÑADIR EJECUTABLE ---
add_executable(${PROJECT_NAME} ${APP_SOURCES} ${RENDERING_SOURCES})
if(EMSCRIPTEN)
# En Emscripten no compilem sdl3gpu_shader (SDL3 GPU no està suportat a WebGL2)
add_executable(${PROJECT_NAME} ${APP_SOURCES})
else()
add_executable(${PROJECT_NAME} ${APP_SOURCES} ${RENDERING_SOURCES})
endif()
# Shaders deben compilarse antes que el ejecutable (Linux/Windows con glslc)
if(NOT APPLE AND GLSLC_EXE)
if(NOT APPLE AND NOT EMSCRIPTEN AND GLSLC_EXE)
add_dependencies(${PROJECT_NAME} shaders)
endif()
@@ -243,12 +265,32 @@ elseif(APPLE)
-rpath @executable_path/../Frameworks/
)
endif()
elseif(EMSCRIPTEN)
target_compile_definitions(${PROJECT_NAME} PRIVATE EMSCRIPTEN_BUILD)
# -fexceptions: habilita excepcions C++ (fkyaml, std::runtime_error...) — sense això qualsevol throw crida abort()
target_compile_options(${PROJECT_NAME} PRIVATE -fexceptions)
target_link_options(${PROJECT_NAME} PRIVATE
"SHELL:--preload-file ${CMAKE_SOURCE_DIR}/data@/data"
"SHELL:--preload-file ${CMAKE_SOURCE_DIR}/config@/config"
"SHELL:--preload-file ${CMAKE_SOURCE_DIR}/gamecontrollerdb.txt@/gamecontrollerdb.txt"
-fexceptions
-sALLOW_MEMORY_GROWTH=1
-sMAX_WEBGL_VERSION=2
-sINITIAL_MEMORY=67108864
-sASSERTIONS=1
# ASYNCIFY només per permetre emscripten_sleep(0) durant la precàrrega de recursos
# (el bucle principal del joc ja usa SDL3 Callback API, no depèn d'ASYNCIFY).
-sASYNCIFY=1
)
set_target_properties(${PROJECT_NAME} PROPERTIES SUFFIX ".html")
elseif(UNIX AND NOT APPLE)
target_compile_definitions(${PROJECT_NAME} PRIVATE LINUX_BUILD)
endif()
# Especificar la ubicación del ejecutable
set_target_properties(${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR})
# Especificar la ubicación del ejecutable (en desktop; a wasm queda a build/wasm/)
if(NOT EMSCRIPTEN)
set_target_properties(${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR})
endif()
# --- 5. STATIC ANALYSIS TARGETS ---
@@ -315,29 +357,31 @@ else()
message(STATUS "clang-format no encontrado - targets 'format' y 'format-check' no disponibles")
endif()
# --- 6. PACK RESOURCES TARGETS ---
set(PACK_TOOL_SOURCES
${CMAKE_SOURCE_DIR}/tools/pack_resources/pack_resources.cpp
${CMAKE_SOURCE_DIR}/source/core/resources/resource_pack.cpp
)
# --- 6. PACK RESOURCES TARGETS (no en Emscripten: s'utilitza --preload-file) ---
if(NOT EMSCRIPTEN)
set(PACK_TOOL_SOURCES
${CMAKE_SOURCE_DIR}/tools/pack_resources/pack_resources.cpp
${CMAKE_SOURCE_DIR}/source/core/resources/resource_pack.cpp
)
add_executable(pack_tool ${PACK_TOOL_SOURCES})
target_include_directories(pack_tool PRIVATE ${CMAKE_SOURCE_DIR}/source)
set_target_properties(pack_tool PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/tools/pack_resources
)
add_executable(pack_tool ${PACK_TOOL_SOURCES})
target_include_directories(pack_tool PRIVATE ${CMAKE_SOURCE_DIR}/source)
set_target_properties(pack_tool PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/tools/pack_resources
)
file(GLOB_RECURSE DATA_FILES "${CMAKE_SOURCE_DIR}/data/*")
file(GLOB_RECURSE DATA_FILES "${CMAKE_SOURCE_DIR}/data/*")
add_custom_command(
OUTPUT "${CMAKE_SOURCE_DIR}/resources.pack"
COMMAND $<TARGET_FILE:pack_tool>
"${CMAKE_SOURCE_DIR}/data"
"${CMAKE_SOURCE_DIR}/resources.pack"
DEPENDS pack_tool ${DATA_FILES}
WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
COMMENT "Generando resources.pack desde data/..."
)
add_custom_command(
OUTPUT "${CMAKE_SOURCE_DIR}/resources.pack"
COMMAND $<TARGET_FILE:pack_tool>
"${CMAKE_SOURCE_DIR}/data"
"${CMAKE_SOURCE_DIR}/resources.pack"
DEPENDS pack_tool ${DATA_FILES}
WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
COMMENT "Generando resources.pack desde data/..."
)
add_custom_target(pack DEPENDS "${CMAKE_SOURCE_DIR}/resources.pack")
add_dependencies(${PROJECT_NAME} pack)
add_custom_target(pack DEPENDS "${CMAKE_SOURCE_DIR}/resources.pack")
add_dependencies(${PROJECT_NAME} pack)
endif()

View File

@@ -54,9 +54,11 @@ endif
ifeq ($(OS),Windows_NT)
WIN_TARGET_FILE := $(DIR_BIN)$(APP_NAME)
WIN_RELEASE_FILE := $(RELEASE_FOLDER)/$(APP_NAME)
WIN_RELEASE_FILE_PS := $(subst ','',$(WIN_RELEASE_FILE))
else
WIN_TARGET_FILE := $(TARGET_FILE)
WIN_RELEASE_FILE := $(RELEASE_FILE)
WIN_RELEASE_FILE_PS := $(WIN_RELEASE_FILE)
endif
# ==============================================================================
@@ -148,7 +150,7 @@ windows_release:
@powershell -Command "Copy-Item 'README.md' -Destination '$(RELEASE_FOLDER)'"
@powershell -Command "Copy-Item 'gamecontrollerdb.txt' -Destination '$(RELEASE_FOLDER)'"
@powershell -Command "Copy-Item 'release\windows\dll\*.dll' -Destination '$(RELEASE_FOLDER)'"
@powershell -Command "Copy-Item -Path '$(TARGET_FILE)' -Destination '\"$(WIN_RELEASE_FILE).exe\"'"
@powershell -Command "Copy-Item -Path '$(TARGET_FILE).exe' -Destination '$(WIN_RELEASE_FILE_PS).exe'"
strip -s -R .comment -R .gnu.version "$(WIN_RELEASE_FILE).exe" --strip-unneeded
# Crea el fichero .zip
@@ -283,6 +285,39 @@ linux_release:
# Elimina la carpeta temporal
$(RMDIR) "$(RELEASE_FOLDER)"
# ==============================================================================
# COMPILACIÓN PARA WEBASSEMBLY (requiere Docker)
# ==============================================================================
wasm:
@echo "Compilando para WebAssembly - Version: $(VERSION)"
docker run --rm \
-v $(DIR_ROOT):/src \
-w /src \
emscripten/emsdk:latest \
bash -c "emcmake cmake -S . -B build/wasm -DCMAKE_BUILD_TYPE=Release && cmake --build build/wasm"
$(MKDIR) "$(DIST_DIR)/wasm"
cp build/wasm/$(TARGET_NAME).html $(DIST_DIR)/wasm/
cp build/wasm/$(TARGET_NAME).js $(DIST_DIR)/wasm/
cp build/wasm/$(TARGET_NAME).wasm $(DIST_DIR)/wasm/
cp build/wasm/$(TARGET_NAME).data $(DIST_DIR)/wasm/
@echo "Output: $(DIST_DIR)/wasm/"
# Versió Debug del build wasm: arrenca directament a la GAME (sense logo/loading/title)
# i activa l'editor i la consola. Sortida a dist/wasm_debug/.
wasm_debug:
@echo "Compilando WebAssembly Debug - Version: $(VERSION)"
docker run --rm \
-v $(DIR_ROOT):/src \
-w /src \
emscripten/emsdk:latest \
bash -c "emcmake cmake -S . -B build/wasm_debug -DCMAKE_BUILD_TYPE=Debug && cmake --build build/wasm_debug"
$(MKDIR) "$(DIST_DIR)/wasm_debug"
cp build/wasm_debug/$(TARGET_NAME).html $(DIST_DIR)/wasm_debug/
cp build/wasm_debug/$(TARGET_NAME).js $(DIST_DIR)/wasm_debug/
cp build/wasm_debug/$(TARGET_NAME).wasm $(DIST_DIR)/wasm_debug/
cp build/wasm_debug/$(TARGET_NAME).data $(DIST_DIR)/wasm_debug/
@echo "Output: $(DIST_DIR)/wasm_debug/"
# ==============================================================================
# REGLAS ESPECIALES
# ==============================================================================
@@ -304,6 +339,8 @@ help:
@echo " make windows_release - Crear release para Windows"
@echo " make linux_release - Crear release para Linux"
@echo " make macos_release - Crear release para macOS"
@echo " make wasm - Crear release per a WebAssembly (requereix Docker)"
@echo " make wasm_debug - Crear build Debug per a WebAssembly (entra directe a la GAME)"
@echo ""
@echo " Herramientas:"
@echo " make compile_shaders - Compilar shaders SPIR-V"
@@ -314,4 +351,4 @@ help:
@echo " make show_version - Mostrar version actual ($(VERSION))"
@echo " make help - Mostrar esta ayuda"
.PHONY: all debug release windows_release macos_release linux_release compile_shaders pack_tool resources.pack show_version help
.PHONY: all debug release windows_release macos_release linux_release wasm wasm_debug compile_shaders pack_tool resources.pack show_version help

View File

@@ -201,7 +201,7 @@ categories:
DEBUG: [MODE, START]
DEBUG MODE: [ON, OFF]
DEBUG START: [HERE, ROOM, POS, SCENE]
DEBUG START SCENE: [LOGO, LOADING, TITLE, CREDITS, GAME, ENDING, ENDING2]
DEBUG START SCENE: [LOGO, LOADING, TITLE, CREDITS, GAME, DEMO, ENDING, ENDING2]
- keyword: ITEMS
handler: cmd_items
@@ -220,9 +220,9 @@ categories:
- keyword: SCENE
handler: cmd_scene
description: Change scene
usage: "SCENE [LOGO|LOADING|TITLE|CREDITS|GAME|ENDING|ENDING2|RESTART]"
usage: "SCENE [LOGO|LOADING|TITLE|CREDITS|GAME|DEMO|ENDING|ENDING2|RESTART]"
completions:
SCENE: [LOGO, LOADING, TITLE, CREDITS, GAME, ENDING, ENDING2, RESTART]
SCENE: [LOGO, LOADING, TITLE, CREDITS, GAME, DEMO, ENDING, ENDING2, RESTART]
- keyword: EDIT
handler: cmd_edit

View File

@@ -8,6 +8,7 @@ title:
keyboard: "2. REDEFINIR TECLES"
joystick: "3. REDEFINIR MANDO"
projects: "4. PROJECTES"
press_to_play: "PREM PER JUGAR"
keys:
prompt0: "PREM UNA TECLA PER A ESQUERRA"
prompt1: "PREM UNA TECLA PER A DRETA"
@@ -103,6 +104,8 @@ achievements:
ui:
press_again_menu: "PREM DE NOU PER TORNAR AL MENÚ"
press_again_exit: "PREM DE NOU PER EIXIR"
gamepad_connected: "CONNECTAT"
gamepad_disconnected: "DESCONNECTAT"
border_enabled: "VORA ACTIVADA"
border_disabled: "VORA DESACTIVADA"
fullscreen_enabled: "PANTALLA COMPLETA ACTIVADA"

View File

@@ -8,6 +8,7 @@ title:
keyboard: "2. REDEFINE KEYBOARD"
joystick: "3. REDEFINE JOYSTICK"
projects: "4. PROJECTS"
press_to_play: "PRESS TO PLAY"
keys:
prompt0: "PRESS KEY FOR LEFT"
prompt1: "PRESS KEY FOR RIGHT"
@@ -103,6 +104,8 @@ achievements:
ui:
press_again_menu: "PRESS AGAIN TO RETURN TO MENU"
press_again_exit: "PRESS AGAIN TO EXIT"
gamepad_connected: "CONNECTED"
gamepad_disconnected: "DISCONNECTED"
border_enabled: "BORDER ENABLED"
border_disabled: "BORDER DISABLED"
fullscreen_enabled: "FULLSCREEN ENABLED"

View File

@@ -43,12 +43,16 @@ struct JA_Channel_t {
struct JA_Music_t {
SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000};
Uint32 length{0};
Uint8* buffer{nullptr};
// OGG comprimit en memòria. Propietat nostra; es copia des del fitxer una
// sola vegada en JA_LoadMusic i es descomprimix en chunks per streaming.
Uint8* ogg_data{nullptr};
Uint32 ogg_length{0};
stb_vorbis* vorbis{nullptr}; // Handle del decoder, viu tot el cicle del JA_Music_t
char* filename{nullptr};
int pos{0};
int times{0};
int times{0}; // Loops restants (-1 = infinit, 0 = un sol play)
SDL_AudioStream* stream{nullptr};
JA_Music_state state{JA_MUSIC_INVALID};
};
@@ -76,6 +80,57 @@ inline void JA_StopMusic();
inline void JA_StopChannel(const int channel);
inline int JA_PlaySoundOnChannel(JA_Sound_t* sound, const int channel, const int loop = 0, const int group = 0);
// --- Music streaming internals ---
// Bytes-per-sample per canal (sempre s16)
static constexpr int JA_MUSIC_BYTES_PER_SAMPLE = 2;
// Quants shorts decodifiquem per crida a get_samples_short_interleaved.
// 8192 shorts = 4096 samples/channel en estèreo ≈ 85ms de so a 48kHz.
static constexpr int JA_MUSIC_CHUNK_SHORTS = 8192;
// Umbral d'audio per davant del cursor de reproducció. Mantenim ≥ 0.5 s a
// l'SDL_AudioStream per absorbir jitter de frame i evitar underruns.
static constexpr float JA_MUSIC_LOW_WATER_SECONDS = 0.5f;
// Decodifica un chunk del vorbis i el volca a l'stream. Retorna samples
// decodificats per canal (0 = EOF de l'stream vorbis).
inline int JA_FeedMusicChunk(JA_Music_t* music) {
if (!music || !music->vorbis || !music->stream) return 0;
short chunk[JA_MUSIC_CHUNK_SHORTS];
const int channels = music->spec.channels;
const int samples_per_channel = stb_vorbis_get_samples_short_interleaved(
music->vorbis,
channels,
chunk,
JA_MUSIC_CHUNK_SHORTS);
if (samples_per_channel <= 0) return 0;
const int bytes = samples_per_channel * channels * JA_MUSIC_BYTES_PER_SAMPLE;
SDL_PutAudioStreamData(music->stream, chunk, bytes);
return samples_per_channel;
}
// Reompli l'stream fins que tinga ≥ JA_MUSIC_LOW_WATER_SECONDS bufferats.
// En arribar a EOF del vorbis, aplica el loop (times) o deixa drenar.
inline void JA_PumpMusic(JA_Music_t* music) {
if (!music || !music->vorbis || !music->stream) return;
const int bytes_per_second = music->spec.freq * music->spec.channels * JA_MUSIC_BYTES_PER_SAMPLE;
const int low_water_bytes = static_cast<int>(JA_MUSIC_LOW_WATER_SECONDS * static_cast<float>(bytes_per_second));
while (SDL_GetAudioStreamAvailable(music->stream) < low_water_bytes) {
const int decoded = JA_FeedMusicChunk(music);
if (decoded > 0) continue;
// EOF: si queden loops, rebobinar; si no, tallar i deixar drenar.
if (music->times != 0) {
stb_vorbis_seek_start(music->vorbis);
if (music->times > 0) music->times--;
} else {
break;
}
}
}
// --- Core Functions ---
inline void JA_Update() {
@@ -93,13 +148,11 @@ inline void JA_Update() {
}
}
if (current_music->times != 0) {
if ((Uint32)SDL_GetAudioStreamAvailable(current_music->stream) < (current_music->length / 2)) {
SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length);
}
if (current_music->times > 0) current_music->times--;
} else {
if (SDL_GetAudioStreamAvailable(current_music->stream) == 0) JA_StopMusic();
// Streaming: rellenem l'stream fins al low-water-mark i parem si el
// vorbis s'ha esgotat i no queden loops.
JA_PumpMusic(current_music);
if (current_music->times == 0 && SDL_GetAudioStreamAvailable(current_music->stream) == 0) {
JA_StopMusic();
}
}
@@ -139,19 +192,31 @@ inline void JA_Quit() {
// --- Music Functions ---
inline JA_Music_t* JA_LoadMusic(const Uint8* buffer, Uint32 length) {
JA_Music_t* music = new JA_Music_t();
if (!buffer || length == 0) return nullptr;
int chan, samplerate;
short* output;
music->length = stb_vorbis_decode_memory(buffer, length, &chan, &samplerate, &output) * chan * 2;
// Còpia del OGG comprimit: stb_vorbis llig de forma persistent aquesta
// memòria mentre el handle estiga viu, així que hem de posseir-la nosaltres.
Uint8* ogg_copy = static_cast<Uint8*>(SDL_malloc(length));
if (!ogg_copy) return nullptr;
SDL_memcpy(ogg_copy, buffer, length);
music->spec.channels = chan;
music->spec.freq = samplerate;
int error = 0;
stb_vorbis* vorbis = stb_vorbis_open_memory(ogg_copy, static_cast<int>(length), &error, nullptr);
if (!vorbis) {
SDL_free(ogg_copy);
SDL_Log("JA_LoadMusic: stb_vorbis_open_memory failed (error %d)", error);
return nullptr;
}
auto* music = new JA_Music_t();
music->ogg_data = ogg_copy;
music->ogg_length = length;
music->vorbis = vorbis;
const stb_vorbis_info info = stb_vorbis_get_info(vorbis);
music->spec.channels = info.channels;
music->spec.freq = static_cast<int>(info.sample_rate);
music->spec.format = SDL_AUDIO_S16;
music->buffer = static_cast<Uint8*>(SDL_malloc(music->length));
SDL_memcpy(music->buffer, output, music->length);
free(output);
music->pos = 0;
music->state = JA_MUSIC_STOPPED;
return music;
@@ -190,23 +255,29 @@ inline JA_Music_t* JA_LoadMusic(const char* filename) {
}
inline void JA_PlayMusic(JA_Music_t* music, const int loop = -1) {
if (!JA_musicEnabled || !music) return; // Añadida comprobación de music
if (!JA_musicEnabled || !music || !music->vorbis) return;
JA_StopMusic();
current_music = music;
current_music->pos = 0;
current_music->state = JA_MUSIC_PLAYING;
current_music->times = loop;
// Rebobinem l'stream de vorbis al principi. Cobreix tant play-per-primera-
// vegada com replays/canvis de track que tornen a la mateixa pista.
stb_vorbis_seek_start(current_music->vorbis);
current_music->stream = SDL_CreateAudioStream(&current_music->spec, &JA_audioSpec);
if (!current_music->stream) { // Comprobar creación de stream
if (!current_music->stream) {
SDL_Log("Failed to create audio stream!");
current_music->state = JA_MUSIC_STOPPED;
return;
}
if (!SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length)) printf("[ERROR] SDL_PutAudioStreamData failed!\n");
SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume);
// Pre-cargem el buffer abans de bindejar per evitar un underrun inicial.
JA_PumpMusic(current_music);
if (!SDL_BindAudioStream(sdlAudioDevice, current_music->stream)) printf("[ERROR] SDL_BindAudioStream failed!\n");
}
@@ -235,13 +306,17 @@ inline void JA_ResumeMusic() {
inline void JA_StopMusic() {
if (!current_music || current_music->state == JA_MUSIC_INVALID || current_music->state == JA_MUSIC_STOPPED) return;
current_music->pos = 0;
current_music->state = JA_MUSIC_STOPPED;
if (current_music->stream) {
SDL_DestroyAudioStream(current_music->stream);
current_music->stream = nullptr;
}
// No liberamos filename aquí, se debería liberar en JA_DeleteMusic
// Deixem el handle de vorbis viu — es tanca en JA_DeleteMusic.
// Rebobinem perquè un futur JA_PlayMusic comence des del principi.
if (current_music->vorbis) {
stb_vorbis_seek_start(current_music->vorbis);
}
// No liberem filename aquí; es fa en JA_DeleteMusic.
}
inline void JA_FadeOutMusic(const int milliseconds) {
@@ -267,9 +342,10 @@ inline void JA_DeleteMusic(JA_Music_t* music) {
JA_StopMusic();
current_music = nullptr;
}
SDL_free(music->buffer);
if (music->stream) SDL_DestroyAudioStream(music->stream);
free(music->filename); // filename se libera aquí
if (music->vorbis) stb_vorbis_close(music->vorbis);
SDL_free(music->ogg_data);
free(music->filename); // filename es libera aquí
delete music;
}
@@ -281,17 +357,14 @@ inline float JA_SetMusicVolume(float volume) {
return JA_musicVolume;
}
inline void JA_SetMusicPosition(float value) {
if (!current_music) return;
current_music->pos = value * current_music->spec.freq;
// Nota: Esta implementación de 'pos' no parece usarse en JA_Update para
// el streaming. El streaming siempre parece empezar desde el principio.
inline void JA_SetMusicPosition(float /*value*/) {
// No implementat amb el backend de streaming. Mai va arribar a usar-se
// en el codi existent, així que es manté com a stub.
}
inline float JA_GetMusicPosition() {
if (!current_music) return 0;
return float(current_music->pos) / float(current_music->spec.freq);
// Nota: Ver `JA_SetMusicPosition`
// Veure nota a JA_SetMusicPosition.
return 0.0f;
}
inline void JA_EnableMusic(const bool value) {

View File

@@ -9,6 +9,7 @@
#include "core/locale/locale.hpp" // Para Locale
#include "core/rendering/render_info.hpp" // Para RenderInfo
#include "core/rendering/screen.hpp" // Para Screen
#include "core/system/global_events.hpp" // Para GlobalEvents::consumeGamepadButtonPressed
#include "game/options.hpp" // Para Options, options, OptionsVideo, Section
#include "game/scene_manager.hpp" // Para SceneManager
#include "game/ui/console.hpp" // Para Console
@@ -20,7 +21,8 @@ namespace GlobalInputs {
// Funciones internas
namespace {
void handleQuit() {
// En la escena GAME el comportamiento es siempre el mismo (con o sin modo kiosko)
// En la escena GAME el comportamiento es siempre el mismo (con o sin modo kiosko):
// Escape torna al menu principal. Això també és vàlid en la versió web.
if (SceneManager::current == SceneManager::Scene::GAME) {
const std::string CODE = "PRESS AGAIN TO RETURN TO MENU";
if (stringInVector(Notifier::get()->getCodes(), CODE)) {
@@ -41,6 +43,11 @@ namespace GlobalInputs {
return;
}
#ifdef __EMSCRIPTEN__
// A la versió web no es pot eixir del joc des de fora de l'escena GAME
// (el navegador gestiona la pestanya; Escape no tanca res).
return;
#else
// Comportamiento normal fuera del modo kiosko
const std::string CODE = "PRESS AGAIN TO EXIT";
if (stringInVector(Notifier::get()->getCodes(), CODE)) {
@@ -48,6 +55,7 @@ namespace GlobalInputs {
} else {
Notifier::get()->show({Locale::get()->get("ui.press_again_exit")}, Notifier::Style::DEFAULT, -1, true, CODE); // NOLINT(readability-static-accessed-through-instance)
}
#endif // __EMSCRIPTEN__
}
void handleSkipSection() {
@@ -145,6 +153,13 @@ namespace GlobalInputs {
// Detecta qué acción global ha sido presionada (si alguna)
auto getPressedAction() -> InputAction { // NOLINT(readability-function-cognitive-complexity)
// Qualsevol botó del comandament actua com a ACCEPT (saltar escenes
// d'attract mode: logo, loading, credits, demo, ending...). El botó
// BACK queda filtrat prèviament a GlobalEvents per no colidir amb EXIT
// (excepte en emscripten, on BACK no pot sortir i sí pot saltar).
if (GlobalEvents::consumeGamepadButtonPressed()) {
return InputAction::ACCEPT;
}
if (Input::get()->checkAction(InputAction::EXIT, Input::DO_NOT_ALLOW_REPEAT)) {
return InputAction::EXIT;
}

View File

@@ -390,12 +390,21 @@ void Input::update() { // NOLINT(readability-convert-member-functions-to-static
// --- MANDOS ---
for (const auto& gamepad : gamepads_) {
for (auto& binding : gamepad->bindings) {
bool button_is_down_now = static_cast<int>(SDL_GetGamepadButton(gamepad->pad, static_cast<SDL_GamepadButton>(binding.second.button))) != 0;
for (auto& [action, state] : gamepad->bindings) {
bool is_down_now = static_cast<int>(SDL_GetGamepadButton(gamepad->pad, static_cast<SDL_GamepadButton>(state.button))) != 0;
// JUMP accepta qualsevol dels 4 botons frontals (South/East/North/West)
if (action == Action::JUMP) {
is_down_now = is_down_now ||
(SDL_GetGamepadButton(gamepad->pad, SDL_GAMEPAD_BUTTON_SOUTH) != 0) ||
(SDL_GetGamepadButton(gamepad->pad, SDL_GAMEPAD_BUTTON_EAST) != 0) ||
(SDL_GetGamepadButton(gamepad->pad, SDL_GAMEPAD_BUTTON_NORTH) != 0) ||
(SDL_GetGamepadButton(gamepad->pad, SDL_GAMEPAD_BUTTON_WEST) != 0);
}
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
binding.second.just_pressed = button_is_down_now && !binding.second.is_held;
binding.second.is_held = button_is_down_now;
state.just_pressed = is_down_now && !state.is_held;
state.is_held = is_down_now;
}
}
}
@@ -421,7 +430,13 @@ auto Input::addGamepad(int device_index) -> std::string { // NOLINT(readability
auto name = gamepad->name;
std::cout << "Gamepad connected (" << name << ")" << '\n';
gamepads_.push_back(std::move(gamepad));
return name + " CONNECTED";
// Aplica els bindings d'Options al nou gamepad (en hot-plug/wasm el ctor
// ja ha cridat applyGamepadBindingsFromOptions però llavors gamepads_
// estava buit i no s'ha fet res).
applyGamepadBindingsFromOptions();
return name;
}
auto Input::removeGamepad(SDL_JoystickID id) -> std::string { // NOLINT(readability-convert-member-functions-to-static)
@@ -433,7 +448,7 @@ auto Input::removeGamepad(SDL_JoystickID id) -> std::string { // NOLINT(readabi
std::string name = (*it)->name;
std::cout << "Gamepad disconnected (" << name << ")" << '\n';
gamepads_.erase(it);
return name + " DISCONNECTED";
return name;
}
std::cerr << "No se encontró el gamepad con ID " << id << '\n';
return {};

View File

@@ -60,7 +60,15 @@ class Input {
// Movimiento del jugador
{Action::LEFT, ButtonState{.button = static_cast<int>(SDL_GAMEPAD_BUTTON_DPAD_LEFT)}},
{Action::RIGHT, ButtonState{.button = static_cast<int>(SDL_GAMEPAD_BUTTON_DPAD_RIGHT)}},
{Action::JUMP, ButtonState{.button = static_cast<int>(SDL_GAMEPAD_BUTTON_WEST)}}} {}
{Action::JUMP, ButtonState{.button = static_cast<int>(SDL_GAMEPAD_BUTTON_WEST)}},
// Botó BACK del mando → sortir escena / tancar joc
{Action::EXIT, ButtonState{.button = static_cast<int>(SDL_GAMEPAD_BUTTON_BACK)}},
{Action::CANCEL, ButtonState{.button = static_cast<int>(SDL_GAMEPAD_BUTTON_BACK)}},
// Botó START del mando → pausa
{Action::PAUSE, ButtonState{.button = static_cast<int>(SDL_GAMEPAD_BUTTON_START)}},
// Shoulders → paleta següent / mode d'ordenació de paleta següent
{Action::NEXT_PALETTE, ButtonState{.button = static_cast<int>(SDL_GAMEPAD_BUTTON_LEFT_SHOULDER)}},
{Action::NEXT_PALETTE_SORT, ButtonState{.button = static_cast<int>(SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER)}}} {}
~Gamepad() {
if (pad != nullptr) {

View File

@@ -119,9 +119,10 @@ void RenderInfo::render() const {
// Fuente: preferir la de la consola si está disponible
auto text_obj = (Console::get() != nullptr) ? Console::get()->getText() : Screen::get()->getText();
// Posición Y: debajo de la consola + offset animado propio
// Posición Y: debajo de la consola + altura animada de la pila de notificaciones + offset animado propio
const int CONSOLE_Y = (Console::get() != nullptr) ? Console::get()->getVisibleHeight() : 0;
const int Y = CONSOLE_Y + static_cast<int>(y_);
const int NOTIFIER_Y = (Notifier::get() != nullptr) ? Notifier::get()->getVisibleHeight() : 0;
const int Y = CONSOLE_Y + NOTIFIER_Y + static_cast<int>(y_);
// Rectángulo de fondo: ancho completo, alto ajustado al texto
const SDL_FRect RECT = {
@@ -141,17 +142,15 @@ void RenderInfo::render() const {
MSG_COLOR);
}
// Activa o desactiva el overlay y notifica a Notifier del cambio de offset
// Activa o desactiva el overlay (la posición Y se calcula pull-side en render())
void RenderInfo::toggle() {
switch (status_) {
case Status::HIDDEN:
status_ = Status::RISING;
Screen::get()->updateZoomFactor();
if (Notifier::get() != nullptr) { Notifier::get()->addYOffset(HEIGHT); }
break;
case Status::ACTIVE:
status_ = Status::VANISHING;
if (Notifier::get() != nullptr) { Notifier::get()->removeYOffset(HEIGHT); }
break;
default:
break;

View File

@@ -1,6 +1,10 @@
#include "core/rendering/screen.hpp"
#include <SDL3/SDL.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#include <emscripten/html5.h>
#endif
#include <algorithm> // Para max, min, transform
#include <cctype> // Para toupper
@@ -11,21 +15,83 @@
#include <iterator> // Para istreambuf_iterator, operator==
#include <string> // Para char_traits, string, operator+, operator==
#include "core/input/mouse.hpp" // Para updateCursorVisibility
#include "core/rendering/render_info.hpp" // Para RenderInfo
#include "core/rendering/sdl3gpu/sdl3gpu_shader.hpp" // Para SDL3GPUShader
#include "core/rendering/surface.hpp" // Para Surface, readPalFile
#include "core/rendering/text.hpp" // Para Text
#include "core/resources/resource_cache.hpp" // Para Resource
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
#include "core/resources/resource_list.hpp" // Para Asset, AssetType
#include "game/options.hpp" // Para Options, options, OptionsVideo, Border
#include "game/ui/console.hpp" // Para Console
#include "game/ui/notifier.hpp" // Para Notifier
#include "core/input/mouse.hpp" // Para updateCursorVisibility
#include "core/rendering/render_info.hpp" // Para RenderInfo
#ifndef __EMSCRIPTEN__
#include "core/rendering/sdl3gpu/sdl3gpu_shader.hpp" // Para SDL3GPUShader (no suportat a WebGL2)
#endif
#include "core/rendering/surface.hpp" // Para Surface, readPalFile
#include "core/rendering/text.hpp" // Para Text
#include "core/resources/resource_cache.hpp" // Para Resource
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
#include "core/resources/resource_list.hpp" // Para Asset, AssetType
#include "game/options.hpp" // Para Options, options, OptionsVideo, Border
#include "game/ui/console.hpp" // Para Console
#include "game/ui/notifier.hpp" // Para Notifier
// [SINGLETON]
Screen* Screen::screen = nullptr;
#ifdef __EMSCRIPTEN__
// ============================================================================
// Restauració del canvas en wasm/Emscripten
// ============================================================================
//
// Problema: SDL3 + Emscripten no notifica de manera fiable els canvis de mida
// del canvas HTML. En concret:
// - SDL_EVENT_WINDOW_LEAVE_FULLSCREEN no s'emet quan l'usuari surt de
// fullscreen amb Esc/F11 (libsdl-org/SDL#13300).
// - SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED i SDL_EVENT_DISPLAY_ORIENTATION
// tampoc es disparen de manera fiable (libsdl-org/SDL#11389).
// - Resultat: en sortir de fullscreen el canvas queda a la mida correcta
// però SDL encara creu que està en fullscreen amb la resolució anterior,
// i el joc es veu minúscul fins que l'usuari força un refresh manual
// (p. ex., canviant el mode d'escalat amb F7).
//
// Solució: registrem callbacks natius d'Emscripten (fullscreenchange, resize,
// orientationchange) que re-sincronitzen SDL amb l'estat real del navegador.
// Tots delegen en Screen::handleCanvasResized(), que crida setVideoMode()
// amb l'estat de fullscreen actualitzat — això és el que realment restaura
// la finestra SDL perquè dins setVideoMode es crida SDL_SetWindowFullscreen,
// que és imprescindible per treure SDL del seu estat intern de fullscreen.
//
// Els callbacks diferixen la feina amb emscripten_async_call(0ms) perquè
// quan l'event es dispara el navegador encara no ha acabat de redimensionar
// el canvas: llegir la mida en aquest instant donaria un valor obsolet.
// Posposar al següent tick del event loop garanteix que el canvas ja està
// estable quan actuem.
//
// Referències:
// - https://github.com/libsdl-org/SDL/issues/13300
// - https://github.com/libsdl-org/SDL/issues/11389
// - https://discourse.libsdl.org/t/sdl-emscripten-allow-resize-events-on-fullscreen-windows/66279
// ============================================================================
namespace {
void deferredCanvasResize(void* /*user_data*/) {
if (Screen::get() != nullptr) { Screen::get()->handleCanvasResized(); }
}
auto onEmFullscreenChange(int /*event_type*/, const EmscriptenFullscreenChangeEvent* event, void* /*user_data*/) -> EM_BOOL {
// Actualitzem Options::video.fullscreen amb l'estat real del navegador
// abans de diferir la restauració: quan l'usuari surt amb Esc no passem
// per setVideoMode() i l'estat intern quedaria desincronitzat.
Options::video.fullscreen = (event != nullptr && event->isFullscreen != 0);
emscripten_async_call(deferredCanvasResize, nullptr, 0);
return EM_FALSE;
}
auto onEmResize(int /*event_type*/, const EmscriptenUiEvent* /*event*/, void* /*user_data*/) -> EM_BOOL {
emscripten_async_call(deferredCanvasResize, nullptr, 0);
return EM_FALSE;
}
auto onEmOrientationChange(int /*event_type*/, const EmscriptenOrientationChangeEvent* /*event*/, void* /*user_data*/) -> EM_BOOL {
emscripten_async_call(deferredCanvasResize, nullptr, 0);
return EM_FALSE;
}
} // namespace
#endif
// [SINGLETON] Crearemos el objeto con esta función estática
void Screen::init() {
Screen::screen = new Screen();
@@ -166,6 +232,20 @@ void Screen::toggleVideoMode() {
setVideoMode(Options::video.fullscreen);
}
// Re-sincronitza SDL amb l'estat real del canvas del navegador. L'invoquen els
// callbacks natius d'Emscripten definits a dalt (vegeu el bloc de documentació
// just després dels includes) quan es detecta un fullscreenchange, resize o
// orientationchange. Delegar a setVideoMode() és el que realment restaura la
// finestra: per sota crida SDL_SetWindowFullscreen, imprescindible perquè
// SDL tregui el seu estat intern de fullscreen quan l'usuari ha sortit amb
// Esc sense passar pel nostre toggleVideoMode(). No fem res fora d'emscripten
// perquè en desktop SDL ja emet SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED correctament.
void Screen::handleCanvasResized() {
#ifdef __EMSCRIPTEN__
setVideoMode(Options::video.fullscreen);
#endif
}
// Reduce el tamaño de la ventana
auto Screen::decWindowZoom() -> bool {
if (static_cast<int>(Options::video.fullscreen) == 0) {
@@ -293,16 +373,16 @@ void Screen::adjustWindowSize() {
window_width_ = Options::game.width + (Options::video.border.enabled ? Options::video.border.width * 2 : 0);
window_height_ = Options::game.height + (Options::video.border.enabled ? Options::video.border.height * 2 : 0);
// Reservamos memoria una sola vez.
// Si el buffer es más pequeño que la superficie, crash asegurado.
border_pixel_buffer_.resize(static_cast<size_t>(window_width_ * window_height_));
// border_surface_ sempre té el tamany complet del borde (game + 2*border_w/h),
// independentment de si el borde està visible o no. El buffer ARGB que l'ombra
// ha de ser ALMENYS tan gran com la surface; si no, toARGBBuffer() escriu fora
// de bounds i corromp el heap (bug latent a desktop fins a disparar-lo un toggleBorder).
const size_t FULL_BORDER_BUFFER_SIZE =
static_cast<size_t>(Options::game.width + (Options::video.border.width * 2)) *
static_cast<size_t>(Options::game.height + (Options::video.border.height * 2));
border_pixel_buffer_.resize(FULL_BORDER_BUFFER_SIZE);
game_pixel_buffer_.resize(static_cast<size_t>(Options::game.width * Options::game.height));
// border_pixel_buffer_ es el buffer que se sube a la GPU (tamaño total ventana).
if (Options::video.border.enabled) {
border_pixel_buffer_.resize(static_cast<size_t>(window_width_ * window_height_));
}
// Lógica de centrado y redimensionado de ventana SDL
if (static_cast<int>(Options::video.fullscreen) == 0) {
int old_w;
@@ -605,6 +685,10 @@ void Screen::nextShader() {
// El device GPU se crea siempre (independientemente de postfx) para evitar
// conflictos SDL_Renderer/SDL_GPU al hacer toggle F4 en Windows/Vulkan.
void Screen::initShaders() {
#ifdef __EMSCRIPTEN__
// A WebGL2 no hi ha SDL3 GPU, el render va per SDL_Renderer sense shaders.
shader_backend_.reset();
#else
SDL_Texture* tex = Options::video.border.enabled ? border_texture_ : game_texture_;
if (!shader_backend_) {
@@ -633,6 +717,7 @@ void Screen::initShaders() {
if (Options::video.shader.current_shader == Rendering::ShaderType::CRTPI) {
applyCurrentCrtPiPreset();
}
#endif
}
// Obtiene información sobre la pantalla
@@ -736,10 +821,23 @@ auto Screen::initSDLVideo() -> bool {
SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND);
SDL_SetRenderVSync(renderer_, Options::video.vertical_sync ? 1 : SDL_RENDERER_VSYNC_DISABLED);
registerEmscriptenEventCallbacks();
std::cout << "Video system initialized successfully\n";
return true;
}
// Registra els callbacks natius d'Emscripten que restauren el canvas quan
// SDL3 no emet els events equivalents. Fora d'Emscripten és un no-op.
// Vegeu el bloc de documentació a dalt del fitxer per al context complet.
void Screen::registerEmscriptenEventCallbacks() { // NOLINT(readability-convert-member-functions-to-static)
#ifdef __EMSCRIPTEN__
emscripten_set_fullscreenchange_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, nullptr, EM_TRUE, onEmFullscreenChange);
emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, nullptr, EM_TRUE, onEmResize);
emscripten_set_orientationchange_callback(nullptr, EM_TRUE, onEmOrientationChange);
#endif
}
// Crea el objeto de texto
void Screen::createText() { // NOLINT(readability-convert-member-functions-to-static)
// Carga la surface de la fuente directamente del archivo

View File

@@ -38,6 +38,7 @@ class Screen {
// Video y ventana
void setVideoMode(bool mode); // Establece el modo de video
void toggleVideoMode(); // Cambia entre pantalla completa y ventana
void handleCanvasResized(); // Restaura el canvas quan SDL3 no reporta el canvi (emscripten only: sortida de fullscreen amb Esc, rotació, resize); no-op fora d'emscripten
void toggleIntegerScale(); // Alterna entre activar y desactivar el escalado entero
void toggleVSync(); // Alterna entre activar y desactivar el V-Sync
auto decWindowZoom() -> bool; // Reduce el tamaño de la ventana
@@ -125,18 +126,19 @@ class Screen {
static Screen* screen;
// Métodos privados
void renderNotifications() const; // Dibuja las notificaciones
void adjustWindowSize(); // Calcula el tamaño de la ventana
void adjustRenderLogicalSize(); // Ajusta el tamaño lógico del renderizador
void surfaceToTexture(); // Copia la surface a la textura
void textureToRenderer(); // Copia la textura al renderizador
void renderOverlays(); // Renderiza todos los overlays
void initShaders(); // Inicializa los shaders
void applyCurrentPostFXPreset(); // Aplica los parámetros del preset PostFX actual al backend
void applyCurrentCrtPiPreset(); // Aplica los parámetros del preset CrtPi actual al backend
void getDisplayInfo(); // Obtiene información sobre la pantalla
auto initSDLVideo() -> bool; // Arranca SDL VIDEO y crea la ventana
void createText(); // Crea el objeto de texto
void renderNotifications() const; // Dibuja las notificaciones
void adjustWindowSize(); // Calcula el tamaño de la ventana
void adjustRenderLogicalSize(); // Ajusta el tamaño lógico del renderizador
void surfaceToTexture(); // Copia la surface a la textura
void textureToRenderer(); // Copia la textura al renderizador
void renderOverlays(); // Renderiza todos los overlays
void initShaders(); // Inicializa los shaders
void applyCurrentPostFXPreset(); // Aplica los parámetros del preset PostFX actual al backend
void applyCurrentCrtPiPreset(); // Aplica los parámetros del preset CrtPi actual al backend
void getDisplayInfo(); // Obtiene información sobre la pantalla
auto initSDLVideo() -> bool; // Arranca SDL VIDEO y crea la ventana
void registerEmscriptenEventCallbacks(); // Registra els callbacks natius per restaurar el canvas en wasm (no-op fora d'emscripten)
void createText(); // Crea el objeto de texto
// Constructor y destructor
Screen();

View File

@@ -38,10 +38,10 @@ namespace Resource {
// [SINGLETON] Con este método obtenemos el objeto cache y podemos trabajar con él
auto Cache::get() -> Cache* { return Cache::cache; }
// Constructor
// Constructor — no dispara la carga. Director llama a beginLoad() + loadStep()
// desde iterate() para que el bucle SDL3 esté vivo durante la carga.
Cache::Cache()
: loading_text_(Screen::get()->getText()) {
load();
}
// Vacia todos los vectores de recursos
@@ -53,12 +53,11 @@ namespace Resource {
text_files_.clear();
texts_.clear();
animations_.clear();
rooms_.clear();
}
// Carga todos los recursos
// Carga todos los recursos de golpe (usado solo por reload() en hot-reload de debug)
void Cache::load() {
// Nota: el overlay de debug (RenderInfo) se inicializa después de esta carga,
// por lo que updateZoomFactor() se llamará correctamente en RenderInfo::init().
calculateTotal();
Screen::get()->setBorderColor(static_cast<Uint8>(PaletteColor::BLACK));
std::cout << "\n** LOADING RESOURCES" << '\n';
@@ -73,7 +72,162 @@ namespace Resource {
std::cout << "\n** RESOURCES LOADED" << '\n';
}
// Recarga todos los recursos
// Prepara el loader incremental. Director lo llama una vez tras Cache::init().
void Cache::beginLoad() {
calculateTotal();
Screen::get()->setBorderColor(static_cast<Uint8>(PaletteColor::BLACK));
std::cout << "\n** LOADING RESOURCES (incremental)" << '\n';
stage_ = LoadStage::SOUNDS;
stage_index_ = 0;
}
auto Cache::isLoadDone() const -> bool {
return stage_ == LoadStage::DONE;
}
// Carga assets hasta agotar el presupuesto de tiempo o completar todas las etapas.
// Devuelve true cuando ya no queda nada por cargar.
auto Cache::loadStep(int budget_ms) -> bool {
if (stage_ == LoadStage::DONE) return true;
const Uint64 start_ns = SDL_GetTicksNS();
const Uint64 budget_ns = static_cast<Uint64>(budget_ms) * 1'000'000ULL;
auto listOf = [](List::Type t) { return List::get()->getListByType(t); };
while (stage_ != LoadStage::DONE) {
switch (stage_) {
case LoadStage::SOUNDS: {
auto list = listOf(List::Type::SOUND);
if (stage_index_ == 0) {
std::cout << "\n>> SOUND FILES" << '\n';
sounds_.clear();
}
if (stage_index_ >= list.size()) {
stage_ = LoadStage::MUSICS;
stage_index_ = 0;
break;
}
loadOneSound(stage_index_++);
break;
}
case LoadStage::MUSICS: {
auto list = listOf(List::Type::MUSIC);
if (stage_index_ == 0) {
std::cout << "\n>> MUSIC FILES" << '\n';
musics_.clear();
}
if (stage_index_ >= list.size()) {
stage_ = LoadStage::SURFACES;
stage_index_ = 0;
break;
}
loadOneMusic(stage_index_++);
break;
}
case LoadStage::SURFACES: {
auto list = listOf(List::Type::BITMAP);
if (stage_index_ == 0) {
std::cout << "\n>> SURFACES" << '\n';
surfaces_.clear();
}
if (stage_index_ >= list.size()) {
stage_ = LoadStage::SURFACES_POST;
stage_index_ = 0;
break;
}
loadOneSurface(stage_index_++);
break;
}
case LoadStage::SURFACES_POST: {
finalizeSurfaces();
stage_ = LoadStage::PALETTES;
stage_index_ = 0;
break;
}
case LoadStage::PALETTES: {
auto list = listOf(List::Type::PALETTE);
if (stage_index_ == 0) {
std::cout << "\n>> PALETTES" << '\n';
palettes_.clear();
}
if (stage_index_ >= list.size()) {
stage_ = LoadStage::TEXT_FILES;
stage_index_ = 0;
break;
}
loadOnePalette(stage_index_++);
break;
}
case LoadStage::TEXT_FILES: {
auto list = listOf(List::Type::FONT);
if (stage_index_ == 0) {
std::cout << "\n>> TEXT FILES" << '\n';
text_files_.clear();
}
if (stage_index_ >= list.size()) {
stage_ = LoadStage::ANIMATIONS;
stage_index_ = 0;
break;
}
loadOneTextFile(stage_index_++);
break;
}
case LoadStage::ANIMATIONS: {
auto list = listOf(List::Type::ANIMATION);
if (stage_index_ == 0) {
std::cout << "\n>> ANIMATIONS" << '\n';
animations_.clear();
}
if (stage_index_ >= list.size()) {
stage_ = LoadStage::ROOMS;
stage_index_ = 0;
break;
}
loadOneAnimation(stage_index_++);
break;
}
case LoadStage::ROOMS: {
auto list = listOf(List::Type::ROOM);
if (stage_index_ == 0) {
std::cout << "\n>> ROOMS" << '\n';
rooms_.clear();
}
if (stage_index_ >= list.size()) {
stage_ = LoadStage::TEXTS;
stage_index_ = 0;
break;
}
loadOneRoom(stage_index_++);
break;
}
case LoadStage::TEXTS: {
// createText itera sobre una lista fija de 5 fuentes
constexpr size_t TEXT_COUNT = 5;
if (stage_index_ == 0) {
std::cout << "\n>> CREATING TEXT_OBJECTS" << '\n';
texts_.clear();
}
if (stage_index_ >= TEXT_COUNT) {
stage_ = LoadStage::DONE;
stage_index_ = 0;
std::cout << "\n** RESOURCES LOADED" << '\n';
break;
}
createOneText(stage_index_++);
break;
}
case LoadStage::DONE:
break;
}
if ((SDL_GetTicksNS() - start_ns) >= budget_ns) break;
}
return stage_ == LoadStage::DONE;
}
// Recarga todos los recursos (síncrono, solo para hot-reload de debug)
void Cache::reload() {
clear();
load();
@@ -217,93 +371,96 @@ namespace Resource {
throw;
}
// Carga los sonidos
void Cache::loadSounds() { // NOLINT(readability-convert-member-functions-to-static)
std::cout << "\n>> SOUND FILES" << '\n';
// Lista fija de text objects. Compartida entre createText() y createOneText(i).
namespace {
struct TextObjectInfo {
std::string key; // Identificador del recurso
std::string texture_file; // Nombre del archivo de textura
std::string text_file; // Nombre del archivo de texto
};
const std::vector<TextObjectInfo>& getTextObjectInfos() {
static const std::vector<TextObjectInfo> info = {
{.key = "aseprite", .texture_file = "aseprite.gif", .text_file = "aseprite.fnt"},
{.key = "gauntlet", .texture_file = "gauntlet.gif", .text_file = "gauntlet.fnt"},
{.key = "smb2", .texture_file = "smb2.gif", .text_file = "smb2.fnt"},
{.key = "subatomic", .texture_file = "subatomic.gif", .text_file = "subatomic.fnt"},
{.key = "8bithud", .texture_file = "8bithud.gif", .text_file = "8bithud.fnt"}};
return info;
}
} // namespace
// --- Helpers incrementales (un asset por llamada) ---
void Cache::loadOneSound(size_t index) {
auto list = List::get()->getListByType(List::Type::SOUND);
sounds_.clear();
const auto& l = list[index];
try {
auto name = getFileName(l);
setCurrentLoading(name);
JA_Sound_t* sound = nullptr;
for (const auto& l : list) {
try {
auto name = getFileName(l);
JA_Sound_t* sound = nullptr;
// Try loading from resource pack first
auto audio_data = Helper::loadFile(l);
if (!audio_data.empty()) {
sound = JA_LoadSound(audio_data.data(), static_cast<Uint32>(audio_data.size()));
}
// Fallback to file path if memory loading failed
if (sound == nullptr) {
sound = JA_LoadSound(l.c_str());
}
if (sound == nullptr) {
throw std::runtime_error("Failed to decode audio file");
}
sounds_.emplace_back(SoundResource{.name = name, .sound = sound});
printWithDots("Sound : ", name, "[ LOADED ]");
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("SOUND", l, e);
auto audio_data = Helper::loadFile(l);
if (!audio_data.empty()) {
sound = JA_LoadSound(audio_data.data(), static_cast<Uint32>(audio_data.size()));
}
if (sound == nullptr) {
sound = JA_LoadSound(l.c_str());
}
if (sound == nullptr) {
throw std::runtime_error("Failed to decode audio file");
}
sounds_.emplace_back(SoundResource{.name = name, .sound = sound});
printWithDots("Sound : ", name, "[ LOADED ]");
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("SOUND", l, e);
}
}
// Carga las musicas
void Cache::loadMusics() { // NOLINT(readability-convert-member-functions-to-static)
std::cout << "\n>> MUSIC FILES" << '\n';
void Cache::loadOneMusic(size_t index) {
auto list = List::get()->getListByType(List::Type::MUSIC);
musics_.clear();
const auto& l = list[index];
try {
auto name = getFileName(l);
setCurrentLoading(name);
JA_Music_t* music = nullptr;
for (const auto& l : list) {
try {
auto name = getFileName(l);
JA_Music_t* music = nullptr;
// Try loading from resource pack first
auto audio_data = Helper::loadFile(l);
if (!audio_data.empty()) {
music = JA_LoadMusic(audio_data.data(), static_cast<Uint32>(audio_data.size()));
}
// Fallback to file path if memory loading failed
if (music == nullptr) {
music = JA_LoadMusic(l.c_str());
}
if (music == nullptr) {
throw std::runtime_error("Failed to decode music file");
}
musics_.emplace_back(MusicResource{.name = name, .music = music});
printWithDots("Music : ", name, "[ LOADED ]");
updateLoadingProgress(1);
} catch (const std::exception& e) {
throwLoadError("MUSIC", l, e);
auto audio_data = Helper::loadFile(l);
if (!audio_data.empty()) {
music = JA_LoadMusic(audio_data.data(), static_cast<Uint32>(audio_data.size()));
}
if (music == nullptr) {
music = JA_LoadMusic(l.c_str());
}
if (music == nullptr) {
throw std::runtime_error("Failed to decode music file");
}
musics_.emplace_back(MusicResource{.name = name, .music = music});
printWithDots("Music : ", name, "[ LOADED ]");
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("MUSIC", l, e);
}
}
// Carga las texturas
void Cache::loadSurfaces() { // NOLINT(readability-convert-member-functions-to-static)
std::cout << "\n>> SURFACES" << '\n';
void Cache::loadOneSurface(size_t index) {
auto list = List::get()->getListByType(List::Type::BITMAP);
surfaces_.clear();
for (const auto& l : list) {
try {
auto name = getFileName(l);
surfaces_.emplace_back(SurfaceResource{.name = name, .surface = std::make_shared<Surface>(l)});
surfaces_.back().surface->setTransparentColor(0);
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("BITMAP", l, e);
}
const auto& l = list[index];
try {
auto name = getFileName(l);
setCurrentLoading(name);
surfaces_.emplace_back(SurfaceResource{.name = name, .surface = std::make_shared<Surface>(l)});
surfaces_.back().surface->setTransparentColor(0);
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("BITMAP", l, e);
}
}
void Cache::finalizeSurfaces() {
// Reconfigura el color transparente de algunas surfaces
getSurface("loading_screen_color.gif")->setTransparentColor();
getSurface("ending1.gif")->setTransparentColor();
@@ -314,104 +471,132 @@ namespace Resource {
getSurface("standard.gif")->setTransparentColor(16);
}
// Carga las paletas
void Cache::loadPalettes() { // NOLINT(readability-convert-member-functions-to-static)
void Cache::loadOnePalette(size_t index) {
auto list = List::get()->getListByType(List::Type::PALETTE);
const auto& l = list[index];
try {
auto name = getFileName(l);
setCurrentLoading(name);
palettes_.emplace_back(ResourcePalette{.name = name, .palette = readPalFile(l)});
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("PALETTE", l, e);
}
}
void Cache::loadOneTextFile(size_t index) {
auto list = List::get()->getListByType(List::Type::FONT);
const auto& l = list[index];
try {
auto name = getFileName(l);
setCurrentLoading(name);
text_files_.emplace_back(TextFileResource{.name = name, .text_file = Text::loadTextFile(l)});
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("FONT", l, e);
}
}
void Cache::loadOneAnimation(size_t index) {
auto list = List::get()->getListByType(List::Type::ANIMATION);
const auto& l = list[index];
try {
auto name = getFileName(l);
setCurrentLoading(name);
auto yaml_bytes = Helper::loadFile(l);
if (yaml_bytes.empty()) {
throw std::runtime_error("File is empty or could not be loaded");
}
animations_.emplace_back(AnimationResource{.name = name, .yaml_data = yaml_bytes});
printWithDots("Animation : ", name, "[ LOADED ]");
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("ANIMATION", l, e);
}
}
void Cache::loadOneRoom(size_t index) {
auto list = List::get()->getListByType(List::Type::ROOM);
const auto& l = list[index];
try {
auto name = getFileName(l);
setCurrentLoading(name);
rooms_.emplace_back(RoomResource{.name = name, .room = std::make_shared<Room::Data>(Room::loadYAML(l))});
printWithDots("Room : ", name, "[ LOADED ]");
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("ROOM", l, e);
}
}
void Cache::createOneText(size_t index) {
const auto& infos = getTextObjectInfos();
const auto& res_info = infos[index];
texts_.emplace_back(TextResource{
.name = res_info.key,
.text = std::make_shared<Text>(getSurface(res_info.texture_file), getTextFile(res_info.text_file))});
printWithDots("Text : ", res_info.key, "[ DONE ]");
}
// --- Bucles completos (solo usados por reload() síncrono) ---
void Cache::loadSounds() {
std::cout << "\n>> SOUND FILES" << '\n';
auto list = List::get()->getListByType(List::Type::SOUND);
sounds_.clear();
for (size_t i = 0; i < list.size(); ++i) loadOneSound(i);
}
void Cache::loadMusics() {
std::cout << "\n>> MUSIC FILES" << '\n';
auto list = List::get()->getListByType(List::Type::MUSIC);
musics_.clear();
for (size_t i = 0; i < list.size(); ++i) loadOneMusic(i);
}
void Cache::loadSurfaces() {
std::cout << "\n>> SURFACES" << '\n';
auto list = List::get()->getListByType(List::Type::BITMAP);
surfaces_.clear();
for (size_t i = 0; i < list.size(); ++i) loadOneSurface(i);
finalizeSurfaces();
}
void Cache::loadPalettes() {
std::cout << "\n>> PALETTES" << '\n';
auto list = List::get()->getListByType(List::Type::PALETTE);
palettes_.clear();
for (const auto& l : list) {
try {
auto name = getFileName(l);
palettes_.emplace_back(ResourcePalette{.name = name, .palette = readPalFile(l)});
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("PALETTE", l, e);
}
}
for (size_t i = 0; i < list.size(); ++i) loadOnePalette(i);
}
// Carga los ficheros de texto
void Cache::loadTextFiles() { // NOLINT(readability-convert-member-functions-to-static)
void Cache::loadTextFiles() {
std::cout << "\n>> TEXT FILES" << '\n';
auto list = List::get()->getListByType(List::Type::FONT);
text_files_.clear();
for (const auto& l : list) {
try {
auto name = getFileName(l);
text_files_.emplace_back(TextFileResource{.name = name, .text_file = Text::loadTextFile(l)});
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("FONT", l, e);
}
}
for (size_t i = 0; i < list.size(); ++i) loadOneTextFile(i);
}
// Carga las animaciones
void Cache::loadAnimations() { // NOLINT(readability-convert-member-functions-to-static)
void Cache::loadAnimations() {
std::cout << "\n>> ANIMATIONS" << '\n';
auto list = List::get()->getListByType(List::Type::ANIMATION);
animations_.clear();
for (const auto& l : list) {
try {
auto name = getFileName(l);
// Cargar bytes del archivo YAML sin parsear (carga lazy)
auto yaml_bytes = Helper::loadFile(l);
if (yaml_bytes.empty()) {
throw std::runtime_error("File is empty or could not be loaded");
}
animations_.emplace_back(AnimationResource{.name = name, .yaml_data = yaml_bytes});
printWithDots("Animation : ", name, "[ LOADED ]");
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("ANIMATION", l, e);
}
}
for (size_t i = 0; i < list.size(); ++i) loadOneAnimation(i);
}
// Carga las habitaciones desde archivos YAML
void Cache::loadRooms() { // NOLINT(readability-convert-member-functions-to-static)
void Cache::loadRooms() {
std::cout << "\n>> ROOMS" << '\n';
auto list = List::get()->getListByType(List::Type::ROOM);
rooms_.clear();
for (const auto& l : list) {
try {
auto name = getFileName(l);
rooms_.emplace_back(RoomResource{.name = name, .room = std::make_shared<Room::Data>(Room::loadYAML(l))});
printWithDots("Room : ", name, "[ LOADED ]");
updateLoadingProgress();
} catch (const std::exception& e) {
throwLoadError("ROOM", l, e);
}
}
for (size_t i = 0; i < list.size(); ++i) loadOneRoom(i);
}
void Cache::createText() { // NOLINT(readability-convert-member-functions-to-static)
struct ResourceInfo {
std::string key; // Identificador del recurso
std::string texture_file; // Nombre del archivo de textura
std::string text_file; // Nombre del archivo de texto
};
void Cache::createText() {
std::cout << "\n>> CREATING TEXT_OBJECTS" << '\n';
std::vector<ResourceInfo> resources = {
{.key = "aseprite", .texture_file = "aseprite.gif", .text_file = "aseprite.fnt"},
{.key = "gauntlet", .texture_file = "gauntlet.gif", .text_file = "gauntlet.fnt"},
{.key = "smb2", .texture_file = "smb2.gif", .text_file = "smb2.fnt"},
{.key = "subatomic", .texture_file = "subatomic.gif", .text_file = "subatomic.fnt"},
{.key = "8bithud", .texture_file = "8bithud.gif", .text_file = "8bithud.fnt"}};
for (const auto& res_info : resources) {
texts_.emplace_back(TextResource{.name = res_info.key, .text = std::make_shared<Text>(getSurface(res_info.texture_file), getTextFile(res_info.text_file))});
printWithDots("Text : ", res_info.key, "[ DONE ]");
}
texts_.clear();
const auto& infos = getTextObjectInfos();
for (size_t i = 0; i < infos.size(); ++i) createOneText(i);
}
// Vacía el vector de sonidos
@@ -501,33 +686,28 @@ namespace Resource {
SDL_FRect rect_full = {.x = X_PADDING, .y = BAR_POSITION, .w = FULL_BAR_WIDTH, .h = BAR_HEIGHT};
surface->fillRect(&rect_full, BAR_COLOR);
// Mostra el nom del recurs que està a punt de carregar-se, centrat sobre la barra
if (!current_loading_name_.empty()) {
const float TEXT_Y = BAR_POSITION - static_cast<float>(TEXT_HEIGHT) - 2.0F;
loading_text_->writeColored(
CENTER_X - (loading_text_->length(current_loading_name_) / 2),
static_cast<int>(TEXT_Y),
current_loading_name_,
LOADING_TEXT_COLOR);
}
Screen::get()->render();
}
// Comprueba los eventos de la pantalla de carga
void Cache::checkEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_EVENT_QUIT:
exit(0);
break;
case SDL_EVENT_KEY_DOWN:
if (event.key.key == SDLK_ESCAPE) {
exit(0);
}
break;
}
}
// Guarda el nombre del recurso que se está a punto de cargar. El repintado
// lo hace el BootLoader (una vez por frame) — aquí solo se actualiza el estado.
void Cache::setCurrentLoading(const std::string& name) {
current_loading_name_ = name;
}
// Actualiza el progreso de carga
void Cache::updateLoadingProgress(int steps) {
// Incrementa el contador de recursos cargados
void Cache::updateLoadingProgress() {
count_.add(1);
if (count_.loaded % steps == 0 || count_.loaded == count_.total) {
renderProgress();
}
checkEvents();
}
} // namespace Resource

View File

@@ -25,7 +25,13 @@ namespace Resource {
auto getRoom(const std::string& name) -> std::shared_ptr<Room::Data>;
auto getRooms() -> std::vector<RoomResource>&;
void reload(); // Recarga todos los recursos
// --- Incremental loading (Director drives this from iterate()) ---
void beginLoad(); // Prepara el estado del loader incremental
auto loadStep(int budget_ms) -> bool; // Carga assets durante budget_ms; devuelve true si ha terminado
void renderProgress(); // Dibuja la barra de progreso (usada por BootLoader)
[[nodiscard]] auto isLoadDone() const -> bool;
void reload(); // Recarga todos los recursos (síncrono, usado en hot-reload de debug)
#ifdef _DEBUG
void reloadRoom(const std::string& name); // Recarga una habitación desde disco
#endif
@@ -47,7 +53,21 @@ namespace Resource {
}
};
// Métodos de carga de recursos
// Etapas del loader incremental
enum class LoadStage {
SOUNDS,
MUSICS,
SURFACES,
SURFACES_POST, // Ajuste de transparent colors tras cargar todas las surfaces
PALETTES,
TEXT_FILES,
ANIMATIONS,
ROOMS,
TEXTS,
DONE
};
// Métodos de carga de recursos (bucle completo, usados por reload() síncrono)
void loadSounds();
void loadMusics();
void loadSurfaces();
@@ -57,17 +77,27 @@ namespace Resource {
void loadRooms();
void createText();
// Helpers incrementales: cargan un único asset de la categoría correspondiente
void loadOneSound(size_t index);
void loadOneMusic(size_t index);
void loadOneSurface(size_t index);
void finalizeSurfaces(); // Ajuste de transparent colors tras cargar surfaces
void loadOnePalette(size_t index);
void loadOneTextFile(size_t index);
void loadOneAnimation(size_t index);
void loadOneRoom(size_t index);
void createOneText(size_t index);
// Métodos de limpieza
void clear();
void clearSounds();
void clearMusics();
// Métodos de gestión de carga
void load();
void load(); // Carga completa síncrona (usado solo por reload())
void calculateTotal();
void renderProgress();
static void checkEvents();
void updateLoadingProgress(int steps = 5);
void updateLoadingProgress();
void setCurrentLoading(const std::string& name); // Desa el nom del recurs en curs
// Helper para mensajes de error de carga
[[noreturn]] static void throwLoadError(const std::string& asset_type, const std::string& file_path, const std::exception& e);
@@ -91,6 +121,11 @@ namespace Resource {
ResourceCount count_{}; // Contador de recursos
std::shared_ptr<Text> loading_text_; // Texto para la pantalla de carga
std::string current_loading_name_; // Nom del recurs que s'està a punt de carregar
// Estado del loader incremental
LoadStage stage_{LoadStage::DONE}; // Arranca en DONE hasta que beginLoad() lo cambie
size_t stage_index_{0}; // Cursor dentro de la categoría actual
};
} // namespace Resource

View File

@@ -23,6 +23,7 @@
#include "game/gameplay/cheevos.hpp" // Para Cheevos
#include "game/options.hpp" // Para Options, options, OptionsVideo
#include "game/scene_manager.hpp" // Para SceneManager
#include "game/scenes/boot_loader.hpp" // Para BootLoader
#include "game/scenes/credits.hpp" // Para Credits
#include "game/scenes/ending.hpp" // Para Ending
#include "game/scenes/ending2.hpp" // Para Ending2
@@ -40,7 +41,7 @@
#include "game/editor/map_editor.hpp" // Para MapEditor
#endif
#ifndef _WIN32
#if !defined(_WIN32) && !defined(__EMSCRIPTEN__)
#include <pwd.h>
#endif
@@ -48,12 +49,17 @@
Director::Director() {
std::cout << "Game start" << '\n';
#ifdef __EMSCRIPTEN__
// En Emscripten els assets estan al root del filesystem virtual (/data, /config)
executable_path_ = "";
#else
// Obtiene la ruta del ejecutable
std::string base = SDL_GetBasePath();
if (!base.empty() && base.back() == '/') {
base.pop_back();
}
executable_path_ = base;
#endif
// Crea la carpeta del sistema donde guardar datos
createSystemFolder("jailgames");
@@ -83,7 +89,7 @@ Director::Director() {
// Preparar ruta al pack (en macOS bundle está en Contents/Resources/)
std::string pack_path = executable_path_ + PREFIX + "/resources.pack";
#ifdef RELEASE_BUILD
#if defined(RELEASE_BUILD) && !defined(__EMSCRIPTEN__)
// ============================================================
// RELEASE BUILD: Pack-first architecture
// ============================================================
@@ -141,6 +147,18 @@ Director::Director() {
Options::setConfigFile(Resource::List::get()->get("config.yaml")); // NOLINT(readability-static-accessed-through-instance)
Options::loadFromFile();
#ifdef __EMSCRIPTEN__
// A la versió web el navegador gestiona la finestra: forcem zoom x3
// perquè la textura 256x192 no es vegi minúscula al canvas HTML,
// i desactivem el borde per aprofitar al màxim l'espai del canvas.
Options::video.fullscreen = false;
Options::video.integer_scale = true;
Options::window.zoom = 4;
Options::video.border.enabled = true;
Options::video.border.height = 8;
Options::video.border.width = 8;
#endif
// Configura la ruta y carga los presets de PostFX
Options::setPostFXFile(Resource::List::get()->get("postfx.yaml")); // NOLINT(readability-static-accessed-through-instance)
Options::loadPostFXFromFile();
@@ -160,15 +178,15 @@ Director::Director() {
// Crea los objetos
Screen::init();
// Initialize resources (works for both release and development)
// Inicializa el singleton del cache sin disparar la carga. La carga real
// la hace Director::iterate() llamando a Cache::loadStep() en cada frame,
// de forma que la ventana, los eventos y la barra de progreso están vivos
// desde el primer tick.
Resource::Cache::init();
Notifier::init("", "8bithud");
RenderInfo::init();
Console::init("8bithud");
Screen::get()->setNotificationsEnabled(true);
Resource::Cache::get()->beginLoad();
// Special handling for gamecontrollerdb.txt - SDL needs filesystem path
#ifdef RELEASE_BUILD
#if defined(RELEASE_BUILD) && !defined(__EMSCRIPTEN__)
// In release, construct the path manually (not from Asset which has empty executable_path)
std::string gamecontroller_db = executable_path_ + PREFIX + "/gamecontrollerdb.txt";
Input::init(gamecontroller_db);
@@ -181,18 +199,41 @@ Director::Director() {
Input::get()->applyKeyboardBindingsFromOptions();
Input::get()->applyGamepadBindingsFromOptions();
std::cout << "\n"; // Fin de inicialización mínima de sistemas
// Construeix l'escena inicial (BootLoader). finishBoot() la canviarà a
// LOGO (o la que digui Debug) quan Cache::loadStep() complete la càrrega.
SceneManager::current = SceneManager::Scene::BOOT_LOADER;
switchToActiveScene();
}
// Inicialitzacions que depenen del cache poblat. Es crida des d'iterate()
// just quan Cache::loadStep() retorna true, amb la finestra i el bucle ja vius.
void Director::finishBoot() {
Notifier::init("", "8bithud");
RenderInfo::init();
Console::init("8bithud");
Screen::get()->setNotificationsEnabled(true);
#ifdef _DEBUG
Debug::init();
#ifdef __EMSCRIPTEN__
// A wasm el debug.yaml viu a SYSTEM_FOLDER (MEMFS no persistent) i no està
// disponible. Saltem el loadFromFile i entrem directament a la GAME.
SceneManager::current = SceneManager::Scene::GAME;
#else
Debug::get()->setDebugFile(Resource::List::get()->get("debug.yaml"));
Debug::get()->loadFromFile();
SceneManager::current = Debug::get()->getInitialScene();
#endif
MapEditor::init();
#else
// En release, pasamos a LOGO siempre tras la carga
SceneManager::current = SceneManager::Scene::LOGO;
#endif
std::cout << "\n"; // Fin de inicialización de sistemas
// Inicializa el sistema de localización (antes de Cheevos que usa textos traducidos)
#ifdef RELEASE_BUILD
#if defined(RELEASE_BUILD) && !defined(__EMSCRIPTEN__)
{
// En release el locale está en el pack, no en el filesystem
std::string locale_key = Resource::List::get()->get(Options::language + ".yaml"); // NOLINT(readability-static-accessed-through-instance)
@@ -205,7 +246,7 @@ Director::Director() {
#endif
// Special handling for cheevos.bin - also needs filesystem path
#ifdef RELEASE_BUILD
#if defined(RELEASE_BUILD) && !defined(__EMSCRIPTEN__)
std::string cheevos_path = system_folder_ + "/cheevos.bin";
Cheevos::init(cheevos_path);
#else
@@ -217,6 +258,11 @@ Director::~Director() {
// Guarda las opciones a un fichero
Options::saveToFile();
// Destruir l'escena activa ABANS dels singletons. Si no, el unique_ptr membre
// destrueix l'escena al final del destructor — quan Audio, Screen, Resource...
// ja són morts — i qualsevol accés en els seus destructors és un UAF.
active_scene_.reset();
// Destruye los singletones
Cheevos::destroy();
Locale::destroy();
@@ -241,6 +287,12 @@ Director::~Director() {
// Crea la carpeta del sistema donde guardar datos
void Director::createSystemFolder(const std::string& folder) { // NOLINT(readability-convert-member-functions-to-static)
#ifdef __EMSCRIPTEN__
// En Emscripten utilitzem MEMFS (no persistent entre sessions).
// No cal crear directoris: MEMFS els crea automàticament en escriure-hi.
system_folder_ = "/config/" + folder;
return;
#else
#ifdef _WIN32
system_folder_ = std::string(getenv("APPDATA")) + "/" + folder;
#elif __APPLE__
@@ -292,6 +344,7 @@ void Director::createSystemFolder(const std::string& folder) { // NOLINT(readab
}
}
}
#endif // __EMSCRIPTEN__
}
// Carga la configuración de assets desde assets.yaml
@@ -311,118 +364,117 @@ void Director::setFileList() { // NOLINT(readability-convert-member-functions-t
Resource::List::get()->loadFromFile(config_path, PREFIX, system_folder_);
}
// Ejecuta la seccion de juego con el logo
void Director::runLogo() {
auto logo = std::make_unique<Logo>();
logo->run();
// Construeix l'escena segons SceneManager::current i la deixa en active_scene_.
// Substitueix els vells runLogo(), runTitle(), runGame(), etc.
void Director::switchToActiveScene() {
// Si la escena anterior va demanar RESTART_CURRENT, restaurem la que estava activa
if (SceneManager::current == SceneManager::Scene::RESTART_CURRENT) {
SceneManager::current = SceneManager::scene_before_restart;
}
// Destrueix l'escena anterior (pot parar música, etc. al seu destructor)
active_scene_.reset();
switch (SceneManager::current) {
case SceneManager::Scene::BOOT_LOADER:
active_scene_ = std::make_unique<BootLoader>();
break;
case SceneManager::Scene::LOGO:
active_scene_ = std::make_unique<Logo>();
break;
case SceneManager::Scene::LOADING_SCREEN:
active_scene_ = std::make_unique<LoadingScreen>();
break;
case SceneManager::Scene::TITLE:
active_scene_ = std::make_unique<Title>();
break;
case SceneManager::Scene::CREDITS:
active_scene_ = std::make_unique<Credits>();
break;
case SceneManager::Scene::DEMO:
active_scene_ = std::make_unique<Game>(Game::Mode::DEMO);
break;
case SceneManager::Scene::GAME:
Audio::get()->stopMusic();
active_scene_ = std::make_unique<Game>(Game::Mode::GAME);
break;
case SceneManager::Scene::GAME_OVER:
active_scene_ = std::make_unique<GameOver>();
break;
case SceneManager::Scene::ENDING:
active_scene_ = std::make_unique<Ending>();
break;
case SceneManager::Scene::ENDING2:
active_scene_ = std::make_unique<Ending2>();
break;
default:
break;
}
current_scene_ = SceneManager::current;
}
// Ejecuta la seccion de juego de la pantalla de carga
void Director::runLoadingScreen() {
auto loading_screen = std::make_unique<LoadingScreen>();
loading_screen->run();
}
// SDL_AppIterate: executa un frame de l'escena activa
auto Director::iterate() -> SDL_AppResult {
if (SceneManager::current == SceneManager::Scene::QUIT) {
return SDL_APP_SUCCESS;
}
// Ejecuta la seccion de juego con el titulo y los menus
void Director::runTitle() {
auto title = std::make_unique<Title>();
title->run();
}
// Ejecuta la seccion de los creditos del juego
void Director::runCredits() {
auto credits = std::make_unique<Credits>();
credits->run();
}
// Ejecuta la seccion de la demo, donde se ven pantallas del juego
void Director::runDemo() {
auto game = std::make_unique<Game>(Game::Mode::DEMO);
game->run();
}
// Ejecuta la seccion del final del juego
void Director::runEnding() {
auto ending = std::make_unique<Ending>();
ending->run();
}
// Ejecuta la seccion del final del juego
void Director::runEnding2() {
auto ending2 = std::make_unique<Ending2>();
ending2->run();
}
// Ejecuta la seccion del final de la partida
void Director::runGameOver() {
auto game_over = std::make_unique<GameOver>();
game_over->run();
}
// Ejecuta la seccion de juego donde se juega
void Director::runGame() {
Audio::get()->stopMusic();
auto game = std::make_unique<Game>(Game::Mode::GAME);
game->run();
}
auto Director::run() -> int {
// Bucle principal
while (SceneManager::current != SceneManager::Scene::QUIT) {
const SceneManager::Scene ACTIVE = SceneManager::current;
switch (SceneManager::current) {
case SceneManager::Scene::LOGO:
runLogo();
break;
case SceneManager::Scene::LOADING_SCREEN:
runLoadingScreen();
break;
case SceneManager::Scene::TITLE:
runTitle();
break;
case SceneManager::Scene::CREDITS:
runCredits();
break;
case SceneManager::Scene::DEMO:
runDemo();
break;
case SceneManager::Scene::GAME:
runGame();
break;
case SceneManager::Scene::GAME_OVER:
runGameOver();
break;
case SceneManager::Scene::ENDING:
runEnding();
break;
case SceneManager::Scene::ENDING2:
runEnding2();
break;
case SceneManager::Scene::RESTART_CURRENT:
// La escena salió por RESTART_CURRENT → relanzar la escena guardada
SceneManager::current = SceneManager::scene_before_restart;
break;
default:
break;
}
// Si la escena que acaba de correr dejó RESTART_CURRENT pendiente,
// restaurar la escena que estaba activa para relanzarla en la próxima iteración
if (SceneManager::current == SceneManager::Scene::RESTART_CURRENT) {
SceneManager::current = ACTIVE;
// Fase de boot: anem cridant loadStep() fins que el cache estiga ple.
// Durant aquesta fase l'escena activa és BootLoader (una barra de progrés).
if (boot_loading_) {
try {
// Budget de 50ms: durant el boot el joc va a ~15-20 FPS, suficient
// per veure la barra avançar suau i processar events del WM/ESC,
// i evita el 50% d'ineficiència que provocaria un budget < vsync.
if (Resource::Cache::get()->loadStep(50 /*ms*/)) {
finishBoot();
boot_loading_ = false;
// finishBoot() ja ha fixat SceneManager::current a LOGO (o la que
// digui Debug). El canvi d'escena es fa just a sota.
}
} catch (const std::exception& e) {
std::cerr << "Fatal error during resource load: " << e.what() << '\n';
SceneManager::current = SceneManager::Scene::QUIT;
return SDL_APP_FAILURE;
}
}
return 0;
// Si l'escena ha canviat (o s'ha demanat RESTART_CURRENT), canviar-la abans del frame
if (SceneManager::current != current_scene_ || SceneManager::current == SceneManager::Scene::RESTART_CURRENT) {
switchToActiveScene();
}
if (active_scene_) {
active_scene_->iterate();
}
return SDL_APP_CONTINUE;
}
// SDL_AppEvent: despatxa un event a l'escena activa
auto Director::handleEvent(const SDL_Event& event) -> SDL_AppResult {
#ifndef __EMSCRIPTEN__
// A la versió web no tenim event de quit del navegador
if (event.type == SDL_EVENT_QUIT) {
SceneManager::current = SceneManager::Scene::QUIT;
return SDL_APP_SUCCESS;
}
#endif
if (active_scene_) {
active_scene_->handleEvent(event);
}
return SDL_APP_CONTINUE;
}

View File

@@ -2,29 +2,33 @@
#include <SDL3/SDL.h>
#include <memory> // Para unique_ptr
#include <string> // Para string
#include "game/scene_manager.hpp" // Para SceneManager::Scene
#include "game/scenes/scene.hpp" // Para Scene base
class Director {
public:
Director(); // Constructor
~Director(); // Destructor
static auto run() -> int; // Bucle principal
Director(); // Constructor: inicialitza sistemes i crea l'escena inicial
~Director(); // Destructor
// SDL3 Callback API: un frame i un event
auto iterate() -> SDL_AppResult;
auto handleEvent(const SDL_Event& event) -> SDL_AppResult;
private:
// --- Variables ---
std::string executable_path_; // Path del ejecutable
std::string system_folder_; // Carpeta del sistema donde guardar datos
std::unique_ptr<Scene> active_scene_; // Escena activa
SceneManager::Scene current_scene_{SceneManager::Scene::BOOT_LOADER}; // Tipus d'escena activa
bool boot_loading_{true}; // True mientras Cache::loadStep() no haya acabado
// --- Funciones ---
void createSystemFolder(const std::string& folder); // Crea la carpeta del sistema donde guardar datos
void setFileList(); // Carga la configuración de assets desde assets.yaml
static void runLogo(); // Ejecuta la seccion de juego con el logo
static void runLoadingScreen(); // Ejecuta la seccion de juego de la pantalla de carga
static void runTitle(); // Ejecuta la seccion de juego con el titulo y los menus
static void runCredits(); // Ejecuta la seccion de los creditos del juego
static void runDemo(); // Ejecuta la seccion de la demo, donde se ven pantallas del juego
static void runEnding(); // Ejecuta la seccion del final del juego
static void runEnding2(); // Ejecuta la seccion del final del juego
static void runGameOver(); // Ejecuta la seccion del final de la partida
static void runGame(); // Ejecuta la seccion de juego donde se juega
};
void switchToActiveScene(); // Construeix l'escena segons SceneManager::current
void finishBoot(); // Inits que dependen del cache, ejecutado tras loadStep==done
};

View File

@@ -1,23 +1,65 @@
#include "core/system/global_events.hpp"
#include "core/input/input.hpp" // Para Input (gamepad add/remove)
#include "core/input/mouse.hpp"
#include "core/locale/locale.hpp" // Para Locale
#include "game/options.hpp" // Para Options, options, OptionsGame, OptionsAudio
#include "game/scene_manager.hpp" // Para SceneManager
#include "game/scene_manager.hpp" // Para SceneManager::current (filtrar BACK a GAME)
#include "game/ui/console.hpp" // Para Console
#include "game/ui/notifier.hpp" // Para Notifier
namespace GlobalEvents {
// Comprueba los eventos que se pueden producir en cualquier sección del juego
void handle(const SDL_Event& event) {
// Evento de salida de la aplicación
if (event.type == SDL_EVENT_QUIT) {
SceneManager::current = SceneManager::Scene::QUIT;
return;
}
namespace {
// Flag per saber si en aquest frame s'ha rebut un button down del gamepad.
// El consumeix GlobalInputs perquè un botó del comandament salti escenes.
bool gamepad_button_pressed_ = false;
} // namespace
// Comprueba los eventos que se pueden producir en cualquier sección del juego.
// Nota: SDL_EVENT_QUIT el gestiona Director::handleEvent() directament.
void handle(const SDL_Event& event) {
if (event.type == SDL_EVENT_RENDER_DEVICE_RESET || event.type == SDL_EVENT_RENDER_TARGETS_RESET) {
// reLoadTextures();
}
// Connexió/desconnexió de gamepads: cal enrutar-los a Input perquè
// afegisca el dispositiu a gamepads_. Sense això, en wasm els gamepads
// mai es detecten (la Gamepad API del navegador només els exposa
// després que l'usuari els active, més tard que el discoverGamepads
// inicial). En desktop també arregla la connexió en calent.
if (event.type == SDL_EVENT_GAMEPAD_ADDED || event.type == SDL_EVENT_GAMEPAD_REMOVED) {
if (Input::get() != nullptr) {
std::string name = Input::get()->handleEvent(event);
if (!name.empty() && Notifier::get() != nullptr && Locale::get() != nullptr) {
const std::string KEY = (event.type == SDL_EVENT_GAMEPAD_ADDED)
? "ui.gamepad_connected"
: "ui.gamepad_disconnected";
Notifier::get()->show({name + " " + Locale::get()->get(KEY)});
}
}
}
// Marcar polsació de qualsevol botó del comandament (els consumirà GlobalInputs
// per saltar escenes d'attract mode). Queden exclosos els botons reservats a
// accions globals perquè el "any button → ACCEPT" no se'ls mengi abans que
// checkAction() els pugui enrutar:
// - BACK → EXIT (a emscripten només a l'escena GAME, ja que no pot tancar).
// - LEFT_SHOULDER / RIGHT_SHOULDER → NEXT_PALETTE / NEXT_PALETTE_SORT.
if (event.type == SDL_EVENT_GAMEPAD_BUTTON_DOWN) {
const auto BUTTON = event.gbutton.button;
const bool IS_BACK = (BUTTON == SDL_GAMEPAD_BUTTON_BACK);
const bool IS_SHOULDER = (BUTTON == SDL_GAMEPAD_BUTTON_LEFT_SHOULDER || BUTTON == SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER);
#ifdef __EMSCRIPTEN__
const bool RESERVE_BACK = IS_BACK && SceneManager::current == SceneManager::Scene::GAME;
#else
const bool RESERVE_BACK = IS_BACK;
#endif
if (!RESERVE_BACK && !IS_SHOULDER) {
gamepad_button_pressed_ = true;
}
}
// Enrutar eventos de texto a la consola cuando está activa
if (Console::get() != nullptr && Console::get()->isActive()) {
if (event.type == SDL_EVENT_TEXT_INPUT || event.type == SDL_EVENT_KEY_DOWN) {
@@ -28,4 +70,10 @@ namespace GlobalEvents {
Mouse::handleEvent(event);
}
auto consumeGamepadButtonPressed() -> bool {
const bool RESULT = gamepad_button_pressed_;
gamepad_button_pressed_ = false;
return RESULT;
}
} // namespace GlobalEvents

View File

@@ -5,4 +5,9 @@
namespace GlobalEvents {
// Comprueba los eventos que se pueden producir en cualquier sección del juego
void handle(const SDL_Event& event);
// True si en aquest frame s'ha rebut un SDL_EVENT_GAMEPAD_BUTTON_DOWN.
// Es consumeix (i es reseteja) per GlobalInputs::getPressedAction perquè
// qualsevol botó del comandament actuï com a "ACCEPT" (saltar escena).
auto consumeGamepadButtonPressed() -> bool;
} // namespace GlobalEvents

View File

@@ -11,6 +11,7 @@ namespace SceneManager {
// --- Escenas del programa ---
enum class Scene {
BOOT_LOADER, // Carga inicial de recursos dirigida por iterate()
LOGO, // Pantalla del logo
LOADING_SCREEN, // Pantalla de carga
TITLE, // Pantalla de título/menú principal
@@ -34,7 +35,7 @@ namespace SceneManager {
};
// --- Variables de estado globales ---
inline Scene current = Scene::LOGO; // Escena actual (en _DEBUG sobrescrito por Director tras cargar debug.yaml)
inline Scene current = Scene::BOOT_LOADER; // Arranca siempre cargando recursos; Director conmuta a LOGO al terminar
inline Options options = Options::LOGO_TO_LOADING_SCREEN; // Opciones de la escena actual
inline Scene scene_before_restart = Scene::LOGO; // escena a relanzar tras RESTART_CURRENT

View File

@@ -0,0 +1,14 @@
#include "game/scenes/boot_loader.hpp"
#include "core/resources/resource_cache.hpp"
#include "game/scene_manager.hpp"
void BootLoader::iterate() {
Resource::Cache::get()->renderProgress();
}
void BootLoader::handleEvent(const SDL_Event& event) {
if (event.type == SDL_EVENT_QUIT) {
SceneManager::current = SceneManager::Scene::QUIT;
}
}

View File

@@ -0,0 +1,17 @@
#pragma once
#include <SDL3/SDL.h>
#include "game/scenes/scene.hpp"
// Escena mínima que Director usa mientras el cache se carga incrementalmente.
// No avanza la carga — lo hace Director::iterate() llamando a Cache::loadStep()
// antes de despachar la escena. Aquí solo se pinta la barra de progreso.
class BootLoader : public Scene {
public:
BootLoader() = default;
~BootLoader() override = default;
void iterate() override;
void handleEvent(const SDL_Event& event) override;
};

View File

@@ -37,12 +37,9 @@ Credits::Credits()
Audio::get()->playMusic("title.ogg"); // Inicia la musica
}
// Comprueba el manejador de eventos
void Credits::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
GlobalEvents::handle(event);
}
// Despatx d'un event (SDL3 Callback API)
void Credits::handleEvent(const SDL_Event& event) {
GlobalEvents::handle(event);
}
// Comprueba las entradas
@@ -124,8 +121,7 @@ void Credits::update() {
const float DELTA_TIME = delta_timer_->tick();
total_time_ += DELTA_TIME; // Actualiza el tiempo total
handleEvents(); // Comprueba los eventos
handleInput(); // Comprueba las entradas
handleInput(); // Comprueba las entradas
updateState(DELTA_TIME); // Actualiza la máquina de estados
@@ -238,10 +234,8 @@ void Credits::render() {
Screen::get()->render();
}
// Bucle para el logo del juego
void Credits::run() {
while (SceneManager::current == SceneManager::Scene::CREDITS) {
update();
render();
}
// Un frame de l'escena (SDL3 Callback API)
void Credits::iterate() {
update();
render();
}

View File

@@ -2,22 +2,25 @@
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include <string> // Para string
#include <vector> // Para vector
class AnimatedSprite; // lines 11-11
#include <memory> // Para shared_ptr
#include <string> // Para string
#include <vector> // Para vector
#include "game/scenes/scene.hpp" // Para Scene
class AnimatedSprite; // lines 11-11
class Surface;
class PixelReveal;
class DeltaTimer;
class Credits {
class Credits : public Scene {
public:
// --- Constructor y Destructor ---
Credits();
~Credits(); // NOLINT(modernize-use-equals-default, performance-trivially-destructible) -- defined in .cpp for unique_ptr with forward declarations
~Credits() override; // NOLINT(modernize-use-equals-default, performance-trivially-destructible) -- defined in .cpp for unique_ptr with forward declarations
// --- Bucle principal ---
void run();
// --- Bucle principal (SDL3 Callback API) ---
void iterate() override;
void handleEvent(const SDL_Event& event) override;
private:
// --- Tipos anidados ---
@@ -55,7 +58,6 @@ class Credits {
// --- Métodos privados ---
void update(); // Actualiza las variables
void render(); // Dibuja en pantalla
static void handleEvents(); // Comprueba el manejador de eventos
static void handleInput(); // Comprueba las entradas
void updateState(float delta_time); // Actualiza la máquina de estados
void transitionToState(State new_state); // Transición entre estados

View File

@@ -19,7 +19,9 @@
#include "utils/utils.hpp" // Para PaletteColor
// Destructor
Ending::~Ending() = default;
Ending::~Ending() {
Audio::get()->stopMusic();
}
// Constructor
Ending::Ending()
@@ -32,6 +34,7 @@ Ending::Ending()
iniScenes(); // Inicializa las escenas
Screen::get()->setBorderColor(static_cast<Uint8>(PaletteColor::BLACK)); // Cambia el color del borde
Audio::get()->playMusic("ending1.ogg");
}
// Actualiza el objeto
@@ -39,8 +42,7 @@ void Ending::update() {
const float DELTA_TIME = delta_timer_->tick();
total_time_ += DELTA_TIME; // Actualiza el tiempo total
handleEvents(); // Comprueba los eventos
handleInput(); // Comprueba las entradas
handleInput(); // Comprueba las entradas
updateState(DELTA_TIME); // Actualiza la máquina de estados
updateSpriteCovers(); // Actualiza las cortinillas de los elementos
@@ -86,12 +88,9 @@ void Ending::render() {
Screen::get()->render();
}
// Comprueba el manejador de eventos
void Ending::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
GlobalEvents::handle(event);
}
// Despatx d'un event (SDL3 Callback API)
void Ending::handleEvent(const SDL_Event& event) {
GlobalEvents::handle(event);
}
// Comprueba las entradas
@@ -355,16 +354,10 @@ void Ending::iniScenes() { // NOLINT(readability-convert-member-functions-to-st
scenes_.push_back(sc);
}
// Bucle principal
void Ending::run() {
Audio::get()->playMusic("ending1.ogg");
while (SceneManager::current == SceneManager::Scene::ENDING) {
update();
render();
}
Audio::get()->stopMusic();
// Un frame de l'escena (SDL3 Callback API)
void Ending::iterate() {
update();
render();
}
// Actualiza las cortinillas de los elementos

View File

@@ -5,19 +5,22 @@
#include <memory> // Para shared_ptr
#include <string> // Para string
#include <vector> // Para vector
class Sprite; // lines 8-8
class Surface; // lines 9-9
#include "game/scenes/scene.hpp" // Para Scene
class Sprite; // lines 8-8
class Surface; // lines 9-9
class PixelReveal;
class DeltaTimer;
class Ending {
class Ending : public Scene {
public:
// --- Constructor y Destructor ---
Ending();
~Ending(); // NOLINT(modernize-use-equals-default, performance-trivially-destructible) -- defined in .cpp for unique_ptr with forward declarations
~Ending() override; // NOLINT(modernize-use-equals-default, performance-trivially-destructible) -- defined in .cpp for unique_ptr with forward declarations
// --- Bucle principal ---
void run();
// --- Bucle principal (SDL3 Callback API) ---
void iterate() override;
void handleEvent(const SDL_Event& event) override;
private:
// --- Enumeraciones ---
@@ -77,7 +80,6 @@ class Ending {
// --- Métodos ---
void update(); // Actualiza el objeto
void render(); // Dibuja el final en pantalla
static void handleEvents(); // Comprueba el manejador de eventos
static void handleInput(); // Comprueba las entradas
void iniTexts(); // Inicializa los textos
void iniPics(); // Inicializa las imágenes

View File

@@ -41,14 +41,20 @@ Ending2::Ending2()
placeSprites(); // Coloca los sprites en su sito
createSpriteTexts(); // Crea los sprites con las texturas con los textos
createTexts(); // Crea los sprites con las texturas con los textos del final
Audio::get()->playMusic("ending2.ogg");
}
// Destructor
Ending2::~Ending2() {
Audio::get()->stopMusic();
}
// Actualiza el objeto
void Ending2::update() {
const float DELTA_TIME = delta_timer_->tick();
handleEvents(); // Comprueba los eventos
handleInput(); // Comprueba las entradas
handleInput(); // Comprueba las entradas
updateState(DELTA_TIME); // Actualiza el estado
@@ -95,12 +101,9 @@ void Ending2::render() {
Screen::get()->render();
}
// Comprueba el manejador de eventos
void Ending2::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
GlobalEvents::handle(event);
}
// Despatx d'un event (SDL3 Callback API)
void Ending2::handleEvent(const SDL_Event& event) {
GlobalEvents::handle(event);
}
// Comprueba las entradas
@@ -109,16 +112,10 @@ void Ending2::handleInput() {
GlobalInputs::handle();
}
// Bucle principal
void Ending2::run() {
Audio::get()->playMusic("ending2.ogg");
while (SceneManager::current == SceneManager::Scene::ENDING2) {
update();
render();
}
Audio::get()->stopMusic();
// Un frame de l'escena (SDL3 Callback API)
void Ending2::iterate() {
update();
render();
}
// Actualiza el estado

View File

@@ -7,19 +7,21 @@
#include <vector> // Para vector
#include "core/rendering/sprite/dissolve_sprite.hpp" // Para SurfaceDissolveSprite
#include "game/scenes/scene.hpp" // Para Scene
#include "utils/defines.hpp" // Para GameCanvas::WIDTH, GameCanvas::FIRST_QUAR...
class MovingSprite;
class DeltaTimer;
class Ending2 {
class Ending2 : public Scene {
public:
// --- Constructor y Destructor ---
Ending2();
~Ending2() = default;
~Ending2() override;
// --- Bucle principal ---
void run();
// --- Bucle principal (SDL3 Callback API) ---
void iterate() override;
void handleEvent(const SDL_Event& event) override;
private:
// --- Enumeraciones ---
@@ -58,7 +60,6 @@ class Ending2 {
// --- Métodos ---
void update(); // Actualiza el objeto
void render(); // Dibuja el final en pantalla
static void handleEvents(); // Comprueba el manejador de eventos
static void handleInput(); // Comprueba las entradas
void updateState(float delta_time); // Actualiza el estado
void transitionToState(EndingState new_state); // Transición entre estados

View File

@@ -163,9 +163,19 @@ Game::Game(Mode mode)
SceneManager::current = (mode_ == Mode::GAME) ? SceneManager::Scene::GAME : SceneManager::Scene::DEMO;
SceneManager::options = SceneManager::Options::NONE;
// Arranca la música del juego (abans a run())
keepMusicPlaying();
if (!scoreboard_data_->music && mode_ == Mode::GAME) {
Audio::get()->pauseMusic();
}
}
Game::~Game() {
if (mode_ == Mode::GAME) {
Audio::get()->stopMusic();
}
ItemTracker::destroy();
GameControl::change_player_skin = nullptr;
@@ -188,38 +198,35 @@ Game::~Game() {
#endif
}
// Comprueba los eventos de la cola
void Game::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
GlobalEvents::handle(event);
// Despatx d'un event (SDL3 Callback API)
void Game::handleEvent(const SDL_Event& event) {
GlobalEvents::handle(event);
#ifdef _DEBUG
// En modo editor: click del ratón cierra la consola
if (Console::get()->isActive() && MapEditor::get()->isActive() &&
event.type == SDL_EVENT_MOUSE_BUTTON_DOWN) {
Console::get()->toggle();
}
if (!Console::get()->isActive()) {
// Tecla 9: toggle editor (funciona tanto dentro como fuera del editor)
if (event.type == SDL_EVENT_KEY_DOWN && event.key.key == SDLK_9 && static_cast<int>(event.key.repeat) == 0) {
if (MapEditor::get()->isActive()) {
GameControl::exit_editor();
Notifier::get()->show({Locale::get()->get("game.editor_disabled")}); // NOLINT(readability-static-accessed-through-instance)
} else {
GameControl::enter_editor();
Notifier::get()->show({Locale::get()->get("game.editor_enabled")}); // NOLINT(readability-static-accessed-through-instance)
}
} else if (event.type == SDL_EVENT_KEY_DOWN && event.key.key == SDLK_8 && static_cast<int>(event.key.repeat) == 0 && MapEditor::get()->isActive()) {
MapEditor::get()->showGrid(!MapEditor::get()->isGridEnabled());
} else if (MapEditor::get()->isActive()) {
MapEditor::get()->handleEvent(event);
} else {
handleDebugEvents(event);
}
}
#endif
// En modo editor: click del ratón cierra la consola
if (Console::get()->isActive() && MapEditor::get()->isActive() &&
event.type == SDL_EVENT_MOUSE_BUTTON_DOWN) {
Console::get()->toggle();
}
if (!Console::get()->isActive()) {
// Tecla 9: toggle editor (funciona tanto dentro como fuera del editor)
if (event.type == SDL_EVENT_KEY_DOWN && event.key.key == SDLK_9 && static_cast<int>(event.key.repeat) == 0) {
if (MapEditor::get()->isActive()) {
GameControl::exit_editor();
Notifier::get()->show({Locale::get()->get("game.editor_disabled")}); // NOLINT(readability-static-accessed-through-instance)
} else {
GameControl::enter_editor();
Notifier::get()->show({Locale::get()->get("game.editor_enabled")}); // NOLINT(readability-static-accessed-through-instance)
}
} else if (event.type == SDL_EVENT_KEY_DOWN && event.key.key == SDLK_8 && static_cast<int>(event.key.repeat) == 0 && MapEditor::get()->isActive()) {
MapEditor::get()->showGrid(!MapEditor::get()->isGridEnabled());
} else if (MapEditor::get()->isActive()) {
MapEditor::get()->handleEvent(event);
} else {
handleDebugEvents(event);
}
}
#endif
}
// Comprueba el teclado
@@ -262,29 +269,17 @@ void Game::handleInput() {
GlobalInputs::handle();
}
// Bucle para el juego
void Game::run() {
keepMusicPlaying();
if (!scoreboard_data_->music && mode_ == Mode::GAME) {
Audio::get()->pauseMusic();
}
while (SceneManager::current == SceneManager::Scene::GAME || SceneManager::current == SceneManager::Scene::DEMO) {
update();
render();
}
if (mode_ == Mode::GAME) {
Audio::get()->stopMusic();
}
// Un frame de l'escena (SDL3 Callback API)
void Game::iterate() {
update();
render();
}
// Actualiza el juego, las variables, comprueba la entrada, etc.
void Game::update() {
const float DELTA_TIME = delta_timer_.tick();
handleEvents(); // Comprueba los eventos
handleInput(); // Comprueba las entradas
handleInput(); // Comprueba las entradas
#ifdef _DEBUG
Debug::get()->clear();

View File

@@ -8,6 +8,7 @@
#include <vector> // Para vector
#include "game/entities/player.hpp" // Para PlayerSpawn
#include "game/scenes/scene.hpp" // Para Scene
#include "utils/delta_timer.hpp" // Para DeltaTimer
class Room; // lines 12-12
class RoomTracker; // lines 13-13
@@ -15,7 +16,7 @@ class Scoreboard; // lines 14-14
class Stats; // lines 15-15
class Surface;
class Game {
class Game : public Scene {
public:
// --- Estructuras ---
enum class Mode {
@@ -33,10 +34,11 @@ class Game {
// --- Constructor y Destructor ---
explicit Game(Mode mode);
~Game();
~Game() override;
// --- Bucle para el juego ---
void run();
// --- Bucle para el juego (SDL3 Callback API) ---
void iterate() override;
void handleEvent(const SDL_Event& event) override;
private:
// --- Constantes de tiempo ---
@@ -57,7 +59,6 @@ class Game {
// --- Métodos ---
void update(); // Actualiza el juego, las variables, comprueba la entrada, etc.
void render(); // Pinta los objetos en pantalla
void handleEvents(); // Comprueba los eventos de la cola
void renderRoomName(); // Escribe el nombre de la pantalla
void transitionToState(State new_state); // Cambia al estado especificado y resetea los timers
void updatePlaying(float delta_time); // Actualiza el juego en estado PLAYING

View File

@@ -49,8 +49,7 @@ void GameOver::update() {
const float DELTA_TIME = delta_timer_->tick();
elapsed_time_ += DELTA_TIME;
handleEvents(); // Comprueba los eventos
handleInput(); // Comprueba las entradas
handleInput(); // Comprueba las entradas
updateState(); // Actualiza el estado de la escena
updateColor(); // Actualiza el color usado para renderizar los textos e imagenes
@@ -91,12 +90,9 @@ void GameOver::render() {
Screen::get()->render();
}
// Comprueba el manejador de eventos
void GameOver::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
GlobalEvents::handle(event);
}
// Despatx d'un event (SDL3 Callback API)
void GameOver::handleEvent(const SDL_Event& event) {
GlobalEvents::handle(event);
}
// Comprueba las entradas
@@ -105,12 +101,10 @@ void GameOver::handleInput() {
GlobalInputs::handle();
}
// Bucle principal
void GameOver::run() {
while (SceneManager::current == SceneManager::Scene::GAME_OVER) {
update();
render();
}
// Un frame de l'escena (SDL3 Callback API)
void GameOver::iterate() {
update();
render();
}
// Actualiza el color usado para renderizar los textos e imagenes

View File

@@ -2,19 +2,22 @@
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include <vector> // Para vector
class AnimatedSprite; // lines 7-7
class DeltaTimer; // Forward declaration
#include <memory> // Para shared_ptr
#include <vector> // Para vector
class GameOver {
#include "game/scenes/scene.hpp" // Para Scene
class AnimatedSprite; // lines 7-7
class DeltaTimer; // Forward declaration
class GameOver : public Scene {
public:
// Constructor y Destructor
GameOver();
~GameOver() = default;
~GameOver() override = default;
// Bucle principal
void run();
// Bucle principal (SDL3 Callback API)
void iterate() override;
void handleEvent(const SDL_Event& event) override;
private:
// --- Enumeraciones ---
@@ -45,13 +48,12 @@ class GameOver {
static constexpr int NIGHTMARE_TEXT_Y_OFFSET = 120; // Offset Y del texto nightmare desde TEXT_Y
// --- Métodos ---
void update(); // Actualiza el objeto
void render(); // Dibuja el final en pantalla
static void handleEvents(); // Comprueba el manejador de eventos
static void handleInput(); // Comprueba las entradas
void updateState(); // Actualiza el estado y transiciones
void updateColor(); // Actualiza el color usado para renderizar
void renderSprites(); // Dibuja los sprites
void update(); // Actualiza el objeto
void render(); // Dibuja el final en pantalla
static void handleInput(); // Comprueba las entradas
void updateState(); // Actualiza el estado y transiciones
void updateColor(); // Actualiza el color usado para renderizar
void renderSprites(); // Dibuja los sprites
// --- Variables miembro ---
// Objetos y punteros a recursos

View File

@@ -41,19 +41,23 @@ LoadingScreen::LoadingScreen()
// Cambia el color del borde
Screen::get()->setBorderColor(stringToColor("white"));
transitionToState(State::SILENT1);
// Ajusta el volumen i neteja la pantalla (abans a run())
Audio::get()->setMusicVolume(50);
Screen::get()->start();
Screen::get()->clearRenderer();
Screen::get()->render();
}
// Destructor
LoadingScreen::~LoadingScreen() {
Audio::get()->stopMusic();
Audio::get()->setMusicVolume(100);
}
// Comprueba el manejador de eventos
void LoadingScreen::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
GlobalEvents::handle(event);
}
// Despatx d'un event (SDL3 Callback API)
void LoadingScreen::handleEvent(const SDL_Event& event) {
GlobalEvents::handle(event);
}
// Comprueba las entradas
@@ -347,8 +351,7 @@ void LoadingScreen::renderColoredBorder(PaletteColor color) {
void LoadingScreen::update() {
const float DELTA_TIME = delta_timer_->tick();
handleEvents(); // Comprueba los eventos
handleInput(); // Comprueba las entradas
handleInput(); // Comprueba las entradas
updateState(DELTA_TIME); // Actualiza el estado y gestiona transiciones
@@ -400,22 +403,10 @@ void LoadingScreen::render() {
Screen::get()->render();
}
// Bucle para el logo del juego
void LoadingScreen::run() {
// Ajusta el volumen
Audio::get()->setMusicVolume(50);
// Limpia la pantalla
Screen::get()->start();
Screen::get()->clearRenderer();
Screen::get()->render();
while (SceneManager::current == SceneManager::Scene::LOADING_SCREEN) {
update();
render();
}
Audio::get()->setMusicVolume(100);
// Un frame de l'escena (SDL3 Callback API)
void LoadingScreen::iterate() {
update();
render();
}
// Pinta el borde

View File

@@ -5,19 +5,21 @@
#include <array> // Para std::array
#include <memory> // Para shared_ptr
#include "game/scenes/scene.hpp" // Para Scene
#include "utils/delta_timer.hpp" // Para DeltaTimer
#include "utils/utils.hpp" // Para PaletteColor
class Sprite; // Forward declaration
class Surface; // Forward declaration
class LoadingScreen {
class LoadingScreen : public Scene {
public:
// --- Constructor y Destructor ---
LoadingScreen();
~LoadingScreen();
~LoadingScreen() override;
// --- Bucle principal ---
void run();
// --- Bucle principal (SDL3 Callback API) ---
void iterate() override;
void handleEvent(const SDL_Event& event) override;
private:
// --- Enumeraciones ---
@@ -81,7 +83,6 @@ class LoadingScreen {
// --- Métodos ---
void update(); // Actualiza las variables
void render(); // Dibuja en pantalla
static void handleEvents(); // Comprueba el manejador de eventos
static void handleInput(); // Comprueba las entradas
void updateState(float delta_time); // Actualiza el estado actual
void transitionToState(State new_state); // Transiciona a un nuevo estado

View File

@@ -54,12 +54,9 @@ Logo::Logo()
Screen::get()->setBorderColor(static_cast<Uint8>(PaletteColor::BLACK));
}
// Comprueba el manejador de eventos
void Logo::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
GlobalEvents::handle(event);
}
// Despatx d'un event (SDL3 Callback API)
void Logo::handleEvent(const SDL_Event& event) {
GlobalEvents::handle(event);
}
// Comprueba las entradas
@@ -201,8 +198,7 @@ void Logo::updateState(float delta_time) {
void Logo::update() {
const float DELTA_TIME = delta_timer_->tick();
handleEvents(); // Comprueba los eventos
handleInput(); // Comprueba las entradas
handleInput(); // Comprueba las entradas
updateState(DELTA_TIME); // Actualiza el estado y gestiona transiciones
updateJAILGAMES(DELTA_TIME); // Gestiona el logo de JAILGAME
@@ -228,12 +224,10 @@ void Logo::render() { // NOLINT(readability-convert-member-functions-to-static)
Screen::get()->render();
}
// Bucle para el logo del juego
void Logo::run() {
while (SceneManager::current == SceneManager::Scene::LOGO) {
update();
render();
}
// Un frame de l'escena (SDL3 Callback API)
void Logo::iterate() {
update();
render();
}
// Termina la sección

View File

@@ -6,11 +6,12 @@
#include <memory> // Para shared_ptr
#include <vector> // Para vector
#include "game/scenes/scene.hpp" // Para Scene
#include "utils/delta_timer.hpp" // Para DeltaTimer
class Sprite; // Forward declaration
class Surface; // Forward declaration
class Logo {
class Logo : public Scene {
public:
// --- Tipos ---
using EasingFunction = std::function<float(float)>; // Función de easing (permite lambdas)
@@ -28,10 +29,11 @@ class Logo {
// --- Constructor y Destructor ---
Logo();
~Logo() = default;
~Logo() override = default;
// --- Bucle principal ---
void run();
// --- Bucle principal (SDL3 Callback API) ---
void iterate() override;
void handleEvent(const SDL_Event& event) override;
private:
// --- Constantes de tiempo (en segundos) ---
@@ -48,7 +50,6 @@ class Logo {
// --- Métodos ---
void update(); // Actualiza las variables
void render(); // Dibuja en pantalla
static void handleEvents(); // Comprueba el manejador de eventos
static void handleInput(); // Comprueba las entradas
void updateJAILGAMES(float delta_time); // Gestiona el logo de JAILGAME (time-based)
void updateTextureColors(); // Gestiona el color de las texturas

View File

@@ -0,0 +1,13 @@
#pragma once
#include <SDL3/SDL.h>
// Interfície base per a totes les escenes del joc.
// Cada escena concreta implementa iterate() (un frame) i handleEvent() (un event).
// Director crida aquests mètodes des de SDL_AppIterate / SDL_AppEvent.
class Scene {
public:
virtual ~Scene() = default;
virtual void iterate() = 0;
virtual void handleEvent(const SDL_Event& event) = 0;
};

View File

@@ -81,28 +81,40 @@ void Title::initMarquee() {
last_active_letter_ = 0;
}
// Comprueba el manejador de eventos
void Title::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
GlobalEvents::handle(event);
// Despatx d'un event (SDL3 Callback API)
void Title::handleEvent(const SDL_Event& event) {
GlobalEvents::handle(event);
// Manejo especial para captura de botones de gamepad
if (is_remapping_joystick_ && !remap_completed_ &&
(event.type == SDL_EVENT_GAMEPAD_BUTTON_DOWN || event.type == SDL_EVENT_GAMEPAD_AXIS_MOTION)) {
handleJoystickRemap(event);
continue; // No procesar más este evento
// Manejo especial para captura de botones de gamepad
if (is_remapping_joystick_ && !remap_completed_ &&
(event.type == SDL_EVENT_GAMEPAD_BUTTON_DOWN || event.type == SDL_EVENT_GAMEPAD_AXIS_MOTION)) {
handleJoystickRemap(event);
return; // No procesar más este evento
}
// Qualsevol botó del comandament al menú principal inicia partida directament
// (els bindings ja estan definits, no cal "pulsar 1" amb el teclat). El botó
// BACK queda exclòs perquè es reserva per a EXIT — excepte a emscripten, on
// no es pot sortir del joc i BACK pot actuar com a botó genèric d'inici.
if (event.type == SDL_EVENT_GAMEPAD_BUTTON_DOWN &&
state_ == State::MAIN_MENU &&
!is_remapping_keyboard_ && !is_remapping_joystick_
#ifndef __EMSCRIPTEN__
&& event.gbutton.button != SDL_GAMEPAD_BUTTON_BACK
#endif
) {
handleMainMenuKeyPress(SDLK_1); // PLAY
return;
}
if (event.type == SDL_EVENT_KEY_DOWN && !Console::get()->isActive()) {
// Si estamos en modo remap de teclado, capturar tecla
if (is_remapping_keyboard_ && !remap_completed_) {
handleKeyboardRemap(event);
}
if (event.type == SDL_EVENT_KEY_DOWN && !Console::get()->isActive()) {
// Si estamos en modo remap de teclado, capturar tecla
if (is_remapping_keyboard_ && !remap_completed_) {
handleKeyboardRemap(event);
}
// Si estamos en el menú principal normal
else if (state_ == State::MAIN_MENU && !is_remapping_keyboard_ && !is_remapping_joystick_) {
handleMainMenuKeyPress(event.key.key);
}
// Si estamos en el menú principal normal
else if (state_ == State::MAIN_MENU && !is_remapping_keyboard_ && !is_remapping_joystick_) {
handleMainMenuKeyPress(event.key.key);
}
}
}
@@ -242,7 +254,6 @@ void Title::renderMarquee() const {
void Title::update() {
const float DELTA_TIME = delta_timer_->tick();
handleEvents(); // Comprueba los eventos
handleInput(DELTA_TIME); // Comprueba las entradas
updateState(DELTA_TIME); // Actualiza el estado actual
@@ -434,12 +445,10 @@ void Title::render() {
Screen::get()->render();
}
// Bucle para el logo del juego
void Title::run() {
while (SceneManager::current == SceneManager::Scene::TITLE) {
update();
render();
}
// Un frame de l'escena (SDL3 Callback API)
void Title::iterate() {
update();
render();
}
// Crea y rellena la textura para mostrar los logros

View File

@@ -8,19 +8,21 @@
#include <vector> // Para vector
#include "game/scene_manager.hpp" // Para SceneManager::Scene
#include "game/scenes/scene.hpp" // Para Scene
#include "utils/delta_timer.hpp" // Para DeltaTimer
class Sprite; // Forward declaration
class Surface; // Forward declaration
class Text; // Forward declaration
class Title {
class Title : public Scene {
public:
// --- Constructor y Destructor ---
Title();
~Title();
~Title() override;
// --- Bucle principal ---
void run();
// --- Bucle principal (SDL3 Callback API) ---
void iterate() override;
void handleEvent(const SDL_Event& event) override;
private:
// --- Estructuras y enumeraciones ---
@@ -61,7 +63,6 @@ class Title {
// --- Métodos ---
void update(); // Actualiza las variables
void render(); // Dibuja en pantalla
void handleEvents(); // Comprueba el manejador de eventos
void handleMainMenuKeyPress(SDL_Keycode key); // Maneja las teclas del menu principal
void handleInput(float delta_time); // Comprueba las entradas
void updateState(float delta_time); // Actualiza el estado actual

View File

@@ -14,7 +14,7 @@
#include "core/rendering/text.hpp" // Para Text
#include "core/resources/resource_cache.hpp" // Para Resource
#include "game/options.hpp" // Para Options
#include "game/ui/notifier.hpp" // Para Notifier
#include "utils/easing_functions.hpp" // Para Easing::cubicInOut
// ── Helpers de texto ──────────────────────────────────────────────────────────
@@ -194,22 +194,16 @@ void Console::update(float delta_time) { // NOLINT(readability-function-cogniti
// Animación de altura (resize cuando msg_lines_ cambia); solo en ACTIVE
if (status_ == Status::ACTIVE && height_ != target_height_) {
const float PREV_HEIGHT = height_;
if (height_ < target_height_) {
height_ = std::min(height_ + (SLIDE_SPEED * delta_time), target_height_);
} else {
height_ = std::max(height_ - (SLIDE_SPEED * delta_time), target_height_);
if (anim_progress_ == 0.0F) {
// Iniciar animación de resize
anim_start_ = height_;
anim_end_ = target_height_;
}
// Actualizar el Notifier incrementalmente con el delta de altura
if (Notifier::get() != nullptr) {
const int DELTA_PX = static_cast<int>(height_) - static_cast<int>(PREV_HEIGHT);
if (DELTA_PX > 0) {
Notifier::get()->addYOffset(DELTA_PX);
notifier_offset_applied_ += DELTA_PX;
} else if (DELTA_PX < 0) {
Notifier::get()->removeYOffset(-DELTA_PX);
notifier_offset_applied_ += DELTA_PX;
}
anim_progress_ = std::min(anim_progress_ + (delta_time / ANIM_DURATION), 1.0F);
height_ = anim_start_ + ((anim_end_ - anim_start_) * Easing::cubicInOut(anim_progress_));
if (anim_progress_ >= 1.0F) {
height_ = target_height_;
anim_progress_ = 0.0F;
}
// Reconstruir la Surface al nuevo tamaño (pequeña: 256×~18-72px)
const float WIDTH = Options::game.width;
@@ -220,28 +214,23 @@ void Console::update(float delta_time) { // NOLINT(readability-function-cogniti
// Redibujar texto cada frame
redrawText();
switch (status_) {
case Status::RISING: {
y_ += SLIDE_SPEED * delta_time;
if (y_ >= 0.0F) {
y_ = 0.0F;
// Animación de apertura/cierre (basada en tiempo con easing)
if (status_ == Status::RISING || status_ == Status::VANISHING) {
anim_progress_ = std::min(anim_progress_ + (delta_time / ANIM_DURATION), 1.0F);
y_ = anim_start_ + ((anim_end_ - anim_start_) * Easing::cubicInOut(anim_progress_));
if (anim_progress_ >= 1.0F) {
y_ = anim_end_;
anim_progress_ = 0.0F;
if (status_ == Status::RISING) {
status_ = Status::ACTIVE;
}
break;
}
case Status::VANISHING: {
y_ -= SLIDE_SPEED * delta_time;
if (y_ <= -height_) {
y_ = -height_;
} else {
status_ = Status::HIDDEN;
// Resetear el mensaje una vez completamente oculta
msg_lines_ = {std::string(CONSOLE_NAME) + " " + std::string(CONSOLE_VERSION)};
target_height_ = calcTargetHeight(static_cast<int>(msg_lines_.size()));
}
break;
}
default:
break;
}
SDL_FRect rect = {.x = 0, .y = y_, .w = Options::game.width, .h = height_};
@@ -265,6 +254,9 @@ void Console::toggle() {
target_height_ = calcTargetHeight(static_cast<int>(msg_lines_.size()));
height_ = target_height_;
y_ = -height_;
anim_start_ = y_;
anim_end_ = 0.0F;
anim_progress_ = 0.0F;
status_ = Status::RISING;
input_line_.clear();
cursor_timer_ = 0.0F;
@@ -273,24 +265,18 @@ void Console::toggle() {
typewriter_chars_ = static_cast<int>(msg_lines_[0].size());
typewriter_timer_ = 0.0F;
SDL_StartTextInput(SDL_GetKeyboardFocus());
if (Notifier::get() != nullptr) {
const int OFFSET = static_cast<int>(height_);
Notifier::get()->addYOffset(OFFSET);
notifier_offset_applied_ = OFFSET;
}
if (on_toggle) { on_toggle(true); }
break;
case Status::ACTIVE:
// Al cerrar: mantener el texto visible hasta que esté completamente oculta
anim_start_ = y_;
anim_end_ = -height_;
anim_progress_ = 0.0F;
status_ = Status::VANISHING;
target_height_ = height_; // No animar durante VANISHING
target_height_ = height_; // No animar altura durante VANISHING
history_index_ = -1;
saved_input_.clear();
SDL_StopTextInput(SDL_GetKeyboardFocus());
if (Notifier::get() != nullptr) {
Notifier::get()->removeYOffset(notifier_offset_applied_);
notifier_offset_applied_ = 0;
}
if (on_toggle) { on_toggle(false); }
break;
default:

View File

@@ -51,14 +51,14 @@ class Console {
};
// Constantes visuales
static constexpr Uint8 BG_COLOR = 0; // PaletteColor::BLACK
static constexpr Uint8 BORDER_COLOR = 9; // PaletteColor::BRIGHT_GREEN
static constexpr Uint8 MSG_COLOR = 8; // PaletteColor::GREEN
static constexpr float SLIDE_SPEED = 180.0F;
static constexpr Uint8 BG_COLOR = 0; // PaletteColor::BLACK
static constexpr Uint8 BORDER_COLOR = 9; // PaletteColor::BRIGHT_GREEN
static constexpr Uint8 MSG_COLOR = 8; // PaletteColor::GREEN
static constexpr float ANIM_DURATION = 0.3F; // Duración de cualquier animación (segundos)
// Constantes de consola
static constexpr std::string_view CONSOLE_NAME = "JDD Console";
static constexpr std::string_view CONSOLE_VERSION = "v2.2";
static constexpr std::string_view CONSOLE_VERSION = "v2.3";
static constexpr int MAX_LINE_CHARS = 32;
static constexpr int MAX_HISTORY_SIZE = 20;
static constexpr float CURSOR_ON_TIME = 0.5F;
@@ -99,9 +99,13 @@ class Console {
int typewriter_chars_{0}; // Caracteres de msg_lines_ actualmente visibles
float typewriter_timer_{0.0F};
// Animación basada en tiempo (0→1 en ANIM_DURATION)
float anim_progress_{0.0F}; // Progreso normalizado [0, 1]
float anim_start_{0.0F}; // Valor inicial (y_ o height_)
float anim_end_{0.0F}; // Valor final
// Animación de altura dinámica
float target_height_{0.0F}; // Altura objetivo (según número de líneas de mensaje)
int notifier_offset_applied_{0}; // Acumulador del offset enviado al Notifier
float target_height_{0.0F}; // Altura objetivo (según número de líneas de mensaje)
// Historial de comandos (navegable con flechas arriba/abajo)
std::deque<std::string> history_;

View File

@@ -491,6 +491,9 @@ static auto cmdDebug(const std::vector<std::string>& args) -> std::string { //
if (args[2] == "GAME") {
target = SceneManager::Scene::GAME;
name = "game";
} else if (args[2] == "DEMO") {
target = SceneManager::Scene::DEMO;
name = "demo";
} else if (args[2] == "LOGO") {
target = SceneManager::Scene::LOGO;
name = "logo";
@@ -651,10 +654,10 @@ static auto cmdItems(const std::vector<std::string>& args) -> std::string {
return "Items: " + std::to_string(count);
}
// SCENE [LOGO|LOADING|TITLE|CREDITS|GAME|ENDING|ENDING2|RESTART]
// SCENE [LOGO|LOADING|TITLE|CREDITS|GAME|DEMO|ENDING|ENDING2|RESTART]
static auto cmdScene(const std::vector<std::string>& args) -> std::string {
if (Options::kiosk.enabled) { return "Not allowed in kiosk mode"; }
if (args.empty()) { return "usage: scene [logo|loading|title|credits|game|ending|ending2|restart]"; }
if (args.empty()) { return "usage: scene [logo|loading|title|credits|game|demo|ending|ending2|restart]"; }
if (args[0] == "RESTART") {
SceneManager::scene_before_restart = SceneManager::current;
@@ -677,6 +680,7 @@ static auto cmdScene(const std::vector<std::string>& args) -> std::string {
if (args[0] == "TITLE") { return GO_TO(SceneManager::Scene::TITLE, "Title"); }
if (args[0] == "CREDITS") { return GO_TO(SceneManager::Scene::CREDITS, "Credits"); }
if (args[0] == "GAME") { return GO_TO(SceneManager::Scene::GAME, "Game"); }
if (args[0] == "DEMO") { return GO_TO(SceneManager::Scene::DEMO, "Demo"); }
if (args[0] == "ENDING") { return GO_TO(SceneManager::Scene::ENDING, "Ending"); }
if (args[0] == "ENDING2") { return GO_TO(SceneManager::Scene::ENDING2, "Ending 2"); }
return "Unknown scene: " + args[0];
@@ -948,11 +952,16 @@ static auto cmdKiosk(const std::vector<std::string>& args) -> std::string {
// EXIT / QUIT
static auto cmdExit(const std::vector<std::string>& args) -> std::string {
#ifdef __EMSCRIPTEN__
(void)args;
return "Not allowed in web version";
#else
if (Options::kiosk.enabled && (args.empty() || args[0] != "PLEASE")) {
return "Not allowed in kiosk mode";
}
SceneManager::current = SceneManager::Scene::QUIT;
return "Quitting...";
#endif
}
// SIZE

View File

@@ -15,6 +15,7 @@
#include "core/rendering/text.hpp" // Para Text, Text::CENTER_FLAG, Text::COLOR_FLAG
#include "core/resources/resource_cache.hpp" // Para Resource
#include "game/options.hpp" // Para Options, options, NotificationPosition
#include "game/ui/console.hpp" // Para Console
#include "utils/delta_timer.hpp" // Para DeltaTimer
#include "utils/utils.hpp" // Para PaletteColor
@@ -73,8 +74,11 @@ void Notifier::render() {
// Actualiza el estado de las notificaiones
void Notifier::update(float delta_time) {
// Base Y leída cada frame: cada notificación se dibuja en rect.y (relativo a BASE) + BASE
const float BASE = static_cast<float>(getStackBaseY());
for (auto& notification : notifications_) {
// Si la notificación anterior está "saliendo", no hagas nada
// Si la notificación anterior está "entrando", no hagas nada (stall del resto)
if (!notifications_.empty() && &notification != &notifications_.front()) {
const auto& previous_notification = *(std::prev(&notification));
if (previous_notification.state == Status::RISING) {
@@ -84,17 +88,17 @@ void Notifier::update(float delta_time) {
switch (notification.state) {
case Status::RISING: {
const float DISPLACEMENT = SLIDE_SPEED * delta_time;
notification.rect.y += DISPLACEMENT;
if (notification.rect.y >= notification.y) {
notification.rect.y = notification.y;
const float TARGET = static_cast<float>(notification.y);
notification.rect.y += SLIDE_SPEED * delta_time;
if (notification.rect.y >= TARGET) {
notification.rect.y = TARGET;
notification.state = Status::STAY;
notification.elapsed_time = 0.0F;
}
break;
}
case Status::STAY: {
notification.rect.y = static_cast<float>(notification.y);
notification.elapsed_time += delta_time;
if (notification.elapsed_time >= notification.display_duration) {
notification.state = Status::VANISHING;
@@ -103,10 +107,8 @@ void Notifier::update(float delta_time) {
}
case Status::VANISHING: {
const float DISPLACEMENT = SLIDE_SPEED * delta_time;
notification.rect.y -= DISPLACEMENT;
const float TARGET_Y = notification.y - notification.travel_dist;
const float TARGET_Y = static_cast<float>(notification.y - notification.travel_dist);
notification.rect.y -= SLIDE_SPEED * delta_time;
if (notification.rect.y <= TARGET_Y) {
notification.rect.y = TARGET_Y;
notification.state = Status::FINISHED;
@@ -120,8 +122,13 @@ void Notifier::update(float delta_time) {
default:
break;
}
}
notification.sprite->setPosition(notification.rect);
// Refrescar posiciones de sprite cada frame (convierte rect.y relativo a absoluto)
for (auto& notification : notifications_) {
SDL_FRect sprite_rect = notification.rect;
sprite_rect.y += BASE;
notification.sprite->setPosition(sprite_rect);
}
clearFinishedNotifications();
@@ -170,15 +177,13 @@ void Notifier::show(std::vector<std::string> texts, const Style& style, int icon
// Posición horizontal
float desp_h = ((Options::game.width / 2) - (WIDTH / 2));
;
// Posición vertical
const int DESP_V = y_offset_;
// Offset
// Offset vertical (relativo a la base de la pila, que se consulta cada frame)
const auto TRAVEL_DIST = HEIGHT + PADDING_OUT;
const int TRAVEL_MOD = 1;
const int OFFSET = !notifications_.empty() ? notifications_.back().y + (TRAVEL_MOD * notifications_.back().travel_dist) : DESP_V;
const int OFFSET = !notifications_.empty()
? notifications_.back().y + (TRAVEL_MOD * notifications_.back().travel_dist)
: 0;
// Crea la notificacion
Notification n;
@@ -191,8 +196,9 @@ void Notifier::show(std::vector<std::string> texts, const Style& style, int icon
n.texts = texts;
n.shape = SHAPE;
n.display_duration = style.duration;
const float Y_POS = OFFSET + -TRAVEL_DIST;
n.rect = {.x = desp_h, .y = Y_POS, .w = WIDTH, .h = HEIGHT};
// Posición inicial relativa a la base: arranca "travel_dist" por encima del target (=OFFSET)
const float Y_POS_REL = static_cast<float>(OFFSET) - TRAVEL_DIST;
n.rect = {.x = desp_h, .y = Y_POS_REL, .w = WIDTH, .h = HEIGHT};
// Crea la textura
n.surface = std::make_shared<Surface>(WIDTH, HEIGHT);
@@ -252,8 +258,10 @@ void Notifier::show(std::vector<std::string> texts, const Style& style, int icon
// Deja de dibujar en la textura
Screen::get()->setRendererSurface(previuos_renderer);
// Crea el sprite de la notificación
n.sprite = std::make_shared<Sprite>(n.surface, n.rect);
// Crea el sprite de la notificación (rect absoluto a partir del relativo + BASE)
SDL_FRect initial_sprite_rect = n.rect;
initial_sprite_rect.y += static_cast<float>(getStackBaseY());
n.sprite = std::make_shared<Sprite>(n.surface, initial_sprite_rect);
// Añade la notificación a la lista
notifications_.emplace_back(n);
@@ -278,9 +286,21 @@ void Notifier::clearNotifications() {
clearFinishedNotifications();
}
// Ajusta el offset vertical base
void Notifier::addYOffset(int px) { y_offset_ += px; }
void Notifier::removeYOffset(int px) { y_offset_ -= px; }
// Y absoluta de la base de la pila (justo debajo de Console, o 0 si no hay Console)
auto Notifier::getStackBaseY() const -> int {
return Console::get() != nullptr ? Console::get()->getVisibleHeight() : 0;
}
// Altura animada ocupada por la pila (usa rect.y animado, no el target — para transiciones suaves)
auto Notifier::getVisibleHeight() const -> int {
int bottom = 0;
for (const auto& n : notifications_) {
if (n.state == Status::FINISHED) { continue; }
const int N_BOTTOM = static_cast<int>(n.rect.y + n.rect.h);
if (N_BOTTOM > bottom) { bottom = N_BOTTOM; }
}
return bottom;
}
// Obtiene los códigos de las notificaciones
auto Notifier::getCodes() -> std::vector<std::string> {

View File

@@ -59,9 +59,9 @@ class Notifier {
auto isActive() -> bool; // Indica si hay notificaciones activas
auto getCodes() -> std::vector<std::string>; // Obtiene códigos de notificaciones
// Offset vertical (para evitar solapamiento con Console y renderInfo)
void addYOffset(int px); // Suma píxeles al offset base
void removeYOffset(int px); // Resta píxeles al offset base
// Altura animada ocupada por la pila de notificaciones, en píxeles (relativa a la base).
// Crece/decrece suavemente con las animaciones de entrada/salida.
[[nodiscard]] auto getVisibleHeight() const -> int;
private:
// Tipos anidados
@@ -78,8 +78,8 @@ class Notifier {
std::vector<std::string> texts;
Status state{Status::RISING};
Shape shape{Shape::SQUARED};
SDL_FRect rect{.x = 0.0F, .y = 0.0F, .w = 0.0F, .h = 0.0F};
int y{0};
SDL_FRect rect{.x = 0.0F, .y = 0.0F, .w = 0.0F, .h = 0.0F}; // rect.y es relativo a la base de la pila
int y{0}; // Top objetivo de la notificación relativo a la base de la pila
int travel_dist{0};
std::string code;
bool can_be_removed{true};
@@ -97,8 +97,9 @@ class Notifier {
static Notifier* notifier;
// Métodos privados
void clearFinishedNotifications(); // Elimina las notificaciones finalizadas
void clearNotifications(); // Finaliza y elimina todas las notificaciones activas
void clearFinishedNotifications(); // Elimina las notificaciones finalizadas
void clearNotifications(); // Finaliza y elimina todas las notificaciones activas
[[nodiscard]] auto getStackBaseY() const -> int; // Y absoluta de la base de la pila (leída de Console)
// Constructor y destructor privados [SINGLETON]
Notifier(const std::string& icon_file, const std::string& text);
@@ -111,5 +112,4 @@ class Notifier {
std::vector<Notification> notifications_; // Lista de notificaciones activas
bool stack_{false}; // Indica si las notificaciones se apilan
bool has_icons_{false}; // Indica si el notificador tiene textura para iconos
int y_offset_{0}; // Offset vertical base (ajustado por Console y renderInfo)
};

View File

@@ -5,14 +5,24 @@ Empezado en Castalla el 01/07/2022.
*/
#include <memory>
#define SDL_MAIN_USE_CALLBACKS 1
#include <SDL3/SDL_main.h>
#include "core/system/director.hpp"
auto main() -> int {
// Crea el objeto Director
auto director = std::make_unique<Director>();
// Bucle principal
return Director::run();
SDL_AppResult SDL_AppInit(void** appstate, int /*argc*/, char* /*argv*/[]) {
*appstate = new Director();
return SDL_APP_CONTINUE;
}
SDL_AppResult SDL_AppIterate(void* appstate) {
return static_cast<Director*>(appstate)->iterate();
}
SDL_AppResult SDL_AppEvent(void* appstate, SDL_Event* event) {
return static_cast<Director*>(appstate)->handleEvent(*event);
}
void SDL_AppQuit(void* appstate, SDL_AppResult /*result*/) {
delete static_cast<Director*>(appstate);
}

View File

@@ -6,7 +6,7 @@
namespace Texts {
constexpr const char* WINDOW_CAPTION = "© 2022 JailDoctor's Dilemma — JailDesigner";
constexpr const char* COPYRIGHT = "@2022 JailDesigner";
constexpr const char* VERSION = "1.13"; // Versión por defecto
constexpr const char* VERSION = "1.14"; // Versión por defecto
} // namespace Texts
// Tamaño de bloque