gitflarePublicPartly agent-ready40
shadow-fight-web-version
No description yet.
- LicenseApache-2.0
- LanguageJavaScript
- Last landed
132be7cOct 23, 2026
Make the player visible with a procedural 3D humanoid
132be7c// Dependency-free WebGL renderer for the fight scene. Reads the engine state from// public/game/engine.mjs (createMatch/step) and draws lit, articulated fighters on a stage// with a perspective camera. All pose / camera math lives in public/pose.mjs (pure).//// Usage:// import { createRenderer } from './render3d.mjs';// const r = createRenderer(canvas, { stage }); // stage: optional plain data from stage.mjs// r.render(state, dtSeconds); // every frame// r.resize(width, height); // when the canvas size changes import { UNIT, multiply, translation, scaling, rotationY, computeCamera, targetPose, smoothPose, buildSkeleton, hexToRgb, PALETTES, clamp} from './pose.mjs';import { CONFIG } from './game/engine.mjs';import { humanoidParts, sphereMesh, resolveDt, keyLightDir, shadowDiscs } from './humanoid.mjs';import { clampToArena, frameCamera, drawOrder, rimColor, contrastColor } from './render-utils.mjs'; const VERT = `attribute vec3 aPos; attribute vec3 aNrm;uniform mat4 uProj, uView, uModel;varying vec3 vNrm; varying vec3 vWorld;void main(){ vec4 w = uModel * vec4(aPos,1.0); vWorld = w.xyz; vNrm = normalize(mat3(uModel) * aNrm); gl_Position = uProj * uView * w;}`; const FRAG = `precision mediump float;varying vec3 vNrm; varying vec3 vWorld;uniform vec3 uColor, uLightDir, uLightColor, uAmbient, uSkyColor, uEye, uFogColor;uniform vec3 uFillDir, uFillColor;uniform float uFog, uShininess;void main(){ vec3 n = normalize(vNrm); float diff = max(dot(n, uLightDir), 0.0); float hemi = 0.5 + 0.5 * n.y; vec3 v = normalize(uEye - vWorld); vec3 h = normalize(uLightDir + v); float spec = pow(max(dot(n, h), 0.0), 32.0) * uShininess; vec3 rim = uSkyColor * pow(1.0 - max(dot(n, v), 0.0), 3.0) * 0.35; float fill = max(dot(n, uFillDir), 0.0) * 0.5; vec3 col = uColor * (uAmbient * hemi + uLightColor * diff + uFillColor * fill) + uLightColor * spec + rim; float d = length(uEye - vWorld); float f = clamp(1.0 - exp(-d * d * uFog * 0.004), 0.0, 1.0); col = mix(col, uFogColor, f); col = col / (col + vec3(0.6)); // soft tone-map gl_FragColor = vec4(pow(col, vec3(0.85)), 1.0);}`; /** Unit cube (-0.5..0.5) with per-face normals, as interleaved [px,py,pz,nx,ny,nz]. */export function cubeMesh() { const faces = [ [[0, 0, 1], [[-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1]]], [[0, 0, -1], [[1, -1, -1], [-1, -1, -1], [-1, 1, -1], [1, 1, -1]]], [[0, 1, 0], [[-1, 1, 1], [1, 1, 1], [1, 1, -1], [-1, 1, -1]]], [[0, -1, 0], [[-1, -1, -1], [1, -1, -1], [1, -1, 1], [-1, -1, 1]]], [[1, 0, 0], [[1, -1, 1], [1, -1, -1], [1, 1, -1], [1, 1, 1]]], [[-1, 0, 0], [[-1, -1, -1], [-1, -1, 1], [-1, 1, 1], [-1, 1, -1]]] ]; const verts = [], idx = []; for (const [n, q] of faces) { const base = verts.length / 6; for (const p of q) verts.push(p[0] * 0.5, p[1] * 0.5, p[2] * 0.5, n[0], n[1], n[2]); idx.push(base, base + 1, base + 2, base, base + 2, base + 3); } return { vertices: new Float32Array(verts), indices: new Uint16Array(idx) };} function compile(gl, type, src) { const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s); if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error('shader: ' + gl.getShaderInfoLog(s)); return s;} /** Build the default stage boxes for a level when no stage data is supplied. */export function defaultStage(level) { const theme = (level && level.theme) || {}; const w = (((level && level.arena) || {}).width || 960) * UNIT; const ground = hexToRgb(theme.ground, [0.2, 0.18, 0.28]); const sky = hexToRgb(theme.sky, [0.1, 0.12, 0.23]); const accent = hexToRgb(theme.accent, [0.96, 0.78, 0.4]); const boxes = [ { name: 'floor', position: [w / 2, -0.1, 0], size: [w + 6, 0.2, 8], color: ground }, { name: 'backwall', position: [w / 2, 2.2, -3.6], size: [w + 6, 4.4, 0.3], color: sky.map((c) => c * 0.8 + 0.05) }, { name: 'ledge', position: [w / 2, 0.02, -2.9], size: [w + 6, 0.04, 1.2], color: accent.map((c) => c * 0.5) } ]; const pillars = 5; for (let i = 0; i < pillars; i++) { const x = -1 + (w + 2) * (i / (pillars - 1)); boxes.push({ name: 'pillar' + i, position: [x, 1.9, -3.2], size: [0.35, 3.8, 0.35], color: ground.map((c) => c * 0.9 + 0.08) }); boxes.push({ name: 'lantern' + i, position: [x, 2.6, -2.9], size: [0.16, 0.26, 0.16], color: accent, emissive: 1 }); } return { boxes, sky, fog: theme.fog ?? 0.25, lightDir: [0.35, 0.8, 0.5], lightColor: [1.0, 0.92, 0.8], ambient: [0.35, 0.37, 0.45] };} /** Accepts stage data (from stage.mjs or defaultStage) in a few plausible shapes and normalises it. */export function normalizeStage(stage, level) { const d = defaultStage(level); if (!stage || typeof stage !== 'object') return d; const boxes = []; const push = (o, name) => { if (!o || typeof o !== 'object') return; const position = o.position || o.pos || o.center || [o.x ?? 0, o.y ?? 0, o.z ?? 0]; const size = o.size || o.scale || [o.w ?? o.width ?? 1, o.h ?? o.height ?? 1, o.d ?? o.depth ?? 1]; const color = Array.isArray(o.color) ? o.color : hexToRgb(o.color, [0.5, 0.5, 0.5]); boxes.push({ name: o.name || name, position, size, color, emissive: o.emissive ? 1 : 0 }); }; const list = stage.boxes || stage.geometry || stage.objects || stage.meshes; if (Array.isArray(list)) list.forEach((o, i) => push(o, 'box' + i)); else { push(stage.floor, 'floor'); push(stage.backWall || stage.wall, 'backwall'); if (Array.isArray(stage.pillars)) stage.pillars.forEach((p, i) => push(p, 'pillar' + i)); } const lights = Array.isArray(stage.lights) ? stage.lights : []; const key = lights.find((l) => l.type === 'directional' || l.direction) || stage.light; const amb = lights.find((l) => l.type === 'ambient') || null; return { boxes: boxes.length ? boxes : d.boxes, sky: Array.isArray(stage.sky) ? stage.sky : hexToRgb(stage.sky, d.sky), fog: typeof stage.fog === 'number' ? stage.fog : d.fog, lightDir: (key && (key.direction || key.dir)) || d.lightDir, lightColor: (key && (Array.isArray(key.color) ? key.color : hexToRgb(key.color, d.lightColor))) || d.lightColor, ambient: (amb && (Array.isArray(amb.color) ? amb.color : hexToRgb(amb.color, d.ambient))) || stage.ambient || d.ambient };} /** * Create a renderer bound to a canvas. Returns { render(state, dt), resize(w, h), gl }. * Throws if WebGL is unavailable so the caller can fall back. */export function createRenderer(canvas, options = {}) { const gl = canvas.getContext('webgl', { antialias: true, alpha: false }) || canvas.getContext('experimental-webgl'); if (!gl) throw new Error('WebGL not supported'); const prog = gl.createProgram(); gl.attachShader(prog, compile(gl, gl.VERTEX_SHADER, VERT)); gl.attachShader(prog, compile(gl, gl.FRAGMENT_SHADER, FRAG)); gl.linkProgram(prog); if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) throw new Error('link: ' + gl.getProgramInfoLog(prog)); gl.useProgram(prog); const mesh = cubeMesh(); const vbo = gl.createBuffer(), ibo = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vbo); gl.bufferData(gl.ARRAY_BUFFER, mesh.vertices, gl.STATIC_DRAW); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, mesh.indices, gl.STATIC_DRAW); const sphere = sphereMesh(); const svbo = gl.createBuffer(), sibo = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, svbo); gl.bufferData(gl.ARRAY_BUFFER, sphere.vertices, gl.STATIC_DRAW); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, sibo); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, sphere.indices, gl.STATIC_DRAW); const aPos = gl.getAttribLocation(prog, 'aPos'), aNrm = gl.getAttribLocation(prog, 'aNrm'); gl.enableVertexAttribArray(aPos); gl.enableVertexAttribArray(aNrm); let bound = null; function bindMesh(which) { if (bound === which) return; bound = which; gl.bindBuffer(gl.ARRAY_BUFFER, which === 'sphere' ? svbo : vbo); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, which === 'sphere' ? sibo : ibo); gl.vertexAttribPointer(aPos, 3, gl.FLOAT, false, 24, 0); gl.vertexAttribPointer(aNrm, 3, gl.FLOAT, false, 24, 12); } bindMesh('cube'); const U = {}; for (const n of ['uProj', 'uView', 'uModel', 'uColor', 'uLightDir', 'uLightColor', 'uAmbient', 'uSkyColor', 'uEye', 'uFogColor', 'uFog', 'uShininess', 'uFillDir', 'uFillColor']) U[n] = gl.getUniformLocation(prog, n); gl.enable(gl.DEPTH_TEST); gl.enable(gl.CULL_FACE); gl.cullFace(gl.BACK); let width = canvas.width, height = canvas.height; let stage = null, stageLevelId = undefined; const poses = [null, null]; let clock = 0, shake = 0, lastTime = null; const lastEvents = new Set(); function drawBox(model, size, color, emissive = 0) { bindMesh('cube'); gl.uniformMatrix4fv(U.uModel, false, multiply(model, scaling(size[0], size[1], size[2]))); gl.uniform3fv(U.uColor, emissive ? color.map((c) => c * 2.5) : color); gl.uniform1f(U.uShininess, emissive ? 0 : 0.25); gl.drawElements(gl.TRIANGLES, mesh.indices.length, gl.UNSIGNED_SHORT, 0); } function drawBlob(model, size, color, shininess = 0.25) { bindMesh('sphere'); gl.uniformMatrix4fv(U.uModel, false, multiply(model, scaling(size[0], size[1], size[2]))); gl.uniform3fv(U.uColor, color); gl.uniform1f(U.uShininess, shininess); gl.drawElements(gl.TRIANGLES, sphere.indices.length, gl.UNSIGNED_SHORT, 0); } function resize(w, h) { width = w; height = h; if (canvas.width !== w) canvas.width = w; if (canvas.height !== h) canvas.height = h; } function render(state, dtOrOpts = 1 / 60) { if (!state) return; const step = resolveDt(dtOrOpts, lastTime); const dt = step.dt; lastTime = step.time; clock += dt; const levelId = state.level && state.level.id; if (!stage || stageLevelId !== levelId) { stage = normalizeStage(options.stage, state.level); stageLevelId = levelId; } for (const ev of state.events || []) if (ev.type === 'hit') shake = Math.min(1, shake + ev.damage / 20); shake *= Math.exp(-dt * 8); const arenaW = ((state.level && state.level.arena && state.level.arena.width) || 960) * UNIT; const fighters = (state.fighters || []).map((f) => ({ ...f, x: clampToArena(f.x * UNIT, arenaW) / UNIT })); const fr = frameCamera(fighters.map((f) => f.x * UNIT), width / height, Math.PI / 4, arenaW); const need = fr.distance * 1.1; const cam = computeCamera({ ...state, fighters }, width / height, { minDistance: Math.max(5.5, need), maxDistance: Math.max(10, need) }); const jitter = shake * 0.04; const view = multiply(cam.view, translation(Math.sin(clock * 71) * jitter, Math.cos(clock * 53) * jitter, 0)); gl.viewport(0, 0, width, height); const sky = stage.sky; gl.clearColor(sky[0] * 0.6, sky[1] * 0.6, sky[2] * 0.7, 1); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.uniformMatrix4fv(U.uProj, false, cam.projection); gl.uniformMatrix4fv(U.uView, false, view); const key = keyLightDir(stage.lightDir); gl.uniform3fv(U.uLightDir, key); gl.uniform3fv(U.uFillDir, keyLightDir([-key[0], 0.3, Math.abs(key[2]) + 0.6])); gl.uniform3fv(U.uFillColor, [0.45, 0.55, 0.75]); gl.uniform3fv(U.uLightColor, stage.lightColor); gl.uniform3fv(U.uAmbient, stage.ambient); gl.uniform3fv(U.uSkyColor, sky); gl.uniform3fv(U.uEye, cam.eye); gl.uniform3fv(U.uFogColor, [sky[0] * 0.6, sky[1] * 0.6, sky[2] * 0.7]); gl.uniform1f(U.uFog, clamp(stage.fog, 0, 1)); for (const item of drawOrder(stage.boxes.length, fighters.length, 0)) { if (item.kind === 'layer') { const b = stage.boxes[item.index]; drawBox(translation(b.position[0], b.position[1], b.position[2]), b.size, b.color, b.emissive); continue; } const i = item.index, f = fighters[i], isPlayer = i === 0; const target = targetPose(f, clock + i * 1.7, CONFIG.attacks); poses[i] = smoothPose(poses[i], target, dt, f.stance === 'hit' || f.stance === 'punch' || f.stance === 'kick' ? 30 : 14); const palette = PALETTES[i % PALETTES.length]; const h = f.y * UNIT, sh = clamp(1 - h * 0.35, 0.3, 1); for (const d of shadowDiscs(f.x * UNIT, h)) drawBlob(translation(d.position[0], d.position[1], d.position[2]), d.size, sky.map((c) => c * 0.25 * (1 - d.darkness * 0.9)), 0); const parts = humanoidParts(f, poses[i], palette); // Outline / rim pass: inverted hull (enlarged boxes, front faces culled). const rim = rimColor(sky, isPlayer).map((c) => c / 2.5); const grow = isPlayer ? 0.05 : 0.03; gl.cullFace(gl.FRONT); for (const part of parts) drawBlob(part.matrix, part.size.map((v) => v + grow), rim.map((c) => c * 2.5), 0); gl.cullFace(gl.BACK); const flash = f.stance === 'hit' ? 0.5 : 0; for (const part of parts) { const base = isPlayer ? contrastColor(part.color, sky) : part.color; drawBlob(part.matrix, part.size, flash ? base.map((c) => c + flash) : base, part.shininess); } } gl.flush(); } return { gl, render, resize, get stage() { return stage; } };}