/* ((Triforce, 11-29) The Character page's stage: Link in 3D, drawn with WebGL2 from the player's own game files (the launcher sends the posed mesh and the textures: launcher/Core/GameFiles/LinkScene.cs). Studio light: a warm key with a soft shadow map, a cool fill, a gold rim and a sky/ground ambient; normal maps and AO; ACES tone mapping. The model turns, the lights stay. Drag turns him, the wheel zooms, a double click looks at the face and back. Colours: each colour map can carry a "tint" (a mask of where a part is, two parts a map at most, and the part's colour): that is the live preview while a colour is picked; the launcher then sends OOTRR's own recoloured map (exact) in its place. Char3D.create(canvas) -> { load(info, meshBuffer, fetchTex), setTint(texName, slots), setColorMap(texName, tex), clearColorMaps(), look(where), resize(), stop() } with tex = {w, h, data: Uint8Array RGBA}. */ 'use strict'; (function () { const VS = `#version 300 es layout(location=0) in vec3 aPos; layout(location=1) in vec3 aNrm; layout(location=2) in vec4 aTan; layout(location=3) in vec2 aUv; layout(location=4) in vec4 aCol; uniform mat4 uModel, uVP, uLightVP; out vec3 vPos; out vec3 vNrm; out vec4 vTan; out vec2 vUv; out vec4 vLight; out vec4 vCol; void main() { vec4 w = uModel * vec4(aPos, 1.0); vPos = w.xyz; vNrm = mat3(uModel) * aNrm; vTan = vec4(mat3(uModel) * aTan.xyz, aTan.w); vUv = aUv; vLight = uLightVP * w; vCol = aCol; gl_Position = uVP * w; }`; const FS = `#version 300 es precision highp float; in vec3 vPos; in vec3 vNrm; in vec4 vTan; in vec2 vUv; in vec4 vLight; in vec4 vCol; uniform int uDebug, uStrands; uniform sampler2D uAlb, uNrm, uAo, uLut, uGrey, uMask, uShadow, uNrm2, uEmc; uniform int uHasEmc; uniform int uHasAlb, uHasNrm, uHasAo, uHasLut, uHasNrm2, uKind, uAlphaMode, uTint; uniform vec4 uTintA, uTintB; /* rgb: the part's colour at its median texel (linear), a: that texel's luminance (0: not tinted) */ uniform vec2 uTintG; /* (11-30) each part's contrast: its texels scale as (y / a)^g, at most 3.6x the median (OOTRR flattens its top: 99% ~3.8x) */ uniform vec3 uEye; uniform float uExposure, uTile; out vec4 frag; float lum(vec3 c) { return dot(c, vec3(0.2126, 0.7152, 0.0722)); } vec3 aces(vec3 x) { const float a = 2.51, b = 0.03, c = 2.43, d = 0.59, e = 0.14; return clamp((x * (a * x + b)) / (x * (c * x + d) + e), 0.0, 1.0); } float shadowAt(vec3 n, vec3 l) { vec3 p = vLight.xyz / vLight.w * 0.5 + 0.5; if (p.x < 0.0 || p.x > 1.0 || p.y < 0.0 || p.y > 1.0 || p.z > 1.0) return 1.0; float bias = 0.0012 + 0.0025 * (1.0 - max(dot(n, l), 0.0)); vec2 texel = 1.0 / vec2(textureSize(uShadow, 0)); float s = 0.0; for (int y = -2; y <= 2; y++) for (int x = -2; x <= 2; x++) s += (p.z - bias <= texture(uShadow, p.xy + vec2(x, y) * texel * 1.2).r) ? 1.0 : 0.0; return s / 25.0; } void main() { vec4 alb = uHasAlb == 1 ? texture(uAlb, vUv) : vec4(0.6, 0.6, 0.6, 1.0); if (uHasLut == 1) { /* young Link's hair has no colour map: the game's own hair ramp (its warm half), varied a strand at a time by the vertex colour, darker where the strand mask says the strand turns under */ float g = texture(uGrey, vUv).r; vec3 c = texture(uLut, vec2(0.58 + 0.38 * clamp(vCol.r, 0.0, 1.0), 0.5)).rgb; c = mix(vec3(lum(c)), c, 0.78) * (0.72 + 0.28 * g) * mix(0.82, 1.0, clamp(vCol.g, 0.0, 1.0)); /* strands: fine stripes across the card (its u), each strand its own shade */ float su = vUv.x * float(uStrands); float id = floor(su), fr = fract(su); float h1 = fract(sin(id * 12.9898 + floor(vUv.y * 3.0) * 4.1) * 43758.5); float edge = smoothstep(0.0, 0.25, fr) * smoothstep(1.0, 0.75, fr); c *= mix(0.62, 1.08, h1) * mix(0.78, 1.0, edge); alb = vec4(c, 1.0); } if (uAlphaMode == 1 && alb.a < 0.45) discard; if (uAlphaMode == 3) { frag = vec4(0.06, 0.025, 0.02, alb.r * 0.5); return; } if (uKind == 5) { /* Navi's body: her light */ vec3 c = alb.rgb; float f = pow(1.0 - abs(dot(normalize(vNrm), normalize(uEye - vPos))), 2.0); frag = vec4(pow(aces(c * (1.6 + 2.2 * f)), vec3(1.0 / 2.2)), 1.0); return; } if (uKind == 6) { /* her wings: thin and lit, their own glow added */ vec3 e = uHasEmc == 1 ? texture(uEmc, vUv).rgb : vec3(0.0); vec3 c = alb.rgb * 0.55 + e * 1.8; frag = vec4(pow(aces(c), vec3(1.0 / 2.2)), clamp(alb.a * 0.7 + lum(e), 0.0, 1.0)); return; } if (uKind == 8) { vec3 c = alb.rgb; if (uAlphaMode == 1 && alb.a < 0.45) discard; frag = vec4(pow(aces(c * 1.4 + c * c * 0.8), vec3(1.0 / 2.2)), 1.0); return; } if (uKind == 7) { if (alb.a < 0.3) discard; frag = vec4(pow(aces(alb.rgb * 2.0), vec3(1.0 / 2.2)), 0.55); return; } if (uAlphaMode == 4) { frag = vec4(pow(clamp(alb.rgb * 1.4, 0.0, 1.0), vec3(1.0 / 2.2)), 0.0); return; } /* the eye's highlights: added */ vec3 base = alb.rgb; if (uTint == 1) { vec2 m = texture(uMask, vUv).rg; float y = lum(base); if (uTintA.a > 0.0 && m.r > 0.0) base = mix(base, uTintA.rgb * min(pow(clamp(y / uTintA.a, 0.0, 4.0), uTintG.x), 3.6), m.r); if (uTintB.a > 0.0 && m.g > 0.0) base = mix(base, uTintB.rgb * min(pow(clamp(y / uTintB.a, 0.0, 4.0), uTintG.y), 3.6), m.g); } if (uKind == 1) base *= vec3(1.0, 0.9, 0.82); /* skin: the game's skin shading warms it */ if (uKind == 3) base = mix(base, base * 1.35, 0.6); /* eyes: the game lights them from inside */ vec3 n = normalize(vNrm); if (!gl_FrontFacing) n = -n; if (uHasNrm == 1) { vec3 t = normalize(vTan.xyz - n * dot(n, vTan.xyz)); vec3 b = cross(n, t) * (vTan.w < 0.0 ? -1.0 : 1.0); vec2 xy = texture(uNrm, vUv).rg * 2.0 - 1.0; if (uHasNrm2 == 1) xy += (texture(uNrm2, vUv * uTile).rg * 2.0 - 1.0) * 0.6; vec3 tn = vec3(xy, sqrt(max(1.0 - dot(xy, xy), 0.0))); n = normalize(mat3(t, b, n) * tn); } float ao = uHasAo == 1 ? mix(1.0, texture(uAo, vUv).r, 0.85) : 1.0; vec3 v = normalize(uEye - vPos); /* lights: key (warm, upper left front, shadowed), fill (cool, right), rim (gold, behind) */ vec3 lk = normalize(vec3(-0.55, 0.72, 0.62)), lf = normalize(vec3(0.85, 0.25, 0.45)), lr = normalize(vec3(0.35, 0.55, -0.9)); vec3 ck = vec3(1.0, 0.9, 0.76) * 3.1, cf = vec3(0.46, 0.56, 0.8) * 0.8, cr = vec3(1.0, 0.78, 0.42) * 2.4; float rough = uKind == 1 ? 0.5 : uKind == 2 ? 0.42 : uKind == 3 ? 0.12 : uKind == 4 ? 0.3 : 0.82; float spec = uKind == 1 ? 0.35 : uKind == 2 ? 0.5 : uKind == 3 ? 1.0 : uKind == 4 ? 0.9 : 0.18; float sh = shadowAt(n, lk); float wrap = uKind == 1 ? 0.35 : 0.08; float dk = max((dot(n, lk) + wrap) / (1.0 + wrap), 0.0) * sh; float df = max((dot(n, lf) + wrap) / (1.0 + wrap), 0.0); float fres = pow(1.0 - max(dot(n, v), 0.0), 3.0); float dr = max(dot(n, lr), 0.0) * (0.35 + 0.65 * fres); float sp = pow(2.0, 12.0 * (1.0 - rough)); vec3 hk = normalize(lk + v), hr = normalize(lr + v); float sk = pow(max(dot(n, hk), 0.0), sp) * (sp + 8.0) / 25.0 * sh; float sr = pow(max(dot(n, hr), 0.0), sp) * (sp + 8.0) / 25.0; vec3 specCol = uKind == 4 ? base * 1.6 + 0.04 : vec3(0.04 + 0.08 * fres); vec3 sky = vec3(0.34, 0.36, 0.42), ground = vec3(0.22, 0.16, 0.1); vec3 amb = mix(ground, sky, n.y * 0.5 + 0.5) * 0.55; vec3 col = base * (amb * ao + ck * dk * ao + cf * df * ao + cr * dr * 0.55) + specCol * spec * (ck * sk + cr * sr * 0.6) * ao; if (uKind == 1) col += base * vec3(0.9, 0.25, 0.15) * 0.09 * (1.0 - dk); if (uKind == 3) col += base * 0.55; /* eyes: lit from within, never black in shadow */ if (uKind == 2) { vec3 tt = normalize(vTan.xyz); float th = dot(tt, hk), kk = sqrt(max(1.0 - th * th, 0.0)); float s1 = pow(kk, 90.0), s2 = pow(sqrt(max(1.0 - pow(dot(tt, normalize(hk + n * 0.12)), 2.0), 0.0)), 24.0); col += (ck * 0.05 * s1 + base * ck * 0.06 * s2) * sh * ao; } /* skin: a little warmth where the light turns */ col = aces(col * uExposure); frag = vec4(pow(col, vec3(1.0 / 2.2)), uAlphaMode == 2 ? alb.a : 1.0); }`; const SVS = `#version 300 es layout(location=0) in vec3 aPos; layout(location=3) in vec2 aUv; uniform mat4 uModel, uLightVP; out vec2 vUv; void main() { vUv = aUv; gl_Position = uLightVP * uModel * vec4(aPos, 1.0); }`; const SFS = `#version 300 es precision mediump float; in vec2 vUv; uniform sampler2D uAlb; uniform int uCut; out vec4 o; void main() { if (uCut == 1 && texture(uAlb, vUv).a < 0.45) discard; o = vec4(1.0); }`; /* the floor: a dark disc lit from above, with his shadow and a gold ring at its edge */ const GVS = `#version 300 es layout(location=0) in vec2 aXZ; uniform mat4 uVP, uLightVP; uniform float uR; out vec2 vXZ; out vec4 vLight; void main() { vXZ = aXZ; vec4 w = vec4(aXZ.x * uR, 0.0, aXZ.y * uR, 1.0); vLight = uLightVP * w; gl_Position = uVP * w; }`; const GFS = `#version 300 es precision highp float; in vec2 vXZ; in vec4 vLight; uniform sampler2D uShadow; out vec4 o; void main() { float r = length(vXZ); if (r > 1.0) discard; vec3 p = vLight.xyz / vLight.w * 0.5 + 0.5; float s = 0.0; vec2 texel = 1.0 / vec2(textureSize(uShadow, 0)); for (int y = -3; y <= 3; y++) for (int x = -3; x <= 3; x++) s += (p.z - 0.003 <= texture(uShadow, p.xy + vec2(x, y) * texel * 2.0).r) ? 1.0 : 0.0; s /= 49.0; float pool = smoothstep(1.0, 0.0, r); vec3 c = mix(vec3(0.02, 0.018, 0.014), vec3(0.2, 0.15, 0.08), pool * pool) * (0.35 + 0.65 * s); float ring = smoothstep(0.03, 0.0, abs(r - 0.93)) * 0.9 + smoothstep(0.012, 0.0, abs(r - 0.86)) * 0.4; c += vec3(0.88, 0.66, 0.24) * ring * 0.45; float a = smoothstep(1.0, 0.82, r) * (0.75 + 0.25 * pool); o = vec4(pow(c, vec3(1.0 / 2.2)) * a, a); }`; /* Navi's glow: a soft disc that faces the camera, added over everything */ const HVS = `#version 300 es layout(location=0) in vec2 aXZ; uniform mat4 uVP; uniform vec3 uAt, uRight, uUp; uniform float uR; out vec2 vQ; void main() { vQ = aXZ; gl_Position = uVP * vec4(uAt + (uRight * aXZ.x + uUp * aXZ.y) * uR, 1.0); }`; const HFS = `#version 300 es precision mediump float; in vec2 vQ; uniform vec3 uCol; out vec4 o; void main() { float r = length(vQ); if (r > 1.0) discard; float a = exp(-r * r * 5.0) * 0.85 + exp(-r * r * 40.0) * 0.6; o = vec4(uCol * a, 0.0); }`; const KIND = { cloth: 0, skin: 1, hair: 2, eye: 3, metal: 4, lash: 0, fur: 0, shade: 0, glint: 0, navi: 5, wing: 6, navifur: 7, fairy: 8 }; const SOFT = { lash: 1, shade: 1, glint: 1, wing: 1, navifur: 1 }; function compile(gl, vs, fs) { const p = gl.createProgram(); for (const [t, s] of [[gl.VERTEX_SHADER, vs], [gl.FRAGMENT_SHADER, fs]]) { const sh = gl.createShader(t); gl.shaderSource(sh, s); gl.compileShader(sh); if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(sh)); gl.attachShader(p, sh); } gl.linkProgram(p); if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p)); const u = {}; const n = gl.getProgramParameter(p, gl.ACTIVE_UNIFORMS); for (let i = 0; i < n; i++) { const a = gl.getActiveUniform(p, i); u[a.name] = gl.getUniformLocation(p, a.name); } return { p, u }; } /* column-major 4x4 helpers */ function mul(a, b) { const o = new Float32Array(16); for (let c = 0; c < 4; c++) for (let r = 0; r < 4; r++) { let s = 0; for (let k = 0; k < 4; k++) s += a[k * 4 + r] * b[c * 4 + k]; o[c * 4 + r] = s; } return o; } function persp(fov, asp, n, f) { const t = 1 / Math.tan(fov / 2), o = new Float32Array(16); o[0] = t / asp; o[5] = t; o[10] = (f + n) / (n - f); o[11] = -1; o[14] = 2 * f * n / (n - f); return o; } function ortho(l, r, b, t, n, f) { const o = new Float32Array(16); o[0] = 2 / (r - l); o[5] = 2 / (t - b); o[10] = -2 / (f - n); o[12] = -(r + l) / (r - l); o[13] = -(t + b) / (t - b); o[14] = -(f + n) / (f - n); o[15] = 1; return o; } function lookAt(e, c, up) { const z = norm([e[0] - c[0], e[1] - c[1], e[2] - c[2]]), x = norm(cross(up, z)), y = cross(z, x); return new Float32Array([x[0], y[0], z[0], 0, x[1], y[1], z[1], 0, x[2], y[2], z[2], 0, -dot(x, e), -dot(y, e), -dot(z, e), 1]); } function rotY(a) { const c = Math.cos(a), s = Math.sin(a); return new Float32Array([c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1]); } function norm(v) { const l = Math.hypot(v[0], v[1], v[2]) || 1; return [v[0] / l, v[1] / l, v[2] / l]; } function cross(a, b) { return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; } function dot(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } function create(canvas) { const gl = canvas.getContext('webgl2', { antialias: true, alpha: true, premultipliedAlpha: true, preserveDrawingBuffer: false }); if (!gl) return null; const aniso = gl.getExtension('EXT_texture_filter_anisotropic'); const main = compile(gl, VS, FS), shadow = compile(gl, SVS, SFS), floor = compile(gl, GVS, GFS), halo = compile(gl, HVS, HFS); const SHADOW = 2048; const shadowTex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, shadowTex); gl.texStorage2D(gl.TEXTURE_2D, 1, gl.DEPTH_COMPONENT24, SHADOW, SHADOW); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); const shadowFb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, shadowFb); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, shadowTex, 0); gl.bindFramebuffer(gl.FRAMEBUFFER, null); const floorBuf = gl.createBuffer(), floorVao = gl.createVertexArray(); gl.bindVertexArray(floorVao); gl.bindBuffer(gl.ARRAY_BUFFER, floorBuf); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW); gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0); gl.bindVertexArray(null); const white = tex1([255, 255, 255, 255]), flat = tex1([128, 128, 255, 255]); function tex1(c) { const t = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, t); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(c)); return t; } const S = { parts: [], vao: null, buf: [], tex: new Map(), color: new Map(), tints: new Map(), masks: new Map(), info: null, yaw: 0.35, yawTo: 0.35, pitch: 0.04, pitchTo: 0.04, dist: 0, distTo: 0, tgt: [0, 1, 0], tgtTo: [0, 1, 0], face: false, spin: false, idleAt: 0, dirty: true, raf: 0, gen: 0, ready: false, naviCol: [0.75, 0.88, 1.0] }; // ((11-30, the owner) no idle turn: Link turns only when dragged or with the arrows function upload(t, srgb, clamp) { const g = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, g); gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); gl.texImage2D(gl.TEXTURE_2D, 0, srgb ? gl.SRGB8_ALPHA8 : gl.RGBA8, t.w, t.h, 0, gl.RGBA, gl.UNSIGNED_BYTE, t.data); gl.generateMipmap(gl.TEXTURE_2D); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); const wrap = clamp ? gl.CLAMP_TO_EDGE : gl.REPEAT; gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap); if (aniso) gl.texParameterf(gl.TEXTURE_2D, aniso.TEXTURE_MAX_ANISOTROPY_EXT, 8); return g; } /* info: LinkScene's JSON; mesh: ArrayBuffer; fetchTex(name) -> Promise<{w,h,data}|null>. Resolves once every texture is in. */ async function load(info, mesh, fetchTex) { const gen = ++S.gen; S.ready = false; const vao = gl.createVertexArray(), vb = gl.createBuffer(), ib = gl.createBuffer(); gl.bindVertexArray(vao); gl.bindBuffer(gl.ARRAY_BUFFER, vb); gl.bufferData(gl.ARRAY_BUFFER, mesh, gl.STATIC_DRAW); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ib); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, mesh, gl.STATIC_DRAW); gl.bindVertexArray(null); const want = new Set(); for (const p of info.parts) for (const k of ['alb', 'nrm', 'nrm2', 'ao', 'lut', 'grey', 'emc']) if (p[k] && !S.tex.has(p[k])) want.add(p[k]); await Promise.all([...want].map(async n => { const t = await fetchTex(n).catch(() => null); if (gen !== S.gen) return; const srgb = info.parts.some(p => p.alb === n || p.lut === n || p.emc === n); S.tex.set(n, t ? upload(t, srgb, n.startsWith('eye:') || info.parts.some(p => p.lut === n)) : null); })); if (gen !== S.gen) { gl.deleteVertexArray(vao); gl.deleteBuffer(vb); gl.deleteBuffer(ib); return; } if (S.vao) { gl.deleteVertexArray(S.vao); S.buf.forEach(b => gl.deleteBuffer(b)); } S.vao = vao; S.buf = [vb, ib]; S.info = info; S.parts = info.parts.filter(p => !(SOFT[p.kind] && !p.alb) && !(p.alb && !S.tex.get(p.alb) && !p.lut)); const h = info.max[1] - info.min[1]; S.height = h; const fit = body(); S.tgtTo = fit.tgt.slice(); S.distTo = fit.dist; if (!S.dist) { S.tgt = fit.tgt.slice(); S.dist = fit.dist * 1.25; } S.face = false; S.ready = true; S.dirty = true; if (!S.raf) S.raf = requestAnimationFrame(frame); } function body() { const h = S.height || 1.2; return { tgt: [0, h * 0.47, 0], dist: h * 2.75 }; } function headView() { const h = S.height || 1.2; return { tgt: [0, h * 0.84, 0], dist: h * 1.2 }; } function look(where) { const v = where === 'face' ? headView() : body(); S.face = where === 'face'; S.tgtTo = v.tgt; S.distTo = v.dist; S.dirty = true; if (S.face) { S.yawTo = Math.round(S.yawTo / (2 * Math.PI)) * 2 * Math.PI + 0.25; S.pitchTo = 0.02; } } function draw(proj, view, eye, light) { const W = canvas.width, H = canvas.height; const model = rotY(S.yaw); /* shadow pass */ gl.bindFramebuffer(gl.FRAMEBUFFER, shadowFb); gl.viewport(0, 0, SHADOW, SHADOW); gl.clear(gl.DEPTH_BUFFER_BIT); gl.enable(gl.DEPTH_TEST); gl.disable(gl.CULL_FACE); gl.disable(gl.BLEND); gl.colorMask(false, false, false, false); gl.useProgram(shadow.p); gl.uniformMatrix4fv(shadow.u.uModel, false, model); gl.uniformMatrix4fv(shadow.u.uLightVP, false, light); gl.bindVertexArray(S.vao); bindAttrs(); gl.activeTexture(gl.TEXTURE0); gl.uniform1i(shadow.u.uAlb, 0); for (const p of S.parts) { if (SOFT[p.kind] || p.kind === 'eye' || p.kind === 'navi') continue; const cut = cutOf(p); gl.uniform1i(shadow.u.uCut, cut === 1 ? 1 : 0); ptrs(p); gl.bindTexture(gl.TEXTURE_2D, (p.alb && S.tex.get(p.alb)) || white); gl.drawElements(gl.TRIANGLES, p.icount, gl.UNSIGNED_INT, p.ioff); } gl.colorMask(true, true, true, true); gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.viewport(0, 0, W, H); gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); const vp = mul(proj, view); /* floor */ gl.useProgram(floor.p); gl.uniformMatrix4fv(floor.u.uVP, false, vp); gl.uniformMatrix4fv(floor.u.uLightVP, false, light); gl.uniform1f(floor.u.uR, S.height * 0.46); gl.activeTexture(gl.TEXTURE7); gl.bindTexture(gl.TEXTURE_2D, shadowTex); gl.uniform1i(floor.u.uShadow, 7); gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.depthMask(false); gl.bindVertexArray(floorVao); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); gl.depthMask(true); gl.disable(gl.BLEND); /* Link */ gl.useProgram(main.p); gl.uniformMatrix4fv(main.u.uModel, false, model); gl.uniformMatrix4fv(main.u.uVP, false, vp); gl.uniformMatrix4fv(main.u.uLightVP, false, light); gl.uniform3fv(main.u.uEye, eye); gl.uniform1f(main.u.uExposure, 0.86); gl.uniform1i(main.u.uAlb, 0); gl.uniform1i(main.u.uNrm, 1); gl.uniform1i(main.u.uAo, 2); gl.uniform1i(main.u.uLut, 3); gl.uniform1i(main.u.uGrey, 4); gl.uniform1i(main.u.uMask, 5); gl.uniform1i(main.u.uNrm2, 6); gl.uniform1i(main.u.uShadow, 7); gl.uniform1i(main.u.uEmc, 8); gl.bindVertexArray(S.vao); const opaque = S.parts.filter(p => !SOFT[p.kind]), soft = S.parts.filter(p => SOFT[p.kind]); for (const p of opaque) drawPart(p); gl.enable(gl.BLEND); gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.depthMask(false); for (const p of soft) { if (p.kind === 'glint') gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ZERO, gl.ONE); drawPart(p); if (p.kind === 'glint') gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); } gl.depthMask(true); gl.disable(gl.BLEND); /* Navi's glow */ const at = S.info && S.info.navi; if (at) { const c = Math.cos(S.yaw), s = Math.sin(S.yaw); const w = [c * at[0] + s * at[2], at[1], -s * at[0] + c * at[2]]; const right = [view[0], view[4], view[8]], upv = [view[1], view[5], view[9]]; gl.useProgram(halo.p); gl.uniformMatrix4fv(halo.u.uVP, false, vp); gl.uniform3fv(halo.u.uAt, w); gl.uniform3fv(halo.u.uRight, right); gl.uniform3fv(halo.u.uUp, upv); gl.uniform1f(halo.u.uR, S.height * 0.16); gl.uniform3fv(halo.u.uCol, S.naviCol); /* (depth-tested: when she flies behind him, his head hides her glow) */ gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE); gl.depthMask(false); gl.bindVertexArray(floorVao); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); gl.depthMask(true); gl.disable(gl.BLEND); } } function cutOf(p) { return p.kind === 'fairy' ? 1 : p.kind === 'glint' ? 4 : p.kind === 'shade' ? 3 : p.kind === 'lash' ? 2 : (p.kind === 'hair' || p.kind === 'fur' || /Alpha|Mask|Feather|Band/.test(p.mat)) ? 1 : 0; } function bindAttrs() { gl.bindBuffer(gl.ARRAY_BUFFER, S.buf[0]); for (let i = 0; i < 5; i++) gl.enableVertexAttribArray(i); } function ptrs(p) { const stride = 64; gl.bindBuffer(gl.ARRAY_BUFFER, S.buf[0]); gl.vertexAttribPointer(0, 3, gl.FLOAT, false, stride, p.voff); gl.vertexAttribPointer(1, 3, gl.FLOAT, false, stride, p.voff + 12); gl.vertexAttribPointer(2, 4, gl.FLOAT, false, stride, p.voff + 24); gl.vertexAttribPointer(3, 2, gl.FLOAT, false, stride, p.voff + 40); gl.vertexAttribPointer(4, 4, gl.FLOAT, false, stride, p.voff + 48); } function drawPart(p) { ptrs(p); const albName = p.alb; const colorMap = albName && S.color.get(albName); const t = (n) => (n && S.tex.get(n)) || null; const alb = colorMap || t(albName); bindTex(0, alb || white); gl.uniform1i(main.u.uHasAlb, alb ? 1 : 0); bindTex(1, t(p.nrm) || flat); gl.uniform1i(main.u.uHasNrm, t(p.nrm) ? 1 : 0); bindTex(2, t(p.ao) || white); gl.uniform1i(main.u.uHasAo, t(p.ao) ? 1 : 0); const lut = !alb && t(p.lut) && t(p.grey); bindTex(3, lut ? t(p.lut) : white); bindTex(4, lut ? t(p.grey) : white); gl.uniform1i(main.u.uHasLut, lut ? 1 : 0); bindTex(8, t(p.emc) || white); gl.uniform1i(main.u.uHasEmc, t(p.emc) ? 1 : 0); bindTex(6, t(p.nrm2) || flat); gl.uniform1i(main.u.uHasNrm2, t(p.nrm2) ? 1 : 0); gl.uniform1f(main.u.uTile, 1.0); const tint = albName && S.tints.get(albName); if (tint && S.masks.get(albName)) { bindTex(5, S.masks.get(albName)); gl.uniform1i(main.u.uTint, 1); gl.uniform4fv(main.u.uTintA, tint[0] ? tint[0].slice(0, 4) : [0, 0, 0, 0]); gl.uniform4fv(main.u.uTintB, tint[1] ? tint[1].slice(0, 4) : [0, 0, 0, 0]); gl.uniform2f(main.u.uTintG, tint[0] && tint[0][4] || 1, tint[1] && tint[1][4] || 1); // ((11-30) each slot's contrast } else { bindTex(5, white); gl.uniform1i(main.u.uTint, 0); } gl.uniform1i(main.u.uKind, KIND[p.kind] || 0); gl.uniform1i(main.u.uDebug, window.charDebug || 0); gl.uniform1i(main.u.uStrands, window.charStrands || 80); gl.uniform1i(main.u.uAlphaMode, cutOf(p)); if (p.kind === 'hair') gl.enable(gl.SAMPLE_ALPHA_TO_COVERAGE); gl.drawElements(gl.TRIANGLES, p.icount, gl.UNSIGNED_INT, p.ioff); if (p.kind === 'hair') gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE); } function bindTex(unit, t) { gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(gl.TEXTURE_2D, t); } let last = 0; function frame(now) { S.raf = requestAnimationFrame(frame); const dt = Math.min(0.05, (now - (last || now)) / 1000); last = now; if (!S.ready) return; if (S.spin && !S.drag && !S.face && now - S.idleAt > 2500) { S.yawTo += dt * 0.32; } const k = 1 - Math.pow(0.0008, dt); const moved = Math.abs(S.yawTo - S.yaw) + Math.abs(S.pitchTo - S.pitch) + Math.abs(S.distTo - S.dist) + Math.abs(S.tgtTo[1] - S.tgt[1]); if (moved < 1e-5 && !S.dirty) return; S.yaw += (S.yawTo - S.yaw) * k; S.pitch += (S.pitchTo - S.pitch) * k; S.dist += (S.distTo - S.dist) * k; for (let i = 0; i < 3; i++) S.tgt[i] += (S.tgtTo[i] - S.tgt[i]) * k; S.dirty = false; const W = canvas.width, H = canvas.height; const eye = [S.tgt[0], S.tgt[1] + Math.sin(S.pitch) * S.dist, S.tgt[2] + Math.cos(S.pitch) * S.dist]; const proj = persp(26 * Math.PI / 180, W / H, 0.05, 20); const view = lookAt(eye, S.tgt, [0, 1, 0]); const h = S.height; const lightDir = norm([-0.55, 0.72, 0.62]); const lc = [lightDir[0] * 4, h * 0.5 + lightDir[1] * 4, lightDir[2] * 4]; const light = mul(ortho(-h * 0.75, h * 0.75, -h * 0.75, h * 0.75, 0.5, 9), lookAt(lc, [0, h * 0.5, 0], [0, 1, 0])); draw(proj, view, eye, light); } /* input: drag turns him (and tilts the view a little), the wheel zooms, a double click looks at his face and back */ canvas.addEventListener('pointerdown', e => { S.drag = { x: e.clientX, y: e.clientY }; S.idleAt = performance.now(); canvas.setPointerCapture(e.pointerId); canvas.classList.add('grab'); }); canvas.addEventListener('pointermove', e => { if (!S.drag) return; S.yawTo += (e.clientX - S.drag.x) * 0.011; S.pitchTo = Math.max(-0.25, Math.min(0.55, S.pitchTo + (e.clientY - S.drag.y) * 0.004)); S.drag = { x: e.clientX, y: e.clientY }; S.idleAt = performance.now(); S.dirty = true; }); const up = () => { S.drag = null; S.idleAt = performance.now(); canvas.classList.remove('grab'); }; canvas.addEventListener('pointerup', up); canvas.addEventListener('pointercancel', up); canvas.addEventListener('wheel', e => { e.preventDefault(); const b = body(), f = headView(); S.distTo = Math.max(f.dist * 0.8, Math.min(b.dist * 1.3, S.distTo * (e.deltaY > 0 ? 1.12 : 0.89))); /* (closer: the view slides up toward the face) */ const t = Math.max(0, Math.min(1, (b.dist - S.distTo) / (b.dist - f.dist))); S.tgtTo = [0, b.tgt[1] + (f.tgt[1] - b.tgt[1]) * t, 0]; S.face = t > 0.6; S.idleAt = performance.now(); S.dirty = true; }, { passive: false }); canvas.addEventListener('dblclick', () => look(S.face ? 'body' : 'face')); function resize() { const r = canvas.getBoundingClientRect(), d = Math.min(2, window.devicePixelRatio || 1); const w = Math.max(1, Math.round(r.width * d)), h = Math.max(1, Math.round(r.height * d)); if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; S.dirty = true; } } resize(); return { load, look, resize, turn(by) { S.yawTo += by; S.idleAt = performance.now(); S.dirty = true; }, spin(on) { S.spin = on; }, /* a part's live colour: slots [[r,g,b,yref,contrast] | null, ...] in linear light, or null to stop */ /* Navi's glow colour (#rrggbb), null for her own */ setNaviColor(hex) { const c = hex ? [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16) / 255) : [0.75, 0.88, 1.0]; S.naviCol = c.map(x => Math.max(0.12, x)); S.dirty = true; }, setTint(name, slots) { if (slots) S.tints.set(name, slots); else S.tints.delete(name); S.dirty = true; }, setMask(name, t) { const old = S.masks.get(name); if (old) gl.deleteTexture(old); if (t) S.masks.set(name, upload(t, false, false)); else S.masks.delete(name); S.dirty = true; }, setColorMap(name, t) { const old = S.color.get(name); if (old) gl.deleteTexture(old); if (t) S.color.set(name, upload(t, true, false)); else S.color.delete(name); S.dirty = true; }, /* every texture let go (another hero's files carry the same names) */ clearTextures() { for (const g of S.tex.values()) if (g) gl.deleteTexture(g); S.tex.clear(); for (const g of S.color.values()) gl.deleteTexture(g); S.color.clear(); for (const g of S.masks.values()) gl.deleteTexture(g); S.masks.clear(); S.tints.clear(); S.ready = false; S.dirty = true; }, clearColorMaps() { for (const t of S.color.values()) gl.deleteTexture(t); S.color.clear(); S.tints.clear(); S.dirty = true; }, get ready() { return S.ready; }, stop() { cancelAnimationFrame(S.raf); S.raf = 0; }, start() { if (!S.raf) { S.dirty = true; S.raf = requestAnimationFrame(frame); } }, }; } window.Char3D = { create }; })();