/** * Main PBR rendering shader for IFC geometry. * Features: PBR lighting, section plane clipping, selection highlight, * glass fresnel, ACES tone mapping, screen-space edge enhancement. */ export declare const mainShaderSource = "\n struct Uniforms {\n viewProj: mat4x4,\n model: mat4x4,\n baseColor: vec4,\n metallicRoughness: vec2, // x = metallic, y = roughness\n _padding1: vec2,\n sectionPlane: vec4, // xyz = plane normal, w = plane distance\n flags: vec4, // x = isSelected, y = section/clip bits, z = edgeEnabled, w = edgeIntensityMilli\n clipBoxMin: vec4, // xyz = clip-box min corner (world), w = pad\n clipBoxMax: vec4, // xyz = clip-box max corner (world), w = pad\n // Quantized-vertex dequantization (issue #1682 phase 6):\n // xyz = lattice-aligned quantMin (batch-origin-relative), w = step.\n // Only read by vs_main_quantized; zero elsewhere.\n quantParams: vec4,\n }\n @binding(0) @group(0) var uniforms: Uniforms;\n\n // Global lighting environment \u2014 one buffer shared by every mesh in\n // the pass (bound once per frame at group(1)). Field packing must\n // match packEnvironmentUniforms() in environment.ts.\n struct Environment {\n sunDirection: vec3, // unit vector TOWARD the sun\n sunIntensity: f32,\n sunColor: vec3,\n ambientIntensity: f32,\n skyColor: vec3, // hemisphere-ambient sky tint\n exposure: f32,\n groundColor: vec3, // hemisphere-ambient ground tint\n fillIntensity: f32,\n rimIntensity: f32,\n _pad0: f32,\n _pad1: f32,\n _pad2: f32,\n }\n @binding(0) @group(1) var env: Environment;\n\n struct VertexInput {\n @location(0) position: vec3,\n @location(1) normal: vec3,\n @location(2) entityId: u32,\n }\n\n struct VertexOutput {\n @builtin(position) position: vec4,\n @location(0) worldPos: vec3,\n @location(1) normal: vec3,\n @location(2) @interpolate(flat) entityId: u32,\n @location(3) viewPos: vec3, // For edge detection\n // Per-draw albedo carried from the vertex stage so the fragment shader\n // is shared by the flat path (vs_main writes uniforms.baseColor \u2014 the\n // per-batch / overlay-override colour) AND the instanced path\n // (vs_instanced writes the per-occurrence colour from the instance\n // buffer). For the flat path this is identical to reading\n // uniforms.baseColor directly (the value is constant across the draw).\n @location(4) color: vec4,\n // Per-occurrence selection flag for the instanced path (bit 0 = selected).\n // vs_main writes 0 (the flat path selects via uniforms.flags.x instead);\n // vs_instanced writes the per-instance flag from the instance buffer, so a\n // single selected occurrence highlights without re-drawing.\n @location(5) @interpolate(flat) instSelected: u32,\n }\n\n // Per-instance vertex-buffer inputs (slot 1, stepMode 'instance') used by\n // vs_instanced. The mat4 arrives as four COLUMN vec4s (WGSL mat4x4 is\n // column-major), matching composeInstanceMatrix's column-major output +\n // the pipeline's slot-1 attribute offsets (0/16/32/48).\n //\n // Location namespaces: vertex-INPUT @location (this struct + VertexInput)\n // and inter-stage @location (VertexOutput) are INDEPENDENT in WGSL, so\n // InstanceInput.m1 @location(4) does NOT collide with VertexOutput.color\n // @location(4) \u2014 exactly as VertexInput.entityId and VertexOutput.entityId\n // already BOTH use @location(2). Within the INPUT namespace the per-vertex\n // inputs (0..2) and per-instance inputs (3..8) stay distinct.\n struct InstanceInput {\n @location(3) m0: vec4,\n @location(4) m1: vec4,\n @location(5) m2: vec4,\n @location(6) m3: vec4,\n @location(7) instEntityId: u32,\n @location(8) instColor: vec4,\n @location(9) instSelected: u32,\n }\n\n // 12-byte quantized vertex (issue #1682 phase 6): uint16x4 (lattice\n // position xyz + packed octahedral normal in w as (u8x << 8 | u8y))\n // followed by the u32 entityId lane. Dequantization is BIT-EXACT for\n // the 2^-10 lattice: quantMin and q*step are both (integer)\u00B72^-10,\n // so coincident points across batches stay coincident (the shared-\n // origin z-fight guarantee survives quantization).\n struct QuantizedVertexInput {\n @location(0) q: vec4, // uint16x4: x, y, z, packedOct\n @location(2) entityId: u32,\n }\n\n fn octDecodeN(packed: u32) -> vec3 {\n let ox = (f32((packed >> 8u) & 255u) / 255.0) * 2.0 - 1.0;\n let oy = (f32(packed & 255u) / 255.0) * 2.0 - 1.0;\n var n = vec3(ox, oy, 1.0 - abs(ox) - abs(oy));\n if (n.z < 0.0) {\n let tx = (1.0 - abs(oy)) * select(-1.0, 1.0, ox >= 0.0);\n let ty = (1.0 - abs(ox)) * select(-1.0, 1.0, oy >= 0.0);\n n = vec3(tx, ty, n.z);\n }\n return normalize(n);\n }\n\n // Shared flat-path vertex shading \u2014 vs_main and vs_main_quantized\n // differ ONLY in how position/normal are sourced.\n fn shadeFlatVertex(localPos: vec3, localNormal: vec3, entityId: u32) -> VertexOutput {\n var output: VertexOutput;\n let worldPos = uniforms.model * vec4(localPos, 1.0);\n output.position = uniforms.viewProj * worldPos;\n // Anti z-fighting depth nudge \u2014 see vs_main's comment.\n let colorSalt = (entityId >> 24u) * 2654435761u;\n let zHash = (((entityId & 0x00FFFFFFu) ^ colorSalt) * 2654435761u) & 255u;\n output.position.z *= 1.0 + f32(zHash) * 1e-6;\n output.worldPos = worldPos.xyz;\n output.normal = normalize((uniforms.model * vec4(localNormal, 0.0)).xyz);\n output.entityId = entityId;\n output.color = uniforms.baseColor;\n output.instSelected = 0u;\n output.viewPos = (uniforms.viewProj * worldPos).xyz;\n return output;\n }\n\n @vertex\n fn vs_main_quantized(input: QuantizedVertexInput) -> VertexOutput {\n let p = uniforms.quantParams.xyz\n + vec3(f32(input.q.x), f32(input.q.y), f32(input.q.z)) * uniforms.quantParams.w;\n return shadeFlatVertex(p, octDecodeN(input.q.w), input.entityId);\n }\n\n @vertex\n fn vs_main(input: VertexInput, @builtin(instance_index) instanceIndex: u32) -> VertexOutput {\n var output: VertexOutput;\n let worldPos = uniforms.model * vec4(input.position, 1.0);\n output.position = uniforms.viewProj * worldPos;\n // Anti z-fighting: deterministic depth nudge.\n // Knuth multiplicative hash spreads sequential IDs across 0-255 so\n // coplanar faces from different entities always get distinct depths.\n // Material-layer walls slice into one closed solid per layer, all\n // sharing the PARENT wall's expressId, so adjacent layers' coincident\n // interface caps would get the same entity nudge and z-fight into a\n // flickering comb (\"see inside the wall\"). To separate them we fold in\n // an 8-bit MATERIAL-COLOUR salt that mergeGeometry/interleaveTextured\n // baked into the HIGH 8 bits of the entityId lane (low 24 = picking id,\n // masked off by encodeId24). Crucially the salt comes from the mesh's\n // OWN colour, NOT the per-draw baseColor uniform \u2014 so the base opaque\n // pass and the lens/IDS/compare/4D OVERLAY pass (which redraws the same\n // geometry with a DIFFERENT draw colour) compute the SAME nudge, and\n // the overlay pipeline's depthCompare:'equal' matches instead of\n // rejecting every fragment. At 1e-6 per step the max world-space offset\n // is <3mm at 10m \u2014 invisible.\n let colorSalt = (input.entityId >> 24u) * 2654435761u;\n let zHash = (((input.entityId & 0x00FFFFFFu) ^ colorSalt) * 2654435761u) & 255u;\n output.position.z *= 1.0 + f32(zHash) * 1e-6;\n output.worldPos = worldPos.xyz;\n output.normal = normalize((uniforms.model * vec4(input.normal, 0.0)).xyz);\n output.entityId = input.entityId;\n output.color = uniforms.baseColor;\n output.instSelected = 0u; // flat path selects via uniforms.flags.x\n // Store view-space position for edge detection\n output.viewPos = (uniforms.viewProj * worldPos).xyz;\n return output;\n }\n\n // Instanced vertex entry \u2014 one template's geometry drawn once per\n // occurrence. The per-instance mat4 already folds SWAP * rel_k * T(origin)\n // (composed CPU-side, see instanced-render.ts), so it maps the template's\n // LOCAL vertex straight to WebGL Y-up world space \u2014 no uniforms.model.\n // rel_k and SWAP are rigid (no scale), so the same matrix transforms\n // normals. entityId + colour come per-occurrence from the instance buffer.\n @vertex\n fn vs_instanced(input: VertexInput, inst: InstanceInput) -> VertexOutput {\n var output: VertexOutput;\n let instMat = mat4x4(inst.m0, inst.m1, inst.m2, inst.m3);\n let worldPos = instMat * vec4(input.position, 1.0);\n output.position = uniforms.viewProj * worldPos;\n // Same per-entity depth nudge as vs_main. No colour salt here: the\n // instanced path has no base-vs-overlay coincident redraw (yet), so the\n // raw picking id is enough to separate coplanar entities.\n let zHash = ((inst.instEntityId & 0x00FFFFFFu) * 2654435761u) & 255u;\n output.position.z *= 1.0 + f32(zHash) * 1e-6;\n output.worldPos = worldPos.xyz;\n output.normal = normalize((instMat * vec4(input.normal, 0.0)).xyz);\n output.entityId = inst.instEntityId;\n output.color = inst.instColor;\n output.instSelected = inst.instSelected;\n output.viewPos = (uniforms.viewProj * worldPos).xyz;\n return output;\n }\n\n // PBR helper functions\n fn fresnelSchlick(cosTheta: f32, F0: vec3) -> vec3 {\n return F0 + (1.0 - F0) * pow(clamp(1.0 - cosTheta, 0.0, 1.0), 5.0);\n }\n\n fn distributionGGX(NdotH: f32, roughness: f32) -> f32 {\n let a = roughness * roughness;\n let a2 = a * a;\n let NdotH2 = NdotH * NdotH;\n let num = a2;\n let denomBase = (NdotH2 * (a2 - 1.0) + 1.0);\n let denom = 3.14159265 * denomBase * denomBase;\n return num / max(denom, 0.0000001);\n }\n\n fn geometrySchlickGGX(NdotV: f32, roughness: f32) -> f32 {\n let r = (roughness + 1.0);\n let k = (r * r) / 8.0;\n let num = NdotV;\n let denom = NdotV * (1.0 - k) + k;\n return num / max(denom, 0.0000001);\n }\n\n fn geometrySmith(NdotV: f32, NdotL: f32, roughness: f32) -> f32 {\n let ggx2 = geometrySchlickGGX(NdotV, roughness);\n let ggx1 = geometrySchlickGGX(NdotL, roughness);\n return ggx1 * ggx2;\n }\n\n fn encodeId24(id: u32) -> vec4 {\n let r = f32((id >> 16u) & 255u) / 255.0;\n let g = f32((id >> 8u) & 255u) / 255.0;\n let b = f32(id & 255u) / 255.0;\n return vec4(r, g, b, 1.0);\n }\n\n struct FragmentOutput {\n @location(0) color: vec4,\n @location(1) objectIdEncoded: vec4,\n }\n\n @fragment\n fn fs_main(input: VertexOutput) -> FragmentOutput {\n // Per-instance hide/isolate: bit 1 of the instance flags lane marks a hidden\n // occurrence. Discard it so it neither draws nor writes depth (and the pick\n // pass applies the same discard, so it isn't pickable). vs_main writes\n // instSelected=0u for flat geometry, so this never affects the flat path.\n if ((input.instSelected & 2u) != 0u) {\n discard;\n }\n // Per-instance opacity routing (instanced passes only \u2014 flags.x bit 2). The\n // opaque instanced pass draws fully-opaque (or selected) occurrences; the\n // transparent instanced sub-pass (bit 3, alpha-blended) draws the rest. Discard\n // the occurrences belonging to the OTHER pass so each is drawn exactly once.\n // Lens-ghost / x-ray / compare write a low per-instance alpha into input.color.a.\n if ((uniforms.flags.x & 4u) != 0u) {\n let occOpaque = input.color.a >= 0.99 || (input.instSelected & 1u) != 0u;\n let transparentPass = (uniforms.flags.x & 8u) != 0u;\n if (transparentPass) {\n if (occOpaque) { discard; }\n } else {\n if (!occOpaque) { discard; }\n }\n }\n // Section plane clipping - discard fragments ABOVE the plane.\n // flags.y packs two bits: bit 0 = enabled, bit 1 = flipped.\n let sectionEnabled = (uniforms.flags.y & 1u) == 1u;\n if (sectionEnabled) {\n let planeNormal = uniforms.sectionPlane.xyz;\n let planeDistance = uniforms.sectionPlane.w;\n let flipped = (uniforms.flags.y & 2u) == 2u;\n let side = select(1.0, -1.0, flipped);\n let distToPlane = (dot(input.worldPos, planeNormal) - planeDistance) * side;\n if (distToPlane > 0.0) {\n discard;\n }\n }\n // Clip box (section / crop box): discard fragments OUTSIDE the AABB.\n // flags.y bit 2 = clip-box enabled.\n if ((uniforms.flags.y & 4u) != 0u) {\n let p = input.worldPos;\n if (any(p < uniforms.clipBoxMin.xyz) || any(p > uniforms.clipBoxMax.xyz)) {\n discard;\n }\n }\n\n // Compute normal via derivative-based flat shading.\n //\n // Industry-standard solution for BIM/CAD viewers \u2014 what\n // Three.js (material.flatShading = true), Autodesk Forge,\n // Speckle, and xeokit all do for opaque surfaces. Rationale:\n //\n // * BIM geometry is overwhelmingly flat surfaces (walls,\n // slabs, roofs, beams), and CSG operations (opening\n // subtraction, layer slicing) emit those surfaces as\n // dense strips of coplanar triangles. Per-vertex normal\n // averaging gives a SLIGHTLY-different normal at each\n // vertex due to f32 noise from boolean output; the\n // boundary between strips then reads as a visible darker/\n // brighter scar line \u2014 the horizontal striations on\n // walls, stripes on roofs, visible triangulation reports\n // across every CSG kernel we have tried (legacy BSP,\n // Manifold).\n // * cross(dpdx, dpdy) of world position evaluates to the\n // EXACT face normal in the fragment shader. Every\n // fragment on a flat face \u2014 across an arbitrarily-fine\n // triangulation \u2014 gets the IDENTICAL normal, so coplanar\n // splits become invisible by construction. No CPU-side\n // welding, smooth-grouping, or coplanar-face merging\n // fixes the symptom as cleanly.\n //\n // Trade-off: genuinely curved surfaces (cylinder tessellations,\n // BSpline approximations) shade with visible facets. For BIM\n // that's acceptable \u2014 curved surfaces are < 5 % of typical\n // model triangle count and the faceting matches CAD-tool\n // (Revit, ArchiCAD) on-screen behaviour at default quality.\n //\n // We still fall back to the vertex normal when derivatives\n // are unavailable (extreme polygon degeneracy where dpdx /\n // dpdy collapse to zero \u2014 practically never on real geometry).\n let faceN = cross(dpdx(input.worldPos), dpdy(input.worldPos));\n let fLen2 = dot(faceN, faceN);\n var N: vec3;\n if (fLen2 > 1e-10) {\n N = faceN * inverseSqrt(fLen2);\n } else {\n // Degenerate derivative \u2014 fall back to the vertex normal\n // if it's populated, else +Y.\n N = input.normal;\n let nLen2 = dot(N, N);\n if (nLen2 > 1e-6) {\n N = N * inverseSqrt(nLen2);\n } else {\n N = vec3(0.0, 1.0, 0.0);\n }\n }\n\n // Stabilize the SIGN of the derivative face normal with the vertex\n // normal. The screen-space cross product gives the exact face\n // normal DIRECTION for coplanar strips (the scar-line fix), but at\n // grazing angles its SIGN becomes numerically unstable per quad \u2014\n // hemisphere/rim lighting then band-flips across large regions of\n // flat walls/slabs (diagonal lighter/darker bands). The interpolated\n // vertex normal is quad-noise-free, so use it only to orient N.\n // Guard: skip when the vertex normal is missing or nearly\n // perpendicular to the face normal (unreliable witness).\n let vN = input.normal;\n let alignDot = dot(N, vN);\n if (alignDot * alignDot > 0.03 * dot(vN, vN)) {\n N = N * sign(alignDot);\n }\n\n // Lighting environment \u2014 sun/hemisphere/exposure come from the\n // global env uniform (defaults reproduce the historic hardcoded\n // values); fill + rim directions stay fixed in view-agnostic\n // world space as stylistic shaping lights.\n let sunLight = env.sunDirection;\n let fillLight = normalize(vec3(-0.5, 0.3, -0.3)); // Fill light\n let rimLight = normalize(vec3(0.0, 0.2, -1.0)); // Rim light for edge definition\n\n // Hemisphere ambient\n let hemisphereFactor = N.y * 0.5 + 0.5;\n let ambient = mix(env.groundColor, env.skyColor, hemisphereFactor) * env.ambientIntensity;\n\n // Two-sided sun light so inner faces (I-beam channels) stay visible\n let NdotL = abs(dot(N, sunLight));\n let wrap = 0.3;\n let diffuseSun = max((NdotL + wrap) / (1.0 + wrap), 0.0) * env.sunIntensity;\n\n // Fill light - two-sided\n let NdotFill = abs(dot(N, fillLight));\n let diffuseFill = NdotFill * env.fillIntensity;\n\n // Rim light for edge definition\n let NdotRim = max(dot(N, rimLight), 0.0);\n let rim = pow(NdotRim, 4.0) * env.rimIntensity;\n\n var baseColor = input.color.rgb;\n\n // Detect if the color is close to white/gray (low saturation)\n let baseGray = dot(baseColor, vec3(0.299, 0.587, 0.114));\n let baseSaturation = length(baseColor - vec3(baseGray)) / max(baseGray, 0.001);\n let isWhiteish = 1.0 - smoothstep(0.0, 0.3, baseSaturation);\n\n // Darken whites/grays more to reduce washed-out appearance\n baseColor = mix(baseColor, baseColor * 0.7, isWhiteish * 0.4);\n\n // Combine all lighting. Keep the lighting term separate so the\n // selection highlight can reuse it (re-light a blue albedo) without\n // the base material colour bleeding through.\n let lightTerm = ambient + env.sunColor * diffuseSun + vec3(diffuseFill + rim);\n var color = baseColor * lightTerm;\n\n // flags.x is a bitfield:\n // bit 0 (value 1) = isSelected \u2192 selection-highlight + force opaque\n // bit 1 (value 2) = isOverlay \u2192 color-override pass; preserve\n // baseColor.a (overlay pipeline has\n // src-alpha blending) AND skip the\n // glass-fresnel branch so low-alpha\n // ghost tints don't pick up the\n // near-white reflection tint meant\n // for real glass materials.\n // Selected via the per-draw flag (flat path) OR the per-occurrence flag\n // (instanced path \u2014 vs_instanced reads it from the instance buffer).\n let isSelected = ((uniforms.flags.x & 1u) == 1u) || ((input.instSelected & 1u) == 1u);\n let isOverlay = (uniforms.flags.x & 2u) == 2u;\n\n // Selection highlight \u2014 a blue albedo RE-LIT by the scene lighting.\n //\n // We override the material albedo with selection-blue and re-light\n // it with the SAME lightTerm used for unselected surfaces, then\n // discard the view-dependent (fresnel) term below. Two requirements\n // are in tension and this satisfies both:\n //\n // * No base-material bleed-through. The old fresnel-glow mix left\n // ~80 % of the lit object colour visible at face centres (the\n // green-site / red-roof wash-out). Here the base colour never\n // enters the result \u2014 only lightTerm (geometry/light, colour-\n // independent) modulates the constant blue albedo.\n // * Facet/crease structure must survive. A single FLAT colour\n // (the previous fix) collapsed every face to the same blue, so\n // internal edges \u2014 which read as the per-face shading STEP, not\n // just the faint screen-space edge line \u2014 disappeared on\n // selection. Re-lighting keeps that per-face brightness step, so\n // creases read on the highlight exactly as they do unselected.\n //\n // The luminance of lightTerm is remapped by a multiplicative gain\n // (which preserves the per-face brightness RATIOS, so creases read\n // as strongly as on the unselected surface) calibrated so a sunlit\n // face hits full selection-blue, with a floor/ceiling clamp so\n // shadowed faces only dim and bright scenes never wash out.\n if (isSelected) {\n let shadeLum = dot(lightTerm, vec3(0.299, 0.587, 0.114));\n let shade = clamp(shadeLum * 1.55, 0.45, 1.2);\n color = vec3(0.3, 0.6, 1.0) * shade;\n }\n\n // flags.x bit 5 (value 32) = EMPHASIZE overlay: render the colour\n // override FULLY UNLIT and saturated (no lighting attenuation, no\n // wash-to-white) so the focused clash pair reads as a solid, vivid,\n // distinct colour that pops against the lit model \u2014 like a clash tool.\n // A faint normal-based shade keeps the silhouette from going flat. (#1277)\n let emphasizedOverlay = isOverlay && (uniforms.flags.x & 32u) != 0u;\n if (emphasizedOverlay) {\n let facet = 0.85 + 0.15 * abs(dot(N, normalize(vec3(0.3, 1.0, 0.2))));\n color = baseColor * facet;\n }\n\n // Beautiful fresnel effect for transparent materials (glass)\n // Skip when selected \u2014 the glass shine and desaturation wash out the\n // blue highlight, making it appear white instead of blue.\n // Also force alpha to 1.0 for selected objects so the highlight is\n // fully opaque (the selection pipeline has no alpha blending).\n // Emphasized clash overlay paints a SOLID vivid fill (force opaque) so\n // it isn't blended down to a pale tint against the geometry beneath.\n var finalAlpha = select(input.color.a, 1.0, isSelected || emphasizedOverlay);\n if (finalAlpha < 0.99 && !isSelected && !isOverlay) {\n // Calculate view direction for fresnel\n let V = normalize(-input.worldPos);\n let NdotV = max(dot(N, V), 0.0);\n\n // Enhanced fresnel effect - stronger at edges (grazing angles)\n // Using Schlick's approximation for realistic glass reflection\n let fresnelPower = 1.5; // Higher = softer edge reflections\n let fresnel = pow(1.0 - NdotV, fresnelPower);\n\n // Glass reflection tint (sky/environment reflection at edges)\n let reflectionTint = vec3(0.92, 0.96, 1.0); // Cool sky reflection\n let reflectionStrength = fresnel * 0.6; // Strong edge reflections\n\n // Mix in reflection tint at edges\n color = mix(color, color * reflectionTint, reflectionStrength);\n\n // Add realistic glass shine - brighter at edges where light reflects\n let glassShine = fresnel * 0.12;\n color += glassShine;\n\n // Slight desaturation at edges (glass reflects environment, not just color)\n let edgeDesaturation = fresnel * 0.25;\n let gray = dot(color, vec3(0.299, 0.587, 0.114));\n color = mix(color, vec3(gray), edgeDesaturation);\n\n // Make glass more transparent (reduce opacity by 30%)\n finalAlpha = finalAlpha * 0.7;\n }\n\n // Exposure adjustment (historic default 0.85 darkens overall)\n color *= env.exposure;\n\n // Contrast enhancement\n color = (color - 0.5) * 1.15 + 0.5;\n color = max(color, vec3(0.0));\n\n // Saturation boost - stronger for colored surfaces, less for whites\n let gray = dot(color, vec3(0.299, 0.587, 0.114));\n // More saturation for colored surfaces. isWhiteish is derived from\n // the base material colour, so for a SELECTED object it would leak a\n // material dependence into the highlight (breaking the no-bleed-\n // through contract). The selection blue is a fully-saturated colour,\n // so force the colored-surface boost (1.4) when selected \u2014 keeping\n // the highlight identical regardless of the underlying material.\n let satBoost = select(mix(1.4, 1.1, isWhiteish), 1.4, isSelected);\n color = mix(vec3(gray), color, satBoost);\n\n // ACES filmic tone mapping\n let a = 2.51;\n let b = 0.03;\n let c = 2.43;\n let d = 0.59;\n let e = 0.14;\n color = clamp((color * (a * color + b)) / (color * (c * color + d) + e), vec3(0.0), vec3(1.0));\n\n // Subtle edge enhancement using screen-space derivatives.\n //\n // Use the SHADED normal (face normal from dpdx/dpdy above)\n // for the normal-gradient term, not the interpolated vertex\n // normal \u2014 otherwise we get spurious dark stripes on flat\n // surfaces whose vertex normals carry numerical noise from\n // CSG output (the visible scar-line symptom would just\n // resurface here even after the lit-normal fix). With the\n // face normal, coplanar adjacent triangles agree exactly \u2192\n // zero normal gradient \u2192 no false edge; only the genuine\n // creases between perpendicular faces produce a real\n // gradient and get the intended outline.\n let depthGradient = length(vec2(\n dpdx(input.viewPos.z),\n dpdy(input.viewPos.z)\n ));\n let normalGradient = length(vec2(\n length(dpdx(N)),\n length(dpdy(N))\n ));\n\n if (uniforms.flags.z == 1u) {\n // Threshold filters subtle normal discontinuities at internal\n // triangle edges between coplanar entities in the same batch.\n let edgeFactor = smoothstep(0.02, 0.12, depthGradient * 10.0 + normalGradient * 5.0);\n let edgeIntensity = f32(uniforms.flags.w) / 1000.0;\n let edgeDarkenStrength = clamp(0.25 * edgeIntensity, 0.0, 0.85);\n let edgeDarken = mix(1.0, 1.0 - edgeDarkenStrength, edgeFactor);\n color *= edgeDarken;\n }\n\n // Gamma correction\n color = pow(color, vec3(1.0 / 2.2));\n\n var out: FragmentOutput;\n out.color = vec4(color, finalAlpha);\n out.objectIdEncoded = encodeId24(input.entityId);\n return out;\n }\n "; //# sourceMappingURL=main.wgsl.d.ts.map