Compare commits

..

21 Commits

Author SHA1 Message Date
08031810c9 Añadidas las unidades para trabajar con paletas 2024-02-05 16:43:30 +01:00
16baf48d8c Añadidos ficheros .gif 2024-02-05 16:33:53 +01:00
07caf71ce3 demo: El teclado se crea y se destruye según se use o no 2023-09-16 12:50:51 +02:00
c656d48b72 demo: El teclado se crea y se destruye según se use o no 2023-09-13 18:30:12 +02:00
2d03333463 on_screen_keyboard: arreglado bug al reducir el numero de columna o fila 2023-08-18 08:04:13 +02:00
477fc35e29 on_screen_keyboard: Añadidos bordes 2023-05-28 19:45:32 +02:00
d2e94ce74b on_screen_keyboard: Mejorada la calidad del cursor
on_screen_keyboard: Compatibilidad con fuentes de texto de tamaño variable
2023-05-28 19:35:49 +02:00
120c3791cf on_screen_keyboard: Ya se pueden añadir y quitar caracteres al texto de salida 2023-05-28 18:33:52 +02:00
921f9d2606 Input: Modificado el input por defecto para la acción de cancelar con teclado 2023-05-28 18:26:33 +02:00
c51eb06a61 on_screen_keyboard: Ya se dibuja el cursor 2023-05-28 17:44:59 +02:00
cc421e56ea on_screen_keyboard: Ya se dibuja el teclado en la pantalla 2023-05-28 12:58:02 +02:00
ad9a3fb594 utils: Añadida la función randColor 2023-05-28 11:58:34 +02:00
5d58d24cb9 on_screen_keyboard: Se empiezan a dibujar algunas teclas en pantalla 2023-05-28 10:38:04 +02:00
2b5a2cb588 utils: Añadidas las funciones darkenColor y lightenColor 2023-05-28 09:17:30 +02:00
73849a2fef on_screen_keyboard: Ya dibuja el objeto básico en pantalla 2023-05-28 09:09:26 +02:00
54947dce2d OnScreenKeyboard: Creado el esqueleto base 2023-05-26 11:00:51 +02:00
40701d9029 input: Retocados los mensajes de información 2023-05-26 08:43:20 +02:00
1746e38a56 demo: Pequeños retoques en el efecto de fuego 2023-05-26 08:39:43 +02:00
c12e8841b4 demo: Optimizado el calculo del efecto de fuego 2023-05-25 22:16:59 +02:00
ab90709963 demo: El efecto de fuego se ha optimizado pintando los pixels en una textura 2023-05-25 20:42:15 +02:00
6012b6ac5f demo: Se puede cambiar el efecto de fondo desde el teclado 2023-05-25 17:13:44 +02:00
14 changed files with 1507 additions and 77 deletions

BIN
data/nokia.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

194
data/nokia.txt Normal file
View File

@@ -0,0 +1,194 @@
# box width
8
# box height
8
# 32 espacio ( )
4
# 33 !
2
# 34 "
3
# 35 #
5
# 36 $
5
# 37 %
6
# 38 &
6
# 39 '
1
# 40 (
3
# 41 )
3
# 42 *
5
# 43 +
5
# 44 ,
2
# 45 -
4
# 46 .
2
# 47 /
3
# 48 0
5
# 49 1
3
# 50 2
5
# 51 3
5
# 52 4
5
# 53 5
5
# 54 6
5
# 55 7
5
# 56 8
5
# 57 9
5
# 58 :
2
# 59 ;
2
# 60 <
4
# 61 =
4
# 62 >
4
# 63 ?
5
# 64 @
6
# 65 A
5
# 66 B
5
# 67 C
5
# 68 D
5
# 69 E
5
# 70 F
5
# 71 G
5
# 72 H
5
# 73 I
2
# 74 J
4
# 75 K
6
# 76 L
4
# 77 M
7
# 78 N
6
# 79 O
6
# 80 P
5
# 81 Q
6
# 82 R
5
# 83 S
4
# 84 T
6
# 85 U
5
# 86 V
6
# 87 W
7
# 88 X
6
# 89 Y
6
# 90 Z
5
# 91 [
2
# 92 \
3
# 93 ]
2
# 94 ^
3
# 95 _
6
# 96 `
2
# 97 a
5
# 98 b
5
# 99 c
4
# 100 d
5
# 101 e
5
# 102 f
3
# 103 g
5
# 104 h
5
# 105 i
2
# 106 j
3
# 107 k
5
# 108 l
2
# 109 m
8
# 110 n
5
# 111 o
5
# 112 p
5
# 113 q
5
# 114 r
4
# 115 s
4
# 116 t
3
# 117 u
5
# 118 v
5
# 119 w
7
# 120 x
5
# 121 y
5
# 122 z
5
# 123 { -> ñ
5
# 124 | -> ç
5
# 125 }
0
# 126 ~
0

BIN
data/pal01.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 273 B

BIN
data/pal02.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 273 B

BIN
data/williams.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

236
main.cpp
View File

@@ -15,8 +15,11 @@ Código fuente creado por JailDesigner
#include "units/texture.h" #include "units/texture.h"
#include "units/screen.h" #include "units/screen.h"
#include "units/input.h" #include "units/input.h"
#include "units/on_screen_keyboard.h"
#include "quickcg.h" #include "quickcg.h"
using namespace QuickCG; using namespace QuickCG;
using namespace std;
// Punteros // Punteros
SDL_Event *event; SDL_Event *event;
@@ -32,13 +35,7 @@ Text *text;
Text *debugText; Text *debugText;
Texture *texture; Texture *texture;
MovingSprite *sprite; MovingSprite *sprite;
OnScreenKeyboard *osk = nullptr;
// Listas
enum e_fx // Tipos de efectos disponibles para el fondo
{
fx_fire,
fx_gradient
};
// Variables de uso general // Variables de uso general
Uint32 ticks = 0; // Variable para la frecuencia de actualización de la lógica del programa Uint32 ticks = 0; // Variable para la frecuencia de actualización de la lógica del programa
@@ -47,8 +44,10 @@ bool should_exit = false; // Variable para saber si ha terminado el progra,a
int counter = 0; // Contador para lo que se necesite int counter = 0; // Contador para lo que se necesite
string controllerName; // Nombre del primer mando detectado string controllerName; // Nombre del primer mando detectado
string inputPressed; // Texto con el último input que se ha pulsado string inputPressed; // Texto con el último input que se ha pulsado
e_fx fx = fx_fire; // Efecto seleccionado para el fondo int fx = 0; // Efecto seleccionado para el fondo
int fxTotal = 2; // Cantidad total de efectos disponibles para el fondo // 0 - Degradado
// 1 - Fuego
int fxTotal = 2; // Cantidad total de efectos disponibles para el fondo
// Variables para el efecto del degradado // Variables para el efecto del degradado
int gradColorMin = 64; // Minimo color más alto del degradado int gradColorMin = 64; // Minimo color más alto del degradado
@@ -57,12 +56,16 @@ int gradCurrentColor = 192; // Color actual más alto del degradado
int gradBreathDirection = 0; // Indica si gradCurrentColor crece o decrece int gradBreathDirection = 0; // Indica si gradCurrentColor crece o decrece
// Variables para el efecto de fuego // Variables para el efecto de fuego
const int fireScreenWidth = 320; // Ancho del efecto de fuego const int fireDesp = 3; // Desplazamiento inferior del efecto de fuego para eliminar las primeras filas
const int fireScreenHeight = 243; // Alto del efecto de fuego const int fireWidth = 320; // Ancho del efecto de fuego
int fire[fireScreenHeight][fireScreenWidth]; // Buffer con el fuego const int fireHeight = 240 + fireDesp; // Alto del efecto de fuego
ColorRGB palette[256]; // Paleta de color para el fuego Uint8 fire[fireHeight][fireWidth]; // Buffer con el fuego
const int fireDesp = 240 - fireScreenHeight + 3; // Fila donde comienza a dibujarse el efecto de fuego Uint32 palette[256]; // Paleta de color para el fuego
int fireModifier = 28; // Valor para modificar el efecto de fuego (0-30) int fireModifier = 28; // Valor para modificar el efecto de fuego (0-30)
SDL_Texture *fireTexture; // Textura donde pintar los pixels del fuego
Uint32 *fireBuffer; // Ubiación donde se guardan los pixeles del fuego
int pitch; // No se utiliza pero se necesita para dibujar los pixeles en la textura
SDL_Rect fireSource = {0, 0, fireWidth, fireHeight - fireDesp}; // Parte de la textura donde está el efecto de fuego que se copiará a la pantalla
// Inicializa las opciones // Inicializa las opciones
void initOptions(); void initOptions();
@@ -91,6 +94,9 @@ void initInput();
// Inicializa el texto // Inicializa el texto
void initText(); void initText();
// Inicializa el teclado en pantalla
void initOnScreenKeyboard();
// Inicializa el sprite // Inicializa el sprite
void initSprite(); void initSprite();
@@ -161,6 +167,8 @@ void initAsset(char *argv[])
asset->add("/data/smb2.png", t_bitmap); asset->add("/data/smb2.png", t_bitmap);
asset->add("/data/debug.txt", t_font); asset->add("/data/debug.txt", t_font);
asset->add("/data/debug.png", t_bitmap); asset->add("/data/debug.png", t_bitmap);
asset->add("/data/nokia.txt", t_font);
asset->add("/data/nokia.png", t_bitmap);
asset->add("/data/z80.png", t_bitmap); asset->add("/data/z80.png", t_bitmap);
asset->add("/data/notify.png", t_bitmap); asset->add("/data/notify.png", t_bitmap);
asset->add("/data/notify.wav", t_sound); asset->add("/data/notify.wav", t_sound);
@@ -236,6 +244,39 @@ void initText()
debugText = new Text(asset->get("debug.txt"), asset->get("debug.png"), renderer); debugText = new Text(asset->get("debug.txt"), asset->get("debug.png"), renderer);
} }
// Inicializa el teclado en pantalla
void initOnScreenKeyboard()
{
osk = new OnScreenKeyboard(renderer, input, asset->get("nokia.png"), asset->get("nokia.txt"), options, options->screen.nativeWidth - 30, options->screen.nativeHeight - 80, "JailDesigner");
osk->setBgColor({123, 99, 63});
osk->setCaption("JAILER_ID");
osk->setChars(USE_UPPER | USE_LOWER | USE_NUMBER);
}
// Elimina el teclado en pantalla
void deleteOnScreenKeyboard()
{
if (osk != nullptr)
{
delete osk;
osk = nullptr;
}
}
// Dibuja el teclado en pantalla
void renderOnScreenKeyboard()
{
if (osk != nullptr)
osk->render();
}
// Actualiza el teclado en pantalla
void updateOnScreenKeyboard()
{
if (osk != nullptr)
osk->update();
}
// Inicializa el sprite // Inicializa el sprite
void initSprite() void initSprite()
{ {
@@ -255,14 +296,16 @@ void initSprite()
// Inicializa el efecto de fuego // Inicializa el efecto de fuego
void initFire() void initFire()
{ {
// Intializes random number generator // Inicializa el generador de numeros aleatorios
srand((unsigned)SDL_GetTicks()); srand((unsigned)SDL_GetTicks());
// Inicializa el buffer de fuego // Inicializa el buffer de fuego
for (int y = 0; y < fireScreenHeight; ++y) for (int y = 0; y < fireHeight; ++y)
for (int x = 0; x < fireScreenWidth; ++x) for (int x = 0; x < fireWidth; ++x)
fire[y][x] = 0; fire[y][x] = 0;
fireTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, fireWidth, fireHeight);
// Inicializa la paleta // Inicializa la paleta
for (int x = 0; x < 256; ++x) for (int x = 0; x < 256; ++x)
{ {
@@ -270,11 +313,15 @@ void initFire()
// Hue goes from 0 to 85: red to yellow // Hue goes from 0 to 85: red to yellow
// Saturation is always the maximum: 255 // Saturation is always the maximum: 255
// Lightness is 0..255 for x=0..128, and 255 for x=128..255 // Lightness is 0..255 for x=0..128, and 255 for x=128..255
ColorRGB color = HSLtoRGB(ColorHSL(x / 3, 255, std::min(255, x * 2))); ColorRGB color = HSLtoRGB(ColorHSL(x / 3, 255, min(255, x * 2)));
// set the palette to the calculated RGB value
// palette[x] = RGBtoINT(color); // Pon en la paleta el color calculado
palette[x] = color; palette[x] = (Uint32)16777216 * 255 + 65536 * color.r + 256 * color.g + color.b;
} }
// Coloca algo de fuego en la textura
for (int x = 0; x < 100; ++x)
updateFire();
} }
// Inicializa todo // Inicializa todo
@@ -307,6 +354,9 @@ void initAll(char *argv[])
// Inicializa el texto // Inicializa el texto
initText(); initText();
// Inicializa el teclado en pantalla
// initOnScreenKeyboard();
// Inicializa el sprite // Inicializa el sprite
initSprite(); initSprite();
@@ -328,7 +378,6 @@ void checkEvents()
{ {
switch (event->key.keysym.scancode) switch (event->key.keysym.scancode)
{ {
case SDL_SCANCODE_ESCAPE: case SDL_SCANCODE_ESCAPE:
should_exit = true; should_exit = true;
break; break;
@@ -342,19 +391,33 @@ void checkEvents()
break; break;
case SDL_SCANCODE_F3: case SDL_SCANCODE_F3:
--fireModifier; ++fx %= fxTotal;
fireModifier = std::max(0, fireModifier);
break; break;
case SDL_SCANCODE_F4: case SDL_SCANCODE_F4:
++fireModifier; --fireModifier;
fireModifier = std::min(30, fireModifier); fireModifier = max(0, fireModifier);
break; break;
case SDL_SCANCODE_N: case SDL_SCANCODE_F5:
++fireModifier;
fireModifier = min(30, fireModifier);
break;
case SDL_SCANCODE_F6:
screen->showNotification("Ejemplo de notificacion", "con 2 lineas de texto", 0); screen->showNotification("Ejemplo de notificacion", "con 2 lineas de texto", 0);
break; break;
case SDL_SCANCODE_F7:
if (osk == nullptr)
initOnScreenKeyboard();
else
deleteOnScreenKeyboard();
break;
case SDL_SCANCODE_F8:
break;
default: default:
break; break;
} }
@@ -444,26 +507,30 @@ void updateGradient()
// Actualiza el efecto de fuego // Actualiza el efecto de fuego
void updateFire() void updateFire()
{ {
const int w = fireScreenWidth; const int w = fireWidth;
const int h = fireScreenHeight; const int h = fireHeight;
const int mod = 157 - fireModifier; const int mod = 157 - fireModifier;
// for (int x = 0; x < w; ++x)
// const int max = 10; // Bloquea la textura para poder escribir en los pixeles
// const int mod = max - abs((counter % (max * 2)) - max); SDL_LockTexture(fireTexture, NULL, (void **)&fireBuffer, &pitch);
// for (int x = 0; x < w; ++x)
// fire[h - 1][x] = 0; // Crea la fila inferior del fuego con pixels aleatorios
// for (int x = mod; x < w - mod; ++x)
// randomize the bottom row of the fire buffer
for (int x = 0; x < w; ++x) for (int x = 0; x < w; ++x)
// fire[h - 1][x] = abs(32768 + rand()) % 256; {
fire[h - 1][x] = rand() % 256; fire[h - 1][x] = rand() % 256;
// do the fire calculations for every pixel, from top to bottom fireBuffer[x + (h - 1) * 320] = palette[fire[h - 1][x]];
}
// Calcula los pixeles del efecto de fuego, desde la fila superior hasta la inferior
for (int y = 0; y < h - 1; ++y) for (int y = 0; y < h - 1; ++y)
for (int x = 0; x < w; ++x) for (int x = 0; x < w; ++x)
{ {
fire[y][x] = fire[y][x] = ((fire[(y + 1) % h][(x - 1 + w) % w] + fire[(y + 1) % h][(x) % w] + fire[(y + 1) % h][(x + 1) % w] + fire[(y + 2) % h][(x) % w]) * 32) / mod;
((fire[(y + 1) % h][(x - 1 + w) % w] + fire[(y + 1) % h][(x) % w] + fire[(y + 1) % h][(x + 1) % w] + fire[(y + 2) % h][(x) % w]) * 32) / mod; fireBuffer[x + y * 320] = palette[fire[y][x]];
} }
// Desbloquea la textura
SDL_UnlockTexture(fireTexture);
} }
// Actualiza el efecto de fondo // Actualiza el efecto de fondo
@@ -471,12 +538,12 @@ void updateFX()
{ {
switch (fx) switch (fx)
{ {
case fx_fire: case 0: // Degradado
updateFire(); updateGradient();
break; break;
case fx_gradient: case 1: // Fuego
updateGradient(); updateFire();
break; break;
default: default:
@@ -502,11 +569,10 @@ void update()
// Incrementa el contador // Incrementa el contador
counter++; counter++;
// Actualiza el objeto screen // Actualiza los objetos
screen->update(); updateOnScreenKeyboard(); // Actualiza el teclado en pantalla
screen->update(); // Actualiza la pantalla
// Actualiza el sprite updateSprite(); // Actualiza el sprite
updateSprite();
// Actualiza el efecto de fondo // Actualiza el efecto de fondo
updateFX(); updateFX();
@@ -541,13 +607,7 @@ void renderGradient()
// Dibuja el efecto de fuego // Dibuja el efecto de fuego
void renderFire() void renderFire()
{ {
for (int y = 0; y < fireScreenHeight - 3; ++y) SDL_RenderCopy(renderer, fireTexture, &fireSource, NULL);
for (int x = 0; x < fireScreenWidth; ++x)
{
const ColorRGB c = palette[std::min(255, std::max(0, fire[y][x]))];
SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, 255);
SDL_RenderDrawPoint(renderer, x, y + fireDesp);
}
} }
// Dibuja el efecto de fondo // Dibuja el efecto de fondo
@@ -555,12 +615,12 @@ void renderFX()
{ {
switch (fx) switch (fx)
{ {
case fx_fire: case 0: // Degradado
renderFire(); renderGradient();
break; break;
case fx_gradient: case 1: // Fuego
renderGradient(); renderFire();
break; break;
default: default:
@@ -571,16 +631,45 @@ void renderFX()
// Dibuja el texto // Dibuja el texto
void renderText() void renderText()
{ {
const string text1 = "Jail Engine DEMO";
const string text2 = "2023,2024 JailDesigner";
const string text3 = "Pulsa 'F1' o 'F2' para disminuir o aumentar la ventana";
const string text4 = "Pulsa 'F3' para cambiar el efecto de fondo: ";
const string text5 = "Pulsa 'F4' o 'F5' para modificar el efecto de fuego: ";
const string text6 = "Pulsa 'F6' para mostrar una notificacion";
const string text7 = "Pulsa 'F7' para mostrar u ocultar el teclado";
const string text8 = "Pulsa 'F8' para añadir o eliminar sprites";
const string text9 = "Controles:";
const string text10 = "Pulsa 'ESCAPE' para terminar el programa";
const string fxName = fx == 0 ? "Degradado" : "Fuego";
const int center = options->screen.nativeWidth / 2;
text->setZoom(2); text->setZoom(2);
text->writeDX(TXT_CENTER | TXT_STROKE, options->screen.nativeWidth / 2, text->getCharacterSize(), "Jail Engine DEMO", 1, {255, 255, 255}, 1, {0, 0, 192}); text->writeDX(TXT_CENTER | TXT_STROKE, center, text->getCharacterSize(), text1, 1, {255, 255, 255}, 1, {0, 0, 192});
text->disableZoom(); text->disableZoom();
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_STROKE, options->screen.nativeWidth / 2, text->getCharacterSize() * 4, "2023 JailDesigner", 1, {240, 240, 240}, 1, {0, 0, 192}); text->writeDX(TXT_CENTER | TXT_COLOR | TXT_STROKE, center, text->getCharacterSize() * 4, text2, 1, {240, 240, 240}, 1, {0, 0, 192});
debugText->writeDX(TXT_CENTER | TXT_COLOR | TXT_STROKE, options->screen.nativeWidth / 2, text->getCharacterSize() * 7, "Pulsa 'F1' o 'F2' para disminuir o aumentar la ventana", 1, {240, 240, 240}, 1, {0, 0, 192});
debugText->writeDX(TXT_CENTER | TXT_COLOR | TXT_STROKE, options->screen.nativeWidth / 2, text->getCharacterSize() * 9, "Pulsa 'N' para mostrar una notificacion", 1, {240, 240, 240}, 1, {0, 0, 192}); debugText->writeDX(TXT_CENTER | TXT_COLOR | TXT_STROKE, center, text->getCharacterSize() * 7, text3, 1, {240, 240, 240}, 1, {0, 0, 192});
debugText->writeDX(TXT_CENTER | TXT_COLOR | TXT_STROKE, options->screen.nativeWidth / 2, text->getCharacterSize() * 11, controllerName, 1, {240, 240, 240}, 1, {0, 0, 192});
debugText->writeDX(TXT_CENTER | TXT_COLOR | TXT_STROKE, options->screen.nativeWidth / 2, text->getCharacterSize() * 13, inputPressed, 1, {240, 240, 240}, 1, {0, 0, 192}); debugText->writeDX(TXT_CENTER | TXT_COLOR | TXT_STROKE, center, text->getCharacterSize() * 9, text4 + fxName, 1, {240, 240, 240}, 1, {0, 0, 192});
debugText->writeDX(TXT_CENTER | TXT_COLOR | TXT_STROKE, options->screen.nativeWidth / 2, options->screen.nativeHeight - (text->getCharacterSize() * 2), "Pulsa 'ESCAPE' para terminar el programa", 1, {240, 240, 240}, 1, {0, 0, 192}); if (fxName == "Fuego")
debugText->writeDX(TXT_CENTER | TXT_COLOR | TXT_STROKE, options->screen.nativeWidth / 2, text->getCharacterSize() * 17, "Pulsa 'F3' o 'F4' para modificar el fuego: " + to_string(fireModifier), 1, {240, 240, 240}, 1, {0, 0, 192}); debugText->writeDX(TXT_CENTER | TXT_COLOR | TXT_STROKE, center, text->getCharacterSize() * 10, text5 + to_string(fireModifier), 1, {240, 240, 240}, 1, {0, 0, 192});
debugText->writeDX(TXT_CENTER | TXT_COLOR | TXT_STROKE, center, text->getCharacterSize() * 12, text6, 1, {240, 240, 240}, 1, {0, 0, 192});
debugText->writeDX(TXT_CENTER | TXT_COLOR | TXT_STROKE, center, text->getCharacterSize() * 13, text7, 1, {240, 240, 240}, 1, {0, 0, 192});
debugText->writeDX(TXT_CENTER | TXT_COLOR | TXT_STROKE, center, text->getCharacterSize() * 14, text8, 1, {240, 240, 240}, 1, {0, 0, 192});
debugText->writeDX(TXT_CENTER | TXT_COLOR | TXT_STROKE, center, text->getCharacterSize() * 16, text9, 1, {240, 240, 240}, 1, {0, 0, 192});
debugText->writeDX(TXT_CENTER | TXT_COLOR | TXT_STROKE, center, text->getCharacterSize() * 17, controllerName, 1, {240, 240, 240}, 1, {0, 0, 192});
debugText->writeDX(TXT_CENTER | TXT_COLOR | TXT_STROKE, center, text->getCharacterSize() * 18, inputPressed, 1, {240, 240, 240}, 1, {0, 0, 192});
debugText->writeDX(TXT_CENTER | TXT_COLOR | TXT_STROKE, center, options->screen.nativeHeight - (text->getCharacterSize() * 2), text10, 1, {240, 240, 240}, 1, {0, 0, 192});
} }
// Dibuja los elementos del programa en pantalla // Dibuja los elementos del programa en pantalla
@@ -598,6 +687,9 @@ void render()
// Dinuja el texto // Dinuja el texto
renderText(); renderText();
// Dibuja el teclado en pantalla
renderOnScreenKeyboard();
// Vuelca el buffer en pantalla // Vuelca el buffer en pantalla
screen->blit(); screen->blit();
@@ -612,6 +704,10 @@ void freeAll()
if (texture != nullptr) if (texture != nullptr)
delete texture; delete texture;
// Finaliza el teclado en pantalla
if (osk != nullptr)
delete osk;
// Finaliza el texto // Finaliza el texto
if (text != nullptr) if (text != nullptr)
delete text; delete text;

478
units/gif.c Normal file
View File

@@ -0,0 +1,478 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#define EXTENSION_INTRODUCER 0x21
#define IMAGE_DESCRIPTOR 0x2C
#define TRAILER 0x3B
#define GRAPHIC_CONTROL 0xF9
#define APPLICATION_EXTENSION 0xFF
#define COMMENT_EXTENSION 0xFE
#define PLAINTEXT_EXTENSION 0x01
#define READ(dst, size) memcpy(dst, buffer, size); buffer += size
typedef struct
{
unsigned short width;
unsigned short height;
unsigned char fields;
unsigned char background_color_index;
unsigned char pixel_aspect_ratio;
}
screen_descriptor_t;
typedef struct
{
unsigned char r;
unsigned char g;
unsigned char b;
}
rgb;
typedef struct
{
unsigned short image_left_position;
unsigned short image_top_position;
unsigned short image_width;
unsigned short image_height;
unsigned char fields;
}
image_descriptor_t;
typedef struct
{
unsigned char byte;
int prev;
int len;
}
dictionary_entry_t;
typedef struct
{
unsigned char extension_code;
unsigned char block_size;
}
extension_t;
typedef struct
{
unsigned char fields;
unsigned short delay_time;
unsigned char transparent_color_index;
}
graphic_control_extension_t;
typedef struct
{
unsigned char application_id[ 8 ];
unsigned char version[ 3 ];
}
application_extension_t;
typedef struct
{
unsigned short left;
unsigned short top;
unsigned short width;
unsigned short height;
unsigned char cell_width;
unsigned char cell_height;
unsigned char foreground_color;
unsigned char background_color;
}
plaintext_extension_t;
//static unsigned short width = 0;
//static unsigned short height = 0;
//static unsigned char* uncompressed_data = NULL;
void uncompress( int code_length,
const unsigned char *input,
int input_length,
unsigned char *out )
{
//int maxbits;
int i, bit;
int code, prev = -1;
dictionary_entry_t *dictionary;
int dictionary_ind;
unsigned int mask = 0x01;
int reset_code_length;
int clear_code; // This varies depending on code_length
int stop_code; // one more than clear code
int match_len;
clear_code = 1 << ( code_length );
stop_code = clear_code + 1;
// To handle clear codes
reset_code_length = code_length;
// Create a dictionary large enough to hold "code_length" entries.
// Once the dictionary overflows, code_length increases
dictionary = ( dictionary_entry_t * )
malloc( sizeof( dictionary_entry_t ) * ( 1 << ( code_length + 1 ) ) );
// Initialize the first 2^code_len entries of the dictionary with their
// indices. The rest of the entries will be built up dynamically.
// Technically, it shouldn't be necessary to initialize the
// dictionary. The spec says that the encoder "should output a
// clear code as the first code in the image data stream". It doesn't
// say must, though...
for ( dictionary_ind = 0;
dictionary_ind < ( 1 << code_length );
dictionary_ind++ )
{
dictionary[ dictionary_ind ].byte = dictionary_ind;
// XXX this only works because prev is a 32-bit int (> 12 bits)
dictionary[ dictionary_ind ].prev = -1;
dictionary[ dictionary_ind ].len = 1;
}
// 2^code_len + 1 is the special "end" code; don't give it an entry here
dictionary_ind++;
dictionary_ind++;
// TODO verify that the very last byte is clear_code + 1
while ( input_length )
{
code = 0x0;
// Always read one more bit than the code length
for ( i = 0; i < ( code_length + 1 ); i++ )
{
// This is different than in the file read example; that
// was a call to "next_bit"
bit = ( *input & mask ) ? 1 : 0;
mask <<= 1;
if ( mask == 0x100 )
{
mask = 0x01;
input++;
input_length--;
}
code = code | ( bit << i );
}
if ( code == clear_code )
{
code_length = reset_code_length;
dictionary = ( dictionary_entry_t * ) realloc( dictionary,
sizeof( dictionary_entry_t ) * ( 1 << ( code_length + 1 ) ) );
for ( dictionary_ind = 0;
dictionary_ind < ( 1 << code_length );
dictionary_ind++ )
{
dictionary[ dictionary_ind ].byte = dictionary_ind;
// XXX this only works because prev is a 32-bit int (> 12 bits)
dictionary[ dictionary_ind ].prev = -1;
dictionary[ dictionary_ind ].len = 1;
}
dictionary_ind++;
dictionary_ind++;
prev = -1;
continue;
}
else if ( code == stop_code )
{
/*if ( input_length > 1 )
{
fprintf( stderr, "Malformed GIF (early stop code)\n" );
exit( 0 );
}*/
break;
}
// Update the dictionary with this character plus the _entry_
// (character or string) that came before it
if ( ( prev > -1 ) && ( code_length < 12 ) )
{
if ( code > dictionary_ind )
{
fprintf( stderr, "code = %.02x, but dictionary_ind = %.02x\n",
code, dictionary_ind );
exit( 0 );
}
// Special handling for KwKwK
if ( code == dictionary_ind )
{
int ptr = prev;
while ( dictionary[ ptr ].prev != -1 )
{
ptr = dictionary[ ptr ].prev;
}
dictionary[ dictionary_ind ].byte = dictionary[ ptr ].byte;
}
else
{
int ptr = code;
while ( dictionary[ ptr ].prev != -1 )
{
ptr = dictionary[ ptr ].prev;
}
dictionary[ dictionary_ind ].byte = dictionary[ ptr ].byte;
}
dictionary[ dictionary_ind ].prev = prev;
dictionary[ dictionary_ind ].len = dictionary[ prev ].len + 1;
dictionary_ind++;
// GIF89a mandates that this stops at 12 bits
if ( ( dictionary_ind == ( 1 << ( code_length + 1 ) ) ) &&
( code_length < 11 ) )
{
code_length++;
dictionary = ( dictionary_entry_t * ) realloc( dictionary,
sizeof( dictionary_entry_t ) * ( 1 << ( code_length + 1 ) ) );
}
}
prev = code;
// Now copy the dictionary entry backwards into "out"
match_len = dictionary[ code ].len;
while ( code != -1 )
{
out[ dictionary[ code ].len - 1 ] = dictionary[ code ].byte;
if ( dictionary[ code ].prev == code )
{
fprintf( stderr, "Internal error; self-reference." );
exit( 0 );
}
code = dictionary[ code ].prev;
}
out += match_len;
}
}
static int read_sub_blocks( unsigned char* buffer, unsigned char **data )
{
int data_length;
int index;
unsigned char block_size;
// Everything following are data sub-blocks, until a 0-sized block is
// encountered.
data_length = 0;
*data = NULL;
index = 0;
while ( 1 )
{
READ(&block_size, 1);
if ( block_size == 0 ) // end of sub-blocks
{
break;
}
data_length += block_size;
*data = (unsigned char*)realloc( *data, data_length );
// TODO this could be split across block size boundaries
READ(*data + index, block_size);
index += block_size;
}
return data_length;
}
unsigned char* process_image_descriptor( unsigned char* buffer,
rgb *gct,
int gct_size,
int resolution_bits )
{
image_descriptor_t image_descriptor;
int compressed_data_length;
unsigned char *compressed_data = NULL;
unsigned char lzw_code_size;
int uncompressed_data_length = 0;
unsigned char *uncompressed_data = NULL;
// TODO there could actually be lots of these
READ(&image_descriptor, 9);
// TODO if LCT = true, read the LCT
READ(&lzw_code_size, 1);
compressed_data_length = read_sub_blocks( buffer, &compressed_data );
// width = image_descriptor.image_width;
// height = image_descriptor.image_height;
uncompressed_data_length = image_descriptor.image_width *
image_descriptor.image_height;
uncompressed_data = (unsigned char*)malloc( uncompressed_data_length );
uncompress( lzw_code_size, compressed_data, compressed_data_length,
uncompressed_data );
if ( compressed_data ) free( compressed_data );
//if ( uncompressed_data )
// free( uncompressed_data );
return uncompressed_data;
}
/**
* @param gif_file the file descriptor of a file containing a
* GIF-encoded file. This should point to the first byte in
* the file when invoked.
*/
#define rb (*(buffer++))
uint32_t* LoadPalette(unsigned char *buffer) {
unsigned char header[7];
screen_descriptor_t screen_descriptor;
//int color_resolution_bits;
int global_color_table_size = 0; // number of entries in global_color_table
uint32_t *global_color_table = NULL;
READ(header, 6);
READ(&screen_descriptor, 7);
//color_resolution_bits = ((screen_descriptor.fields & 0x70) >> 4) + 1;
global_color_table = (uint32_t *)calloc(1, 1024);
if (screen_descriptor.fields & 0x80) {
global_color_table_size = 1 << (((screen_descriptor.fields & 0x07) + 1));
//global_color_table = (rgb *)malloc(3 * global_color_table_size);
//READ(global_color_table, 3 * global_color_table_size);
for (int i=0; i<global_color_table_size;++i) {
global_color_table[i] = (buffer[0]<<16) + (buffer[1]<<8) + buffer[2];
buffer+=3;
}
}
return global_color_table;
}
static unsigned char* process_gif_stream(unsigned char *buffer, unsigned short* w, unsigned short* h)
{
unsigned char header[ 7 ];
screen_descriptor_t screen_descriptor;
int color_resolution_bits;
int global_color_table_size =0; // number of entries in global_color_table
rgb *global_color_table = NULL;
unsigned char block_type = 0x0;
// A GIF file starts with a Header (section 17)
READ(header, 6);
header[ 6 ] = 0x0;
// XXX there's another format, GIF87a, that you may still find
// floating around.
/*if ( strcmp( "GIF89a", (char*)header ) )
{
fprintf( stderr,
"Invalid GIF file (header is '%s', should be 'GIF89a')\n",
header );
return NULL;
}*/
// Followed by a logical screen descriptor
// Note that this works because GIFs specify little-endian order; on a
// big-endian machine, the height & width would need to be reversed.
// Can't use sizeof here since GCC does byte alignment;
// sizeof( screen_descriptor_t ) = 8!
READ(&screen_descriptor, 7);
*w = screen_descriptor.width;
*h = screen_descriptor.height;
color_resolution_bits = ( ( screen_descriptor.fields & 0x70 ) >> 4 ) + 1;
if ( screen_descriptor.fields & 0x80 )
{
//int i;
// If bit 7 is set, the next block is a global color table; read it
global_color_table_size = 1 <<
( ( ( screen_descriptor.fields & 0x07 ) + 1 ) );
global_color_table = ( rgb * ) malloc( 3 * global_color_table_size );
// XXX this could conceivably return a short count...
READ(global_color_table, 3 * global_color_table_size);
}
while ( block_type != TRAILER )
{
READ(&block_type, 1);
unsigned char size;
switch ( block_type )
{
case IMAGE_DESCRIPTOR:
return process_image_descriptor(buffer,
global_color_table,
global_color_table_size,
color_resolution_bits);
break;
case EXTENSION_INTRODUCER:
buffer++;
size = *(buffer++);
buffer += size;
do {
size = *(buffer++);
buffer += size;
} while (size != 0);
/*if ( !process_extension( buffer ) )
{
return NULL;
}*/
break;
case TRAILER:
break;
default:
fprintf( stderr, "Bailing on unrecognized block type %.02x\n",
block_type );
return NULL;
}
}
return NULL;
}
unsigned char* LoadGif(unsigned char *buffer, unsigned short* w, unsigned short* h) {
return process_gif_stream(buffer, w, h);
}
/*int main( int argc, char *argv[] )
{
FILE* gif_file;
if ( argc < 2 )
{
fprintf( stderr, "Usage: %s <path-to-gif-file>\n", argv[ 0 ] );
exit( 0 );
}
gif_file = fopen( argv[ 1 ], "rb" );
if ( gif_file == NULL )
{
fprintf( stderr, "Unable to open file '%s'", argv[ 1 ] );
perror( ": " );
}
process_gif_stream( gif_file );
fclose( gif_file );
}*/

View File

@@ -224,16 +224,16 @@ bool Input::discoverGameController()
if (verbose) if (verbose)
{ {
cout << "\n** Checking game controllers" << endl;
if (nJoysticks > 0) if (nJoysticks > 0)
{ {
string stNumJoysticks = nJoysticks == 1 ? "joystick" : "joysticks"; string stNumJoysticks = nJoysticks == 1 ? "joystick" : "joysticks";
string stNumGamePads = numGamepads == 1 ? "is a gamepad" : "are gamepads"; string stNumGamePads = numGamepads == 1 ? "is a gamepad" : "are gamepads";
cout << "\n** Checking game controllers" << endl; cout << nJoysticks << " " << stNumJoysticks << " found (" << numGamepads << " " << stNumGamePads << ")" << endl;
cout << nJoysticks << " " << stNumJoysticks << " found (" << numGamepads << " " << stNumGamePads << ")\n";
} }
else else
{ {
cout << "\n>> No game controllers found\n"; cout << ">> No game controllers found" << endl;
} }
} }
@@ -343,7 +343,7 @@ void Input::setDefaultBindings()
bindKey(INPUT_BUTTON_2, SDL_SCANCODE_X); bindKey(INPUT_BUTTON_2, SDL_SCANCODE_X);
bindKey(INPUT_ACCEPT, SDL_SCANCODE_RETURN); bindKey(INPUT_ACCEPT, SDL_SCANCODE_RETURN);
bindKey(INPUT_CANCEL, SDL_SCANCODE_ESCAPE); bindKey(INPUT_CANCEL, SDL_SCANCODE_BACKSPACE);
bindKey(INPUT_PAUSE, SDL_SCANCODE_H); bindKey(INPUT_PAUSE, SDL_SCANCODE_H);
bindKey(INPUT_EXIT, SDL_SCANCODE_ESCAPE); bindKey(INPUT_EXIT, SDL_SCANCODE_ESCAPE);

View File

@@ -0,0 +1,300 @@
#include "on_screen_keyboard.h"
// #include <iostream>
// Constructor
OnScreenKeyboard::OnScreenKeyboard(SDL_Renderer *renderer, Input *input, string bitmapFile, string textFile, options_t *options, int width, int height, string output, color_t color)
{
// Inicializa variables
this->renderer = renderer;
this->options = options;
this->input = input;
this->width = width;
this->height = height;
// Crea objetos
text = new Text(textFile, bitmapFile, renderer);
texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height);
textureCursor = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, text->getCharacterSize() * 2, text->getCharacterSize() * 2);
SDL_SetTextureBlendMode(textureCursor, SDL_BLENDMODE_BLEND);
// Inicializa variables
this->output = output;
char_upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char_lower = "abcdefghijklmnopqrstuvwxyz";
char_numbers = "0123456789";
char_symbol = " !\"#$%&'()*+,-./:;<=>?@[]";
use_char_upper = true;
use_char_lower = false;
use_char_numbers = false;
use_char_symbol = false;
setLayout();
caption = "";
dest = {(options->screen.nativeWidth - width) / 2, (options->screen.nativeHeight - height) / 2, width, height};
cursor.col = 0;
cursor.row = 0;
cursor.dest = {0, 0, 16, 16};
// Rellena la textura de fondo con el color y el texto
fillTexture();
// Rellena la textura del cursor
SDL_SetRenderTarget(renderer, textureCursor);
color_t c = {192, 0, 0};
SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, 255);
SDL_RenderClear(renderer);
c = lightenColor(c, 20);
SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, 255);
SDL_RenderDrawRect(renderer, NULL);
SDL_SetRenderTarget(renderer, nullptr);
}
// Destructor
OnScreenKeyboard::~OnScreenKeyboard()
{
// Libera la memoria de los objetos
if (text != nullptr)
{
delete text;
}
if (texture != nullptr)
{
SDL_DestroyTexture(texture);
}
}
// Rellena la textura de fondo con el color y el texto
void OnScreenKeyboard::fillTexture()
{
// Destruye la textura si la hubiera
if (texture)
SDL_DestroyTexture(texture);
// Crea la textura
height = (text->getCharacterSize() * 4) + (text->getCharacterSize() * rows * 2);
texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height);
dest = {(options->screen.nativeWidth - width) / 2, (options->screen.nativeHeight - height) / 2, width, height};
// Empieza a dibujar en la textura
SDL_SetRenderTarget(renderer, texture);
// Establece el color de fondo
SDL_SetRenderDrawColor(renderer, bgColor.r, bgColor.g, bgColor.b, 255);
SDL_RenderClear(renderer);
color_t color = lightenColor(bgColor, 20);
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 255);
SDL_RenderDrawRect(renderer, NULL);
// Escribe el texto que aparece en el objeto
text->write(text->getCharacterSize(), text->getCharacterSize(), caption);
// Dibuja el cuadro donde va el texto que se escribirá
const color_t darkColor = darkenColor(bgColor, 10);
SDL_SetRenderDrawColor(renderer, darkColor.r, darkColor.g, darkColor.b, 255);
const int x_rect = (text->getCharacterSize() * 2) + text->lenght(caption);
const int y_rect = text->getCharacterSize();
const int w_rect = width - text->getCharacterSize() - x_rect;
const int h_rect = text->getCharacterSize();
outputDest = {x_rect, y_rect, w_rect, h_rect};
SDL_RenderFillRect(renderer, &outputDest);
// Dibuja los caracteres que conformaran el teclado
const int dist = text->getCharacterSize() * 2;
const int offset_x = text->getCharacterSize();
const int offset_y = text->getCharacterSize() * 3;
for (int j = 0; j < rows; ++j)
for (int i = 0; i < columns; ++i)
{
const int pos = i + (j * columns);
if (pos < (int)layout.size())
{
// color_t color = randColor();
// SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 255);
// SDL_Rect rect = {offset_x + (layout.at(pos).col * dist), offset_y + (layout.at(pos).row * dist), dist, dist};
// SDL_RenderFillRect(renderer, &rect);
// text->write(offset_x + (layout.at(pos).col * dist) + (dist / 2), offset_y + (layout.at(pos).row * dist) + (dist / 2), layout.at(pos).caption);
text->writeCentered(offset_x + (layout.at(pos).col * dist) + (dist / 2), offset_y + (layout.at(pos).row * dist) + (dist / 4), layout.at(pos).caption);
}
}
// Deja de dibujar en la textura
SDL_SetRenderTarget(renderer, nullptr);
}
// Calcula cuantos caracteres se utilizaran para crear el teclado
int OnScreenKeyboard::getTotalChars()
{
int total = 0;
total += use_char_upper ? char_upper.length() : 0;
total += use_char_lower ? char_lower.length() : 0;
total += use_char_numbers ? char_numbers.length() : 0;
total += use_char_symbol ? char_symbol.length() : 0;
return total;
}
// Calcula cuantas columnas necesita el teclado
int OnScreenKeyboard::getColumns()
{
const int keyWidth = text->getCharacterSize() * 2;
int rowWidth = width - text->getCharacterSize();
return rowWidth / keyWidth;
}
// Calcula cuantas filas necesita el teclado
int OnScreenKeyboard::getRows()
{
return (totalChars / getColumns()) + 1;
}
// Establece la disposición del teclado
void OnScreenKeyboard::setLayout()
{
totalChars = getTotalChars();
columns = getColumns();
rows = getRows();
int index_col = 0;
int index_row = 0;
// Establece los caracteres a escribir
string allChars = "";
allChars = use_char_upper ? allChars + char_upper : allChars;
allChars = use_char_lower ? allChars + char_lower : allChars;
allChars = use_char_numbers ? allChars + char_numbers : allChars;
allChars = use_char_symbol ? allChars + char_symbol : allChars;
layout.clear();
for (int i = 0; i < (int)allChars.length(); ++i)
{
key_t key;
key.col = index_col;
key.row = index_row;
key.caption = allChars.substr(i, 1);
layout.push_back(key);
++index_col;
if (index_col == columns)
{
index_col = 0;
++index_row;
}
}
}
// Comprueba las entradas
void OnScreenKeyboard::checkInput()
{
if (input->checkInput(INPUT_LEFT, REPEAT_FALSE))
decCursorCol();
if (input->checkInput(INPUT_RIGHT, REPEAT_FALSE))
incCursorCol();
if (input->checkInput(INPUT_UP, REPEAT_FALSE))
decCursorRow();
if (input->checkInput(INPUT_DOWN, REPEAT_FALSE))
incCursorRow();
if (input->checkInput(INPUT_ACCEPT, REPEAT_FALSE))
addChar();
if (input->checkInput(INPUT_CANCEL, REPEAT_FALSE))
removeChar();
}
// Disminuye en una columna la posición del cursor
void OnScreenKeyboard::decCursorCol()
{
cursor.col = cursor.col > 0 ? cursor.col - 1 : columns - 1;
}
// Incrementa en una columna la posición del cursor
void OnScreenKeyboard::incCursorCol()
{
++cursor.col %= columns;
}
// Disminuye en una fila la posición del cursor
void OnScreenKeyboard::decCursorRow()
{
cursor.row = cursor.row > 0 ? cursor.row - 1 : rows - 1;
}
// Aumenta en una fila la posición del cursor
void OnScreenKeyboard::incCursorRow()
{
++cursor.row %= rows;
}
// Actualiza la posición de la textura del cursor
void OnScreenKeyboard::updateCursor()
{
const int offset_x = text->getCharacterSize();
const int offset_y = text->getCharacterSize() * 3;
cursor.dest.x = dest.x + offset_x + (cursor.col * cursor.dest.w);
cursor.dest.y = dest.y + offset_y + (cursor.row * cursor.dest.h);
}
// Añade un caracter a la salida
void OnScreenKeyboard::addChar()
{
const int pos = cursor.col + cursor.row * columns;
if (pos < (int)layout.size())
output = output + layout.at(pos).caption;
}
// Borra el último caracter de la salida
void OnScreenKeyboard::removeChar()
{
if (output.length() > 0)
output = output.substr(0, output.length() - 1);
}
// Actualiza la lógica del objeto
void OnScreenKeyboard::update()
{
// Comprueba las entradas
checkInput();
// Actualiza la posición de la textura del cursor
updateCursor();
}
// Dibuja el objeto en pantalla
void OnScreenKeyboard::render()
{
SDL_RenderCopy(renderer, texture, nullptr, &dest);
SDL_RenderCopy(renderer, textureCursor, nullptr, &cursor.dest);
const int pos = cursor.col + cursor.row * columns;
const string key = pos < (int)layout.size() ? layout.at(pos).caption : "";
text->writeDX(TXT_CENTER | TXT_COLOR, cursor.dest.x + cursor.dest.w / 2, cursor.dest.y + cursor.dest.w / 4, key, 1, {0, 255, 0});
text->write(dest.x + outputDest.x, dest.y + outputDest.y, output);
}
// Establece el color de fondo
void OnScreenKeyboard::setBgColor(color_t color)
{
bgColor = color;
fillTexture();
}
// Establece el texto a mostrar junto al texto a introducir
void OnScreenKeyboard::setCaption(string text)
{
caption = text;
fillTexture();
}
// Establece qué caracteres ofrecerá el objeto
void OnScreenKeyboard::setChars(Uint8 mode)
{
use_char_upper = ((mode & USE_UPPER) == USE_UPPER);
use_char_lower = ((mode & USE_LOWER) == USE_LOWER);
use_char_numbers = ((mode & USE_NUMBER) == USE_NUMBER);
use_char_symbol = ((mode & USE_SYMBOL) == USE_SYMBOL);
setLayout();
fillTexture();
}

128
units/on_screen_keyboard.h Normal file
View File

@@ -0,0 +1,128 @@
#pragma once
#include <SDL2/SDL.h>
#include "utils.h"
#include "text.h"
#include "input.h"
#ifndef ON_SCREEN_KEYBOARD_H
#define ON_SCREEN_KEYBOARD_H
#define USE_UPPER 1
#define USE_LOWER 2
#define USE_NUMBER 4
#define USE_SYMBOL 8
using namespace std;
class OnScreenKeyboard
{
private:
// Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana
Text *text; // Objeto para dibujar texto
Input *input; // Gestor de eventos de entrada de teclado o gamepad
options_t *options; // Variable con todas las opciones del programa
SDL_Texture *texture; // Textura donde dibujar el objeto
SDL_Texture *textureCursor; // Textura para dibujar el cursor
// Estructuras
struct key_t
{
int col; // Posición horizontal de la tecla
int row; // Posición vertical de la tecla
string caption; // Texto de la tecla
};
struct cursor_t
{
int col;
int row;
SDL_Rect dest;
};
// Variables
string char_upper; // Cadena de texto con las letras en mayúscula
string char_lower; // Cadena de texto con las letras en minuscula
string char_numbers; // Cadena de texto con los números
string char_symbol; // Cadena de texto con los símbolos
bool use_char_upper; // Indica si se utilizará ese set de caracteres
bool use_char_lower; // Indica si se utilizará ese set de caracteres
bool use_char_numbers; // Indica si se utilizará ese set de caracteres
bool use_char_symbol; // Indica si se utilizará ese set de caracteres
int totalChars; // Cantidad de caracteres a utilizar
int columns; // Cantidad de caracteres que hay en una fila del teclado
int rows; // Cantidad de filas de caracteres que tendrá el teclado
color_t bgColor; // Color usado para el fondo
string caption; // Texto a mostrar junto al texto a introducir
int width; // Ancho del objeto
int height; // Altura del objeto
SDL_Rect dest; // Coordenadas donde se dibuja el objeto en pantalla
vector<key_t> layout; // Contiene la disposición del teclado
cursor_t cursor; // Variable para gestionar el cursor
string output; // Texto de salida
SDL_Rect outputDest; // Rectangulo con el texto de salida
// Rellena la textura de fondo con el color y el texto
void fillTexture();
// Calcula cuantos caracteres se utilizaran para crear el teclado
int getTotalChars();
// Calcula cuantas columnas necesita el teclado
int getColumns();
// Calcula cuantas filas necesita el teclado
int getRows();
// Establece la disposición del teclado
void setLayout();
// Comprueba las entradas
void checkInput();
// Disminuye en una columna la posición del cursor
void decCursorCol();
// Incrementa en una columna la posición del cursor
void incCursorCol();
// Disminuye en una fila la posición del cursor
void decCursorRow();
// Aumenta en una columna la posición del cursor
void incCursorRow();
// Actualiza la posición de la textura del cursor
void updateCursor();
// Añade un caracter a la salida
void addChar();
// Borra el último caracter de la salida
void removeChar();
public:
// Constructor
OnScreenKeyboard(SDL_Renderer *renderer, Input *input, string bitmapFile, string textFile, options_t *options, int width, int height, string output = "", color_t color = {0, 0, 0});
// Destructor
~OnScreenKeyboard();
// Actualiza la lógica del objeto
void update();
// Dibuja el objeto en pantalla
void render();
// Establece el color de fondo
void setBgColor(color_t color);
// Establece el texto a mostrar junto al texto a introducir
void setCaption(string text);
// Establece qué caracteres ofrecerá el objeto
void setChars(Uint8 mode);
};
#endif

165
units/paleta.cpp Normal file
View File

@@ -0,0 +1,165 @@
#include "paleta.h"
#include "gif.c"
#include <stdio.h>
struct jSurface_s
{
Uint8 *data;
Uint16 w, h;
};
static SDL_Window *jWin = NULL;
static SDL_Renderer *jRen = NULL;
static SDL_Texture *jTex = NULL;
static jSurface jScreen;
static jSurface jDestSurf;
static jSurface jSourceSurf = NULL;
static Uint32 paleta[256];
static int jWidth = 320;
static int jHeight = 240;
static int jZoom = 2;
static int transparentColor = 0;
jSurface jNewSurface(int w, int h)
{
jSurface surf = (jSurface)malloc(sizeof(jSurface_s));
surf->w = w;
surf->h = h;
surf->data = (Uint8 *)malloc(w * h);
return surf;
}
void jDeleteSurface(jSurface surf)
{
if (surf == NULL)
return;
if (surf->data != NULL)
free(surf->data);
free(surf);
}
void jSetDest(jSurface surf)
{
if (surf == NULL)
jDestSurf = jScreen;
else
jDestSurf = surf;
}
void jSetSource(jSurface surf)
{
jSourceSurf = surf;
}
void jBlit(int dx, int dy, int sx, int sy, int w, int h)
{
if (jSourceSurf == NULL)
return;
for (int iy = 0; iy < h; ++iy)
{
for (int ix = 0; ix < w; ++ix)
jPutPixel(dx + ix, dy + iy, jGetPixel(sx + ix, sy + iy));
}
}
jSurface jLoadSurface(const char *filename)
{
FILE *f = fopen(filename, "rb");
if (!f)
return NULL;
fseek(f, 0, SEEK_END);
long size = ftell(f);
fseek(f, 0, SEEK_SET);
Uint8 *buffer = (Uint8 *)malloc(size);
fread(buffer, size, 1, f);
fclose(f);
Uint16 w, h;
Uint8 *pixels = LoadGif(buffer, &w, &h);
if (pixels == NULL)
{
return NULL;
}
jSurface surf = (jSurface)malloc(sizeof(jSurface_s));
surf->w = w;
surf->h = h;
surf->data = pixels;
free(buffer);
return surf;
}
void jLoadPal(const char *filename)
{
FILE *f = fopen(filename, "rb");
if (!f)
return;
fseek(f, 0, SEEK_END);
long size = ftell(f);
fseek(f, 0, SEEK_SET);
Uint8 *buffer = (Uint8 *)malloc(size);
fread(buffer, size, 1, f);
fclose(f);
Uint32 *pal = LoadPalette(buffer);
if (pal == NULL)
{
return;
}
free(buffer);
for (int i = 0; i < 256; ++i)
{
paleta[i] = pal[i];
}
}
void jInit(const char *titol, int w, int h, int z)
{
SDL_Init(SDL_INIT_EVERYTHING);
jWidth = w;
jHeight = h;
jZoom = z;
jWin = SDL_CreateWindow(titol, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, w * z, h * z, SDL_WINDOW_SHOWN);
jRen = SDL_CreateRenderer(jWin, -1, 0);
SDL_RenderSetLogicalSize(jRen, w, h);
jTex = SDL_CreateTexture(jRen, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, w, h);
jScreen = jNewSurface(w, h);
jDestSurf = jScreen;
}
void jSetPal(int index, Uint32 color)
{
paleta[index] = color;
}
void jCls(Uint8 color)
{
for (int i = 0; i < jDestSurf->w * jDestSurf->h; ++i)
jDestSurf->data[i] = color;
}
void jFlip()
{
Uint32 *pixels;
int pitch;
SDL_LockTexture(jTex, NULL, (void **)&pixels, &pitch);
for (int i = 0; i < jWidth * jHeight; ++i)
pixels[i] = paleta[jScreen->data[i]];
SDL_UnlockTexture(jTex);
SDL_RenderCopy(jRen, jTex, NULL, NULL);
SDL_RenderPresent(jRen);
}
void jPutPixel(int x, int y, Uint8 color)
{
if (x < 0 || y < 0 || x >= jDestSurf->w || y >= jDestSurf->h || color == transparentColor)
return;
jDestSurf->data[x + y * jDestSurf->w] = color;
}
Uint8 jGetPixel(int x, int y)
{
return jSourceSurf->data[x + y * jSourceSurf->w];
}

28
units/paleta.h Normal file
View File

@@ -0,0 +1,28 @@
#pragma once
#include <SDL2/SDL.h>
typedef struct jSurface_s *jSurface;
void init();
void update();
jSurface jNewSurface(int w, int h);
void jDeleteSurface(jSurface surf);
void jSetDest(jSurface surf);
void jSetSource(jSurface surf);
jSurface jLoadSurface(const char* filename);
void jPutPixel(int x, int y, Uint8 color);
Uint8 jGetPixel(int x, int y);
void jBlit(int dx, int dy, int sx, int sy, int w, int h);
void jInit(const char *titol, int w, int h, int z);
void jSetPal(int index, Uint32 color);
void jLoadPal(const char *filename);
void jCls(Uint8 color);
void jFlip();

View File

@@ -1,6 +1,8 @@
#include "utils.h" #include "utils.h"
#include <math.h> #include <math.h>
using namespace std;
// Calcula el cuadrado de la distancia entre dos puntos // Calcula el cuadrado de la distancia entre dos puntos
double distanceSquared(int x1, int y1, int x2, int y2) double distanceSquared(int x1, int y1, int x2, int y2)
{ {
@@ -576,7 +578,37 @@ void initOptions(options_t *options)
options->screen.borderHeight = 0; options->screen.borderHeight = 0;
options->notifications.posV = pos_top; options->notifications.posV = pos_top;
options->notifications.posH = pos_left; options->notifications.posH = pos_left;
options->notifications.sound = true; options->notifications.sound = true;
options->notifications.color = {48, 48, 48}; options->notifications.color = {48, 48, 48};
}
// Oscurece un color
color_t darkenColor(color_t color, int amount)
{
color_t newColor;
newColor.r = max(0, color.r - amount);
newColor.g = max(0, color.g - amount);
newColor.b = max(0, color.b - amount);
return newColor;
}
// Aclara un color
color_t lightenColor(color_t color, int amount)
{
color_t newColor;
newColor.r = min(255, color.r + amount);
newColor.g = min(255, color.g + amount);
newColor.b = min(255, color.b + amount);
return newColor;
}
// Obtiene un color aleatorio
color_t randColor()
{
color_t newColor;
newColor.r = rand() % 256;
newColor.g = rand() % 256;
newColor.b = rand() % 256;
return newColor;
} }

View File

@@ -201,4 +201,13 @@ bool colorAreEqual(color_t color1, color_t color2);
// Inicializa la estructura de opciones // Inicializa la estructura de opciones
void initOptions(options_t *options); void initOptions(options_t *options);
// Oscurece un color
color_t darkenColor(color_t color, int amount);
// Aclara un color
color_t lightenColor(color_t color, int amount);
// Obtiene un color aleatorio
color_t randColor();
#endif #endif