Compare commits
3 Commits
e347e04d33
...
metal
| Author | SHA1 | Date | |
|---|---|---|---|
| d6ffbda00d | |||
| ff7aef827c | |||
| 6ff7ccf69a |
@@ -111,22 +111,35 @@ set(APP_SOURCES
|
|||||||
# Fuentes de librerías de terceros
|
# Fuentes de librerías de terceros
|
||||||
set(EXTERNAL_SOURCES
|
set(EXTERNAL_SOURCES
|
||||||
source/external/jail_audio.cpp
|
source/external/jail_audio.cpp
|
||||||
source/external/jail_shader.cpp
|
|
||||||
source/external/json.hpp
|
source/external/json.hpp
|
||||||
source/external/gif.cpp
|
source/external/gif.cpp
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Fuentes del sistema de renderizado
|
||||||
|
set(RENDERING_SOURCES
|
||||||
|
source/rendering/opengl/opengl_shader.cpp
|
||||||
|
)
|
||||||
|
|
||||||
|
# Añadir backend de Metal en macOS
|
||||||
|
if(APPLE)
|
||||||
|
list(APPEND RENDERING_SOURCES
|
||||||
|
source/rendering/metal/metal_shader.mm
|
||||||
|
)
|
||||||
|
message(STATUS "Metal backend habilitado para macOS")
|
||||||
|
endif()
|
||||||
|
|
||||||
# Configuración de SDL3
|
# Configuración de SDL3
|
||||||
find_package(SDL3 REQUIRED CONFIG REQUIRED COMPONENTS SDL3)
|
find_package(SDL3 REQUIRED CONFIG REQUIRED COMPONENTS SDL3)
|
||||||
message(STATUS "SDL3 encontrado: ${SDL3_INCLUDE_DIRS}")
|
message(STATUS "SDL3 encontrado: ${SDL3_INCLUDE_DIRS}")
|
||||||
|
|
||||||
# --- 2. AÑADIR EJECUTABLE ---
|
# --- 2. AÑADIR EJECUTABLE ---
|
||||||
add_executable(${PROJECT_NAME} ${APP_SOURCES} ${EXTERNAL_SOURCES})
|
add_executable(${PROJECT_NAME} ${APP_SOURCES} ${EXTERNAL_SOURCES} ${RENDERING_SOURCES})
|
||||||
|
|
||||||
# --- 3. DIRECTORIOS DE INCLUSIÓN ---
|
# --- 3. DIRECTORIOS DE INCLUSIÓN ---
|
||||||
target_include_directories(${PROJECT_NAME} PUBLIC
|
target_include_directories(${PROJECT_NAME} PUBLIC
|
||||||
"${CMAKE_SOURCE_DIR}/source"
|
"${CMAKE_SOURCE_DIR}/source"
|
||||||
"${CMAKE_SOURCE_DIR}/source/external"
|
"${CMAKE_SOURCE_DIR}/source/external"
|
||||||
|
"${CMAKE_SOURCE_DIR}/source/rendering"
|
||||||
"${CMAKE_BINARY_DIR}"
|
"${CMAKE_BINARY_DIR}"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -154,6 +167,11 @@ elseif(APPLE)
|
|||||||
target_compile_definitions(${PROJECT_NAME} PRIVATE MACOS_BUILD)
|
target_compile_definitions(${PROJECT_NAME} PRIVATE MACOS_BUILD)
|
||||||
target_compile_options(${PROJECT_NAME} PRIVATE -Wno-deprecated)
|
target_compile_options(${PROJECT_NAME} PRIVATE -Wno-deprecated)
|
||||||
set(CMAKE_OSX_ARCHITECTURES "arm64")
|
set(CMAKE_OSX_ARCHITECTURES "arm64")
|
||||||
|
# Enlazar frameworks de Metal
|
||||||
|
target_link_libraries(${PROJECT_NAME} PRIVATE
|
||||||
|
"-framework Metal"
|
||||||
|
"-framework QuartzCore"
|
||||||
|
)
|
||||||
elseif(UNIX AND NOT APPLE)
|
elseif(UNIX AND NOT APPLE)
|
||||||
target_compile_definitions(${PROJECT_NAME} PRIVATE LINUX_BUILD)
|
target_compile_definitions(${PROJECT_NAME} PRIVATE LINUX_BUILD)
|
||||||
endif()
|
endif()
|
||||||
|
|||||||
@@ -74,8 +74,13 @@ SOUND|${PREFIX}/data/sound/voice_recover.wav
|
|||||||
SOUND|${PREFIX}/data/sound/voice_thankyou.wav
|
SOUND|${PREFIX}/data/sound/voice_thankyou.wav
|
||||||
SOUND|${PREFIX}/data/sound/walk.wav
|
SOUND|${PREFIX}/data/sound/walk.wav
|
||||||
|
|
||||||
# Shaders
|
# Shaders OpenGL (Windows/Linux)
|
||||||
DATA|${PREFIX}/data/shaders/crtpi.glsl
|
DATA|${PREFIX}/data/shaders/crtpi_vertex.glsl
|
||||||
|
DATA|${PREFIX}/data/shaders/crtpi_fragment.glsl
|
||||||
|
|
||||||
|
# Shaders Metal (macOS) - opcionales
|
||||||
|
DATA|${PREFIX}/data/shaders/crtpi_vertex.metal|optional
|
||||||
|
DATA|${PREFIX}/data/shaders/crtpi_fragment.metal|optional
|
||||||
|
|
||||||
# Texturas - Balloons
|
# Texturas - Balloons
|
||||||
ANIMATION|${PREFIX}/data/gfx/balloon/balloon0.ani
|
ANIMATION|${PREFIX}/data/gfx/balloon/balloon0.ani
|
||||||
|
|||||||
@@ -1,237 +0,0 @@
|
|||||||
/*
|
|
||||||
crt-pi - A Raspberry Pi friendly CRT shader.
|
|
||||||
|
|
||||||
Copyright (C) 2015-2016 davej
|
|
||||||
|
|
||||||
This program is free software; you can redistribute it and/or modify it
|
|
||||||
under the terms of the GNU General Public License as published by the Free
|
|
||||||
Software Foundation; either version 2 of the License, or (at your option)
|
|
||||||
any later version.
|
|
||||||
|
|
||||||
|
|
||||||
Notes:
|
|
||||||
|
|
||||||
This shader is designed to work well on Raspberry Pi GPUs (i.e. 1080P @ 60Hz on a game with a 4:3 aspect ratio). It pushes the Pi's GPU hard and enabling some features will slow it down so that it is no longer able to match 1080P @ 60Hz. You will need to overclock your Pi to the fastest setting in raspi-config to get the best results from this shader: 'Pi2' for Pi2 and 'Turbo' for original Pi and Pi Zero. Note: Pi2s are slower at running the shader than other Pis, this seems to be down to Pi2s lower maximum memory speed. Pi2s don't quite manage 1080P @ 60Hz - they drop about 1 in 1000 frames. You probably won't notice this, but if you do, try enabling FAKE_GAMMA.
|
|
||||||
|
|
||||||
SCANLINES enables scanlines. You'll almost certainly want to use it with MULTISAMPLE to reduce moire effects. SCANLINE_WEIGHT defines how wide scanlines are (it is an inverse value so a higher number = thinner lines). SCANLINE_GAP_BRIGHTNESS defines how dark the gaps between the scan lines are. Darker gaps between scan lines make moire effects more likely.
|
|
||||||
|
|
||||||
GAMMA enables gamma correction using the values in INPUT_GAMMA and OUTPUT_GAMMA. FAKE_GAMMA causes it to ignore the values in INPUT_GAMMA and OUTPUT_GAMMA and approximate gamma correction in a way which is faster than true gamma whilst still looking better than having none. You must have GAMMA defined to enable FAKE_GAMMA.
|
|
||||||
|
|
||||||
CURVATURE distorts the screen by CURVATURE_X and CURVATURE_Y. Curvature slows things down a lot.
|
|
||||||
|
|
||||||
By default the shader uses linear blending horizontally. If you find this too blury, enable SHARPER.
|
|
||||||
|
|
||||||
BLOOM_FACTOR controls the increase in width for bright scanlines.
|
|
||||||
|
|
||||||
MASK_TYPE defines what, if any, shadow mask to use. MASK_BRIGHTNESS defines how much the mask type darkens the screen.
|
|
||||||
|
|
||||||
*/
|
|
||||||
|
|
||||||
#pragma parameter CURVATURE_X "Screen curvature - horizontal" 0.10 0.0 1.0 0.01
|
|
||||||
#pragma parameter CURVATURE_Y "Screen curvature - vertical" 0.15 0.0 1.0 0.01
|
|
||||||
#pragma parameter MASK_BRIGHTNESS "Mask brightness" 0.70 0.0 1.0 0.01
|
|
||||||
#pragma parameter SCANLINE_WEIGHT "Scanline weight" 6.0 0.0 15.0 0.1
|
|
||||||
#pragma parameter SCANLINE_GAP_BRIGHTNESS "Scanline gap brightness" 0.12 0.0 1.0 0.01
|
|
||||||
#pragma parameter BLOOM_FACTOR "Bloom factor" 1.5 0.0 5.0 0.01
|
|
||||||
#pragma parameter INPUT_GAMMA "Input gamma" 2.4 0.0 5.0 0.01
|
|
||||||
#pragma parameter OUTPUT_GAMMA "Output gamma" 2.2 0.0 5.0 0.01
|
|
||||||
|
|
||||||
// Haven't put these as parameters as it would slow the code down.
|
|
||||||
#define SCANLINES
|
|
||||||
#define MULTISAMPLE
|
|
||||||
#define GAMMA
|
|
||||||
//#define FAKE_GAMMA
|
|
||||||
//#define CURVATURE
|
|
||||||
//#define SHARPER
|
|
||||||
// MASK_TYPE: 0 = none, 1 = green/magenta, 2 = trinitron(ish)
|
|
||||||
#define MASK_TYPE 2
|
|
||||||
|
|
||||||
|
|
||||||
#ifdef GL_ES
|
|
||||||
#define COMPAT_PRECISION mediump
|
|
||||||
precision mediump float;
|
|
||||||
#else
|
|
||||||
#define COMPAT_PRECISION
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifdef PARAMETER_UNIFORM
|
|
||||||
uniform COMPAT_PRECISION float CURVATURE_X;
|
|
||||||
uniform COMPAT_PRECISION float CURVATURE_Y;
|
|
||||||
uniform COMPAT_PRECISION float MASK_BRIGHTNESS;
|
|
||||||
uniform COMPAT_PRECISION float SCANLINE_WEIGHT;
|
|
||||||
uniform COMPAT_PRECISION float SCANLINE_GAP_BRIGHTNESS;
|
|
||||||
uniform COMPAT_PRECISION float BLOOM_FACTOR;
|
|
||||||
uniform COMPAT_PRECISION float INPUT_GAMMA;
|
|
||||||
uniform COMPAT_PRECISION float OUTPUT_GAMMA;
|
|
||||||
#else
|
|
||||||
#define CURVATURE_X 0.05
|
|
||||||
#define CURVATURE_Y 0.1
|
|
||||||
#define MASK_BRIGHTNESS 0.80
|
|
||||||
#define SCANLINE_WEIGHT 6.0
|
|
||||||
#define SCANLINE_GAP_BRIGHTNESS 0.12
|
|
||||||
#define BLOOM_FACTOR 3.5
|
|
||||||
#define INPUT_GAMMA 2.4
|
|
||||||
#define OUTPUT_GAMMA 2.2
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/* COMPATIBILITY
|
|
||||||
- GLSL compilers
|
|
||||||
*/
|
|
||||||
|
|
||||||
// Uniform para el tamaño de textura (pasado desde C++)
|
|
||||||
uniform vec2 TextureSize;
|
|
||||||
|
|
||||||
#if defined(CURVATURE)
|
|
||||||
varying vec2 screenScale;
|
|
||||||
#endif
|
|
||||||
varying vec2 TEX0;
|
|
||||||
varying float filterWidth;
|
|
||||||
|
|
||||||
#if defined(VERTEX)
|
|
||||||
//uniform mat4 MVPMatrix;
|
|
||||||
//attribute vec4 VertexCoord;
|
|
||||||
//attribute vec2 TexCoord;
|
|
||||||
//uniform vec2 InputSize;
|
|
||||||
//uniform vec2 OutputSize;
|
|
||||||
|
|
||||||
void main()
|
|
||||||
{
|
|
||||||
#if defined(CURVATURE)
|
|
||||||
screenScale = vec2(1.0, 1.0); //TextureSize / InputSize;
|
|
||||||
#endif
|
|
||||||
// Calcula filterWidth dinámicamente basándose en la altura de la textura
|
|
||||||
filterWidth = (768.0 / TextureSize.y) / 3.0;
|
|
||||||
TEX0 = vec2(gl_MultiTexCoord0.x, 1.0-gl_MultiTexCoord0.y)*1.0001;
|
|
||||||
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
|
|
||||||
}
|
|
||||||
#elif defined(FRAGMENT)
|
|
||||||
|
|
||||||
uniform sampler2D Texture;
|
|
||||||
|
|
||||||
#if defined(CURVATURE)
|
|
||||||
vec2 Distort(vec2 coord)
|
|
||||||
{
|
|
||||||
vec2 CURVATURE_DISTORTION = vec2(CURVATURE_X, CURVATURE_Y);
|
|
||||||
// Barrel distortion shrinks the display area a bit, this will allow us to counteract that.
|
|
||||||
vec2 barrelScale = 1.0 - (0.23 * CURVATURE_DISTORTION);
|
|
||||||
coord *= screenScale;
|
|
||||||
coord -= vec2(0.5);
|
|
||||||
float rsq = coord.x * coord.x + coord.y * coord.y;
|
|
||||||
coord += coord * (CURVATURE_DISTORTION * rsq);
|
|
||||||
coord *= barrelScale;
|
|
||||||
if (abs(coord.x) >= 0.5 || abs(coord.y) >= 0.5)
|
|
||||||
coord = vec2(-1.0); // If out of bounds, return an invalid value.
|
|
||||||
else
|
|
||||||
{
|
|
||||||
coord += vec2(0.5);
|
|
||||||
coord /= screenScale;
|
|
||||||
}
|
|
||||||
|
|
||||||
return coord;
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
float CalcScanLineWeight(float dist)
|
|
||||||
{
|
|
||||||
return max(1.0-dist*dist*SCANLINE_WEIGHT, SCANLINE_GAP_BRIGHTNESS);
|
|
||||||
}
|
|
||||||
|
|
||||||
float CalcScanLine(float dy)
|
|
||||||
{
|
|
||||||
float scanLineWeight = CalcScanLineWeight(dy);
|
|
||||||
#if defined(MULTISAMPLE)
|
|
||||||
scanLineWeight += CalcScanLineWeight(dy-filterWidth);
|
|
||||||
scanLineWeight += CalcScanLineWeight(dy+filterWidth);
|
|
||||||
scanLineWeight *= 0.3333333;
|
|
||||||
#endif
|
|
||||||
return scanLineWeight;
|
|
||||||
}
|
|
||||||
|
|
||||||
void main()
|
|
||||||
{
|
|
||||||
// TextureSize ahora viene como uniform, no está hardcodeado
|
|
||||||
#if defined(CURVATURE)
|
|
||||||
vec2 texcoord = Distort(TEX0);
|
|
||||||
if (texcoord.x < 0.0)
|
|
||||||
gl_FragColor = vec4(0.0);
|
|
||||||
else
|
|
||||||
#else
|
|
||||||
vec2 texcoord = TEX0;
|
|
||||||
#endif
|
|
||||||
{
|
|
||||||
vec2 texcoordInPixels = texcoord * TextureSize;
|
|
||||||
#if defined(SHARPER)
|
|
||||||
vec2 tempCoord = floor(texcoordInPixels) + 0.5;
|
|
||||||
vec2 coord = tempCoord / TextureSize;
|
|
||||||
vec2 deltas = texcoordInPixels - tempCoord;
|
|
||||||
float scanLineWeight = CalcScanLine(deltas.y);
|
|
||||||
vec2 signs = sign(deltas);
|
|
||||||
deltas.x *= 2.0;
|
|
||||||
deltas = deltas * deltas;
|
|
||||||
deltas.y = deltas.y * deltas.y;
|
|
||||||
deltas.x *= 0.5;
|
|
||||||
deltas.y *= 8.0;
|
|
||||||
deltas /= TextureSize;
|
|
||||||
deltas *= signs;
|
|
||||||
vec2 tc = coord + deltas;
|
|
||||||
#else
|
|
||||||
float tempY = floor(texcoordInPixels.y) + 0.5;
|
|
||||||
float yCoord = tempY / TextureSize.y;
|
|
||||||
float dy = texcoordInPixels.y - tempY;
|
|
||||||
float scanLineWeight = CalcScanLine(dy);
|
|
||||||
float signY = sign(dy);
|
|
||||||
dy = dy * dy;
|
|
||||||
dy = dy * dy;
|
|
||||||
dy *= 8.0;
|
|
||||||
dy /= TextureSize.y;
|
|
||||||
dy *= signY;
|
|
||||||
vec2 tc = vec2(texcoord.x, yCoord + dy);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
vec3 colour = texture2D(Texture, tc).rgb;
|
|
||||||
|
|
||||||
#if defined(SCANLINES)
|
|
||||||
#if defined(GAMMA)
|
|
||||||
#if defined(FAKE_GAMMA)
|
|
||||||
colour = colour * colour;
|
|
||||||
#else
|
|
||||||
colour = pow(colour, vec3(INPUT_GAMMA));
|
|
||||||
#endif
|
|
||||||
#endif
|
|
||||||
scanLineWeight *= BLOOM_FACTOR;
|
|
||||||
colour *= scanLineWeight;
|
|
||||||
|
|
||||||
#if defined(GAMMA)
|
|
||||||
#if defined(FAKE_GAMMA)
|
|
||||||
colour = sqrt(colour);
|
|
||||||
#else
|
|
||||||
colour = pow(colour, vec3(1.0/OUTPUT_GAMMA));
|
|
||||||
#endif
|
|
||||||
#endif
|
|
||||||
#endif
|
|
||||||
#if MASK_TYPE == 0
|
|
||||||
gl_FragColor = vec4(colour, 1.0);
|
|
||||||
#else
|
|
||||||
#if MASK_TYPE == 1
|
|
||||||
float whichMask = fract((gl_FragCoord.x*1.0001) * 0.5);
|
|
||||||
vec3 mask;
|
|
||||||
if (whichMask < 0.5)
|
|
||||||
mask = vec3(MASK_BRIGHTNESS, 1.0, MASK_BRIGHTNESS);
|
|
||||||
else
|
|
||||||
mask = vec3(1.0, MASK_BRIGHTNESS, 1.0);
|
|
||||||
#elif MASK_TYPE == 2
|
|
||||||
float whichMask = fract((gl_FragCoord.x*1.0001) * 0.3333333);
|
|
||||||
vec3 mask = vec3(MASK_BRIGHTNESS, MASK_BRIGHTNESS, MASK_BRIGHTNESS);
|
|
||||||
if (whichMask < 0.3333333)
|
|
||||||
mask.x = 1.0;
|
|
||||||
else if (whichMask < 0.6666666)
|
|
||||||
mask.y = 1.0;
|
|
||||||
else
|
|
||||||
mask.z = 1.0;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
gl_FragColor = vec4(colour * mask, 1.0);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
157
data/shaders/crtpi_fragment.glsl
Normal file
157
data/shaders/crtpi_fragment.glsl
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
#version 330 core
|
||||||
|
|
||||||
|
// Configuración
|
||||||
|
#define SCANLINES
|
||||||
|
#define MULTISAMPLE
|
||||||
|
#define GAMMA
|
||||||
|
//#define FAKE_GAMMA
|
||||||
|
//#define CURVATURE
|
||||||
|
//#define SHARPER
|
||||||
|
#define MASK_TYPE 2
|
||||||
|
|
||||||
|
#define CURVATURE_X 0.05
|
||||||
|
#define CURVATURE_Y 0.1
|
||||||
|
#define MASK_BRIGHTNESS 0.80
|
||||||
|
#define SCANLINE_WEIGHT 6.0
|
||||||
|
#define SCANLINE_GAP_BRIGHTNESS 0.12
|
||||||
|
#define BLOOM_FACTOR 3.5
|
||||||
|
#define INPUT_GAMMA 2.4
|
||||||
|
#define OUTPUT_GAMMA 2.2
|
||||||
|
|
||||||
|
// Inputs desde vertex shader
|
||||||
|
in vec2 vTexCoord;
|
||||||
|
in float vFilterWidth;
|
||||||
|
#if defined(CURVATURE)
|
||||||
|
in vec2 vScreenScale;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Output
|
||||||
|
out vec4 FragColor;
|
||||||
|
|
||||||
|
// Uniforms
|
||||||
|
uniform sampler2D Texture;
|
||||||
|
uniform vec2 TextureSize;
|
||||||
|
|
||||||
|
#if defined(CURVATURE)
|
||||||
|
vec2 Distort(vec2 coord)
|
||||||
|
{
|
||||||
|
vec2 CURVATURE_DISTORTION = vec2(CURVATURE_X, CURVATURE_Y);
|
||||||
|
vec2 barrelScale = 1.0 - (0.23 * CURVATURE_DISTORTION);
|
||||||
|
coord *= vScreenScale;
|
||||||
|
coord -= vec2(0.5);
|
||||||
|
float rsq = coord.x * coord.x + coord.y * coord.y;
|
||||||
|
coord += coord * (CURVATURE_DISTORTION * rsq);
|
||||||
|
coord *= barrelScale;
|
||||||
|
if (abs(coord.x) >= 0.5 || abs(coord.y) >= 0.5)
|
||||||
|
coord = vec2(-1.0);
|
||||||
|
else
|
||||||
|
{
|
||||||
|
coord += vec2(0.5);
|
||||||
|
coord /= vScreenScale;
|
||||||
|
}
|
||||||
|
return coord;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
float CalcScanLineWeight(float dist)
|
||||||
|
{
|
||||||
|
return max(1.0 - dist * dist * SCANLINE_WEIGHT, SCANLINE_GAP_BRIGHTNESS);
|
||||||
|
}
|
||||||
|
|
||||||
|
float CalcScanLine(float dy)
|
||||||
|
{
|
||||||
|
float scanLineWeight = CalcScanLineWeight(dy);
|
||||||
|
#if defined(MULTISAMPLE)
|
||||||
|
scanLineWeight += CalcScanLineWeight(dy - vFilterWidth);
|
||||||
|
scanLineWeight += CalcScanLineWeight(dy + vFilterWidth);
|
||||||
|
scanLineWeight *= 0.3333333;
|
||||||
|
#endif
|
||||||
|
return scanLineWeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
void main()
|
||||||
|
{
|
||||||
|
#if defined(CURVATURE)
|
||||||
|
vec2 texcoord = Distort(vTexCoord);
|
||||||
|
if (texcoord.x < 0.0) {
|
||||||
|
FragColor = vec4(0.0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
vec2 texcoord = vTexCoord;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
vec2 texcoordInPixels = texcoord * TextureSize;
|
||||||
|
|
||||||
|
#if defined(SHARPER)
|
||||||
|
vec2 tempCoord = floor(texcoordInPixels) + 0.5;
|
||||||
|
vec2 coord = tempCoord / TextureSize;
|
||||||
|
vec2 deltas = texcoordInPixels - tempCoord;
|
||||||
|
float scanLineWeight = CalcScanLine(deltas.y);
|
||||||
|
vec2 signs = sign(deltas);
|
||||||
|
deltas.x *= 2.0;
|
||||||
|
deltas = deltas * deltas;
|
||||||
|
deltas.y = deltas.y * deltas.y;
|
||||||
|
deltas.x *= 0.5;
|
||||||
|
deltas.y *= 8.0;
|
||||||
|
deltas /= TextureSize;
|
||||||
|
deltas *= signs;
|
||||||
|
vec2 tc = coord + deltas;
|
||||||
|
#else
|
||||||
|
float tempY = floor(texcoordInPixels.y) + 0.5;
|
||||||
|
float yCoord = tempY / TextureSize.y;
|
||||||
|
float dy = texcoordInPixels.y - tempY;
|
||||||
|
float scanLineWeight = CalcScanLine(dy);
|
||||||
|
float signY = sign(dy);
|
||||||
|
dy = dy * dy;
|
||||||
|
dy = dy * dy;
|
||||||
|
dy *= 8.0;
|
||||||
|
dy /= TextureSize.y;
|
||||||
|
dy *= signY;
|
||||||
|
vec2 tc = vec2(texcoord.x, yCoord + dy);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
vec3 colour = texture(Texture, tc).rgb;
|
||||||
|
|
||||||
|
#if defined(SCANLINES)
|
||||||
|
#if defined(GAMMA)
|
||||||
|
#if defined(FAKE_GAMMA)
|
||||||
|
colour = colour * colour;
|
||||||
|
#else
|
||||||
|
colour = pow(colour, vec3(INPUT_GAMMA));
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
scanLineWeight *= BLOOM_FACTOR;
|
||||||
|
colour *= scanLineWeight;
|
||||||
|
|
||||||
|
#if defined(GAMMA)
|
||||||
|
#if defined(FAKE_GAMMA)
|
||||||
|
colour = sqrt(colour);
|
||||||
|
#else
|
||||||
|
colour = pow(colour, vec3(1.0 / OUTPUT_GAMMA));
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if MASK_TYPE == 0
|
||||||
|
FragColor = vec4(colour, 1.0);
|
||||||
|
#elif MASK_TYPE == 1
|
||||||
|
float whichMask = fract(gl_FragCoord.x * 0.5);
|
||||||
|
vec3 mask;
|
||||||
|
if (whichMask < 0.5)
|
||||||
|
mask = vec3(MASK_BRIGHTNESS, 1.0, MASK_BRIGHTNESS);
|
||||||
|
else
|
||||||
|
mask = vec3(1.0, MASK_BRIGHTNESS, 1.0);
|
||||||
|
FragColor = vec4(colour * mask, 1.0);
|
||||||
|
#elif MASK_TYPE == 2
|
||||||
|
float whichMask = fract(gl_FragCoord.x * 0.3333333);
|
||||||
|
vec3 mask = vec3(MASK_BRIGHTNESS, MASK_BRIGHTNESS, MASK_BRIGHTNESS);
|
||||||
|
if (whichMask < 0.3333333)
|
||||||
|
mask.x = 1.0;
|
||||||
|
else if (whichMask < 0.6666666)
|
||||||
|
mask.y = 1.0;
|
||||||
|
else
|
||||||
|
mask.z = 1.0;
|
||||||
|
FragColor = vec4(colour * mask, 1.0);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
152
data/shaders/crtpi_fragment.metal
Normal file
152
data/shaders/crtpi_fragment.metal
Normal file
@@ -0,0 +1,152 @@
|
|||||||
|
//
|
||||||
|
// CRT-Pi Fragment Shader - Metal Shading Language
|
||||||
|
// Portado desde GLSL a MSL para macOS
|
||||||
|
//
|
||||||
|
|
||||||
|
#include <metal_stdlib>
|
||||||
|
using namespace metal;
|
||||||
|
|
||||||
|
// Configuración (equivalente a los #define en GLSL)
|
||||||
|
constant bool SCANLINES = true;
|
||||||
|
constant bool MULTISAMPLE = true;
|
||||||
|
constant bool GAMMA = true;
|
||||||
|
constant bool FAKE_GAMMA = false;
|
||||||
|
constant bool CURVATURE = false;
|
||||||
|
constant bool SHARPER = false;
|
||||||
|
constant int MASK_TYPE = 2; // 0=none, 1=green/magenta, 2=trinitron
|
||||||
|
|
||||||
|
constant float CURVATURE_X = 0.05;
|
||||||
|
constant float CURVATURE_Y = 0.1;
|
||||||
|
constant float MASK_BRIGHTNESS = 0.80;
|
||||||
|
constant float SCANLINE_WEIGHT = 6.0;
|
||||||
|
constant float SCANLINE_GAP_BRIGHTNESS = 0.12;
|
||||||
|
constant float BLOOM_FACTOR = 3.5;
|
||||||
|
constant float INPUT_GAMMA = 2.4;
|
||||||
|
constant float OUTPUT_GAMMA = 2.2;
|
||||||
|
|
||||||
|
// Estructura de entrada (salida del vertex shader)
|
||||||
|
struct VertexOut {
|
||||||
|
float4 position [[position]];
|
||||||
|
float2 texCoord;
|
||||||
|
float filterWidth;
|
||||||
|
// float2 screenScale; // Solo si CURVATURE está activo
|
||||||
|
};
|
||||||
|
|
||||||
|
// Uniforms
|
||||||
|
struct Uniforms {
|
||||||
|
float2 textureSize;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Función para calcular el peso de la scanline
|
||||||
|
float CalcScanLineWeight(float dist) {
|
||||||
|
return max(1.0 - dist * dist * SCANLINE_WEIGHT, SCANLINE_GAP_BRIGHTNESS);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Función para calcular scanline con multisampling
|
||||||
|
float CalcScanLine(float dy, float filterWidth) {
|
||||||
|
float scanLineWeight = CalcScanLineWeight(dy);
|
||||||
|
if (MULTISAMPLE) {
|
||||||
|
scanLineWeight += CalcScanLineWeight(dy - filterWidth);
|
||||||
|
scanLineWeight += CalcScanLineWeight(dy + filterWidth);
|
||||||
|
scanLineWeight *= 0.3333333;
|
||||||
|
}
|
||||||
|
return scanLineWeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entry point del fragment shader
|
||||||
|
fragment float4 fragment_main(VertexOut in [[stage_in]],
|
||||||
|
texture2d<float> colorTexture [[texture(0)]],
|
||||||
|
constant Uniforms& uniforms [[buffer(1)]],
|
||||||
|
sampler textureSampler [[sampler(0)]]) {
|
||||||
|
|
||||||
|
float2 texcoord = in.texCoord;
|
||||||
|
|
||||||
|
// Si CURVATURE estuviera activo, aquí iría la función Distort()
|
||||||
|
|
||||||
|
float2 texcoordInPixels = texcoord * uniforms.textureSize;
|
||||||
|
|
||||||
|
float2 tc;
|
||||||
|
float scanLineWeight;
|
||||||
|
|
||||||
|
if (!SHARPER) {
|
||||||
|
// Modo normal (no SHARPER)
|
||||||
|
float tempY = floor(texcoordInPixels.y) + 0.5;
|
||||||
|
float yCoord = tempY / uniforms.textureSize.y;
|
||||||
|
float dy = texcoordInPixels.y - tempY;
|
||||||
|
scanLineWeight = CalcScanLine(dy, in.filterWidth);
|
||||||
|
float signY = sign(dy);
|
||||||
|
dy = dy * dy;
|
||||||
|
dy = dy * dy;
|
||||||
|
dy *= 8.0;
|
||||||
|
dy /= uniforms.textureSize.y;
|
||||||
|
dy *= signY;
|
||||||
|
tc = float2(texcoord.x, yCoord + dy);
|
||||||
|
} else {
|
||||||
|
// Modo SHARPER
|
||||||
|
float2 tempCoord = floor(texcoordInPixels) + 0.5;
|
||||||
|
float2 coord = tempCoord / uniforms.textureSize;
|
||||||
|
float2 deltas = texcoordInPixels - tempCoord;
|
||||||
|
scanLineWeight = CalcScanLine(deltas.y, in.filterWidth);
|
||||||
|
float2 signs = sign(deltas);
|
||||||
|
deltas.x *= 2.0;
|
||||||
|
deltas = deltas * deltas;
|
||||||
|
deltas.y = deltas.y * deltas.y;
|
||||||
|
deltas.x *= 0.5;
|
||||||
|
deltas.y *= 8.0;
|
||||||
|
deltas /= uniforms.textureSize;
|
||||||
|
deltas *= signs;
|
||||||
|
tc = coord + deltas;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Muestrear textura (texture() en GLSL = sample() en MSL)
|
||||||
|
float3 colour = colorTexture.sample(textureSampler, tc).rgb;
|
||||||
|
|
||||||
|
if (SCANLINES) {
|
||||||
|
if (GAMMA) {
|
||||||
|
if (FAKE_GAMMA) {
|
||||||
|
colour = colour * colour;
|
||||||
|
} else {
|
||||||
|
colour = pow(colour, float3(INPUT_GAMMA));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
scanLineWeight *= BLOOM_FACTOR;
|
||||||
|
colour *= scanLineWeight;
|
||||||
|
|
||||||
|
if (GAMMA) {
|
||||||
|
if (FAKE_GAMMA) {
|
||||||
|
colour = sqrt(colour);
|
||||||
|
} else {
|
||||||
|
colour = pow(colour, float3(1.0 / OUTPUT_GAMMA));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Aplicar máscara CRT
|
||||||
|
if (MASK_TYPE == 0) {
|
||||||
|
return float4(colour, 1.0);
|
||||||
|
} else if (MASK_TYPE == 1) {
|
||||||
|
// Máscara verde/magenta
|
||||||
|
float whichMask = fract(in.position.x * 0.5);
|
||||||
|
float3 mask;
|
||||||
|
if (whichMask < 0.5) {
|
||||||
|
mask = float3(MASK_BRIGHTNESS, 1.0, MASK_BRIGHTNESS);
|
||||||
|
} else {
|
||||||
|
mask = float3(1.0, MASK_BRIGHTNESS, 1.0);
|
||||||
|
}
|
||||||
|
return float4(colour * mask, 1.0);
|
||||||
|
} else if (MASK_TYPE == 2) {
|
||||||
|
// Máscara trinitron
|
||||||
|
float whichMask = fract(in.position.x * 0.3333333);
|
||||||
|
float3 mask = float3(MASK_BRIGHTNESS, MASK_BRIGHTNESS, MASK_BRIGHTNESS);
|
||||||
|
if (whichMask < 0.3333333) {
|
||||||
|
mask.x = 1.0;
|
||||||
|
} else if (whichMask < 0.6666666) {
|
||||||
|
mask.y = 1.0;
|
||||||
|
} else {
|
||||||
|
mask.z = 1.0;
|
||||||
|
}
|
||||||
|
return float4(colour * mask, 1.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return float4(colour, 1.0);
|
||||||
|
}
|
||||||
48
data/shaders/crtpi_vertex.glsl
Normal file
48
data/shaders/crtpi_vertex.glsl
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
#version 330 core
|
||||||
|
|
||||||
|
// Configuración
|
||||||
|
#define SCANLINES
|
||||||
|
#define MULTISAMPLE
|
||||||
|
#define GAMMA
|
||||||
|
//#define FAKE_GAMMA
|
||||||
|
//#define CURVATURE
|
||||||
|
//#define SHARPER
|
||||||
|
#define MASK_TYPE 2
|
||||||
|
|
||||||
|
#define CURVATURE_X 0.05
|
||||||
|
#define CURVATURE_Y 0.1
|
||||||
|
#define MASK_BRIGHTNESS 0.80
|
||||||
|
#define SCANLINE_WEIGHT 6.0
|
||||||
|
#define SCANLINE_GAP_BRIGHTNESS 0.12
|
||||||
|
#define BLOOM_FACTOR 3.5
|
||||||
|
#define INPUT_GAMMA 2.4
|
||||||
|
#define OUTPUT_GAMMA 2.2
|
||||||
|
|
||||||
|
// Inputs (desde VAO)
|
||||||
|
layout(location = 0) in vec2 aPosition;
|
||||||
|
layout(location = 1) in vec2 aTexCoord;
|
||||||
|
|
||||||
|
// Outputs al fragment shader
|
||||||
|
out vec2 vTexCoord;
|
||||||
|
out float vFilterWidth;
|
||||||
|
#if defined(CURVATURE)
|
||||||
|
out vec2 vScreenScale;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Uniforms
|
||||||
|
uniform vec2 TextureSize;
|
||||||
|
|
||||||
|
void main()
|
||||||
|
{
|
||||||
|
#if defined(CURVATURE)
|
||||||
|
vScreenScale = vec2(1.0, 1.0);
|
||||||
|
#endif
|
||||||
|
// Calcula filterWidth dinámicamente basándose en la altura de la textura
|
||||||
|
vFilterWidth = (768.0 / TextureSize.y) / 3.0;
|
||||||
|
|
||||||
|
// Pasar coordenadas de textura (invertir Y para SDL)
|
||||||
|
vTexCoord = vec2(aTexCoord.x, 1.0 - aTexCoord.y) * 1.0001;
|
||||||
|
|
||||||
|
// Posición del vértice (ya en espacio de clip [-1, 1])
|
||||||
|
gl_Position = vec4(aPosition, 0.0, 1.0);
|
||||||
|
}
|
||||||
46
data/shaders/crtpi_vertex.metal
Normal file
46
data/shaders/crtpi_vertex.metal
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
//
|
||||||
|
// CRT-Pi Vertex Shader - Metal Shading Language
|
||||||
|
// Portado desde GLSL a MSL para macOS
|
||||||
|
//
|
||||||
|
|
||||||
|
#include <metal_stdlib>
|
||||||
|
using namespace metal;
|
||||||
|
|
||||||
|
// Estructura de entrada del vertex shader (desde el buffer de vértices)
|
||||||
|
struct VertexIn {
|
||||||
|
float2 position [[attribute(0)]]; // Posición del vértice
|
||||||
|
float2 texCoord [[attribute(1)]]; // Coordenadas de textura
|
||||||
|
};
|
||||||
|
|
||||||
|
// Estructura de salida del vertex shader (entrada al fragment shader)
|
||||||
|
struct VertexOut {
|
||||||
|
float4 position [[position]]; // Posición en clip space
|
||||||
|
float2 texCoord; // Coordenadas de textura
|
||||||
|
float filterWidth; // Ancho del filtro calculado
|
||||||
|
// float2 screenScale; // Solo si CURVATURE está activo
|
||||||
|
};
|
||||||
|
|
||||||
|
// Uniforms (constantes del shader)
|
||||||
|
struct Uniforms {
|
||||||
|
float2 textureSize; // Tamaño de la textura (width, height)
|
||||||
|
};
|
||||||
|
|
||||||
|
// Entry point del vertex shader
|
||||||
|
vertex VertexOut vertex_main(VertexIn in [[stage_in]],
|
||||||
|
constant Uniforms& uniforms [[buffer(1)]]) {
|
||||||
|
VertexOut out;
|
||||||
|
|
||||||
|
// Posición del vértice (ya está en espacio de clip [-1, 1])
|
||||||
|
out.position = float4(in.position, 0.0, 1.0);
|
||||||
|
|
||||||
|
// Pasar coordenadas de textura (invertir Y para SDL, igual que en GLSL)
|
||||||
|
out.texCoord = float2(in.texCoord.x, 1.0 - in.texCoord.y) * 1.0001;
|
||||||
|
|
||||||
|
// Calcular filterWidth dinámicamente basándose en la altura de la textura
|
||||||
|
out.filterWidth = (768.0 / uniforms.textureSize.y) / 3.0;
|
||||||
|
|
||||||
|
// Si CURVATURE estuviera activo:
|
||||||
|
// out.screenScale = float2(1.0, 1.0);
|
||||||
|
|
||||||
|
return out;
|
||||||
|
}
|
||||||
468
source/external/jail_shader.cpp
vendored
468
source/external/jail_shader.cpp
vendored
@@ -1,468 +0,0 @@
|
|||||||
#include "jail_shader.h"
|
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_GL_GetProcAddress, SDL_LogError
|
|
||||||
#include <stdint.h> // Para uintptr_t
|
|
||||||
#include <cstring> // Para strncmp
|
|
||||||
#include <stdexcept> // Para runtime_error
|
|
||||||
#include <vector> // Para vector
|
|
||||||
|
|
||||||
#ifdef __APPLE__
|
|
||||||
#include <OpenGL/OpenGL.h> // Para OpenGL en macOS
|
|
||||||
|
|
||||||
#include "CoreFoundation/CoreFoundation.h" // Para Core Foundation en macOS
|
|
||||||
#if ESSENTIAL_GL_PRACTICES_SUPPORT_GL3
|
|
||||||
#include <OpenGL/gl3.h> // Para OpenGL 3 en macOS
|
|
||||||
#else // NO ESSENTIAL_GL_PRACTICES_SUPPORT_GL3
|
|
||||||
#include <OpenGL/gl.h> // Para OpenGL (compatibilidad) en macOS
|
|
||||||
#endif // ESSENTIAL_GL_PRACTICES_SUPPORT_GL3
|
|
||||||
#else // SI NO ES __APPLE__
|
|
||||||
#include <SDL3/SDL_opengl.h> // Para GLuint, GLint, glTexCoord2f, glVertex2f
|
|
||||||
#endif // __APPLE__
|
|
||||||
|
|
||||||
namespace shader {
|
|
||||||
// Constantes
|
|
||||||
const GLuint INVALID_SHADER_ID = 0;
|
|
||||||
const GLuint INVALID_PROGRAM_ID = 0;
|
|
||||||
const GLuint DEFAULT_TEXTURE_ID = 1;
|
|
||||||
|
|
||||||
// Variables globales
|
|
||||||
SDL_Window *win = nullptr;
|
|
||||||
SDL_Renderer *renderer = nullptr;
|
|
||||||
GLuint programId = 0;
|
|
||||||
SDL_Texture *backBuffer = nullptr;
|
|
||||||
SDL_Point win_size = {320 * 4, 256 * 4};
|
|
||||||
SDL_FPoint tex_size = {320, 256};
|
|
||||||
bool usingOpenGL = false;
|
|
||||||
|
|
||||||
#ifndef __APPLE__
|
|
||||||
// Declaración de funciones de extensión de OpenGL (evitando GLEW)
|
|
||||||
PFNGLCREATESHADERPROC glCreateShader;
|
|
||||||
PFNGLSHADERSOURCEPROC glShaderSource;
|
|
||||||
PFNGLCOMPILESHADERPROC glCompileShader;
|
|
||||||
PFNGLGETSHADERIVPROC glGetShaderiv;
|
|
||||||
PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog;
|
|
||||||
PFNGLDELETESHADERPROC glDeleteShader;
|
|
||||||
PFNGLATTACHSHADERPROC glAttachShader;
|
|
||||||
PFNGLCREATEPROGRAMPROC glCreateProgram;
|
|
||||||
PFNGLLINKPROGRAMPROC glLinkProgram;
|
|
||||||
PFNGLVALIDATEPROGRAMPROC glValidateProgram;
|
|
||||||
PFNGLGETPROGRAMIVPROC glGetProgramiv;
|
|
||||||
PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog;
|
|
||||||
PFNGLUSEPROGRAMPROC glUseProgram;
|
|
||||||
PFNGLDELETEPROGRAMPROC glDeleteProgram;
|
|
||||||
PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation;
|
|
||||||
PFNGLUNIFORM2FPROC glUniform2f;
|
|
||||||
|
|
||||||
bool initGLExtensions() {
|
|
||||||
glCreateShader = (PFNGLCREATESHADERPROC)SDL_GL_GetProcAddress("glCreateShader");
|
|
||||||
glShaderSource = (PFNGLSHADERSOURCEPROC)SDL_GL_GetProcAddress("glShaderSource");
|
|
||||||
glCompileShader = (PFNGLCOMPILESHADERPROC)SDL_GL_GetProcAddress("glCompileShader");
|
|
||||||
glGetShaderiv = (PFNGLGETSHADERIVPROC)SDL_GL_GetProcAddress("glGetShaderiv");
|
|
||||||
glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)SDL_GL_GetProcAddress("glGetShaderInfoLog");
|
|
||||||
glDeleteShader = (PFNGLDELETESHADERPROC)SDL_GL_GetProcAddress("glDeleteShader");
|
|
||||||
glAttachShader = (PFNGLATTACHSHADERPROC)SDL_GL_GetProcAddress("glAttachShader");
|
|
||||||
glCreateProgram = (PFNGLCREATEPROGRAMPROC)SDL_GL_GetProcAddress("glCreateProgram");
|
|
||||||
glLinkProgram = (PFNGLLINKPROGRAMPROC)SDL_GL_GetProcAddress("glLinkProgram");
|
|
||||||
glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)SDL_GL_GetProcAddress("glValidateProgram");
|
|
||||||
glGetProgramiv = (PFNGLGETPROGRAMIVPROC)SDL_GL_GetProcAddress("glGetProgramiv");
|
|
||||||
glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)SDL_GL_GetProcAddress("glGetProgramInfoLog");
|
|
||||||
glUseProgram = (PFNGLUSEPROGRAMPROC)SDL_GL_GetProcAddress("glUseProgram");
|
|
||||||
glDeleteProgram = (PFNGLDELETEPROGRAMPROC)SDL_GL_GetProcAddress("glDeleteProgram");
|
|
||||||
glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)SDL_GL_GetProcAddress("glGetUniformLocation");
|
|
||||||
glUniform2f = (PFNGLUNIFORM2FPROC)SDL_GL_GetProcAddress("glUniform2f");
|
|
||||||
|
|
||||||
return glCreateShader && glShaderSource && glCompileShader && glGetShaderiv &&
|
|
||||||
glGetShaderInfoLog && glDeleteShader && glAttachShader && glCreateProgram &&
|
|
||||||
glLinkProgram && glValidateProgram && glGetProgramiv && glGetProgramInfoLog &&
|
|
||||||
glUseProgram && glDeleteProgram && glGetUniformLocation && glUniform2f;
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Función para verificar errores de OpenGL
|
|
||||||
void checkGLError(const char *operation) {
|
|
||||||
GLenum error = glGetError();
|
|
||||||
if (error != GL_NO_ERROR) {
|
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
|
||||||
"Error OpenGL en %s: 0x%x",
|
|
||||||
operation,
|
|
||||||
error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Función para compilar un shader a partir de un std::string
|
|
||||||
GLuint compileShader(const std::string &source, GLuint shader_type) {
|
|
||||||
if (source.empty()) {
|
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "ERROR FATAL: El código fuente del shader está vacío.");
|
|
||||||
throw std::runtime_error("ERROR FATAL: El código fuente del shader está vacío.");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Crear identificador del shader
|
|
||||||
GLuint shader_id = glCreateShader(shader_type);
|
|
||||||
if (shader_id == INVALID_SHADER_ID) {
|
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error al crear el shader.");
|
|
||||||
checkGLError("glCreateShader");
|
|
||||||
return INVALID_SHADER_ID;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Agregar una directiva según el tipo de shader
|
|
||||||
std::string directive = (shader_type == GL_VERTEX_SHADER)
|
|
||||||
? "#define VERTEX\n"
|
|
||||||
: "#define FRAGMENT\n";
|
|
||||||
|
|
||||||
const char *sources[2] = {directive.c_str(), source.c_str()};
|
|
||||||
|
|
||||||
// Especificar el código fuente del shader
|
|
||||||
glShaderSource(shader_id, 2, sources, nullptr);
|
|
||||||
checkGLError("glShaderSource");
|
|
||||||
|
|
||||||
// Compilar el shader
|
|
||||||
glCompileShader(shader_id);
|
|
||||||
checkGLError("glCompileShader");
|
|
||||||
|
|
||||||
// Verificar si la compilación fue exitosa
|
|
||||||
GLint compiled_ok = GL_FALSE;
|
|
||||||
glGetShaderiv(shader_id, GL_COMPILE_STATUS, &compiled_ok);
|
|
||||||
if (compiled_ok != GL_TRUE) {
|
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error en la compilación del shader (%d)!", shader_id);
|
|
||||||
GLint log_length;
|
|
||||||
glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &log_length);
|
|
||||||
if (log_length > 0) {
|
|
||||||
std::vector<GLchar> log(log_length);
|
|
||||||
glGetShaderInfoLog(shader_id, log_length, &log_length, log.data());
|
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Registro de compilación del shader: %s", log.data());
|
|
||||||
}
|
|
||||||
glDeleteShader(shader_id);
|
|
||||||
return INVALID_SHADER_ID;
|
|
||||||
}
|
|
||||||
return shader_id;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Función para compilar un programa de shaders (vertex y fragment) a partir de std::string
|
|
||||||
GLuint compileProgram(const std::string &vertex_shader_source, const std::string &fragment_shader_source) {
|
|
||||||
GLuint program_id = glCreateProgram();
|
|
||||||
if (program_id == INVALID_PROGRAM_ID) {
|
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error al crear el programa de shaders.");
|
|
||||||
checkGLError("glCreateProgram");
|
|
||||||
return INVALID_PROGRAM_ID;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Si el fragment shader está vacío, reutilizamos el código del vertex shader
|
|
||||||
GLuint vertex_shader_id = compileShader(vertex_shader_source, GL_VERTEX_SHADER);
|
|
||||||
GLuint fragment_shader_id = compileShader(fragment_shader_source.empty() ? vertex_shader_source : fragment_shader_source, GL_FRAGMENT_SHADER);
|
|
||||||
|
|
||||||
if (vertex_shader_id != INVALID_SHADER_ID && fragment_shader_id != INVALID_SHADER_ID) {
|
|
||||||
// Asociar los shaders al programa
|
|
||||||
glAttachShader(program_id, vertex_shader_id);
|
|
||||||
checkGLError("glAttachShader vertex");
|
|
||||||
glAttachShader(program_id, fragment_shader_id);
|
|
||||||
checkGLError("glAttachShader fragment");
|
|
||||||
|
|
||||||
glLinkProgram(program_id);
|
|
||||||
checkGLError("glLinkProgram");
|
|
||||||
|
|
||||||
// Verificar el estado del enlace
|
|
||||||
GLint isLinked = GL_FALSE;
|
|
||||||
glGetProgramiv(program_id, GL_LINK_STATUS, &isLinked);
|
|
||||||
if (isLinked == GL_FALSE) {
|
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error al enlazar el programa de shaders.");
|
|
||||||
GLint log_length;
|
|
||||||
glGetProgramiv(program_id, GL_INFO_LOG_LENGTH, &log_length);
|
|
||||||
if (log_length > 0) {
|
|
||||||
std::vector<char> log(log_length);
|
|
||||||
glGetProgramInfoLog(program_id, log_length, &log_length, log.data());
|
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Registro de enlace del programa: %s", log.data());
|
|
||||||
}
|
|
||||||
glDeleteProgram(program_id);
|
|
||||||
program_id = INVALID_PROGRAM_ID;
|
|
||||||
} else {
|
|
||||||
glValidateProgram(program_id);
|
|
||||||
checkGLError("glValidateProgram");
|
|
||||||
|
|
||||||
// Log de información del programa (solo si hay información)
|
|
||||||
GLint log_length;
|
|
||||||
glGetProgramiv(program_id, GL_INFO_LOG_LENGTH, &log_length);
|
|
||||||
if (log_length > 1) // > 1 porque algunos drivers devuelven 1 para cadena vacía
|
|
||||||
{
|
|
||||||
std::vector<char> log(log_length);
|
|
||||||
glGetProgramInfoLog(program_id, log_length, &log_length, log.data());
|
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Registro de información del programa:\n%s", log.data());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: No se pudieron compilar los shaders.");
|
|
||||||
glDeleteProgram(program_id);
|
|
||||||
program_id = INVALID_PROGRAM_ID;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Limpiar los shaders (ya no son necesarios después del enlace)
|
|
||||||
if (vertex_shader_id != INVALID_SHADER_ID) {
|
|
||||||
glDeleteShader(vertex_shader_id);
|
|
||||||
}
|
|
||||||
if (fragment_shader_id != INVALID_SHADER_ID) {
|
|
||||||
glDeleteShader(fragment_shader_id);
|
|
||||||
}
|
|
||||||
|
|
||||||
return program_id;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Función para obtener el ID de textura OpenGL desde SDL3
|
|
||||||
GLuint getTextureID(SDL_Texture *texture) {
|
|
||||||
if (!texture)
|
|
||||||
return DEFAULT_TEXTURE_ID;
|
|
||||||
|
|
||||||
// Intentar obtener el ID de textura OpenGL desde las propiedades de SDL3
|
|
||||||
SDL_PropertiesID props = SDL_GetTextureProperties(texture);
|
|
||||||
GLuint textureId = 0;
|
|
||||||
|
|
||||||
// Intentar diferentes nombres de propiedades según la versión de SDL3
|
|
||||||
textureId = (GLuint)(uintptr_t)SDL_GetPointerProperty(props, "SDL.texture.opengl.texture", nullptr);
|
|
||||||
|
|
||||||
// Si la primera no funciona, intentar con el nombre alternativo
|
|
||||||
if (textureId == 0) {
|
|
||||||
textureId = (GLuint)(uintptr_t)SDL_GetPointerProperty(props, "texture.opengl.texture", nullptr);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Si aún no funciona, intentar obtener como número
|
|
||||||
if (textureId == 0) {
|
|
||||||
textureId = (GLuint)SDL_GetNumberProperty(props, "SDL.texture.opengl.texture", DEFAULT_TEXTURE_ID);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Si ninguna funciona, usar el método manual de bindeo de textura
|
|
||||||
if (textureId == 0) {
|
|
||||||
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
|
||||||
"No se pudo obtener el ID de textura OpenGL, usando ID por defecto (%d)",
|
|
||||||
DEFAULT_TEXTURE_ID);
|
|
||||||
textureId = DEFAULT_TEXTURE_ID;
|
|
||||||
}
|
|
||||||
|
|
||||||
return textureId;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool init(SDL_Window *window, SDL_Texture *back_buffer_texture, const std::string &vertex_shader, const std::string &fragment_shader) {
|
|
||||||
shader::win = window;
|
|
||||||
shader::renderer = SDL_GetRenderer(window);
|
|
||||||
shader::backBuffer = back_buffer_texture;
|
|
||||||
|
|
||||||
if (!shader::renderer) {
|
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: No se pudo obtener el renderer de la ventana.");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
SDL_GetWindowSize(window, &win_size.x, &win_size.y);
|
|
||||||
SDL_GetTextureSize(back_buffer_texture, &tex_size.x, &tex_size.y);
|
|
||||||
|
|
||||||
const auto render_name = SDL_GetRendererName(renderer);
|
|
||||||
if (!render_name) {
|
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: No se pudo obtener el nombre del renderer.");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Limpiar shader anterior si existe
|
|
||||||
if (programId != INVALID_PROGRAM_ID) {
|
|
||||||
glDeleteProgram(programId);
|
|
||||||
programId = INVALID_PROGRAM_ID;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verificar que el renderer sea OpenGL
|
|
||||||
if (!strncmp(render_name, "opengl", 6)) {
|
|
||||||
#ifndef __APPLE__
|
|
||||||
if (!initGLExtensions()) {
|
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "ERROR: No se han podido inicializar las extensiones de OpenGL.");
|
|
||||||
usingOpenGL = false;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
// Compilar el programa de shaders utilizando std::string
|
|
||||||
programId = compileProgram(vertex_shader, fragment_shader);
|
|
||||||
if (programId == INVALID_PROGRAM_ID) {
|
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "ERROR: No se pudo compilar el programa de shaders.");
|
|
||||||
usingOpenGL = false;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Establecer el uniform TextureSize inmediatamente después de compilar
|
|
||||||
// Los uniforms persisten en el programa una vez establecidos
|
|
||||||
glUseProgram(programId);
|
|
||||||
GLint textureSizeLocation = glGetUniformLocation(programId, "TextureSize");
|
|
||||||
if (textureSizeLocation != -1) {
|
|
||||||
glUniform2f(textureSizeLocation, tex_size.x, tex_size.y);
|
|
||||||
checkGLError("glUniform2f(TextureSize) - init");
|
|
||||||
} else {
|
|
||||||
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
|
||||||
"Warning: No se pudo encontrar el uniform 'TextureSize' en el shader");
|
|
||||||
}
|
|
||||||
glUseProgram(0); // Deseleccionar el programa
|
|
||||||
} else {
|
|
||||||
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "ADVERTENCIA: El driver del renderer no es OpenGL (%s).", render_name);
|
|
||||||
usingOpenGL = false;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
usingOpenGL = true;
|
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "** Shader system initialized successfully");
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
void render() {
|
|
||||||
// Establece el color de fondo
|
|
||||||
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
|
|
||||||
SDL_SetRenderTarget(renderer, nullptr);
|
|
||||||
SDL_RenderClear(renderer);
|
|
||||||
|
|
||||||
if (usingOpenGL && programId != INVALID_PROGRAM_ID) {
|
|
||||||
// Obtener el tamaño actual de la ventana (puede haber cambiado desde init)
|
|
||||||
int current_win_width, current_win_height;
|
|
||||||
SDL_GetWindowSize(win, ¤t_win_width, ¤t_win_height);
|
|
||||||
|
|
||||||
// Guardar estados de OpenGL
|
|
||||||
GLint oldProgramId;
|
|
||||||
glGetIntegerv(GL_CURRENT_PROGRAM, &oldProgramId);
|
|
||||||
|
|
||||||
GLint oldViewport[4];
|
|
||||||
glGetIntegerv(GL_VIEWPORT, oldViewport);
|
|
||||||
|
|
||||||
GLboolean wasTextureEnabled = glIsEnabled(GL_TEXTURE_2D);
|
|
||||||
GLint oldTextureId;
|
|
||||||
glGetIntegerv(GL_TEXTURE_BINDING_2D, &oldTextureId);
|
|
||||||
|
|
||||||
// Obtener y bindear la textura
|
|
||||||
GLuint textureId = getTextureID(backBuffer);
|
|
||||||
glEnable(GL_TEXTURE_2D);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, textureId);
|
|
||||||
checkGLError("glBindTexture");
|
|
||||||
|
|
||||||
// Usar nuestro programa de shaders
|
|
||||||
glUseProgram(programId);
|
|
||||||
checkGLError("glUseProgram");
|
|
||||||
|
|
||||||
// Recupera el tamaño lógico configurado con SDL_RenderSetLogicalSize
|
|
||||||
int logicalW, logicalH;
|
|
||||||
SDL_RendererLogicalPresentation mode;
|
|
||||||
SDL_GetRenderLogicalPresentation(renderer, &logicalW, &logicalH, &mode);
|
|
||||||
if (logicalW == 0 || logicalH == 0) {
|
|
||||||
logicalW = current_win_width;
|
|
||||||
logicalH = current_win_height;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Cálculo del viewport
|
|
||||||
int viewportX = 0, viewportY = 0, viewportW = current_win_width, viewportH = current_win_height;
|
|
||||||
const bool USE_INTEGER_SCALE = mode == SDL_LOGICAL_PRESENTATION_INTEGER_SCALE;
|
|
||||||
if (USE_INTEGER_SCALE) {
|
|
||||||
// Calcula el factor de escalado entero máximo que se puede aplicar
|
|
||||||
int scaleX = current_win_width / logicalW;
|
|
||||||
int scaleY = current_win_height / logicalH;
|
|
||||||
int scale = (scaleX < scaleY ? scaleX : scaleY);
|
|
||||||
if (scale < 1) {
|
|
||||||
scale = 1;
|
|
||||||
}
|
|
||||||
viewportW = logicalW * scale;
|
|
||||||
viewportH = logicalH * scale;
|
|
||||||
viewportX = (current_win_width - viewportW) / 2;
|
|
||||||
viewportY = (current_win_height - viewportH) / 2;
|
|
||||||
} else {
|
|
||||||
// Letterboxing: preserva la relación de aspecto usando una escala flotante
|
|
||||||
float windowAspect = static_cast<float>(current_win_width) / current_win_height;
|
|
||||||
float logicalAspect = static_cast<float>(logicalW) / logicalH;
|
|
||||||
if (windowAspect > logicalAspect) {
|
|
||||||
viewportW = static_cast<int>(logicalAspect * current_win_height);
|
|
||||||
viewportX = (current_win_width - viewportW) / 2;
|
|
||||||
} else {
|
|
||||||
viewportH = static_cast<int>(current_win_width / logicalAspect);
|
|
||||||
viewportY = (current_win_height - viewportH) / 2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
glViewport(viewportX, viewportY, viewportW, viewportH);
|
|
||||||
checkGLError("glViewport");
|
|
||||||
|
|
||||||
// Configurar la proyección ortográfica usando el espacio lógico
|
|
||||||
glMatrixMode(GL_PROJECTION);
|
|
||||||
glLoadIdentity();
|
|
||||||
|
|
||||||
// Queremos que el origen esté en la esquina superior izquierda del espacio lógico.
|
|
||||||
glOrtho(0, static_cast<GLdouble>(logicalW), static_cast<GLdouble>(logicalH), 0, -1, 1);
|
|
||||||
glMatrixMode(GL_MODELVIEW);
|
|
||||||
glLoadIdentity();
|
|
||||||
|
|
||||||
// Dibuja el quad con las coordenadas ajustadas.
|
|
||||||
// Se asignan las coordenadas de textura "normales" para que no quede espejado horizontalmente,
|
|
||||||
// y se mantiene el flip vertical para que la imagen no aparezca volteada.
|
|
||||||
glBegin(GL_TRIANGLE_STRIP);
|
|
||||||
// Vértice superior izquierdo
|
|
||||||
glTexCoord2f(0.0f, 1.0f);
|
|
||||||
glVertex2f(0.0f, 0.0f);
|
|
||||||
// Vértice superior derecho
|
|
||||||
glTexCoord2f(1.0f, 1.0f);
|
|
||||||
glVertex2f(static_cast<GLfloat>(logicalW), 0.0f);
|
|
||||||
// Vértice inferior izquierdo
|
|
||||||
glTexCoord2f(0.0f, 0.0f);
|
|
||||||
glVertex2f(0.0f, static_cast<GLfloat>(logicalH));
|
|
||||||
// Vértice inferior derecho
|
|
||||||
glTexCoord2f(1.0f, 0.0f);
|
|
||||||
glVertex2f(static_cast<GLfloat>(logicalW), static_cast<GLfloat>(logicalH));
|
|
||||||
glEnd();
|
|
||||||
checkGLError("render quad");
|
|
||||||
|
|
||||||
SDL_GL_SwapWindow(win);
|
|
||||||
|
|
||||||
// Restaurar estados de OpenGL
|
|
||||||
glUseProgram(oldProgramId);
|
|
||||||
glBindTexture(GL_TEXTURE_2D, oldTextureId);
|
|
||||||
if (!wasTextureEnabled) {
|
|
||||||
glDisable(GL_TEXTURE_2D);
|
|
||||||
}
|
|
||||||
glViewport(oldViewport[0], oldViewport[1], oldViewport[2], oldViewport[3]);
|
|
||||||
} else {
|
|
||||||
// Fallback a renderizado normal de SDL
|
|
||||||
SDL_RenderTexture(renderer, backBuffer, nullptr, nullptr);
|
|
||||||
SDL_RenderPresent(renderer);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void setTextureSize(float width, float height) {
|
|
||||||
if (!usingOpenGL || programId == INVALID_PROGRAM_ID) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Guardar el programa actual
|
|
||||||
GLint oldProgramId;
|
|
||||||
glGetIntegerv(GL_CURRENT_PROGRAM, &oldProgramId);
|
|
||||||
|
|
||||||
// Usar nuestro programa
|
|
||||||
glUseProgram(programId);
|
|
||||||
|
|
||||||
// Obtener la ubicación del uniform TextureSize
|
|
||||||
GLint textureSizeLocation = glGetUniformLocation(programId, "TextureSize");
|
|
||||||
if (textureSizeLocation != -1) {
|
|
||||||
glUniform2f(textureSizeLocation, width, height);
|
|
||||||
checkGLError("glUniform2f(TextureSize)");
|
|
||||||
} else {
|
|
||||||
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
|
||||||
"Warning: No se pudo encontrar el uniform 'TextureSize' en el shader");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Restaurar el programa anterior
|
|
||||||
glUseProgram(oldProgramId);
|
|
||||||
}
|
|
||||||
|
|
||||||
void cleanup() {
|
|
||||||
if (programId != INVALID_PROGRAM_ID) {
|
|
||||||
glDeleteProgram(programId);
|
|
||||||
programId = INVALID_PROGRAM_ID;
|
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Programa de shaders liberado.");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reinicializar variables
|
|
||||||
win = nullptr;
|
|
||||||
renderer = nullptr;
|
|
||||||
backBuffer = nullptr;
|
|
||||||
usingOpenGL = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool isUsingOpenGL() {
|
|
||||||
return usingOpenGL;
|
|
||||||
}
|
|
||||||
|
|
||||||
GLuint getProgramId() {
|
|
||||||
return programId;
|
|
||||||
}
|
|
||||||
} // namespace shader
|
|
||||||
10
source/external/jail_shader.h
vendored
10
source/external/jail_shader.h
vendored
@@ -1,10 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_Texture, SDL_Window
|
|
||||||
#include <string> // Para basic_string, string
|
|
||||||
|
|
||||||
namespace shader {
|
|
||||||
bool init(SDL_Window *ventana, SDL_Texture *texturaBackBuffer, const std::string &vertexShader, const std::string &fragmentShader = "");
|
|
||||||
void render();
|
|
||||||
void setTextureSize(float width, float height); // Establece el tamaño de textura como uniform
|
|
||||||
} // namespace shader
|
|
||||||
166
source/rendering/metal/METAL_BACKEND_NOTES.md
Normal file
166
source/rendering/metal/METAL_BACKEND_NOTES.md
Normal file
@@ -0,0 +1,166 @@
|
|||||||
|
# Metal Shader Backend - Notas de Implementación
|
||||||
|
|
||||||
|
## Estado Actual
|
||||||
|
|
||||||
|
✅ **Completado:**
|
||||||
|
- Shaders MSL (Metal Shading Language) portados desde GLSL
|
||||||
|
- Estructura básica de `MetalShader` class
|
||||||
|
- Inicialización de Metal device y command queue
|
||||||
|
- Compilación de shaders en runtime
|
||||||
|
- Creación de pipeline state
|
||||||
|
- Buffers de vértices, índices y uniforms
|
||||||
|
|
||||||
|
❌ **Pendiente:**
|
||||||
|
- **Render loop completo** (la parte más crítica)
|
||||||
|
- Obtener textura Metal desde SDL_Texture
|
||||||
|
- Gestión de drawables y presentation
|
||||||
|
|
||||||
|
## Diferencias GLSL vs MSL
|
||||||
|
|
||||||
|
| Concepto | GLSL (OpenGL) | MSL (Metal) |
|
||||||
|
|----------|---------------|-------------|
|
||||||
|
| Entrada vertex | `layout(location = 0) in vec2` | `[[attribute(0)]]` |
|
||||||
|
| Salida vertex | `out vec2` | Struct con `[[position]]` |
|
||||||
|
| Uniforms | `uniform vec2` | `constant` struct en `[[buffer(N)]]` |
|
||||||
|
| Sampling | `texture(sampler2D, vec2)` | `texture.sample(sampler, float2)` |
|
||||||
|
| Entry point | `void main()` | `vertex/fragment function_name()` |
|
||||||
|
| Vector types | `vec2, vec3, vec4` | `float2, float3, float4` |
|
||||||
|
|
||||||
|
## Pasos para Completar el Render Loop
|
||||||
|
|
||||||
|
El método `MetalShader::render()` necesita:
|
||||||
|
|
||||||
|
```objc
|
||||||
|
1. Obtener drawable del CAMetalLayer:
|
||||||
|
id<CAMetalDrawable> drawable = [metal_layer_ nextDrawable];
|
||||||
|
|
||||||
|
2. Crear command buffer:
|
||||||
|
id<MTLCommandBuffer> command_buffer = [command_queue_ commandBuffer];
|
||||||
|
|
||||||
|
3. Crear render pass descriptor:
|
||||||
|
MTLRenderPassDescriptor* pass_descriptor = [MTLRenderPassDescriptor renderPassDescriptor];
|
||||||
|
pass_descriptor.colorAttachments[0].texture = drawable.texture;
|
||||||
|
pass_descriptor.colorAttachments[0].loadAction = MTLLoadActionClear;
|
||||||
|
pass_descriptor.colorAttachments[0].storeAction = MTLStoreActionStore;
|
||||||
|
pass_descriptor.colorAttachments[0].clearColor = MTLClearColorMake(0, 0, 0, 1);
|
||||||
|
|
||||||
|
4. Crear render command encoder:
|
||||||
|
id<MTLRenderCommandEncoder> encoder =
|
||||||
|
[command_buffer renderCommandEncoderWithDescriptor:pass_descriptor];
|
||||||
|
|
||||||
|
5. Configurar pipeline y buffers:
|
||||||
|
[encoder setRenderPipelineState:pipeline_state_];
|
||||||
|
[encoder setVertexBuffer:vertex_buffer_ offset:0 atIndex:0];
|
||||||
|
[encoder setVertexBuffer:uniforms_buffer_ offset:0 atIndex:1];
|
||||||
|
[encoder setFragmentBuffer:uniforms_buffer_ offset:0 atIndex:1];
|
||||||
|
[encoder setFragmentTexture:game_texture offset:0 atIndex:0];
|
||||||
|
[encoder setFragmentSamplerState:sampler_state_ atIndex:0];
|
||||||
|
|
||||||
|
6. Dibujar:
|
||||||
|
[encoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle
|
||||||
|
indexCount:6
|
||||||
|
indexType:MTLIndexTypeUInt16
|
||||||
|
indexBuffer:index_buffer_
|
||||||
|
indexBufferOffset:0];
|
||||||
|
|
||||||
|
7. Finalizar:
|
||||||
|
[encoder endEncoding];
|
||||||
|
[command_buffer presentDrawable:drawable];
|
||||||
|
[command_buffer commit];
|
||||||
|
```
|
||||||
|
|
||||||
|
## Problema Crítico: Obtener MTLTexture desde SDL_Texture
|
||||||
|
|
||||||
|
SDL3 renderiza el juego a `back_buffer_` (SDL_Texture). Necesitamos obtener
|
||||||
|
la textura Metal subyacente para pasarla al fragment shader.
|
||||||
|
|
||||||
|
**Opciones:**
|
||||||
|
|
||||||
|
1. **SDL_GetProperty()** - Usar SDL3 properties system:
|
||||||
|
```cpp
|
||||||
|
id<MTLTexture> metal_texture = (__bridge id<MTLTexture>)SDL_GetProperty(
|
||||||
|
SDL_GetTextureProperties(back_buffer_),
|
||||||
|
"SDL.texture.metal.texture",
|
||||||
|
nullptr
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Render to Metal texture directamente** - En lugar de usar SDL_Texture,
|
||||||
|
crear una MTLTexture directamente y renderizar el juego ahí. Más trabajo
|
||||||
|
pero más control.
|
||||||
|
|
||||||
|
3. **Copiar SDL texture a Metal texture** - Menos eficiente pero más simple.
|
||||||
|
|
||||||
|
## Sampler State
|
||||||
|
|
||||||
|
Falta crear el sampler state (equivalente a glTexParameteri en OpenGL):
|
||||||
|
|
||||||
|
```objc
|
||||||
|
MTLSamplerDescriptor* sampler_descriptor = [[MTLSamplerDescriptor alloc] init];
|
||||||
|
sampler_descriptor.minFilter = MTLSamplerMinMagFilterLinear;
|
||||||
|
sampler_descriptor.magFilter = MTLSamplerMinMagFilterLinear;
|
||||||
|
sampler_descriptor.sAddressMode = MTLSamplerAddressModeClampToEdge;
|
||||||
|
sampler_descriptor.tAddressMode = MTLSamplerAddressModeClampToEdge;
|
||||||
|
|
||||||
|
id<MTLSamplerState> sampler_state = [device_ newSamplerStateWithDescriptor:sampler_descriptor];
|
||||||
|
```
|
||||||
|
|
||||||
|
## Build Configuration
|
||||||
|
|
||||||
|
Para compilar en Xcode/CMake, necesitarás:
|
||||||
|
|
||||||
|
1. **CMakeLists.txt** - Añadir metal_shader.mm:
|
||||||
|
```cmake
|
||||||
|
if(APPLE)
|
||||||
|
set(RENDERING_SOURCES
|
||||||
|
${RENDERING_SOURCES}
|
||||||
|
source/rendering/metal/metal_shader.mm
|
||||||
|
)
|
||||||
|
target_link_libraries(${PROJECT_NAME}
|
||||||
|
"-framework Metal"
|
||||||
|
"-framework QuartzCore"
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Compilar shaders .metal** - Opcionalmente pre-compilar:
|
||||||
|
```bash
|
||||||
|
xcrun -sdk macosx metal -c crtpi_vertex.metal -o crtpi_vertex.air
|
||||||
|
xcrun -sdk macosx metal -c crtpi_fragment.metal -o crtpi_fragment.air
|
||||||
|
xcrun -sdk macosx metallib crtpi_*.air -o crtpi.metallib
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Cargar .metallib** en código:
|
||||||
|
```objc
|
||||||
|
NSString* path = [[NSBundle mainBundle] pathForResource:@"crtpi" ofType:@"metallib"];
|
||||||
|
id<MTLLibrary> library = [device_ newLibraryWithFile:path error:&error];
|
||||||
|
```
|
||||||
|
|
||||||
|
## Testing en macOS
|
||||||
|
|
||||||
|
Cuando pruebes en macOS:
|
||||||
|
|
||||||
|
1. Verifica que `SDL_WINDOW_METAL` está activo en screen.cpp
|
||||||
|
2. Compila con `-DCMAKE_BUILD_TYPE=Debug` para ver logs
|
||||||
|
3. Usa Xcode Instruments (Metal Debugger) para inspeccionar frames
|
||||||
|
4. Compara rendimiento con/sin shaders
|
||||||
|
|
||||||
|
## Referencias Útiles
|
||||||
|
|
||||||
|
- [Metal Programming Guide](https://developer.apple.com/metal/)
|
||||||
|
- [Metal Shading Language Specification](https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf)
|
||||||
|
- [SDL3 Metal Integration](https://github.com/libsdl-org/SDL/blob/main/docs/README-metal.md)
|
||||||
|
|
||||||
|
## Próximos Pasos
|
||||||
|
|
||||||
|
1. Implementar `render()` completo
|
||||||
|
2. Resolver obtención de textura desde SDL
|
||||||
|
3. Crear sampler state
|
||||||
|
4. Testear en macOS real
|
||||||
|
5. Optimizar si es necesario (probablemente ya será rápido)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Nota importante**: Metal es significativamente más verboso que OpenGL pero
|
||||||
|
también más eficiente. Una vez que funcione el render loop, el rendimiento
|
||||||
|
debería ser excelente en macOS.
|
||||||
76
source/rendering/metal/metal_shader.h
Normal file
76
source/rendering/metal/metal_shader.h
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "../shader_backend.h"
|
||||||
|
|
||||||
|
#ifdef __APPLE__
|
||||||
|
|
||||||
|
#import <Metal/Metal.h>
|
||||||
|
#import <QuartzCore/CAMetalLayer.h>
|
||||||
|
|
||||||
|
namespace Rendering {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Backend de shaders usando Metal para macOS
|
||||||
|
*
|
||||||
|
* Implementa el renderizado de shaders usando Metal API nativo de Apple:
|
||||||
|
* - MTLDevice para acceso a GPU
|
||||||
|
* - MTLRenderPipelineState para configuración del pipeline
|
||||||
|
* - MTLCommandQueue para enviar comandos a GPU
|
||||||
|
* - MSL (Metal Shading Language) para shaders
|
||||||
|
*/
|
||||||
|
class MetalShader : public ShaderBackend {
|
||||||
|
public:
|
||||||
|
MetalShader() = default;
|
||||||
|
~MetalShader() override;
|
||||||
|
|
||||||
|
bool init(SDL_Window* window,
|
||||||
|
SDL_Texture* texture,
|
||||||
|
const std::string& vertex_source,
|
||||||
|
const std::string& fragment_source) override;
|
||||||
|
|
||||||
|
void render() override;
|
||||||
|
void setTextureSize(float width, float height) override;
|
||||||
|
void cleanup() override;
|
||||||
|
bool isHardwareAccelerated() const override { return is_initialized_; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
// Funciones auxiliares
|
||||||
|
bool createMetalDevice();
|
||||||
|
bool compileShaders(const std::string& vertex_source,
|
||||||
|
const std::string& fragment_source);
|
||||||
|
bool createPipeline();
|
||||||
|
bool createBuffers();
|
||||||
|
id<MTLTexture> getMetalTexture(SDL_Texture* texture);
|
||||||
|
|
||||||
|
// Estado SDL
|
||||||
|
SDL_Window* window_ = nullptr;
|
||||||
|
SDL_Renderer* renderer_ = nullptr;
|
||||||
|
SDL_Texture* back_buffer_ = nullptr;
|
||||||
|
|
||||||
|
// Estado Metal
|
||||||
|
id<MTLDevice> device_ = nil; // GPU device
|
||||||
|
id<MTLCommandQueue> command_queue_ = nil; // Cola de comandos
|
||||||
|
id<MTLRenderPipelineState> pipeline_state_ = nil; // Estado del pipeline
|
||||||
|
id<MTLBuffer> vertex_buffer_ = nil; // Buffer de vértices
|
||||||
|
id<MTLBuffer> index_buffer_ = nil; // Buffer de índices
|
||||||
|
id<MTLBuffer> uniforms_buffer_ = nil; // Buffer de uniforms
|
||||||
|
CAMetalLayer* metal_layer_ = nil; // Layer de Metal
|
||||||
|
|
||||||
|
// Uniforms
|
||||||
|
struct Uniforms {
|
||||||
|
float textureSize[2]; // width, height
|
||||||
|
} uniforms_;
|
||||||
|
|
||||||
|
// Tamaños
|
||||||
|
int window_width_ = 0;
|
||||||
|
int window_height_ = 0;
|
||||||
|
float texture_width_ = 0.0f;
|
||||||
|
float texture_height_ = 0.0f;
|
||||||
|
|
||||||
|
// Estado
|
||||||
|
bool is_initialized_ = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Rendering
|
||||||
|
|
||||||
|
#endif // __APPLE__
|
||||||
301
source/rendering/metal/metal_shader.mm
Normal file
301
source/rendering/metal/metal_shader.mm
Normal file
@@ -0,0 +1,301 @@
|
|||||||
|
// Usar .mm (Objective-C++) en lugar de .cpp para código Metal en macOS
|
||||||
|
|
||||||
|
#include "metal_shader.h"
|
||||||
|
|
||||||
|
#ifdef __APPLE__
|
||||||
|
|
||||||
|
#import <SDL3/SDL.h>
|
||||||
|
#import <SDL3/SDL_metal.h>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Rendering {
|
||||||
|
|
||||||
|
MetalShader::~MetalShader() {
|
||||||
|
cleanup();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool MetalShader::createMetalDevice() {
|
||||||
|
// Obtener el device Metal por defecto (GPU del sistema)
|
||||||
|
device_ = MTLCreateSystemDefaultDevice();
|
||||||
|
if (!device_) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"ERROR: No se pudo crear Metal device");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Crear command queue
|
||||||
|
command_queue_ = [device_ newCommandQueue];
|
||||||
|
if (!command_queue_) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"ERROR: No se pudo crear Metal command queue");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"Metal device creado: %s", [[device_ name] UTF8String]);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool MetalShader::compileShaders(const std::string& vertex_source,
|
||||||
|
const std::string& fragment_source) {
|
||||||
|
// En Metal, los shaders se pueden compilar de dos formas:
|
||||||
|
// 1. Runtime compilation desde strings (lo que haremos aquí)
|
||||||
|
// 2. Pre-compilados a .metallib (más eficiente pero requiere build step)
|
||||||
|
|
||||||
|
NSError* error = nil;
|
||||||
|
|
||||||
|
// Convertir sources a NSString
|
||||||
|
NSString* vertex_code = [NSString stringWithUTF8String:vertex_source.c_str()];
|
||||||
|
NSString* fragment_code = [NSString stringWithUTF8String:fragment_source.c_str()];
|
||||||
|
|
||||||
|
// Combinar vertex + fragment en un solo source (Metal permite múltiples shaders por library)
|
||||||
|
NSString* combined_source = [NSString stringWithFormat:@"%@\n\n%@",
|
||||||
|
vertex_code, fragment_code];
|
||||||
|
|
||||||
|
// Crear library desde source code
|
||||||
|
id<MTLLibrary> library = [device_ newLibraryWithSource:combined_source
|
||||||
|
options:nil
|
||||||
|
error:&error];
|
||||||
|
if (!library) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"ERROR: Fallo al compilar shaders Metal: %s",
|
||||||
|
[[error localizedDescription] UTF8String]);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Obtener funciones del library
|
||||||
|
id<MTLFunction> vertex_function = [library newFunctionWithName:@"vertex_main"];
|
||||||
|
id<MTLFunction> fragment_function = [library newFunctionWithName:@"fragment_main"];
|
||||||
|
|
||||||
|
if (!vertex_function || !fragment_function) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"ERROR: No se encontraron las funciones vertex_main o fragment_main");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Crear pipeline descriptor
|
||||||
|
MTLRenderPipelineDescriptor* pipeline_descriptor = [[MTLRenderPipelineDescriptor alloc] init];
|
||||||
|
pipeline_descriptor.vertexFunction = vertex_function;
|
||||||
|
pipeline_descriptor.fragmentFunction = fragment_function;
|
||||||
|
|
||||||
|
// Configurar formato de color (BGRA8Unorm es común en macOS)
|
||||||
|
pipeline_descriptor.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm;
|
||||||
|
|
||||||
|
// Configurar vertex descriptor (cómo están organizados los vértices)
|
||||||
|
MTLVertexDescriptor* vertex_descriptor = [[MTLVertexDescriptor alloc] init];
|
||||||
|
|
||||||
|
// Atributo 0: position (2 floats)
|
||||||
|
vertex_descriptor.attributes[0].format = MTLVertexFormatFloat2;
|
||||||
|
vertex_descriptor.attributes[0].offset = 0;
|
||||||
|
vertex_descriptor.attributes[0].bufferIndex = 0;
|
||||||
|
|
||||||
|
// Atributo 1: texCoord (2 floats)
|
||||||
|
vertex_descriptor.attributes[1].format = MTLVertexFormatFloat2;
|
||||||
|
vertex_descriptor.attributes[1].offset = 2 * sizeof(float);
|
||||||
|
vertex_descriptor.attributes[1].bufferIndex = 0;
|
||||||
|
|
||||||
|
// Layout del buffer (stride = 4 floats por vértice)
|
||||||
|
vertex_descriptor.layouts[0].stride = 4 * sizeof(float);
|
||||||
|
vertex_descriptor.layouts[0].stepRate = 1;
|
||||||
|
vertex_descriptor.layouts[0].stepFunction = MTLVertexStepFunctionPerVertex;
|
||||||
|
|
||||||
|
pipeline_descriptor.vertexDescriptor = vertex_descriptor;
|
||||||
|
|
||||||
|
// Crear pipeline state
|
||||||
|
pipeline_state_ = [device_ newRenderPipelineStateWithDescriptor:pipeline_descriptor
|
||||||
|
error:&error];
|
||||||
|
if (!pipeline_state_) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"ERROR: Fallo al crear pipeline state: %s",
|
||||||
|
[[error localizedDescription] UTF8String]);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"Shaders Metal compilados correctamente");
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool MetalShader::createBuffers() {
|
||||||
|
// Crear quad de pantalla completa (igual que en OpenGL)
|
||||||
|
// Formato: x, y, u, v
|
||||||
|
float vertices[] = {
|
||||||
|
-1.0f, -1.0f, 0.0f, 0.0f, // Inferior izquierda
|
||||||
|
1.0f, -1.0f, 1.0f, 0.0f, // Inferior derecha
|
||||||
|
1.0f, 1.0f, 1.0f, 1.0f, // Superior derecha
|
||||||
|
-1.0f, 1.0f, 0.0f, 1.0f // Superior izquierda
|
||||||
|
};
|
||||||
|
|
||||||
|
uint16_t indices[] = {
|
||||||
|
0, 1, 2, // Primer triángulo
|
||||||
|
2, 3, 0 // Segundo triángulo
|
||||||
|
};
|
||||||
|
|
||||||
|
// Crear vertex buffer
|
||||||
|
vertex_buffer_ = [device_ newBufferWithBytes:vertices
|
||||||
|
length:sizeof(vertices)
|
||||||
|
options:MTLResourceStorageModeShared];
|
||||||
|
if (!vertex_buffer_) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"ERROR: Fallo al crear vertex buffer");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Crear index buffer
|
||||||
|
index_buffer_ = [device_ newBufferWithBytes:indices
|
||||||
|
length:sizeof(indices)
|
||||||
|
options:MTLResourceStorageModeShared];
|
||||||
|
if (!index_buffer_) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"ERROR: Fallo al crear index buffer");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Crear uniforms buffer
|
||||||
|
uniforms_buffer_ = [device_ newBufferWithLength:sizeof(Uniforms)
|
||||||
|
options:MTLResourceStorageModeShared];
|
||||||
|
if (!uniforms_buffer_) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"ERROR: Fallo al crear uniforms buffer");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool MetalShader::init(SDL_Window* window,
|
||||||
|
SDL_Texture* texture,
|
||||||
|
const std::string& vertex_source,
|
||||||
|
const std::string& fragment_source) {
|
||||||
|
window_ = window;
|
||||||
|
back_buffer_ = texture;
|
||||||
|
renderer_ = SDL_GetRenderer(window);
|
||||||
|
|
||||||
|
if (!renderer_) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"ERROR: No se pudo obtener el renderer");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verificar que es Metal renderer
|
||||||
|
const char* renderer_name = SDL_GetRendererName(renderer_);
|
||||||
|
if (!renderer_name || strncmp(renderer_name, "metal", 5) != 0) {
|
||||||
|
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"Renderer no es Metal: %s", renderer_name ? renderer_name : "unknown");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Obtener tamaños
|
||||||
|
SDL_GetWindowSize(window_, &window_width_, &window_height_);
|
||||||
|
SDL_GetTextureSize(back_buffer_, &texture_width_, &texture_height_);
|
||||||
|
|
||||||
|
// Crear Metal device
|
||||||
|
if (!createMetalDevice()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compilar shaders
|
||||||
|
if (!compileShaders(vertex_source, fragment_source)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Crear buffers
|
||||||
|
if (!createBuffers()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inicializar uniforms
|
||||||
|
uniforms_.textureSize[0] = texture_width_;
|
||||||
|
uniforms_.textureSize[1] = texture_height_;
|
||||||
|
|
||||||
|
// Copiar uniforms al buffer
|
||||||
|
memcpy([uniforms_buffer_ contents], &uniforms_, sizeof(Uniforms));
|
||||||
|
|
||||||
|
// Obtener Metal layer de SDL
|
||||||
|
metal_layer_ = (__bridge CAMetalLayer*)SDL_GetProperty(
|
||||||
|
SDL_GetWindowProperties(window_),
|
||||||
|
SDL_PROP_WINDOW_METAL_LAYER_POINTER,
|
||||||
|
nullptr
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!metal_layer_) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"ERROR: No se pudo obtener Metal layer");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
metal_layer_.device = device_;
|
||||||
|
metal_layer_.pixelFormat = MTLPixelFormatBGRA8Unorm;
|
||||||
|
|
||||||
|
is_initialized_ = true;
|
||||||
|
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"** Metal Shader Backend inicializado correctamente");
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void MetalShader::render() {
|
||||||
|
if (!is_initialized_ || !pipeline_state_) {
|
||||||
|
// Fallback a renderizado normal
|
||||||
|
SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 255);
|
||||||
|
SDL_SetRenderTarget(renderer_, nullptr);
|
||||||
|
SDL_RenderClear(renderer_);
|
||||||
|
SDL_RenderTexture(renderer_, back_buffer_, nullptr, nullptr);
|
||||||
|
SDL_RenderPresent(renderer_);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Implementar render loop de Metal
|
||||||
|
// 1. Obtener drawable del layer
|
||||||
|
// 2. Crear command buffer
|
||||||
|
// 3. Crear render pass descriptor
|
||||||
|
// 4. Encodear comandos de dibujo
|
||||||
|
// 5. Commit y presentar
|
||||||
|
|
||||||
|
// NOTA: Esta es la parte más compleja y requiere más trabajo
|
||||||
|
// Por ahora dejamos un stub para que compile
|
||||||
|
|
||||||
|
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"Metal render() no implementado completamente todavía");
|
||||||
|
}
|
||||||
|
|
||||||
|
void MetalShader::setTextureSize(float width, float height) {
|
||||||
|
if (!is_initialized_) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
texture_width_ = width;
|
||||||
|
texture_height_ = height;
|
||||||
|
|
||||||
|
// Actualizar uniforms
|
||||||
|
uniforms_.textureSize[0] = width;
|
||||||
|
uniforms_.textureSize[1] = height;
|
||||||
|
|
||||||
|
memcpy([uniforms_buffer_ contents], &uniforms_, sizeof(Uniforms));
|
||||||
|
}
|
||||||
|
|
||||||
|
void MetalShader::cleanup() {
|
||||||
|
// En Objective-C++ con ARC, no necesitamos release manual
|
||||||
|
// pero limpiamos las referencias
|
||||||
|
pipeline_state_ = nil;
|
||||||
|
command_queue_ = nil;
|
||||||
|
vertex_buffer_ = nil;
|
||||||
|
index_buffer_ = nil;
|
||||||
|
uniforms_buffer_ = nil;
|
||||||
|
device_ = nil;
|
||||||
|
metal_layer_ = nil;
|
||||||
|
|
||||||
|
is_initialized_ = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
id<MTLTexture> MetalShader::getMetalTexture(SDL_Texture* texture) {
|
||||||
|
// TODO: Obtener la textura Metal desde SDL_Texture
|
||||||
|
// Esto requiere acceder a las properties de SDL3
|
||||||
|
return nil;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Rendering
|
||||||
|
|
||||||
|
#endif // __APPLE__
|
||||||
455
source/rendering/opengl/opengl_shader.cpp
Normal file
455
source/rendering/opengl/opengl_shader.cpp
Normal file
@@ -0,0 +1,455 @@
|
|||||||
|
#include "opengl_shader.h"
|
||||||
|
|
||||||
|
#include <SDL3/SDL.h>
|
||||||
|
#include <cstring>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace Rendering {
|
||||||
|
|
||||||
|
OpenGLShader::~OpenGLShader() {
|
||||||
|
cleanup();
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifndef __APPLE__
|
||||||
|
bool OpenGLShader::initGLExtensions() {
|
||||||
|
glCreateShader = (PFNGLCREATESHADERPROC)SDL_GL_GetProcAddress("glCreateShader");
|
||||||
|
glShaderSource = (PFNGLSHADERSOURCEPROC)SDL_GL_GetProcAddress("glShaderSource");
|
||||||
|
glCompileShader = (PFNGLCOMPILESHADERPROC)SDL_GL_GetProcAddress("glCompileShader");
|
||||||
|
glGetShaderiv = (PFNGLGETSHADERIVPROC)SDL_GL_GetProcAddress("glGetShaderiv");
|
||||||
|
glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)SDL_GL_GetProcAddress("glGetShaderInfoLog");
|
||||||
|
glDeleteShader = (PFNGLDELETESHADERPROC)SDL_GL_GetProcAddress("glDeleteShader");
|
||||||
|
glAttachShader = (PFNGLATTACHSHADERPROC)SDL_GL_GetProcAddress("glAttachShader");
|
||||||
|
glCreateProgram = (PFNGLCREATEPROGRAMPROC)SDL_GL_GetProcAddress("glCreateProgram");
|
||||||
|
glLinkProgram = (PFNGLLINKPROGRAMPROC)SDL_GL_GetProcAddress("glLinkProgram");
|
||||||
|
glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)SDL_GL_GetProcAddress("glValidateProgram");
|
||||||
|
glGetProgramiv = (PFNGLGETPROGRAMIVPROC)SDL_GL_GetProcAddress("glGetProgramiv");
|
||||||
|
glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)SDL_GL_GetProcAddress("glGetProgramInfoLog");
|
||||||
|
glUseProgram = (PFNGLUSEPROGRAMPROC)SDL_GL_GetProcAddress("glUseProgram");
|
||||||
|
glDeleteProgram = (PFNGLDELETEPROGRAMPROC)SDL_GL_GetProcAddress("glDeleteProgram");
|
||||||
|
glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)SDL_GL_GetProcAddress("glGetUniformLocation");
|
||||||
|
glUniform2f = (PFNGLUNIFORM2FPROC)SDL_GL_GetProcAddress("glUniform2f");
|
||||||
|
glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)SDL_GL_GetProcAddress("glGenVertexArrays");
|
||||||
|
glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)SDL_GL_GetProcAddress("glBindVertexArray");
|
||||||
|
glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)SDL_GL_GetProcAddress("glDeleteVertexArrays");
|
||||||
|
glGenBuffers = (PFNGLGENBUFFERSPROC)SDL_GL_GetProcAddress("glGenBuffers");
|
||||||
|
glBindBuffer = (PFNGLBINDBUFFERPROC)SDL_GL_GetProcAddress("glBindBuffer");
|
||||||
|
glBufferData = (PFNGLBUFFERDATAPROC)SDL_GL_GetProcAddress("glBufferData");
|
||||||
|
glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)SDL_GL_GetProcAddress("glDeleteBuffers");
|
||||||
|
glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)SDL_GL_GetProcAddress("glVertexAttribPointer");
|
||||||
|
glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)SDL_GL_GetProcAddress("glEnableVertexAttribArray");
|
||||||
|
|
||||||
|
return glCreateShader && glShaderSource && glCompileShader && glGetShaderiv &&
|
||||||
|
glGetShaderInfoLog && glDeleteShader && glAttachShader && glCreateProgram &&
|
||||||
|
glLinkProgram && glValidateProgram && glGetProgramiv && glGetProgramInfoLog &&
|
||||||
|
glUseProgram && glDeleteProgram && glGetUniformLocation && glUniform2f &&
|
||||||
|
glGenVertexArrays && glBindVertexArray && glDeleteVertexArrays &&
|
||||||
|
glGenBuffers && glBindBuffer && glBufferData && glDeleteBuffers &&
|
||||||
|
glVertexAttribPointer && glEnableVertexAttribArray;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
void OpenGLShader::checkGLError(const char* operation) {
|
||||||
|
GLenum error = glGetError();
|
||||||
|
if (error != GL_NO_ERROR) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"Error OpenGL en %s: 0x%x", operation, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
GLuint OpenGLShader::compileShader(const std::string& source, GLenum shader_type) {
|
||||||
|
if (source.empty()) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"ERROR: El código fuente del shader está vacío");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
GLuint shader_id = glCreateShader(shader_type);
|
||||||
|
if (shader_id == 0) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error al crear shader");
|
||||||
|
checkGLError("glCreateShader");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char* sources[1] = {source.c_str()};
|
||||||
|
glShaderSource(shader_id, 1, sources, nullptr);
|
||||||
|
checkGLError("glShaderSource");
|
||||||
|
|
||||||
|
glCompileShader(shader_id);
|
||||||
|
checkGLError("glCompileShader");
|
||||||
|
|
||||||
|
// Verificar compilación
|
||||||
|
GLint compiled = GL_FALSE;
|
||||||
|
glGetShaderiv(shader_id, GL_COMPILE_STATUS, &compiled);
|
||||||
|
if (compiled != GL_TRUE) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"Error en compilación del shader");
|
||||||
|
GLint log_length;
|
||||||
|
glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &log_length);
|
||||||
|
if (log_length > 0) {
|
||||||
|
std::vector<char> log(log_length);
|
||||||
|
glGetShaderInfoLog(shader_id, log_length, &log_length, log.data());
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"Log de compilación: %s", log.data());
|
||||||
|
}
|
||||||
|
glDeleteShader(shader_id);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return shader_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
GLuint OpenGLShader::linkProgram(GLuint vertex_shader, GLuint fragment_shader) {
|
||||||
|
GLuint program = glCreateProgram();
|
||||||
|
if (program == 0) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"Error al crear programa de shaders");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
glAttachShader(program, vertex_shader);
|
||||||
|
checkGLError("glAttachShader(vertex)");
|
||||||
|
glAttachShader(program, fragment_shader);
|
||||||
|
checkGLError("glAttachShader(fragment)");
|
||||||
|
|
||||||
|
glLinkProgram(program);
|
||||||
|
checkGLError("glLinkProgram");
|
||||||
|
|
||||||
|
// Verificar enlace
|
||||||
|
GLint linked = GL_FALSE;
|
||||||
|
glGetProgramiv(program, GL_LINK_STATUS, &linked);
|
||||||
|
if (linked != GL_TRUE) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"Error al enlazar programa");
|
||||||
|
GLint log_length;
|
||||||
|
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
|
||||||
|
if (log_length > 0) {
|
||||||
|
std::vector<char> log(log_length);
|
||||||
|
glGetProgramInfoLog(program, log_length, &log_length, log.data());
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"Log de enlace: %s", log.data());
|
||||||
|
}
|
||||||
|
glDeleteProgram(program);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
glValidateProgram(program);
|
||||||
|
checkGLError("glValidateProgram");
|
||||||
|
|
||||||
|
return program;
|
||||||
|
}
|
||||||
|
|
||||||
|
void OpenGLShader::createQuadGeometry() {
|
||||||
|
// Datos del quad: posición (x, y) + coordenadas de textura (u, v)
|
||||||
|
// Formato: x, y, u, v
|
||||||
|
float vertices[] = {
|
||||||
|
// Posición // TexCoords
|
||||||
|
-1.0f, -1.0f, 0.0f, 0.0f, // Inferior izquierda
|
||||||
|
1.0f, -1.0f, 1.0f, 0.0f, // Inferior derecha
|
||||||
|
1.0f, 1.0f, 1.0f, 1.0f, // Superior derecha
|
||||||
|
-1.0f, 1.0f, 0.0f, 1.0f // Superior izquierda
|
||||||
|
};
|
||||||
|
|
||||||
|
// Índices para dibujar el quad con dos triángulos
|
||||||
|
unsigned int indices[] = {
|
||||||
|
0, 1, 2, // Primer triángulo
|
||||||
|
2, 3, 0 // Segundo triángulo
|
||||||
|
};
|
||||||
|
|
||||||
|
// Generar y configurar VAO
|
||||||
|
glGenVertexArrays(1, &vao_);
|
||||||
|
glBindVertexArray(vao_);
|
||||||
|
checkGLError("glBindVertexArray");
|
||||||
|
|
||||||
|
// Generar y configurar VBO
|
||||||
|
glGenBuffers(1, &vbo_);
|
||||||
|
glBindBuffer(GL_ARRAY_BUFFER, vbo_);
|
||||||
|
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
|
||||||
|
checkGLError("glBufferData(VBO)");
|
||||||
|
|
||||||
|
// Generar y configurar EBO
|
||||||
|
glGenBuffers(1, &ebo_);
|
||||||
|
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo_);
|
||||||
|
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
|
||||||
|
checkGLError("glBufferData(EBO)");
|
||||||
|
|
||||||
|
// Atributo 0: Posición (2 floats)
|
||||||
|
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0);
|
||||||
|
glEnableVertexAttribArray(0);
|
||||||
|
checkGLError("glVertexAttribPointer(position)");
|
||||||
|
|
||||||
|
// Atributo 1: Coordenadas de textura (2 floats)
|
||||||
|
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float)));
|
||||||
|
glEnableVertexAttribArray(1);
|
||||||
|
checkGLError("glVertexAttribPointer(texcoord)");
|
||||||
|
|
||||||
|
// Desvincular
|
||||||
|
glBindBuffer(GL_ARRAY_BUFFER, 0);
|
||||||
|
glBindVertexArray(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
GLuint OpenGLShader::getTextureID(SDL_Texture* texture) {
|
||||||
|
if (!texture) return 1;
|
||||||
|
|
||||||
|
SDL_PropertiesID props = SDL_GetTextureProperties(texture);
|
||||||
|
GLuint texture_id = 0;
|
||||||
|
|
||||||
|
// Intentar obtener ID de textura OpenGL
|
||||||
|
texture_id = (GLuint)(uintptr_t)SDL_GetPointerProperty(props, "SDL.texture.opengl.texture", nullptr);
|
||||||
|
|
||||||
|
if (texture_id == 0) {
|
||||||
|
texture_id = (GLuint)(uintptr_t)SDL_GetPointerProperty(props, "texture.opengl.texture", nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (texture_id == 0) {
|
||||||
|
texture_id = (GLuint)SDL_GetNumberProperty(props, "SDL.texture.opengl.texture", 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (texture_id == 0) {
|
||||||
|
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"No se pudo obtener ID de textura OpenGL, usando 1 por defecto");
|
||||||
|
texture_id = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return texture_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OpenGLShader::init(SDL_Window* window,
|
||||||
|
SDL_Texture* texture,
|
||||||
|
const std::string& vertex_source,
|
||||||
|
const std::string& fragment_source) {
|
||||||
|
window_ = window;
|
||||||
|
back_buffer_ = texture;
|
||||||
|
renderer_ = SDL_GetRenderer(window);
|
||||||
|
|
||||||
|
if (!renderer_) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"Error: No se pudo obtener el renderer");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Obtener tamaños
|
||||||
|
SDL_GetWindowSize(window_, &window_width_, &window_height_);
|
||||||
|
SDL_GetTextureSize(back_buffer_, &texture_width_, &texture_height_);
|
||||||
|
|
||||||
|
// Verificar que es OpenGL
|
||||||
|
const char* renderer_name = SDL_GetRendererName(renderer_);
|
||||||
|
if (!renderer_name || strncmp(renderer_name, "opengl", 6) != 0) {
|
||||||
|
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"Renderer no es OpenGL: %s", renderer_name ? renderer_name : "unknown");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifndef __APPLE__
|
||||||
|
// Inicializar extensiones OpenGL en Windows/Linux
|
||||||
|
if (!initGLExtensions()) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"Error al inicializar extensiones OpenGL");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Limpiar shader anterior si existe
|
||||||
|
if (program_id_ != 0) {
|
||||||
|
glDeleteProgram(program_id_);
|
||||||
|
program_id_ = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compilar shaders
|
||||||
|
GLuint vertex_shader = compileShader(vertex_source, GL_VERTEX_SHADER);
|
||||||
|
GLuint fragment_shader = compileShader(fragment_source, GL_FRAGMENT_SHADER);
|
||||||
|
|
||||||
|
if (vertex_shader == 0 || fragment_shader == 0) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"Error al compilar shaders");
|
||||||
|
if (vertex_shader != 0) glDeleteShader(vertex_shader);
|
||||||
|
if (fragment_shader != 0) glDeleteShader(fragment_shader);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enlazar programa
|
||||||
|
program_id_ = linkProgram(vertex_shader, fragment_shader);
|
||||||
|
|
||||||
|
// Limpiar shaders (ya no necesarios tras el enlace)
|
||||||
|
glDeleteShader(vertex_shader);
|
||||||
|
glDeleteShader(fragment_shader);
|
||||||
|
|
||||||
|
if (program_id_ == 0) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"Error al crear programa de shaders");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Crear geometría del quad
|
||||||
|
createQuadGeometry();
|
||||||
|
|
||||||
|
// Obtener ubicación del uniform TextureSize
|
||||||
|
glUseProgram(program_id_);
|
||||||
|
texture_size_location_ = glGetUniformLocation(program_id_, "TextureSize");
|
||||||
|
if (texture_size_location_ != -1) {
|
||||||
|
glUniform2f(texture_size_location_, texture_width_, texture_height_);
|
||||||
|
checkGLError("glUniform2f(TextureSize)");
|
||||||
|
} else {
|
||||||
|
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"Uniform 'TextureSize' no encontrado en shader");
|
||||||
|
}
|
||||||
|
glUseProgram(0);
|
||||||
|
|
||||||
|
is_initialized_ = true;
|
||||||
|
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"** OpenGL 3.3 Shader Backend inicializado correctamente");
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void OpenGLShader::render() {
|
||||||
|
if (!is_initialized_ || program_id_ == 0) {
|
||||||
|
// Fallback: renderizado SDL normal
|
||||||
|
SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 255);
|
||||||
|
SDL_SetRenderTarget(renderer_, nullptr);
|
||||||
|
SDL_RenderClear(renderer_);
|
||||||
|
SDL_RenderTexture(renderer_, back_buffer_, nullptr, nullptr);
|
||||||
|
SDL_RenderPresent(renderer_);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Obtener tamaño actual de ventana (puede haber cambiado)
|
||||||
|
int current_width, current_height;
|
||||||
|
SDL_GetWindowSize(window_, ¤t_width, ¤t_height);
|
||||||
|
|
||||||
|
// Guardar estados OpenGL
|
||||||
|
GLint old_program;
|
||||||
|
glGetIntegerv(GL_CURRENT_PROGRAM, &old_program);
|
||||||
|
|
||||||
|
GLint old_viewport[4];
|
||||||
|
glGetIntegerv(GL_VIEWPORT, old_viewport);
|
||||||
|
|
||||||
|
GLboolean was_texture_enabled = glIsEnabled(GL_TEXTURE_2D);
|
||||||
|
GLint old_texture;
|
||||||
|
glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_texture);
|
||||||
|
|
||||||
|
GLint old_vao;
|
||||||
|
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &old_vao);
|
||||||
|
|
||||||
|
// Preparar renderizado
|
||||||
|
SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 255);
|
||||||
|
SDL_SetRenderTarget(renderer_, nullptr);
|
||||||
|
SDL_RenderClear(renderer_);
|
||||||
|
|
||||||
|
// Obtener y bindear textura
|
||||||
|
GLuint texture_id = getTextureID(back_buffer_);
|
||||||
|
glEnable(GL_TEXTURE_2D);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, texture_id);
|
||||||
|
checkGLError("glBindTexture");
|
||||||
|
|
||||||
|
// Usar nuestro programa
|
||||||
|
glUseProgram(program_id_);
|
||||||
|
checkGLError("glUseProgram");
|
||||||
|
|
||||||
|
// Configurar viewport (obtener tamaño lógico de SDL)
|
||||||
|
int logical_w, logical_h;
|
||||||
|
SDL_RendererLogicalPresentation mode;
|
||||||
|
SDL_GetRenderLogicalPresentation(renderer_, &logical_w, &logical_h, &mode);
|
||||||
|
|
||||||
|
if (logical_w == 0 || logical_h == 0) {
|
||||||
|
logical_w = current_width;
|
||||||
|
logical_h = current_height;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calcular viewport considerando aspect ratio
|
||||||
|
int viewport_x = 0, viewport_y = 0;
|
||||||
|
int viewport_w = current_width, viewport_h = current_height;
|
||||||
|
|
||||||
|
if (mode == SDL_LOGICAL_PRESENTATION_INTEGER_SCALE) {
|
||||||
|
int scale_x = current_width / logical_w;
|
||||||
|
int scale_y = current_height / logical_h;
|
||||||
|
int scale = (scale_x < scale_y) ? scale_x : scale_y;
|
||||||
|
if (scale < 1) scale = 1;
|
||||||
|
|
||||||
|
viewport_w = logical_w * scale;
|
||||||
|
viewport_h = logical_h * scale;
|
||||||
|
viewport_x = (current_width - viewport_w) / 2;
|
||||||
|
viewport_y = (current_height - viewport_h) / 2;
|
||||||
|
} else {
|
||||||
|
float window_aspect = static_cast<float>(current_width) / current_height;
|
||||||
|
float logical_aspect = static_cast<float>(logical_w) / logical_h;
|
||||||
|
|
||||||
|
if (window_aspect > logical_aspect) {
|
||||||
|
viewport_w = static_cast<int>(logical_aspect * current_height);
|
||||||
|
viewport_x = (current_width - viewport_w) / 2;
|
||||||
|
} else {
|
||||||
|
viewport_h = static_cast<int>(current_width / logical_aspect);
|
||||||
|
viewport_y = (current_height - viewport_h) / 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
glViewport(viewport_x, viewport_y, viewport_w, viewport_h);
|
||||||
|
checkGLError("glViewport");
|
||||||
|
|
||||||
|
// Dibujar quad usando VAO
|
||||||
|
glBindVertexArray(vao_);
|
||||||
|
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
|
||||||
|
checkGLError("glDrawElements");
|
||||||
|
|
||||||
|
// Presentar
|
||||||
|
SDL_GL_SwapWindow(window_);
|
||||||
|
|
||||||
|
// Restaurar estados OpenGL
|
||||||
|
glUseProgram(old_program);
|
||||||
|
glBindTexture(GL_TEXTURE_2D, old_texture);
|
||||||
|
if (!was_texture_enabled) {
|
||||||
|
glDisable(GL_TEXTURE_2D);
|
||||||
|
}
|
||||||
|
glBindVertexArray(old_vao);
|
||||||
|
glViewport(old_viewport[0], old_viewport[1], old_viewport[2], old_viewport[3]);
|
||||||
|
}
|
||||||
|
|
||||||
|
void OpenGLShader::setTextureSize(float width, float height) {
|
||||||
|
if (!is_initialized_ || program_id_ == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
texture_width_ = width;
|
||||||
|
texture_height_ = height;
|
||||||
|
|
||||||
|
GLint old_program;
|
||||||
|
glGetIntegerv(GL_CURRENT_PROGRAM, &old_program);
|
||||||
|
|
||||||
|
glUseProgram(program_id_);
|
||||||
|
|
||||||
|
if (texture_size_location_ != -1) {
|
||||||
|
glUniform2f(texture_size_location_, width, height);
|
||||||
|
checkGLError("glUniform2f(TextureSize)");
|
||||||
|
}
|
||||||
|
|
||||||
|
glUseProgram(old_program);
|
||||||
|
}
|
||||||
|
|
||||||
|
void OpenGLShader::cleanup() {
|
||||||
|
if (vao_ != 0) {
|
||||||
|
glDeleteVertexArrays(1, &vao_);
|
||||||
|
vao_ = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vbo_ != 0) {
|
||||||
|
glDeleteBuffers(1, &vbo_);
|
||||||
|
vbo_ = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ebo_ != 0) {
|
||||||
|
glDeleteBuffers(1, &ebo_);
|
||||||
|
ebo_ = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (program_id_ != 0) {
|
||||||
|
glDeleteProgram(program_id_);
|
||||||
|
program_id_ = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
is_initialized_ = false;
|
||||||
|
window_ = nullptr;
|
||||||
|
renderer_ = nullptr;
|
||||||
|
back_buffer_ = nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Rendering
|
||||||
98
source/rendering/opengl/opengl_shader.h
Normal file
98
source/rendering/opengl/opengl_shader.h
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "../shader_backend.h"
|
||||||
|
|
||||||
|
#ifdef __APPLE__
|
||||||
|
#include <OpenGL/gl3.h>
|
||||||
|
#else
|
||||||
|
#include <SDL3/SDL_opengl.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace Rendering {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Backend de shaders usando OpenGL 3.3 Core Profile
|
||||||
|
*
|
||||||
|
* Implementa el renderizado de shaders usando APIs modernas de OpenGL:
|
||||||
|
* - VAO (Vertex Array Objects)
|
||||||
|
* - VBO (Vertex Buffer Objects)
|
||||||
|
* - Shaders GLSL #version 330 core
|
||||||
|
*/
|
||||||
|
class OpenGLShader : public ShaderBackend {
|
||||||
|
public:
|
||||||
|
OpenGLShader() = default;
|
||||||
|
~OpenGLShader() override;
|
||||||
|
|
||||||
|
bool init(SDL_Window* window,
|
||||||
|
SDL_Texture* texture,
|
||||||
|
const std::string& vertex_source,
|
||||||
|
const std::string& fragment_source) override;
|
||||||
|
|
||||||
|
void render() override;
|
||||||
|
void setTextureSize(float width, float height) override;
|
||||||
|
void cleanup() override;
|
||||||
|
bool isHardwareAccelerated() const override { return is_initialized_; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
// Funciones auxiliares
|
||||||
|
bool initGLExtensions();
|
||||||
|
GLuint compileShader(const std::string& source, GLenum shader_type);
|
||||||
|
GLuint linkProgram(GLuint vertex_shader, GLuint fragment_shader);
|
||||||
|
void createQuadGeometry();
|
||||||
|
GLuint getTextureID(SDL_Texture* texture);
|
||||||
|
void checkGLError(const char* operation);
|
||||||
|
|
||||||
|
// Estado SDL
|
||||||
|
SDL_Window* window_ = nullptr;
|
||||||
|
SDL_Renderer* renderer_ = nullptr;
|
||||||
|
SDL_Texture* back_buffer_ = nullptr;
|
||||||
|
|
||||||
|
// Estado OpenGL
|
||||||
|
GLuint program_id_ = 0;
|
||||||
|
GLuint vao_ = 0; // Vertex Array Object
|
||||||
|
GLuint vbo_ = 0; // Vertex Buffer Object
|
||||||
|
GLuint ebo_ = 0; // Element Buffer Object
|
||||||
|
|
||||||
|
// Ubicaciones de uniforms
|
||||||
|
GLint texture_size_location_ = -1;
|
||||||
|
|
||||||
|
// Tamaños
|
||||||
|
int window_width_ = 0;
|
||||||
|
int window_height_ = 0;
|
||||||
|
float texture_width_ = 0.0f;
|
||||||
|
float texture_height_ = 0.0f;
|
||||||
|
|
||||||
|
// Estado
|
||||||
|
bool is_initialized_ = false;
|
||||||
|
|
||||||
|
#ifndef __APPLE__
|
||||||
|
// Punteros a funciones OpenGL en Windows/Linux
|
||||||
|
PFNGLCREATESHADERPROC glCreateShader = nullptr;
|
||||||
|
PFNGLSHADERSOURCEPROC glShaderSource = nullptr;
|
||||||
|
PFNGLCOMPILESHADERPROC glCompileShader = nullptr;
|
||||||
|
PFNGLGETSHADERIVPROC glGetShaderiv = nullptr;
|
||||||
|
PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog = nullptr;
|
||||||
|
PFNGLDELETESHADERPROC glDeleteShader = nullptr;
|
||||||
|
PFNGLATTACHSHADERPROC glAttachShader = nullptr;
|
||||||
|
PFNGLCREATEPROGRAMPROC glCreateProgram = nullptr;
|
||||||
|
PFNGLLINKPROGRAMPROC glLinkProgram = nullptr;
|
||||||
|
PFNGLVALIDATEPROGRAMPROC glValidateProgram = nullptr;
|
||||||
|
PFNGLGETPROGRAMIVPROC glGetProgramiv = nullptr;
|
||||||
|
PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog = nullptr;
|
||||||
|
PFNGLUSEPROGRAMPROC glUseProgram = nullptr;
|
||||||
|
PFNGLDELETEPROGRAMPROC glDeleteProgram = nullptr;
|
||||||
|
PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation = nullptr;
|
||||||
|
PFNGLUNIFORM2FPROC glUniform2f = nullptr;
|
||||||
|
PFNGLGENVERTEXARRAYSPROC glGenVertexArrays = nullptr;
|
||||||
|
PFNGLBINDVERTEXARRAYPROC glBindVertexArray = nullptr;
|
||||||
|
PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays = nullptr;
|
||||||
|
PFNGLGENBUFFERSPROC glGenBuffers = nullptr;
|
||||||
|
PFNGLBINDBUFFERPROC glBindBuffer = nullptr;
|
||||||
|
PFNGLBUFFERDATAPROC glBufferData = nullptr;
|
||||||
|
PFNGLDELETEBUFFERSPROC glDeleteBuffers = nullptr;
|
||||||
|
PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer = nullptr;
|
||||||
|
PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray = nullptr;
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Rendering
|
||||||
55
source/rendering/shader_backend.h
Normal file
55
source/rendering/shader_backend.h
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <SDL3/SDL.h>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
namespace Rendering {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Interfaz abstracta para backends de renderizado con shaders
|
||||||
|
*
|
||||||
|
* Esta interfaz define el contrato que todos los backends de shaders
|
||||||
|
* deben cumplir (OpenGL, Metal, Vulkan, etc.)
|
||||||
|
*/
|
||||||
|
class ShaderBackend {
|
||||||
|
public:
|
||||||
|
virtual ~ShaderBackend() = default;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Inicializa el backend de shaders
|
||||||
|
* @param window Ventana SDL
|
||||||
|
* @param texture Textura de backbuffer a la que aplicar shaders
|
||||||
|
* @param vertex_source Código fuente del vertex shader
|
||||||
|
* @param fragment_source Código fuente del fragment shader
|
||||||
|
* @return true si la inicialización fue exitosa
|
||||||
|
*/
|
||||||
|
virtual bool init(SDL_Window* window,
|
||||||
|
SDL_Texture* texture,
|
||||||
|
const std::string& vertex_source,
|
||||||
|
const std::string& fragment_source) = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Renderiza la textura con los shaders aplicados
|
||||||
|
*/
|
||||||
|
virtual void render() = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Establece el tamaño de la textura como parámetro del shader
|
||||||
|
* @param width Ancho de la textura
|
||||||
|
* @param height Alto de la textura
|
||||||
|
*/
|
||||||
|
virtual void setTextureSize(float width, float height) = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Limpia y libera recursos del backend
|
||||||
|
*/
|
||||||
|
virtual void cleanup() = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Verifica si el backend está usando aceleración por hardware
|
||||||
|
* @return true si usa aceleración (OpenGL/Metal/Vulkan)
|
||||||
|
*/
|
||||||
|
virtual bool isHardwareAccelerated() const = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Rendering
|
||||||
@@ -8,9 +8,12 @@
|
|||||||
#include <memory> // Para allocator, shared_ptr, make_shared, __shared_ptr_access
|
#include <memory> // Para allocator, shared_ptr, make_shared, __shared_ptr_access
|
||||||
#include <string> // Para operator+, char_traits, to_string, string
|
#include <string> // Para operator+, char_traits, to_string, string
|
||||||
|
|
||||||
#include "asset.h" // Para Asset
|
#include "asset.h" // Para Asset
|
||||||
#include "external/jail_shader.h" // Para init, render
|
#include "mouse.h" // Para updateCursorVisibility
|
||||||
#include "mouse.h" // Para updateCursorVisibility
|
#include "rendering/opengl/opengl_shader.h" // Para OpenGLShader
|
||||||
|
#ifdef __APPLE__
|
||||||
|
// #include "rendering/metal/metal_shader.h" // Para MetalShader (TODO: descomentar cuando esté completo)
|
||||||
|
#endif
|
||||||
#include "options.h" // Para VideoOptions, video, WindowOptions, window
|
#include "options.h" // Para VideoOptions, video, WindowOptions, window
|
||||||
#include "param.h" // Para Param, param, ParamGame, ParamDebug
|
#include "param.h" // Para Param, param, ParamGame, ParamDebug
|
||||||
#include "text.h" // Para Text, Text::COLOR, Text::STROKE
|
#include "text.h" // Para Text, Text::COLOR, Text::STROKE
|
||||||
@@ -55,9 +58,12 @@ Screen::Screen()
|
|||||||
setDebugInfoEnabled(true);
|
setDebugInfoEnabled(true);
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// Inicializa los shaders
|
// Inicializa los shaders (solo en plataformas no-macOS por ahora)
|
||||||
|
#ifndef __APPLE__
|
||||||
loadShaders();
|
loadShaders();
|
||||||
shader::init(window_, game_canvas_, shader_source_);
|
shader_backend_ = std::make_unique<Rendering::OpenGLShader>();
|
||||||
|
shader_backend_->init(window_, game_canvas_, vertex_shader_source_, fragment_shader_source_);
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
@@ -97,8 +103,8 @@ void Screen::renderPresent() {
|
|||||||
SDL_SetRenderTarget(renderer_, nullptr);
|
SDL_SetRenderTarget(renderer_, nullptr);
|
||||||
clean();
|
clean();
|
||||||
|
|
||||||
if (Options::video.shaders) {
|
if (Options::video.shaders && shader_backend_) {
|
||||||
shader::render();
|
shader_backend_->render();
|
||||||
} else {
|
} else {
|
||||||
SDL_RenderTexture(renderer_, game_canvas_, nullptr, nullptr);
|
SDL_RenderTexture(renderer_, game_canvas_, nullptr, nullptr);
|
||||||
SDL_RenderPresent(renderer_);
|
SDL_RenderPresent(renderer_);
|
||||||
@@ -223,23 +229,40 @@ void Screen::renderInfo() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
// Carga el contenido del archivo GLSL
|
// Carga el contenido de los archivos GLSL
|
||||||
void Screen::loadShaders() {
|
void Screen::loadShaders() {
|
||||||
if (shader_source_.empty()) {
|
if (vertex_shader_source_.empty()) {
|
||||||
const std::string GLSL_FILE = "crtpi.glsl";
|
const std::string VERTEX_FILE = "crtpi_vertex.glsl";
|
||||||
auto data = Asset::get()->loadData(GLSL_FILE);
|
auto data = Asset::get()->loadData(VERTEX_FILE);
|
||||||
if (!data.empty()) {
|
if (!data.empty()) {
|
||||||
shader_source_ = std::string(data.begin(), data.end());
|
vertex_shader_source_ = std::string(data.begin(), data.end());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (fragment_shader_source_.empty()) {
|
||||||
|
const std::string FRAGMENT_FILE = "crtpi_fragment.glsl";
|
||||||
|
auto data = Asset::get()->loadData(FRAGMENT_FILE);
|
||||||
|
if (!data.empty()) {
|
||||||
|
fragment_shader_source_ = std::string(data.begin(), data.end());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inicializa los shaders
|
// Inicializa los shaders
|
||||||
void Screen::initShaders() {
|
void Screen::initShaders() {
|
||||||
|
#ifndef __APPLE__
|
||||||
if (Options::video.shaders) {
|
if (Options::video.shaders) {
|
||||||
loadShaders();
|
loadShaders();
|
||||||
shader::init(window_, game_canvas_, shader_source_);
|
if (!shader_backend_) {
|
||||||
|
shader_backend_ = std::make_unique<Rendering::OpenGLShader>();
|
||||||
|
}
|
||||||
|
shader_backend_->init(window_, game_canvas_, vertex_shader_source_, fragment_shader_source_);
|
||||||
}
|
}
|
||||||
|
#else
|
||||||
|
// En macOS, OpenGL está deprecated y rinde mal
|
||||||
|
// TODO: Implementar backend de Metal para shaders en macOS
|
||||||
|
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
|
"Shaders no disponibles en macOS (OpenGL deprecated). Usa Metal backend.");
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calcula el tamaño de la ventana
|
// Calcula el tamaño de la ventana
|
||||||
@@ -310,6 +333,10 @@ auto Screen::initSDLVideo() -> bool {
|
|||||||
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"Warning: Failed to set OpenGL hint!");
|
"Warning: Failed to set OpenGL hint!");
|
||||||
}
|
}
|
||||||
|
// Configurar contexto OpenGL 3.3 Core Profile
|
||||||
|
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
|
||||||
|
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
|
||||||
|
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// Crear ventana
|
// Crear ventana
|
||||||
|
|||||||
@@ -8,10 +8,15 @@
|
|||||||
#include "color.h" // Para Color
|
#include "color.h" // Para Color
|
||||||
#include "options.h" // Para VideoOptions, video
|
#include "options.h" // Para VideoOptions, video
|
||||||
|
|
||||||
|
// Forward declarations
|
||||||
class Notifier;
|
class Notifier;
|
||||||
class ServiceMenu;
|
class ServiceMenu;
|
||||||
class Text;
|
class Text;
|
||||||
|
|
||||||
|
namespace Rendering {
|
||||||
|
class ShaderBackend;
|
||||||
|
}
|
||||||
|
|
||||||
// --- Clase Screen: gestiona la ventana, el renderizador y los efectos visuales globales (singleton) ---
|
// --- Clase Screen: gestiona la ventana, el renderizador y los efectos visuales globales (singleton) ---
|
||||||
class Screen {
|
class Screen {
|
||||||
public:
|
public:
|
||||||
@@ -203,17 +208,19 @@ class Screen {
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
SDL_Window *window_; // Ventana de la aplicación
|
SDL_Window *window_; // Ventana de la aplicación
|
||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||||
SDL_Texture *game_canvas_; // Textura donde se dibuja todo antes de volcarse al renderizador
|
SDL_Texture *game_canvas_; // Textura donde se dibuja todo antes de volcarse al renderizador
|
||||||
ServiceMenu *service_menu_; // Objeto para mostrar el menú de servicio
|
ServiceMenu *service_menu_; // Objeto para mostrar el menú de servicio
|
||||||
Notifier *notifier_; // Objeto para mostrar las notificaciones por pantalla
|
Notifier *notifier_; // Objeto para mostrar las notificaciones por pantalla
|
||||||
std::shared_ptr<Text> text_; // Objeto para escribir texto en pantalla
|
std::shared_ptr<Text> text_; // Objeto para escribir texto en pantalla
|
||||||
|
std::unique_ptr<Rendering::ShaderBackend> shader_backend_; // Backend de shaders (OpenGL/Metal/Vulkan)
|
||||||
|
|
||||||
// --- Variables de estado ---
|
// --- Variables de estado ---
|
||||||
SDL_FRect src_rect_; // Coordenadas de origen para dibujar la textura del juego
|
SDL_FRect src_rect_; // Coordenadas de origen para dibujar la textura del juego
|
||||||
SDL_FRect dst_rect_; // Coordenadas destino para dibujar la textura del juego
|
SDL_FRect dst_rect_; // Coordenadas destino para dibujar la textura del juego
|
||||||
std::string shader_source_; // Almacena el contenido del archivo GLSL
|
std::string vertex_shader_source_; // Almacena el vertex shader
|
||||||
|
std::string fragment_shader_source_; // Almacena el fragment shader
|
||||||
FPS fps_; // Gestión de frames por segundo
|
FPS fps_; // Gestión de frames por segundo
|
||||||
FlashEffect flash_effect_; // Efecto de flash en pantalla
|
FlashEffect flash_effect_; // Efecto de flash en pantalla
|
||||||
ShakeEffect shake_effect_; // Efecto de agitar la pantalla
|
ShakeEffect shake_effect_; // Efecto de agitar la pantalla
|
||||||
|
|||||||
Reference in New Issue
Block a user