Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

31.1 KB
Raw Blame
#pragma shader "Mesh"
#pragma version 300 es
// Lit domain for the LIGHTING it injects (LightConstants + applyLighting2D),
// not for its canonical vertex stage — that is only supplied to a shader which
// writes none, and this one writes its own to place local vertices by a model
// matrix. So the light math is shared with every 2D lit surface rather than
// copied, and the std140 block stays the engine's to own.
#pragma domain Lit

// What the GEOMETRY carries. A layout may not declare an attribute its shader
// does not consume, so the normal channel and the per-object normal matrix are
// inside this switch on both sides — whether or not the draw asks to be lit.
#pragma feature MESH_NORMALS

// What the DRAW asks for. Orthogonal to the above on purpose: geometry with
// normals can be drawn unlit, and geometry without them can still take light
// (off a constant normal, which is what a 2D surface has).
#pragma feature LIT

// Geometry deformed by joints. Its own transform is NOT read: a skinned mesh's
// node placement is ignored (glTF requires it) because the bones are already
// world-space, so the per-object record carries only a tint.
#pragma feature SKINNED

// A normal map on top of those normals. Its tangent frame comes from the shared
// perturbNormal (screen-space derivatives), so the geometry needs no tangent
// channel — which is why this rides LIT rather than a vertex attribute.
#pragma feature NORMAL_MAP

// Baked light: the second UV set a bake is laid out in, and the rectangle of the
// atlas THIS object occupies. A feature rather than a number in a block — unlike
// the morph weights below — because a vertex attribute a shader does not declare
// may not appear in the layout it is drawn through, which WebGPU rejects.
#pragma feature MESH_LIGHTMAP
// A tangent frame the geometry carries (xyz along +u, w the handedness of the bitangent), for a lit mesh with normals: the
// normal map is then read against the frame it was baked in rather than one derived per pixel from screen-space derivatives.
#pragma feature MESH_TANGENTS

// The shadow-map pass: the same geometry, from the light, writing depth as colour
// instead of shading. A feature and not a second shader, because what has to be
// identical between the two passes is the VERTEX stage — a skinned occluder must
// land where its skinned self lands, and one copy of that is one that cannot drift.
#pragma feature SHADOW_DEPTH

// A caster cut out by its alpha: the shadow program of a material whose alpha is coverage discards where the
// base texture is below the material's u_alphaCutoff, so a card of hair or a leaf casts its own shape and not
// the rectangle it is drawn on.
#pragma feature SHADOW_ALPHA

// The scene's depth prepass of a cut-out: the depth program writes the coverage the colour pass's fragment writes, by the same expression on the same
// inputs, so under alpha-to-coverage both draw the same samples and the colour pass lands on the depth this one left. With SHADOW_DEPTH.
#pragma feature PREPASS_COVERAGE

// A skinned surface coloured by how much ONE joint moves each vertex: the weight a rig is
// painted with, read off the surface instead of a table. The joint is the record's tint x
// (a diagnostic draw has no tint to carry), the colour goes out through the same varying the
// fragment already multiplies a white texture by — so the fragment stage is untouched, and
// the two twins differ only in the lines below that say it.
#pragma feature WEIGHT_HEAT

// GPU-resident geometry. Slot 0 is the mesh's own vertices, which are LOCAL
// space and are never rewritten; slot 1 is the per-object record the frame
// streams, so the same mesh drawn twice costs one more transform rather than
// one more copy of its vertices.

#pragma vertex
layout(location = 0) in vec3 a_position;
layout(location = 1) in vec4 a_color;
layout(location = 2) in vec2 a_texCoord;
#ifdef MESH_NORMALS
layout(location = 3) in vec3 a_normal;
#endif
#ifdef SKINNED
layout(location = 5) in uvec4 a_joints;
layout(location = 6) in vec4 a_weights;
#endif
#ifdef MESH_LIGHTMAP
layout(location = 7) in vec2 a_texCoord1;
#endif
#ifdef MESH_TANGENTS
layout(location = 4) in vec4 a_tangent;
#endif

// The per-object record comes from the frame's texture, not from attributes:
// esInstanceModel / esInstanceTint / esInstanceNormalMatrix /
// esInstanceLightmapRect are injected by the assembler for any vertex stage that
// names one, which is what leaves every slot above the mesh channels free.

#ifdef SKINNED
// This draw's pose, rewritten immediately before it (SkinConstants, binding 5).
layout(std140) uniform SkinConstants {
    mat4 u_bones[256];
};
#endif

// The shapes this draw is blended towards. Declared unconditionally and NOT as a
// feature: whether a draw has any is a number in the block, and making it a
// program instead would double this shader's variants and every material's with
// them — for a branch whose condition is the same at every vertex of a draw.
layout(std140) uniform MorphConstants {
    // x = live shapes, y = vertices, z = texels per vertex, w = texture width.
    vec4 u_morphInfo;
    vec4 u_morphShape[64];
};
// The deltas: one texel per (target, vertex), and a second behind it where the
// targets bend normals. A texture because they are megabytes, and a uniform
// block is not.
uniform highp sampler2D u_morphDeltas;

vec3 morphDelta(float index) {
    float width = u_morphInfo.w;
    return texelFetch(u_morphDeltas, ivec2(int(mod(index, width)), int(index / width)), 0).xyz;
}

// Before the pose, never after: a target was authored against the mesh at rest,
// so the offset it states is a local one.
void applyMorph(inout vec3 position, inout vec3 normal) {
    int live = int(u_morphInfo.x);
    float perVertex = u_morphInfo.z;
    for (int i = 0; i < 64; i++) {
        if (i >= live) break;
        float at = (u_morphShape[i].x * u_morphInfo.y + float(gl_VertexID)) * perVertex;
        position += u_morphShape[i].y * morphDelta(at);
        if (perVertex > 1.5) normal += u_morphShape[i].y * morphDelta(at + 1.0);
    }
}

// The same position from every program of this vertex stage: the depth prepass draws a surface with one and the colour pass lands on that depth
// with another, and a compiler may order the arithmetic of two programs differently unless it is told it may not.
invariant gl_Position;

out vec2 v_texCoord;
out vec4 v_color;
#ifdef MESH_LIGHTMAP
// xy = where in the atlas; z = whether this draw has a bake at all.
//
// The third component and not a fallback texture, because the two branches below
// want DIFFERENT values for "no bake": the lit one adds the bake and wants black,
// the unlit one multiplies by it and wants white. An unbound unit holds one
// colour, so it can be right for one of them and never for both — and the engine
// fills an unused unit with white, which is exactly the half that would be wrong.
out highp vec3 v_lightmap;
#endif
#ifdef LIT
out highp vec3 v_worldNormal;
// The full position, not just the plane's: a tangent frame is derived from how
// it changes across a fragment, which xy alone cannot say for a tilted surface.
out highp vec3 v_worldPos;
#ifdef MESH_TANGENTS
out highp vec4 v_worldTangent;
#endif
#endif
#ifdef SHADOW_DEPTH
// The clip position, and not the depth it divides down to. z/w is not affine across a
// triangle, so a stage that divides here hands the fragment an interpolation of the
// corners' quotients rather than the quotient at the fragment — off by more, the wider
// the depth range one triangle spans. An orthographic map never showed it (w is 1
// throughout), and a cube face looking along a floor is the case that does: the error
// there is worth several world units, which shadows the caster against itself.
out highp vec4 v_shadowClip;
#endif
#ifdef ES_VELOCITY
// Where this point is in the picture now and where it was one frame ago, as clip positions so the
// fragment divides them: z/w is not affine across a triangle, and neither is xy/w. BOTH carry the shift
// their own frame was drawn with: what the previous picture holds at a pixel is what stood at its
// SHIFTED place, so the difference is exactly where in that picture to read.
out highp vec4 v_velCur;
out highp vec4 v_velPrev;
#endif

// A material's own vertex offset, for the shadow program built from this source on its behalf: the
// caster has to bend where the lit surface does, or its shadow stands still. The assembler puts the
// material's hook where the marker is; without ES_MATERIAL_VERTEX none of it exists.
#ifdef ES_MATERIAL_VERTEX
// The vertex's own colour, for a hook that bends by a weight painted in it (see ShaderParser's canonical stage).
highp vec4 es_vertexColor;
// Its second uv, zero on a mesh with none.
highp vec2 es_vertexUv1;
@@ES_VERTEX_HOOK@@
#endif

#if defined(ES_VELOCITY) && defined(SKINNED)
// Last frame's pose of one bone, from the records behind this draw's own: three rows a bone, from texel 8.
highp mat4 esPrevBone(uint joint) {
    int at = 8 + int(joint) * 3;
    highp vec4 r0 = esInstanceTexel(at);
    highp vec4 r1 = esInstanceTexel(at + 1);
    highp vec4 r2 = esInstanceTexel(at + 2);
    return mat4(vec4(r0.x, r1.x, r2.x, 0.0), vec4(r0.y, r1.y, r2.y, 0.0),
                vec4(r0.z, r1.z, r2.z, 0.0), vec4(r0.w, r1.w, r2.w, 1.0));
}
#endif

void main() {
    vec3 local = a_position;
#ifdef MESH_NORMALS
    vec3 localNormal = a_normal;
#else
    vec3 localNormal = vec3(0.0, 0.0, 1.0);
#endif
    applyMorph(local, localNormal);
#ifdef ES_MATERIAL_VERTEX
    es_vertexColor = a_color;
#ifdef MESH_LIGHTMAP
    es_vertexUv1 = a_texCoord1;
#else
    es_vertexUv1 = vec2(0.0);
#endif
    esMaterialVertex(local, localNormal, a_texCoord);
#endif
#ifdef SKINNED
    // The four bones this vertex is bound to, blended by their weights. The
    // result is world-space, so no model matrix follows it.
    mat4 skin = a_weights.x * u_bones[a_joints.x]
              + a_weights.y * u_bones[a_joints.y]
              + a_weights.z * u_bones[a_joints.z]
              + a_weights.w * u_bones[a_joints.w];
    vec4 world = skin * vec4(local, 1.0);
#else
    mat4 model = esInstanceModel();
    vec4 world = model * vec4(local, 1.0);
#endif
    gl_Position = u_projection * world;
    v_texCoord = a_texCoord;
    // A material's hook may leave a colour of its own for the fragment (a terrain tells it where in its pages the vertex lies).
#ifdef ES_MATERIAL_VERTEX
    v_color = es_vertexColor * esInstanceTint();
#else
    v_color = a_color * esInstanceTint();
#endif
#if defined(WEIGHT_HEAT) && defined(SKINNED)
    {
        uint chosen = uint(esInstanceTint().x);
        vec4 own = vec4(equal(a_joints, uvec4(chosen)));
        float heat = dot(own, a_weights);
        // Nothing the joint moves stays a quiet grey, so the part that matters is the part that shows.
        v_color = vec4(heat < 0.01 ? vec3(0.1) : mix(vec3(0.2, 0.4, 1.0), vec3(1.0, 0.25, 0.2), clamp(heat, 0.0, 1.0)), 1.0);
    }
#endif
#ifdef MESH_LIGHTMAP
    highp vec4 lmRect = esInstanceLightmapRect();
    v_lightmap = vec3(a_texCoord1 * lmRect.xy + lmRect.zw,
                      lmRect.x > 0.0 ? 1.0 : 0.0);
#endif
#ifdef SHADOW_DEPTH
    v_shadowClip = gl_Position;
#endif
#ifdef ES_VELOCITY
    {
        // This record is the motion pass's own: the tint texel carries the shift LAST frame was drawn with, and
        // the four texels after the model are last frame's view-projection times last frame's model, as rows.
#ifdef SKINNED
        // Last frame's bones put the vertex where it WAS; the record's rows are then last frame's camera alone.
        highp mat4 prevSkin = a_weights.x * esPrevBone(a_joints.x) + a_weights.y * esPrevBone(a_joints.y)
                            + a_weights.z * esPrevBone(a_joints.z) + a_weights.w * esPrevBone(a_joints.w);
        highp vec4 L = prevSkin * vec4(local, 1.0);
#else
        highp vec4 L = vec4(local, 1.0);
#endif
        highp vec4 before = esInstanceTint();
        v_velCur = gl_Position;
        highp vec4 prev = vec4(dot(esInstanceTexel(4), L), dot(esInstanceTexel(5), L),
                               dot(esInstanceTexel(6), L), dot(esInstanceTexel(7), L));
        v_velPrev = vec4(prev.xy + before.xy * prev.w, prev.zw);
    }
#endif
    // Only the vertex stage has an instance index, and every instance of a
    // merged run reads its own coefficients.
    v_probeSlot = float(ES_INSTANCE_ID);
#ifdef LIT
#if defined(MESH_NORMALS) && defined(SKINNED)
    v_worldNormal = mat3(skin) * localNormal;
#elif defined(MESH_NORMALS)
    v_worldNormal = esInstanceNormalMatrix() * localNormal;
#else
    // A surface with no normal channel faces the viewer, exactly as a sprite does.
    v_worldNormal = vec3(0.0, 0.0, 1.0);
#endif
    v_worldPos = world.xyz;
#ifdef MESH_TANGENTS
#ifdef SKINNED
    v_worldTangent = vec4(mat3(skin) * a_tangent.xyz, a_tangent.w);
#else
    mat3 tangentModel = mat3(esInstanceModel());
    // A mirrored placement turns the bitangent the other way round.
    v_worldTangent = vec4(tangentModel * a_tangent.xyz, determinant(tangentModel) < 0.0 ? -a_tangent.w : a_tangent.w);
#endif
#endif
#endif
}
#pragma end

#pragma fragment
precision mediump float;

in vec2 v_texCoord;
in vec4 v_color;
#ifdef LIT
in highp vec3 v_worldNormal;
in highp vec3 v_worldPos;
#endif
#ifdef SHADOW_DEPTH
in highp vec4 v_shadowClip;
#endif
#ifdef ES_VELOCITY
in highp vec4 v_velCur;
in highp vec4 v_velPrev;
#endif

uniform sampler2D u_texture;
#ifdef NORMAL_MAP
uniform sampler2D u_normalMap;
#endif

#ifdef ES_GBUFFER
// The frame's second attachment beside the colour: what this surface IS (normal, roughness, metalness),
// for the post effects that need to know. This shader's surface is the plain one — a rough dielectric —
// which is a record like any other: "nothing reflects here" is an answer, and one a reflections effect
// would otherwise have to guess.
layout(location = 0) out vec4 fragColor;
layout(location = 1) out vec4 fragSurface;
// The surface's diffuse colour, for light an effect adds after this pass (bounce light): alpha 1 is "written".
layout(location = 2) out vec4 fragAlbedo;

vec2 packNormal(vec3 n) {
    n /= (abs(n.x) + abs(n.y) + abs(n.z));
    vec2 sgn = vec2(n.x >= 0.0 ? 1.0 : -1.0, n.y >= 0.0 ? 1.0 : -1.0);
    vec2 e = n.z >= 0.0 ? n.xy : (1.0 - abs(n.yx)) * sgn;
    return e * 0.5 + 0.5;
}
#else
out vec4 fragColor;
#endif

// Where a material's cut-out is read: its Tiling, Offset and Rotation when it has them (ES_UV_TRANSFORM, the Model shader's), so the
// depth programs that reproduce its coverage cut where its colour pass does.
highp vec2 coverageUv() {
#ifdef ES_UV_TRANSFORM
    highp vec2 uv = v_texCoord * u_uvTiling;
    if (u_uvRotation != 0.0) {
        float c = cos(u_uvRotation), sn = sin(u_uvRotation);
        uv = vec2(c * uv.x + sn * uv.y, -sn * uv.x + c * uv.y);
    }
    return uv + u_uvOffset;
#else
    return v_texCoord;
#endif
}

void main() {
#ifdef ES_VELOCITY
    // How far this pixel's surface moved in the picture since last frame, in uv, and the depth it sits at
    // so a reader can tell whether it is the surface that is visible there. A point that was behind the
    // camera has no previous place: alpha 0 says "nothing known", which reads as the camera's own motion.
    highp vec2 now = v_velCur.xy / v_velCur.w;
    highp vec2 was = v_velPrev.xy / max(v_velPrev.w, 1e-6);
    fragColor = vec4((was - now) * 0.5, gl_FragCoord.z, v_velPrev.w > 1e-6 ? 1.0 : 0.0);
#elif defined(SHADOW_DEPTH)
#ifdef PREPASS_COVERAGE
    // The colour pass's own: base alpha is the texture's times the draw's colour times the material's tint, in that order, and the cut is sharpened to
    // about a pixel. The derivative is taken before the discard, where every fragment of the quad still runs. Nothing is written but the coverage.
    highp float baseAlpha = texture(u_texture, coverageUv()).a * v_color.a * u_tint.a;
    highp float coverage = (baseAlpha - u_alphaCutoff) / max(fwidth(baseAlpha), 1e-4) + 0.5;
    if (coverage <= 0.0) discard;
    fragColor = vec4(0.0, 0.0, 0.0, min(coverage, 1.0));
#else
#ifdef SHADOW_ALPHA
    // A cut-out's shadow is cut where the cut-out is, at the cutoff (glTF's MASK), through the mip chain: seen small from the light, the
    // cut-out keeps its share of the light because its mips keep their coverage at the cutoff (preserveAlphaCoverage).
    if (texture(u_texture, coverageUv()).a * v_color.a < u_alphaCutoff) discard;
#endif
    // The expression the receiver evaluates on u_shadowMatrix, evaluated here on the
    // same matrix and at the same point: whatever each backend's clip z means, both
    // sides mean it alike.
    fragColor = vec4(packDepth(clamp(v_shadowClip.z / v_shadowClip.w * 0.5 + 0.5,
                                     0.0, 1.0)), 1.0);
#endif
#else
    vec4 base = texture(u_texture, v_texCoord) * v_color;
#ifdef LIT
    highp vec3 N = normalize(v_worldNormal);
#ifdef NORMAL_MAP
    N = perturbNormal(N, v_worldPos, v_texCoord, sampleNormal(u_normalMap, v_texCoord));
#endif
    // A double-sided surface is lit from the side it is seen from (glTF's rule).
    if (!gl_FrontFacing) N = -N;
    // A rough dielectric, and the position it really has: a shadow is cast on a
    // point in space, and xy is not one. Specular stays ON — switching it off is
    // not a cheaper PBR, it is a different surface, and a mesh whose material
    // says nothing must still be lit the way the same mesh out of a glTF is.
    // A bake arrives through indirectIrradiance, in place of the sky: the lamps
    // stay the frame's, and the bake holds what reached this point off everything else.
    vec3 shaded = applyLightingPBR(base.rgb, N, v_worldPos, viewDirection(v_worldPos),
                                   0.0, 1.0, 1.0, 1.0);
    fragColor = vec4(shaded, base.a);
#ifdef ES_GBUFFER
    fragSurface = vec4(packNormal(normalize(N)), 1.0, 0.75);
    fragAlbedo = vec4(base.rgb, 1.0);
#endif
#else
#ifdef MESH_LIGHTMAP
    // Unlit AND lightmapped: the bake is the whole of this surface's light, not
    // an addition to a direct term it has none of. This is the case a bake is
    // FOR — a scene whose lights all went into the atlas pays for none of them.
    fragColor = vec4(base.rgb * mix(vec3(1.0), bakedIrradiance(), v_lightmap.z), base.a);
#else
    fragColor = base;
#endif
#endif
#endif
}
#pragma end

#pragma vertex wgsl
#ifdef SKINNED
struct SkinConstants { bones : array<mat4x4f, 256> };
@group(0) @binding(5) var<uniform> skin : SkinConstants;
#endif

// The GLSL twin's MorphConstants, and for the same reason unconditional. The
// texture is declared HERE, in the vertex stage, which is what tells the backend
// that unit 4 has to be visible to it — group-1 textures are fragment-only
// otherwise (see SkinConstants.hpp, which chose a block over a texture for it).
struct MorphConstants { info : vec4f, shape : array<vec4f, 64> };
@group(0) @binding(6) var<uniform> morph : MorphConstants;
@group(1) @binding(4) var t4 : texture_2d<f32>;

fn morphDelta(index : f32) -> vec3f {
    let width = morph.info.w;
    return textureLoad(t4, vec2i(i32(index % width), i32(index / width)), 0).xyz;
}

struct VSIn {
    @location(0) a_position : vec3f,
    @location(1) a_color : vec4f,
    @location(2) a_texCoord : vec2f,
#ifdef MESH_NORMALS
    @location(3) a_normal : vec3f,
#endif
#ifdef SKINNED
    @location(5) a_joints : vec4u,
    @location(6) a_weights : vec4f,
#endif
#ifdef MESH_LIGHTMAP
    @location(7) a_texCoord1 : vec2f,
#endif
#ifdef MESH_TANGENTS
    @location(4) a_tangent : vec4f,
#endif
    // What the GLSL twin reads as gl_VertexID: a morph delta is addressed by it.
    @builtin(vertex_index) vertexIndex : u32,
};
struct VSOut {
    @builtin(position) @invariant pos : vec4f,
    @location(0) v_texCoord : vec2f,
    @location(1) v_color : vec4f,
#ifdef LIT
    @location(2) v_worldNormal : vec3f,
    @location(3) v_worldPos : vec3f,
#ifdef MESH_TANGENTS
    @location(8) v_worldTangent : vec4f,
#endif
#endif
#ifdef SHADOW_DEPTH
    // The clip position, not the depth it divides down to — see the GLSL twin.
    @location(4) v_shadowClip : vec4f,
#endif
#ifdef ES_VELOCITY
    @location(4) v_velCur : vec4f,
    @location(7) v_velPrev : vec4f,
#endif
#ifdef MESH_LIGHTMAP
    @location(5) v_lightmap : vec3f,
#endif
    // Which run of the probe block this instance reads. Flat: an index, and the
    // fragment stage has no instance number of its own.
    @location(6) @interpolate(flat) v_probeSlot : f32,
};

#ifdef ES_MATERIAL_VERTEX
var<private> es_vertexColor : vec4f;
var<private> es_vertexUv1 : vec2f;
@@ES_VERTEX_HOOK@@
#endif

#ifdef ES_VELOCITY
#ifdef SKINNED
// Last frame's pose of one bone, from the records behind this draw's own: three rows a bone, from texel 8.
fn esPrevBone(joint : u32) -> mat4x4f {
    let at = 8 + i32(joint) * 3;
    let r0 = esInstanceTexel(at);
    let r1 = esInstanceTexel(at + 1);
    let r2 = esInstanceTexel(at + 2);
    return mat4x4f(vec4f(r0.x, r1.x, r2.x, 0.0), vec4f(r0.y, r1.y, r2.y, 0.0),
                   vec4f(r0.z, r1.z, r2.z, 0.0), vec4f(r0.w, r1.w, r2.w, 1.0));
}
#endif
#endif

@vertex fn vs_main(v : VSIn, @builtin(instance_index) inst : u32) -> VSOut {
    g_instanceId = i32(inst);
    var local = v.a_position;
#ifdef MESH_NORMALS
    var localNormal = v.a_normal;
#else
    var localNormal = vec3f(0.0, 0.0, 1.0);
#endif
    // Before the pose, never after: a target was authored against the mesh at
    // rest, so the offset it states is a local one.
    let live = i32(morph.info.x);
    for (var i = 0; i < 64; i = i + 1) {
        if (i >= live) { break; }
        let at = (morph.shape[i].x * morph.info.y + f32(v.vertexIndex)) * morph.info.z;
        local = local + morph.shape[i].y * morphDelta(at);
        if (morph.info.z > 1.5) {
            localNormal = localNormal + morph.shape[i].y * morphDelta(at + 1.0);
        }
    }
#ifdef ES_MATERIAL_VERTEX
    es_vertexColor = v.a_color;
#ifdef MESH_LIGHTMAP
    es_vertexUv1 = v.a_texCoord1;
#else
    es_vertexUv1 = vec2f(0.0);
#endif
    esMaterialVertex(&local, &localNormal, v.a_texCoord);
#endif
#ifdef SKINNED
    // The four bones this vertex is bound to, blended by their weights. The
    // result is world-space, so no model matrix follows it.
    let pose = v.a_weights.x * skin.bones[v.a_joints.x]
             + v.a_weights.y * skin.bones[v.a_joints.y]
             + v.a_weights.z * skin.bones[v.a_joints.z]
             + v.a_weights.w * skin.bones[v.a_joints.w];
    let world = pose * vec4f(local, 1.0);
#else
    let world = esInstanceModel() * vec4f(local, 1.0);
#endif

    var out : VSOut;
    out.pos = frame.projection * world;
    out.v_texCoord = v.a_texCoord;
#ifdef ES_MATERIAL_VERTEX
    out.v_color = es_vertexColor * esInstanceTint();
#else
    out.v_color = v.a_color * esInstanceTint();
#endif
#ifdef WEIGHT_HEAT
#ifdef SKINNED
    {
        let chosen = u32(esInstanceTint().x);
        let own = vec4f(v.a_joints == vec4u(chosen));
        let heat = dot(own, v.a_weights);
        out.v_color = vec4f(select(mix(vec3f(0.2, 0.4, 1.0), vec3f(1.0, 0.25, 0.2), clamp(heat, 0.0, 1.0)),
                                   vec3f(0.1), heat < 0.01), 1.0);
    }
#endif
#endif
#ifdef MESH_LIGHTMAP
    let lmRect = esInstanceLightmapRect();
    out.v_lightmap = vec3f(v.a_texCoord1 * lmRect.xy + lmRect.zw,
                           select(0.0, 1.0, lmRect.x > 0.0));
#endif
#ifdef SHADOW_DEPTH
    out.v_shadowClip = out.pos;
#endif
#ifdef ES_VELOCITY
    {
        // See the GLSL twin: the tint texel is last frame's shift, texels 4..7 last frame's matrix as rows.
#ifdef SKINNED
        // See the GLSL twin: last frame's bones place the vertex, the record's rows are the camera alone.
        let prevSkin = v.a_weights.x * esPrevBone(v.a_joints.x) + v.a_weights.y * esPrevBone(v.a_joints.y)
                     + v.a_weights.z * esPrevBone(v.a_joints.z) + v.a_weights.w * esPrevBone(v.a_joints.w);
        let L = prevSkin * vec4f(local, 1.0);
#else
        let L = vec4f(local, 1.0);
#endif
        let before = esInstanceTint();
        out.v_velCur = out.pos;
        let prev = vec4f(dot(esInstanceTexel(4), L), dot(esInstanceTexel(5), L),
                         dot(esInstanceTexel(6), L), dot(esInstanceTexel(7), L));
        out.v_velPrev = vec4f(prev.xy + before.xy * prev.w, prev.zw);
    }
#endif
    // The GLSL twin's v_probeSlot fill.
    out.v_probeSlot = f32(inst);
#ifdef LIT
#ifdef MESH_NORMALS
#ifdef SKINNED
    out.v_worldNormal = mat3x3f(pose[0].xyz, pose[1].xyz, pose[2].xyz) * localNormal;
#else
    out.v_worldNormal = esInstanceNormalMatrix() * localNormal;
#endif
#else
    // A surface with no normal channel faces the viewer, exactly as a sprite does.
    out.v_worldNormal = vec3f(0.0, 0.0, 1.0);
#endif
    out.v_worldPos = world.xyz;
#ifdef MESH_TANGENTS
#ifdef SKINNED
    out.v_worldTangent = vec4f(mat3x3f(pose[0].xyz, pose[1].xyz, pose[2].xyz) * v.a_tangent.xyz, v.a_tangent.w);
#else
    let tangentModel = mat3x3f(esInstanceModel()[0].xyz, esInstanceModel()[1].xyz, esInstanceModel()[2].xyz);
    out.v_worldTangent = vec4f(tangentModel * v.a_tangent.xyz,
                               select(v.a_tangent.w, -v.a_tangent.w, determinant(tangentModel) < 0.0));
#endif
#endif
#endif
    return out;
}
#pragma end

#pragma fragment wgsl
@group(1) @binding(0) var t0 : texture_2d<f32>;
@group(1) @binding(8) var s0 : sampler;
#ifdef NORMAL_MAP
@group(1) @binding(1) var t1 : texture_2d<f32>;
@group(1) @binding(9) var s1 : sampler;
#endif
#ifdef ES_RECEIVE_SHADOW
// The shadow map, on the slot the injected header samples. A fragment-only twin
// gets these from the batch texture contract; one that writes its own says so.
@group(1) @binding(2) var t2 : texture_2d<f32>;
@group(1) @binding(10) var s2 : sampler;
#endif
#ifdef ES_ENV_MAP
// The environment's reflection, one slot on. Same reason as above — and without
// it the injected sampler names an identifier this twin never declared, which
// reaches anyone as an invalid pipeline that does not mention a shader.
@group(1) @binding(3) var t3 : texture_2d<f32>;
@group(1) @binding(11) var s3 : sampler;
#endif
#ifdef MESH_LIGHTMAP
// The baked atlas, on the last slot a draw's own stream can claim.
@group(1) @binding(5) var t5 : texture_2d<f32>;
@group(1) @binding(13) var s5 : sampler;
#endif
// The 2D shadow mask, on the top slot. Unconditional, because the injected
// lighting reads it for every Lit shader rather than behind a feature.
@group(1) @binding(7) var t7 : texture_2d<f32>;
@group(1) @binding(15) var s7 : sampler;

struct VSOut {
    @builtin(position) pos : vec4f,
    @location(0) v_texCoord : vec2f,
    @location(1) v_color : vec4f,
#ifdef LIT
    @location(2) v_worldNormal : vec3f,
    @location(3) v_worldPos : vec3f,
#ifdef MESH_TANGENTS
    @location(8) v_worldTangent : vec4f,
#endif
#endif
#ifdef SHADOW_DEPTH
    @location(4) v_shadowClip : vec4f,
#endif
#ifdef ES_VELOCITY
    @location(4) v_velCur : vec4f,
    @location(7) v_velPrev : vec4f,
#endif
#ifdef MESH_LIGHTMAP
    @location(5) v_lightmap : vec3f,
#endif
    // Which run of the probe block this instance reads. Flat: an index, and the
    // fragment stage has no instance number of its own.
    @location(6) @interpolate(flat) v_probeSlot : f32,
};

// See the GLSL twin.
fn coverageUv(uv0 : vec2f) -> vec2f {
#ifdef ES_UV_TRANSFORM
    var uv = uv0 * mc.u_uvTiling;
    if (mc.u_uvRotation != 0.0) {
        let c = cos(mc.u_uvRotation);
        let sn = sin(mc.u_uvRotation);
        uv = vec2f(c * uv.x + sn * uv.y, -sn * uv.x + c * uv.y);
    }
    return uv + mc.u_uvOffset;
#else
    return uv0;
#endif
}

#ifdef ES_GBUFFER
// What the frame's second attachment takes, beside the colour (see the GLSL twin).
struct FragOut {
    @location(0) color : vec4f,
    @location(1) surface : vec4f,
    @location(2) albedo : vec4f,
};

fn packNormal(n : vec3f) -> vec2f {
    let a = n / (abs(n.x) + abs(n.y) + abs(n.z));
    let sgn = vec2f(select(-1.0, 1.0, a.x >= 0.0), select(-1.0, 1.0, a.y >= 0.0));
    var e = a.xy;
    if (a.z < 0.0) { e = (vec2f(1.0) - abs(a.yx)) * sgn; }
    return e * 0.5 + 0.5;
}

@fragment fn fs_main(v : VSOut, @builtin(front_facing) front : bool) -> FragOut {
#else
@fragment fn fs_main(v : VSOut, @builtin(front_facing) front : bool) -> @location(0) vec4f {
#endif
    // WGSL has no module varying: the entry point hands the injected header the
    // slot its GLSL twin reads straight off one.
    g_probeSlot = v.v_probeSlot;
#ifdef MESH_LIGHTMAP
    g_lightmap = v.v_lightmap;
#endif
#ifdef MESH_TANGENTS
#ifdef LIT
    g_worldTangent = v.v_worldTangent;
#endif
#endif
#ifdef ES_VELOCITY
    // See the GLSL twin. This device's uv runs down the rows, so the sign of y is the reader's to flip.
    let now = v.v_velCur.xy / v.v_velCur.w;
    let was = v.v_velPrev.xy / max(v.v_velPrev.w, 1e-6);
    return vec4f((was - now) * 0.5, v.pos.z, select(0.0, 1.0, v.v_velPrev.w > 1e-6));
#elif defined(SHADOW_DEPTH)
#ifdef PREPASS_COVERAGE
    // See the GLSL twin: the colour pass's coverage, by its expression on its inputs.
    let cuv = coverageUv(v.v_texCoord);
    let duvx = dpdx(cuv);
    let duvy = dpdy(cuv);
    let baseAlpha = textureSampleGrad(t0, s0, cuv, duvx, duvy).a * v.v_color.a * mc.u_tint.a;
    let edge = max(fwidth(baseAlpha), 1e-4);
    let coverage = (baseAlpha - mc.u_alphaCutoff) / max(edge, 1e-4) + 0.5;
    if (coverage <= 0.0) { discard; }
    return vec4f(0.0, 0.0, 0.0, min(coverage, 1.0));
#else
#ifdef SHADOW_ALPHA
    // See the GLSL twin: through the mip chain (level 0 alone left a card's shadow a different shape from WebGL2's), cut at the cutoff.
    let cuv = coverageUv(v.v_texCoord);
    let duvx = dpdx(cuv);
    let duvy = dpdy(cuv);
    if (textureSampleGrad(t0, s0, cuv, duvx, duvy).a * v.v_color.a < mc.u_alphaCutoff) { discard; }
#endif
    // The expression the receiver evaluates on u_shadowMatrix, evaluated here on the
    // same matrix and at the same point: whatever each backend's clip z means, both
    // sides mean it alike.
    return vec4f(packDepth(clamp(v.v_shadowClip.z / v.v_shadowClip.w * 0.5 + 0.5,
                                 0.0, 1.0)), 1.0);
#endif
#else
    // Through the mip chain, as the GLSL twin's texture() is: level 0 alone shimmers on anything seen smaller than its texture, and
    // the gradients are taken here, before any branch, where every fragment of the quad still runs.
    let duvx = dpdx(v.v_texCoord);
    let duvy = dpdy(v.v_texCoord);
    let base = textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy) * v.v_color;
#ifdef LIT
    var N = normalize(v.v_worldNormal);
#ifdef NORMAL_MAP
    N = perturbNormal(N, v.v_worldPos, v.v_texCoord, sampleNormalGrad(t1, s1, v.v_texCoord, duvx, duvy));
#endif
    if (!front) { N = -N; }
    // A rough dielectric, and the position it really has: a shadow is cast on a
    // point in space, and xy is not one. Specular stays ON — switching it off is
    // not a cheaper PBR, it is a different surface, and a mesh whose material
    // says nothing must still be lit the way the same mesh out of a glTF is.
    let shaded = applyLightingPBR(base.rgb, N, v.v_worldPos, viewDirection(v.v_worldPos),
                                  0.0, 1.0, 1.0, 1.0);
#ifdef ES_GBUFFER
    var frag : FragOut;
    frag.color = vec4f(shaded, base.a);
    frag.surface = vec4f(packNormal(normalize(N)), 1.0, 0.75);
    frag.albedo = vec4f(base.rgb, 1.0);
    return frag;
#else
    return vec4f(shaded, base.a);
#endif
#else
#ifdef MESH_LIGHTMAP
    // Unlit AND lightmapped: the bake is the whole of this surface's light.
    return vec4f(base.rgb * mix(vec3f(1.0), bakedIrradiance(), vec3f(v.v_lightmap.z)), base.a);
#else
    return base;
#endif
#endif
#endif
}
#pragma end