Sigo estudiando la manera de hacer juegos con la IA y con c++, aqui estoy trabajando las sombras y echo que la camara se adapte al personaje y le siga en todo momento, tambien se la puede alejar y acercar, teclas del manejo son -w-a-s-d-e y flechas del teclado del pc.
añado tambien el codigo en c++.
extern "C" {
int stat64(const char *path, void *buffer) { return 0; }
int stat6432(const char *path, void *buffer) { return 0; }
int stat64i32(const char *path, void *buffer) { return 0; }
int _stat64(const char *path, void *buffer) { return 0; }
}
#include "raylib.h"
#include "raymath.h"
#include "rlgl.h"
#include <math.h>
#include <stdio.h>
#include <string.h>
#ifndef PI
#define PI 3.14159265358979323846f
#endif
// Shader 1: Guarda la distancia lineal desde la luz fija en lo alto
static const char *vsProfundidad = R"(
#version 330
in vec3 vertexPosition;
uniform mat4 mvp;
uniform mat4 matModel;
out vec4 worldPosDepth;
void main()
{
worldPosDepth = matModel * vec4(vertexPosition, 1.0);
gl_Position = mvp * worldPosDepth;
}
)";
static const char *fsProfundidad = R"(
#version 330
in vec4 worldPosDepth;
uniform vec3 lightCamPos;
uniform float maxLightDist;
out vec4 finalColor;
void main()
{
float dist = length(worldPosDepth.xyz - lightCamPos) / max(maxLightDist, 0.001);
dist = clamp(dist, 0.0, 1.0);
finalColor = vec4(dist, dist, dist, 1.0);
}
)";
// Shader 2: Sol fijo del escenario + luz direccional + ambiente + niebla
static const char *vsSombras = R"(
#version 330
in vec3 vertexPosition;
in vec2 vertexTexCoord;
in vec3 vertexNormal;
in vec4 vertexColor;
uniform mat4 mvp;
uniform mat4 matModel;
uniform mat4 matNormal;
uniform mat4 lightVP;
out vec3 fragPosition;
out vec2 fragTexCoord;
out vec3 fragNormal;
out vec4 fragColor;
out vec4 fragLightSpacePos;
void main()
{
vec4 worldPos = matModel * vec4(vertexPosition, 1.0);
fragPosition = worldPos.xyz;
fragTexCoord = vertexTexCoord;
fragNormal = normalize(vec3(matNormal * vec4(vertexNormal, 1.0)));
fragColor = vertexColor;
fragLightSpacePos = lightVP * worldPos;
gl_Position = mvp * vec4(vertexPosition, 1.0);
}
)";
static const char *fsSombras = R"(
#version 330
in vec3 fragPosition;
in vec2 fragTexCoord;
in vec3 fragNormal;
in vec4 fragColor;
in vec4 fragLightSpacePos;
uniform sampler2D texture0;
uniform sampler2D shadowMap;
uniform vec4 colDiffuse;
uniform vec3 lightDir;
uniform vec3 lightColor;
uniform vec3 ambientColor;
uniform float fogDensity;
uniform vec3 fogColor;
uniform vec3 viewPos;
uniform vec3 lightCamPos;
uniform float maxLightDist;
uniform float shadowBias;
out vec4 finalColor;
float CalcularFactorSombra(vec4 lightSpacePos, vec3 normal, vec3 toLight)
{
vec3 projCoords = lightSpacePos.xyz / max(lightSpacePos.w, 0.0001);
projCoords = projCoords * 0.5 + 0.5;
if (projCoords.x < 0.0 || projCoords.x > 1.0 ||
projCoords.y < 0.0 || projCoords.y > 1.0) {
return 0.0;
}
float currentDepth = length(fragPosition - lightCamPos) / max(maxLightDist, 0.001);
if (currentDepth > 1.0) return 0.0;
float bias = max(shadowBias * (1.0 - dot(normal, toLight)), shadowBias * 0.25);
// Filtro PCF 5x5 para suavizar y difuminar el borde de las sombras del escenario
float shadow = 0.0;
vec2 texelSize = 1.0 / textureSize(shadowMap, 0);
for (int x = -2; x <= 2; x++) {
for (int y = -2; y <= 2; y++) {
float pcfDepth = texture(shadowMap, projCoords.xy + vec2(x, y) * texelSize * 1.35).r;
if (currentDepth - bias > pcfDepth) {
shadow += 1.0;
}
}
}
return shadow / 25.0;
}
void main()
{
vec4 texelColor = texture(texture0, fragTexCoord);
vec3 baseColor = texelColor.rgb * fragColor.rgb * colDiffuse.rgb;
vec3 normal = normalize(fragNormal);
vec3 toLight = normalize(-lightDir);
float diff = max(dot(normal, toLight), 0.0);
float sombra = CalcularFactorSombra(fragLightSpacePos, normal, toLight);
float luzDirectaFactor = diff * (1.0 - sombra * 0.68);
vec3 lighting = ambientColor + (lightColor * luzDirectaFactor);
vec3 litColor = baseColor * lighting;
if (fogDensity > 0.0) {
float dist = length(viewPos - fragPosition);
float fogFactor = 1.0 - exp(-pow(dist * fogDensity, 2.0));
fogFactor = clamp(fogFactor, 0.0, 1.0);
litColor = mix(litColor, fogColor, fogFactor);
}
float alpha = texelColor.a * fragColor.a * colDiffuse.a;
finalColor = vec4(litColor, alpha);
}
)";
static RenderTexture2D CargarMapaSombras(int ancho, int alto) {
RenderTexture2D target = { 0 };
target.id = rlLoadFramebuffer();
target.texture.width = ancho;
target.texture.height = alto;
if (target.id > 0) {
rlEnableFramebuffer(target.id);
target.texture.id = rlLoadTexture(NULL, ancho, alto, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, 1);
target.texture.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
target.texture.mipmaps = 1;
target.depth.id = rlLoadTextureDepth(ancho, alto, false);
target.depth.format = 19;
target.depth.mipmaps = 1;
rlFramebufferAttach(target.id, target.texture.id, RL_ATTACHMENT_COLOR_CHANNEL0, RL_ATTACHMENT_TEXTURE2D, 0);
rlFramebufferAttach(target.id, target.depth.id, RL_ATTACHMENT_DEPTH, RL_ATTACHMENT_RENDERBUFFER, 0);
if (rlFramebufferComplete(target.id)) {
TraceLog(LOG_INFO, "FBO [ID %i] de sombras creado correctamente (%ix%i)", target.id, ancho, alto);
}
rlDisableFramebuffer();
}
return target;
}
static void DescargarMapaSombras(RenderTexture2D target) {
if (target.id > 0) {
rlUnloadFramebuffer(target.id);
}
}
static void AplicarShaderModelo(Model *modelo, Shader shader) {
if (!modelo || modelo->materialCount <= 0) return;
for (int i = 0; i < modelo->materialCount; i++) {
modelo->materials[i].shader = shader;
}
}
// Dibuja un óvalo difuminado sobre el plano XZ (centro opaco, borde transparente)
static void DibujarOvaloSombra(float radioX, float radioZ, int segmentos, Color color) {
if (segmentos < 12) segmentos = 12;
rlBegin(RL_TRIANGLES);
for (int i = 0; i < segmentos; i++) {
float a1 = (2.0f * PI * i) / segmentos;
float a2 = (2.0f * PI * (i + 1)) / segmentos;
float x1 = cosf(a1) * radioX;
float z1 = sinf(a1) * radioZ;
float x2 = cosf(a2) * radioX;
float z2 = sinf(a2) * radioZ;
rlColor4ub(color.r, color.g, color.b, color.a);
rlVertex3f(0.0f, 0.0f, 0.0f);
rlColor4ub(color.r, color.g, color.b, 0);
rlVertex3f(x2, 0.0f, z2);
rlColor4ub(color.r, color.g, color.b, 0);
rlVertex3f(x1, 0.0f, z1);
}
rlEnd();
}
// Dibuja la sombra difuminada bajo los pies junto con los brazos animados en sombra
static void DibujarSombraCompuestaConBrazos(Vector3 posBase, float anguloGrados, float faseAnim, float amplitudBrazo, Color color) {
float balanceo = sinf(faseAnim) * amplitudBrazo;
rlPushMatrix();
rlTranslatef(posBase.x, posBase.y, posBase.z);
rlRotatef(anguloGrados, 0.0f, 1.0f, 0.0f);
DibujarOvaloSombra(0.78f, 1.15f, 36, color);
rlPushMatrix();
rlTranslatef(-0.75f, 0.0f, balanceo);
DibujarOvaloSombra(0.38f, 0.68f, 24, color);
rlPopMatrix();
rlPushMatrix();
rlTranslatef(0.75f, 0.0f, -balanceo);
DibujarOvaloSombra(0.38f, 0.68f, 24, color);
rlPopMatrix();
rlPopMatrix();
}
static float NormalizarAngulo180(float angulo) {
while (angulo > 180.0f) angulo -= 360.0f;
while (angulo < -180.0f) angulo += 360.0f;
return angulo;
}
int main() {
SetConfigFlags(FLAG_WINDOW_RESIZABLE);
const int ancho = 1000;
const int alto = 700;
InitWindow(ancho, alto, "Prueba Lobo 3D - Sombras Oscuras Difuminadas");
const int sombraRes = 2048;
RenderTexture2D mapaSombras = CargarMapaSombras(sombraRes, sombraRes);
Shader shaderProfundidad = LoadShaderFromMemory(vsProfundidad, fsProfundidad);
Shader shaderSombras = LoadShaderFromMemory(vsSombras, fsSombras);
int locLightCamPosDepth = GetShaderLocation(shaderProfundidad, "lightCamPos");
int locMaxLightDistDepth = GetShaderLocation(shaderProfundidad, "maxLightDist");
int locLightDir = GetShaderLocation(shaderSombras, "lightDir");
int locLightColor = GetShaderLocation(shaderSombras, "lightColor");
int locAmbientColor = GetShaderLocation(shaderSombras, "ambientColor");
int locFogDensity = GetShaderLocation(shaderSombras, "fogDensity");
int locFogColor = GetShaderLocation(shaderSombras, "fogColor");
int locViewPos = GetShaderLocation(shaderSombras, "viewPos");
int locLightCamPos = GetShaderLocation(shaderSombras, "lightCamPos");
int locMaxLightDist = GetShaderLocation(shaderSombras, "maxLightDist");
int locShadowBias = GetShaderLocation(shaderSombras, "shadowBias");
int locLightVP = GetShaderLocation(shaderSombras, "lightVP");
int locShadowMap = GetShaderLocation(shaderSombras, "shadowMap");
Vector3 dirLuz = Vector3Normalize((Vector3){ -0.35f, -0.88f, -0.32f });
Vector3 colorLuz = { 1.0f, 0.94f, 0.82f };
Vector3 colorAmbiente = { 0.30f, 0.32f, 0.40f };
float densidadNiebla = 0.018f;
Vector3 colorNiebla = { 0.72f, 0.76f, 0.82f };
float shadowBias = 0.0018f;
float maxLightDist = 90.0f;
Color colorSombraUnificada = { 24, 28, 36, 215 };
SetShaderValue(shaderProfundidad, locMaxLightDistDepth, &maxLightDist, SHADER_UNIFORM_FLOAT);
SetShaderValue(shaderSombras, locLightDir, &dirLuz, SHADER_UNIFORM_VEC3);
SetShaderValue(shaderSombras, locLightColor, &colorLuz, SHADER_UNIFORM_VEC3);
SetShaderValue(shaderSombras, locAmbientColor, &colorAmbiente, SHADER_UNIFORM_VEC3);
SetShaderValue(shaderSombras, locFogDensity, &densidadNiebla, SHADER_UNIFORM_FLOAT);
SetShaderValue(shaderSombras, locFogColor, &colorNiebla, SHADER_UNIFORM_VEC3);
SetShaderValue(shaderSombras, locMaxLightDist, &maxLightDist, SHADER_UNIFORM_FLOAT);
SetShaderValue(shaderSombras, locShadowBias, &shadowBias, SHADER_UNIFORM_FLOAT);
Camera3D camera = { 0 };
Vector3 offsetCamara = { 0.0f, 4.2f, 8.5f };
camera.up = (Vector3){ 0.0f, 1.0f, 0.0f };
camera.fovy = 45.0f;
camera.projection = CAMERA_PERSPECTIVE;
// Posición inicial del lobo.
// NOTA: Ponemos Y en -0.9f para compensar el centro del modelo de Blender y que pise el suelo.
Vector3 posicionLobo = { 0.0f, -0.9f, 2.0f };
float anguloRotacion = 180.0f;
float velocidadGiro = 140.0f;
float escalaLobo = 1.0f;
float velocidadTraslado = 4.0f;
float velocidadAnimacion = 1.0f;
float frameAnimacionCaminar = 0.0f;
float frameAnimacionCintura = 0.0f;
Model modeloLobo = LoadModel("loboescalado10.glb");
AplicarShaderModelo(&modeloLobo, shaderSombras);
int animsCount = 0;
ModelAnimation *animaciones = LoadModelAnimations("loboescalado10.glb", &animsCount);
int indiceAnimCintura = (animsCount > 1) ? 1 : 0;
Vector3 posicionEscenario = { 0.0f, 0.0f, 0.0f };
float escalaEscenario = 28.0f;
Model modeloEscenario = LoadModel("escenario arco..obj");
Texture2D texEscenario = LoadTexture("arcotextura.png");
for (int i = 0; i < modeloEscenario.materialCount; i++) {
modeloEscenario.materials[i].maps[MATERIAL_MAP_DIFFUSE].texture = texEscenario;
}
AplicarShaderModelo(&modeloEscenario, shaderSombras);
Mesh mallaSuelo = GenMeshPlane(20.0f, 20.0f, 1, 1);
Model modeloSuelo = LoadModelFromMesh(mallaSuelo);
Image imgSuelo = GenImageChecked(512, 512, 32, 32, LIGHTGRAY, DARKGRAY);
Texture2D texSuelo = LoadTextureFromImage(imgSuelo);
UnloadImage(imgSuelo);
modeloSuelo.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = texSuelo;
AplicarShaderModelo(&modeloSuelo, shaderSombras);
Vector3 posicionPared = { 0.0f, 1.0f, -3.0f };
Vector3 tamanoPared = { 5.0f, 2.0f, 0.6f };
Mesh mallaPared = GenMeshCube(tamanoPared.x, tamanoPared.y, tamanoPared.z);
Model modeloPared = LoadModelFromMesh(mallaPared);
Image imgPared = GenImageChecked(256, 256, 16, 16, RED, MAROON);
Texture2D texPared = LoadTextureFromImage(imgPared);
UnloadImage(imgPared);
modeloPared.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = texPared;
AplicarShaderModelo(&modeloPared, shaderSombras);
BoundingBox cajasColision[] = {
(BoundingBox){
(Vector3){ posicionPared.x - tamanoPared.x/2.0f, posicionPared.y - tamanoPared.y/2.0f, posicionPared.z - tamanoPared.z/2.0f },
(Vector3){ posicionPared.x + tamanoPared.x/2.0f, posicionPared.y + tamanoPared.y/2.0f, posicionPared.z + tamanoPared.z/2.0f }
},
(BoundingBox){
(Vector3){ -4.0f, -1.0f, -1.0f },
(Vector3){ -1.2f, 3.0f, 1.0f }
},
(BoundingBox){
(Vector3){ 1.2f, -1.0f, -1.0f },
(Vector3){ 4.0f, 3.0f, 1.0f }
}
};
const int numCajasColision = sizeof(cajasColision) / sizeof(cajasColision[0]);
Vector3 centroSolFijo = { 0.0f, 0.0f, 0.0f };
Vector3 posSolCam = Vector3Subtract(centroSolFijo, Vector3Scale(dirLuz, 40.0f));
Matrix lightView = MatrixLookAt(posSolCam, centroSolFijo, (Vector3){ 0.0f, 0.0f, -1.0f });
Matrix lightProj = MatrixOrtho(-22.0f, 22.0f, -22.0f, 22.0f, 1.0f, 90.0f);
Matrix lightVP = MatrixMultiply(lightView, lightProj);
SetShaderValue(shaderProfundidad, locLightCamPosDepth, &posSolCam, SHADER_UNIFORM_VEC3);
SetShaderValue(shaderSombras, locLightCamPos, &posSolCam, SHADER_UNIFORM_VEC3);
SetShaderValueMatrix(shaderSombras, locLightVP, lightVP);
SetTargetFPS(60);
while (!WindowShouldClose()) {
float deltaTime = GetFrameTime();
bool estaMoviendo = false;
bool reproduciendoCintura = false;
if (IsKeyDown(KEY_UP)) offsetCamara.y += 4.0f * deltaTime;
if (IsKeyDown(KEY_DOWN)) offsetCamara.y -= 4.0f * deltaTime;
if (IsKeyDown(KEY_LEFT)) offsetCamara.z -= 6.0f * deltaTime;
if (IsKeyDown(KEY_RIGHT)) offsetCamara.z += 6.0f * deltaTime;
if (offsetCamara.y < 1.0f) offsetCamara.y = 1.0f;
if (offsetCamara.y > 16.0f) offsetCamara.y = 16.0f;
if (offsetCamara.z < 2.5f) offsetCamara.z = 2.5f;
if (offsetCamara.z > 22.0f) offsetCamara.z = 22.0f;
Vector3 posicionAntigua = posicionLobo;
if (IsKeyDown(KEY_E)) {
reproduciendoCintura = true;
}
else {
if (IsKeyDown(KEY_A)) {
anguloRotacion = NormalizarAngulo180(anguloRotacion + velocidadGiro * deltaTime);
}
if (IsKeyDown(KEY_D)) {
anguloRotacion = NormalizarAngulo180(anguloRotacion - velocidadGiro * deltaTime);
}
float radFrente = anguloRotacion * DEG2RAD;
Vector3 dirFrente = { sinf(radFrente), 0.0f, cosf(radFrente) };
if (IsKeyDown(KEY_W)) {
posicionLobo.x += dirFrente.x * velocidadTraslado * deltaTime;
posicionLobo.z += dirFrente.z * velocidadTraslado * deltaTime;
estaMoviendo = true;
}
if (IsKeyDown(KEY_S)) {
posicionLobo.x -= dirFrente.x * velocidadTraslado * deltaTime;
posicionLobo.z -= dirFrente.z * velocidadTraslado * deltaTime;
estaMoviendo = true;
}
}
BoundingBox cajaLobo = {
(Vector3){ posicionLobo.x - 0.4f, posicionLobo.y, posicionLobo.z - 0.4f },
(Vector3){ posicionLobo.x + 0.4f, posicionLobo.y + 1.8f, posicionLobo.z + 0.4f }
};
for (int i = 0; i < numCajasColision; i++) {
if (CheckCollisionBoxes(cajaLobo, cajasColision[i])) {
posicionLobo = posicionAntigua;
break;
}
}
float radVista = anguloRotacion * DEG2RAD;
Vector3 dirVista = { sinf(radVista), 0.0f, cosf(radVista) };
camera.position = (Vector3){
posicionLobo.x - dirVista.x * offsetCamara.z,
posicionLobo.y + offsetCamara.y,
posicionLobo.z - dirVista.z * offsetCamara.z
};
camera.target = (Vector3){
posicionLobo.x + dirVista.x * 4.5f,
posicionLobo.y + 1.4f,
posicionLobo.z + dirVista.z * 4.5f
};
if (animsCount > 0) {
if (reproduciendoCintura) {
frameAnimacionCintura += 24.0f * velocidadAnimacion * deltaTime;
if (frameAnimacionCintura >= 60.0f) frameAnimacionCintura = 0.0f;
UpdateModelAnimation(modeloLobo, animaciones[indiceAnimCintura], (int)frameAnimacionCintura);
frameAnimacionCaminar = 0.0f;
}
else if (estaMoviendo) {
frameAnimacionCaminar += 24.0f * velocidadAnimacion * deltaTime;
if (frameAnimacionCaminar >= 60.0f) frameAnimacionCaminar = 0.0f;
UpdateModelAnimation(modeloLobo, animaciones[0], (int)frameAnimacionCaminar);
frameAnimacionCintura = 0.0f;
}
else {
frameAnimacionCaminar = 0.0f;
frameAnimacionCintura = 0.0f;
UpdateModelAnimation(modeloLobo, animaciones[0], 0);
}
}
// --- PASADA 1: PROFUNDIDAD DESDE EL SOL FIJO (ESCENARIO Y PARED) ---
BeginTextureMode(mapaSombras);
ClearBackground(WHITE);
rlSetMatrixProjection(lightProj);
rlSetMatrixModelview(lightView);
AplicarShaderModelo(&modeloEscenario, shaderProfundidad);
AplicarShaderModelo(&modeloPared, shaderProfundidad);
DrawModelEx(modeloEscenario, posicionEscenario, (Vector3){ 0.0f, 1.0f, 0.0f }, 0.0f,
(Vector3){ escalaEscenario, escalaEscenario, escalaEscenario }, WHITE);
DrawModel(modeloPared, posicionPared, 1.0f, WHITE);
EndTextureMode();
AplicarShaderModelo(&modeloEscenario, shaderSombras);
AplicarShaderModelo(&modeloPared, shaderSombras);
AplicarShaderModelo(&modeloLobo, shaderSombras);
SetShaderValue(shaderSombras, locViewPos, &camera.position, SHADER_UNIFORM_VEC3);
// --- PASADA 2: DIBUJO 3D PRINCIPAL ---
BeginDrawing();
ClearBackground((Color){ 184, 194, 209, 255 });
BeginMode3D(camera);
int slotSombra = 10;
rlActiveTextureSlot(slotSombra);
rlEnableTexture(mapaSombras.texture.id);
SetShaderValue(shaderSombras, locShadowMap, &slotSombra, SHADER_UNIFORM_INT);
DrawModel(modeloSuelo, (Vector3){ 0.0f, 0.0f, 0.0f }, 1.0f, WHITE);
DrawModelEx(modeloEscenario, posicionEscenario, (Vector3){ 0.0f, 1.0f, 0.0f }, 0.0f,
(Vector3){ escalaEscenario, escalaEscenario, escalaEscenario }, WHITE);
float faseActiva = 0.0f;
float amplitudActiva = 0.0f;
if (reproduciendoCintura) {
faseActiva = (frameAnimacionCintura / 60.0f) * 2.0f * PI;
amplitudActiva = 0.35f;
}
else if (estaMoviendo) {
faseActiva = (frameAnimacionCaminar / 60.0f) * 2.0f * PI;
amplitudActiva = 0.45f;
}
Vector3 posSombraPies = {
posicionLobo.x - dirLuz.x * 0.25f,
0.13f,
posicionLobo.z - dirLuz.z * 0.25f
};
DibujarSombraCompuestaConBrazos(posSombraPies, anguloRotacion, faseActiva, amplitudActiva, colorSombraUnificada);
DrawModel(modeloPared, posicionPared, 1.0f, WHITE);
DrawModelEx(modeloLobo, posicionLobo, (Vector3){ 0.0f, 1.0f, 0.0f }, anguloRotacion,
(Vector3){ escalaLobo, escalaLobo, escalaLobo }, WHITE);
for (int i = 0; i < numCajasColision; i++) DrawBoundingBox(cajasColision[i], LIME);
EndMode3D();
DrawText("W: Avanzar | S: Atras | A/D: Girar | [E]: Cintura | Flechas: Altura/Zoom", 20, 20, 16, DARKGRAY);
DrawText("Sol fijo + sombra oscura difuminada bajo los pies.", 20, 45, 14, RED);
const char *textoCoords = TextFormat("Posicion X: %.2f | Y: %.2f | Z: %.2f", posicionLobo.x, posicionLobo.y, posicionLobo.z);
int tamTexto = 24;
int anchoCaja = MeasureText(textoCoords, tamTexto) + 16;
DrawRectangle(14, 66, anchoCaja, tamTexto + 8, Fade(RAYWHITE, 0.85f));
DrawText(textoCoords, 22, 70, tamTexto, BLUE);
EndDrawing();
}
DescargarMapaSombras(mapaSombras);
UnloadShader(shaderSombras);
UnloadShader(shaderProfundidad);
UnloadTexture(texEscenario);
UnloadModel(modeloEscenario);
UnloadTexture(texSuelo);
UnloadModel(modeloSuelo);
UnloadTexture(texPared);
UnloadModel(modeloPared);
if (animsCount > 0) {
UnloadModelAnimations(animaciones, animsCount);
}
UnloadModel(modeloLobo);
CloseWindow();
return 0;
}
No hay comentarios:
Publicar un comentario