Ejemplos avanzados para crear geometría 2D y 3D, incluyendo la implementación de texturas y iluminación, en dos entornos: WebGL (JavaScript) y OpenGL (Lenguaje C).
1. Creación de Geometría 2D y 3D con Texturas e Iluminación en WebGL
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebGL: Texturas e Iluminación</title>
<style>
canvas {
display: block;
margin: auto;
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="webglCanvas" width="600" height="400"></canvas>
<script>
const canvas = document.getElementById("webglCanvas");
const gl = canvas.getContext("webgl");
if (!gl) {
alert("WebGL no es compatible con tu navegador");
throw new Error("WebGL no inicializado");
}
// Vértices del cubo 3D con coordenadas de textura
const vertices = new Float32Array([
// Cara frontal (x, y, z, u, v)
-0.5, -0.5, 0.5, 0.0, 0.0, // Esquina inferior izquierda
0.5, -0.5, 0.5, 1.0, 0.0, // Esquina inferior derecha
0.5, 0.5, 0.5, 1.0, 1.0, // Esquina superior derecha
-0.5, 0.5, 0.5, 0.0, 1.0 // Esquina superior izquierda
// Agrega las otras caras...
]);
const indices = new Uint16Array([
0, 1, 2, 0, 2, 3 // Triángulos para la cara frontal
// Agrega índices para las otras caras...
]);
// Buffer de vértices
const vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
// Buffer de índices
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
// Cargar textura
const texture = gl.createTexture();
const image = new Image();
image.src = 'https://www.example.com/texture.jpg'; // URL de la textura
image.onload = () => {
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
gl.generateMipmap(gl.TEXTURE_2D);
};
// Shader de vértices
const vertexShaderSource = `
attribute vec3 position;
attribute vec2 texCoord;
varying vec2 vTexCoord;
void main(void) {
gl_Position = vec4(position, 1.0);
vTexCoord = texCoord;
}
`;
// Shader de fragmentos
const fragmentShaderSource = `
precision mediump float;
varying vec2 vTexCoord;
uniform sampler2D sampler;
void main(void) {
gl_FragColor = texture2D(sampler, vTexCoord);
}
`;
// Programa de shaders e inicialización
// Completa con lógica adicional para iluminación si lo necesitas.
</script>
</body>
</html>
Este ejemplo renderiza un cubo con una textura aplicada y puede extenderse para incluir iluminación Phong o Gouraud.
2. Geometría 3D con Texturas e Iluminación en OpenGL (Lenguaje C)
#include <GL/glut.h>
#include <SOIL/SOIL.h> // Biblioteca para cargar texturas
float angle = 0.0f;
GLuint texture;
void initGL() {
glEnable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
// Cargar textura
texture = SOIL_load_OGL_texture("texture.jpg", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y);
if (!texture) {
printf("Error cargando la textura\n");
}
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
GLfloat lightPos[] = {1.0f, 1.0f, 1.0f, 1.0f};
glLightfv(GL_LIGHT0, GL_POSITION, lightPos);
}
void drawCube() {
glBindTexture(GL_TEXTURE_2D, texture);
glBegin(GL_QUADS);
// Cara frontal
glTexCoord2f(0.0f, 0.0f); glVertex3f(-0.5f, -0.5f, 0.5f);
glTexCoord2f(1.0f, 0.0f); glVertex3f( 0.5f, -0.5f, 0.5f);
glTexCoord2f(1.0f, 1.0f); glVertex3f( 0.5f, 0.5f, 0.5f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-0.5f, 0.5f, 0.5f);
// Agrega las otras caras...
glEnd();
}
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glRotatef(angle, 1.0f, 1.0f, 0.0f);
drawCube();
glutSwapBuffers();
angle += 0.2f; // Incrementa el ángulo de rotación
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("Cubo con Texturas e Iluminación");
initGL();
glutDisplayFunc(display);
glutIdleFunc(display);
glutMainLoop();
return 0;
}
3. Notas Importantes
- Iluminación avanzada: Para simulaciones realistas, se pueden implementar shaders con iluminación Phong o modelos más complejos como PBR (Physically Based Rendering).
- Texturas: Puedes usar imágenes externas como texturas. Asegúrate de usar rutas o URLs válidas.
- Mejoras futuras: Puedes añadir modelos 3D más complejos (como importación de archivos
.obj) y trabajar con luces dinámicas.
-