Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ velocidad aumenta con el tiempo. En la web es el `index.html` publicado.
| R3.3. HUD | `src/Hud.*` — puntos, mejor puntuación, velocidad y mensajes con `Dibujante::Texto` | `tests/test_partida.cpp` (3.3) |
| R3.4. Assets web | `CMakeLists.txt` — `--preload-file assets@/assets` empaqueta `assets/` en `index.data` | CI (3.4) |

`assets/avatar_run.bmp` (6 fotogramas de 16x24: 4 de carrera, salto, caída) se regenera con
`python3 tools/generar_avatar.py`. Nativo: `./build/runner`. La demo antigua del motor sigue en
`assets/avatar_run.bmp` (6 fotogramas de 64x90: 4 de trote, salto, caída) se genera desde `tools/avatar_fuente.webp` con
`python3 tools/generar_avatar.py` (requiere Pillow y numpy). Nativo: `./build/runner`. La demo antigua del motor sigue en
`./build/juego` (solo nativo).

> En Emscripten los archivos del disco no existen: `--preload-file` los empaqueta en `index.data`
Expand Down
Binary file modified assets/avatar_run.bmp
Binary file not shown.
10 changes: 5 additions & 5 deletions src/Jugador.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,12 @@ SDL_Rect Jugador::Rectangulo() const noexcept

SDL_Rect Jugador::CajaColision() const noexcept
{
// Recorta el borde transparente del sprite (en pixeles de la hoja: 4 por cada lado,
// 1 por arriba, 2 por abajo) para que la colision sea justa; ver Test 3.2
// Recorta los margenes configurados (ver ConfigJugador); Test 3.2 verifica que la caja
// queda dentro de lo que realmente se ve del sprite
SDL_Rect r = Rectangulo();
const int mx = 4 * m_config.escala, my = 1 * m_config.escala;
r.x += mx; r.w -= 2 * mx;
r.y += my; r.h -= my + 2 * m_config.escala; // 2 px menos por abajo (el fotograma de salto recoge las piernas)
const int e = m_config.escala;
r.x += m_config.insetX * e; r.w -= 2 * m_config.insetX * e;
r.y += m_config.insetArriba * e; r.h -= (m_config.insetArriba + m_config.insetAbajo) * e;
return r;
}

Expand Down
13 changes: 9 additions & 4 deletions src/Jugador.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
// semi-implicita a paso fijo, pensada para Juego::Actualizar(dt) a 60 Hz).
// - Estados: Corriendo (en el suelo), Saltando (subiendo), Cayendo (bajando).
//
// Disposicion de la hoja de sprites (assets/avatar_run.bmp), todos los fotogramas del
// Disposicion de la hoja de sprites (assets/avatar_run.bmp, ver tools/generar_avatar.py), todos los fotogramas del
// mismo tamano en una sola fila:
// [0..framesCorrer-1] ciclo de carrera | [frameSalto] subiendo | [frameCaida] bajando
//
Expand Down Expand Up @@ -55,9 +55,14 @@ struct ConfigJugador
{
int x = 80; // borde izquierdo fijo del sprite (px)
double ySuelo = 400.0; // Y del suelo: donde apoyan los pies (px)
int anchoFrame = 16; // tamano de un fotograma en la hoja (px)
int altoFrame = 24;
int escala = 3; // el pixel art se amplia por enteros
int anchoFrame = 64; // tamano de un fotograma en la hoja (px)
int altoFrame = 90;
int escala = 1; // ampliacion entera del sprite al dibujarlo
// Caja de colision = fotograma recortado (px de la hoja). Mas pequena que lo visible a
// proposito: cabeza, gorra y manos sobresalen y no deben matar al jugador por rozar.
int insetX = 12; // por cada lado
int insetArriba = 14;
int insetAbajo = 5; // los fotogramas de trote elevan al avatar 5 px
double gravedad = 1800.0; // px/s^2 hacia abajo
double velocidadSalto = 620.0; // px/s hacia arriba en el instante del salto
int ticsPorFrame = 6; // 6 tics a 60 Hz = 10 fotogramas/s de carrera
Expand Down
12 changes: 8 additions & 4 deletions tests/test_jugador.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ void Rellenar(SDL_Renderer* r, Color c)
std::vector<std::uint32_t> DibujarFrame(SDL_Renderer* r, const Textura& hoja, int frame, Color fondo, const SDL_Rect& destino)
{
Rellenar(r, fondo);
const SDL_Rect origen{ frame * 16, 0, 16, 24 };
const ConfigJugador c;
const SDL_Rect origen{ frame * c.anchoFrame, 0, c.anchoFrame, c.altoFrame };
hoja.Dibujar(r, &origen, destino);
return Leer(r);
}
Expand All @@ -67,7 +68,9 @@ void Test_1_1(SDL_Renderer* r)
std::printf("Test 1.1: carga de texturas\n");
auto hoja = Textura::Cargar(r, std::string(BGE_ASSETS_DIR) + "/avatar_run.bmp");
CHECK(hoja != nullptr, "el sprite sheet del avatar se carga (puntero no nulo)");
CHECK(hoja && hoja->Ancho() == 96 && hoja->Altura() == 24, "dimensiones 96x24 (6 fotogramas de 16x24)");
const ConfigJugador cfgHoja;
CHECK(hoja && hoja->Ancho() == 6 * cfgHoja.anchoFrame && hoja->Altura() == cfgHoja.altoFrame,
"dimensiones de la hoja = 6 fotogramas de anchoFrame x altoFrame (segun ConfigJugador)");

auto falta = Textura::Cargar(r, "assets/no_existe.bmp");
CHECK(falta == nullptr, "ruta inexistente -> nullptr, sin excepcion ni cierre");
Expand All @@ -93,7 +96,8 @@ void Test_1_2(SDL_Renderer* r)
auto hoja = Textura::Cargar(r, std::string(BGE_ASSETS_DIR) + "/avatar_run.bmp");
if (!hoja) { CHECK(false, "no se pudo cargar la hoja"); return; }

const SDL_Rect destino{ 20, 10, 48, 72 }; // escala x3
const ConfigJugador cfgHoja;
const SDL_Rect destino{ 20, 10, cfgHoja.anchoFrame, cfgHoja.altoFrame };
const Color fondos[] = { Colores::Negro, Colores::Blanco, Colores::Verde };
for (const Color& f : fondos)
{
Expand Down Expand Up @@ -213,7 +217,7 @@ void Test_2_2(SDL_Renderer* r)
auto hoja = Textura::Cargar(r, std::string(BGE_ASSETS_DIR) + "/avatar_run.bmp");
if (hoja)
{
const SDL_Rect d{ 20, 10, 48, 72 };
const SDL_Rect d{ 20, 10, cfg.anchoFrame, cfg.altoFrame };
const auto f0 = DibujarFrame(r, *hoja, 0, Colores::Fondo, d);
const auto f1 = DibujarFrame(r, *hoja, 1, Colores::Fondo, d);
const auto f2 = DibujarFrame(r, *hoja, 2, Colores::Fondo, d);
Expand Down
13 changes: 9 additions & 4 deletions tests/test_partida.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ struct Caja4 { int x0 = 1000, y0 = 1000, x1 = -1, y1 = -1; };

std::vector<Caja4> CajasOpacas()
{
const ConfigJugador cfg;
const int fw = cfg.anchoFrame;
std::vector<Caja4> res(6);
SDL_Surface* bmp = SDL_LoadBMP(BGE_ASSETS_DIR "/avatar_run.bmp");
if (!bmp) return res;
Expand All @@ -131,8 +133,8 @@ std::vector<Caja4> CajasOpacas()
{
const auto p = static_cast<std::uint32_t*>(s->pixels)[y * s->pitch / 4 + x] & 0xFFFFFFu;
if (p == 0xFF00FFu) continue;
Caja4& c = res[static_cast<std::size_t>(x / 16)];
c.x0 = std::min(c.x0, x % 16); c.x1 = std::max(c.x1, x % 16);
Caja4& c = res[static_cast<std::size_t>(x / fw)];
c.x0 = std::min(c.x0, x % fw); c.x1 = std::max(c.x1, x % fw);
c.y0 = std::min(c.y0, y); c.y1 = std::max(c.y1, y);
}
SDL_FreeSurface(s);
Expand Down Expand Up @@ -171,8 +173,11 @@ void Test_3_2()
uni.x0, uni.x1, uni.y0, uni.y1, cx0, cx1, cy0, cy1);
CHECK(cx0 >= uni.x0 && cx1 <= uni.x1 && cy0 >= uni.y0 && cy1 <= uni.y1,
"la caja de colision queda dentro del area visible del avatar (sin falsos positivos en margenes)");
CHECK(cx0 - uni.x0 <= 2 && uni.x1 - cx1 <= 2 && cy0 - uni.y0 <= 2 && uni.y1 - cy1 <= 2,
"y cubre casi todo el area visible (a menos de 2 pixeles de sprite por lado)");
const double areaCaja = double(cx1 - cx0 + 1) * (cy1 - cy0 + 1);
const double areaVisible = double(uni.x1 - uni.x0 + 1) * (uni.y1 - uni.y0 + 1);
std::printf(" la caja cubre el %.0f%% del rectangulo visible\n", 100.0 * areaCaja / areaVisible);
CHECK(areaCaja >= 0.45 * areaVisible,
"y cubre una parte sustancial del avatar (>=45%: cabeza, gorra y manos no cuentan; no es una caja diminuta)");
bool porFrame = true;
for (const auto& c : cajas) if (cx0 < c.x0 - 1 || cx1 > c.x1 + 1 || cy0 < c.y0 - 1 || cy1 > c.y1 + 1) porFrame = false;
CHECK(porFrame, "en cada fotograma sobresale como mucho 1 pixel del sprite visible");
Expand Down
Binary file added tools/avatar_fuente.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
129 changes: 75 additions & 54 deletions tools/generar_avatar.py
Original file line number Diff line number Diff line change
@@ -1,63 +1,84 @@
#!/usr/bin/env python3
"""Genera assets/avatar_run.bmp: hoja de sprites 6x(16x24) del avatar (solo biblioteca estandar).
"""Genera assets/avatar_run.bmp (hoja de sprites) a partir de tools/avatar_fuente.webp.

Fotogramas: 0-3 ciclo de carrera, 4 salto (subiendo), 5 caida. Fondo magenta = transparente
(el cargador de Textura lo convierte en alfa 0). Uso: python3 tools/generar_avatar.py [salida.bmp]
Requiere Pillow y numpy (solo para regenerar el asset; el juego no los necesita).
python3 tools/generar_avatar.py [fuente.webp] [salida.bmp]

La imagen fuente tiene UNA sola pose, asi que los 6 fotogramas se derivan de ella con
deformaciones suaves (aplastar / estirar / elevar) que dan sensacion de trote y salto:
0..3 ciclo de carrera (contacto, vuelo, contacto, vuelo) | 4 subiendo | 5 bajando
Para una animacion de piernas real hay que dibujar mas poses y sustituir 'poses' abajo.
El fondo se rellena con magenta (255,0,255) = color clave que Textura convierte en alfa 0.
"""
import struct
import sys
from pathlib import Path

import numpy as np
from PIL import Image

W, H, N = 16, 24, 6
ALTO_SPRITE = 84 # altura del personaje en la hoja (px de pantalla a escala 1)
CELDA_W, CELDA_H = 64, 90 # tamano de cada fotograma (debe coincidir con ConfigJugador)
N = 6
CLAVE = (255, 0, 255)
PIEL, PELO, CAMISA, PANTALON, ZAPATO, OJO = (240, 190, 150), (70, 45, 30), (60, 120, 220), (45, 50, 100), (235, 235, 240), (20, 20, 30)


def frame(i):
px = [[CLAVE] * W for _ in range(H)]

def r(x0, y0, x1, y1, c): # rectangulo inclusivo
for y in range(y0, y1 + 1):
for x in range(x0, x1 + 1):
px[y][x] = c

# Cabeza, pelo y ojo (mira a la derecha)
r(5, 1, 10, 6, PIEL); r(5, 1, 10, 2, PELO); r(5, 3, 6, 4, PELO); r(9, 4, 9, 4, OJO)
# Torso
r(5, 7, 10, 14, CAMISA)

if i in (0, 2): # zancada amplia (2 es el espejo de 0)
back, front = (4, 6), (9, 11)
if i == 2:
back, front = front, back
r(back[0], 15, back[1], 21, PANTALON); r(back[0] - 1, 22, back[1], 23, ZAPATO)
r(front[0], 15, front[1], 20, PANTALON); r(front[0], 21, front[1] + 1, 22, ZAPATO)
arm_back, arm_front = (3, 4), (11, 12)
r(arm_back[0], 8, arm_back[1], 12, PIEL if i == 0 else CAMISA)
r(arm_front[0], 8, arm_front[1], 12, CAMISA if i == 0 else PIEL)
elif i in (1, 3): # piernas juntas, una elevada
r(6, 15, 8, 23, PANTALON); r(6, 22, 9, 23, ZAPATO)
r(8, 15, 10, 19, PANTALON); r(8, 20, 11, 21, ZAPATO)
r(7, 9, 8, 13, PIEL)
elif i == 4: # salto: rodillas recogidas, brazos arriba
r(5, 15, 9, 18, PANTALON); r(9, 17, 10, 19, PANTALON); r(5, 19, 8, 20, ZAPATO); r(9, 20, 11, 21, ZAPATO)
r(3, 3, 4, 8, PIEL); r(11, 3, 12, 8, PIEL)
else: # caida: piernas estiradas, brazos abiertos
r(4, 15, 6, 22, PANTALON); r(3, 23, 6, 23, ZAPATO)
r(9, 15, 11, 22, PANTALON); r(9, 23, 12, 23, ZAPATO)
r(2, 8, 4, 10, PIEL); r(11, 8, 13, 10, PIEL)
return px


def main(ruta):
ancho = W * N
filas = [[frame(f)[y][x] for f in range(N) for x in range(W)] for y in range(H)]
datos = b"".join(b"".join(bytes((b, g, rr)) for rr, g, b in fila) for fila in reversed(filas)) # BGR, de abajo arriba
cabecera = b"BM" + struct.pack("<IHHI", 54 + len(datos), 0, 0, 54)
info = struct.pack("<IiiHHIIiiII", 40, ancho, H, 1, 24, 0, len(datos), 2835, 2835, 0, 0)
with open(ruta, "wb") as f:
f.write(cabecera + info + datos)
print(f"{ruta}: {ancho}x{H}, {N} fotogramas de {W}x{H}")
UMBRAL_ALFA = 128 # alfa binario: sin halos al aplicar el color clave


def preparar(fuente):
im = Image.open(fuente).convert("RGBA")
a = np.array(im)
ys, xs = np.where(a[..., 3] > 10)
im = im.crop((xs.min(), ys.min(), xs.max() + 1, ys.max() + 1))
w = round(im.width * ALTO_SPRITE / im.height)
# Pillow redimensiona RGBA con alfa premultiplicado: los bordes no se ensucian
return im.resize((w, ALTO_SPRITE), Image.LANCZOS)


def deformar(sprite, ancho_f, alto_f):
w, h = sprite.size
return sprite.resize((max(1, round(w * ancho_f)), max(1, round(h * alto_f))), Image.NEAREST)


def montar(sprite):
# (factor ancho, factor alto, elevacion en px, desplazamiento x en px)
# El personaje siempre apoya en la base de la celda; el balanceo en x hace que los
# cuatro fotogramas de carrera sean distintos entre si.
poses = [
(1.04, 0.95, 0, -1), # 0 contacto (aplastado)
(1.00, 1.00, 5, -2), # 1 vuelo
(1.04, 0.95, 0, +1), # 2 contacto
(1.00, 1.00, 5, +2), # 3 vuelo
(0.97, 1.05, 0, 0), # 4 salto: subiendo, estirado
(1.03, 0.96, 0, 0), # 5 caida: aplastandose hacia el suelo
]
hoja = Image.new("RGBA", (CELDA_W * N, CELDA_H), (0, 0, 0, 0))
for i, (fw, fh, elev, dx) in enumerate(poses):
s = deformar(sprite, fw, fh)
x = i * CELDA_W + (CELDA_W - s.width) // 2 + dx
y = CELDA_H - s.height - elev
assert s.width <= CELDA_W and y >= 0, "el sprite no cabe en la celda"
hoja.alpha_composite(s, (x, y))
return hoja


def a_bmp(hoja, salida):
a = np.array(hoja)
opaco = a[..., 3] >= UMBRAL_ALFA
rgb = a[..., :3].copy()
# Ningun pixel del personaje puede coincidir con el color clave
choque = opaco & (rgb == np.array(CLAVE)).all(-1)
rgb[choque] = (254, 0, 255)
rgb[~opaco] = CLAVE
Image.fromarray(rgb, "RGB").save(salida, format="BMP") # BMP de 24 bits, sin compresion


def main():
aqui = Path(__file__).resolve().parent
fuente = Path(sys.argv[1]) if len(sys.argv) > 1 else aqui / "avatar_fuente.webp"
salida = Path(sys.argv[2]) if len(sys.argv) > 2 else aqui.parent / "assets" / "avatar_run.bmp"
sprite = preparar(fuente)
a_bmp(montar(sprite), salida)
print(f"{salida}: {CELDA_W * N}x{CELDA_H}, {N} fotogramas de {CELDA_W}x{CELDA_H} (personaje {sprite.width}x{sprite.height})")


if __name__ == "__main__":
main(sys.argv[1] if len(sys.argv) > 1 else "assets/avatar_run.bmp")
main()
Loading