29#include <unordered_map>
30#include <unordered_set>
46 explicit LineReader(
const std::string& text) : text_(text) {}
47 bool next(std::string& line) {
48 if (pos_ >= text_.size())
return false;
49 const usize end = text_.find(
'\n', pos_);
50 if (end == std::string::npos) {
51 line.assign(text_, pos_, std::string::npos);
54 line.assign(text_, pos_, end - pos_);
61 const std::string& text_;
66std::string nextToken(
const std::string& text,
usize& pos) {
67 while (pos < text.size() && std::isspace(
static_cast<unsigned char>(text[pos]))) ++pos;
68 const usize start = pos;
69 while (pos < text.size() && !std::isspace(
static_cast<unsigned char>(text[pos]))) ++pos;
70 return text.substr(start, pos - start);
76 TextBuilder&
operator<<(
const std::string& s) { text_ += s;
return *
this; }
77 TextBuilder&
operator<<(std::string_view s) { text_ += s;
return *
this; }
78 TextBuilder&
operator<<(
const char* s) { text_ += s;
return *
this; }
79 TextBuilder&
operator<<(
char c) { text_ += c;
return *
this; }
80 const std::string& str()
const {
return text_; }
81 void str(
const char*) { text_.clear(); }
104bool namesRecords(
const std::string& stageText) {
105 return stageText.find(
"esInstance") != std::string::npos || stageText.find(
"esApplyMorph") != std::string::npos;
109std::string instanceRecordWGSL() {
114 "struct InstanceConstants { base : vec4u };\n"
116 +
") var<uniform> inst : InstanceConstants;\n"
119 "var<private> g_instanceId : i32 = 0;\n"
120 "fn esFrameTexel(texel : i32) -> vec4f {\n"
121 " return textureLoad(t" + unit +
", vec2i(texel % " + width +
", texel / " + width +
"), 0);\n"
124 "fn esDrawEntry() -> vec4f { return esFrameTexel(i32(inst.base.x)); }\n"
125 "fn esInstanceTexel(texel : i32) -> vec4f {\n"
126 " return esFrameTexel((i32(esDrawEntry().x) + g_instanceId) * " + texels +
" + texel);\n"
128 "fn esInstanceModel() -> mat4x4f {\n"
132 " return mat4x4f(vec4f(r0.x, r1.x, r2.x, 0.0), vec4f(r0.y, r1.y, r2.y, 0.0),\n"
133 " vec4f(r0.z, r1.z, r2.z, 0.0), vec4f(r0.w, r1.w, r2.w, 1.0));\n"
135 "fn esInstanceNormalMatrix() -> mat3x3f {\n"
140 "fn esInstanceTint() -> vec4f { return esInstanceTexel("
142 "fn esInstanceLightmapRect() -> vec4f { return esInstanceTexel("
155std::string instanceRecordGLSLDecls() {
157 "layout(std140) uniform InstanceConstants {\n"
158 " highp uvec4 u_instanceBase;\n"
161 "#define ES_DRAW_ID gl_DrawID\n"
163 "#define ES_DRAW_ID 0\n"
165 :
"#define ES_DRAW_ID 0\n") +
167 "#define ES_RECORD_ID gl_InstanceIndex\n"
169 "#define ES_RECORD_ID gl_InstanceID\n"
171 "#define ES_DRAW_RECORD int(esDrawEntry().x)\n"
173 "#undef ES_INSTANCE_ID\n"
174 "#define ES_INSTANCE_ID (ES_RECORD_ID + int(esDrawEntry().y))\n"
175 "uniform highp sampler2D u_instanceData;\n"
176 "highp vec4 esFrameTexel(int texel);\n"
177 "highp vec4 esDrawEntry();\n"
178 "highp vec4 esInstanceTexel(int texel);\n"
179 "highp mat4 esInstanceModel();\n"
180 "highp mat3 esInstanceNormalMatrix();\n"
181 "highp vec4 esInstanceTint();\n"
182 "highp vec4 esInstanceLightmapRect();\n";
185std::string instanceRecordGLSLBodies() {
189 "highp vec4 esFrameTexel(int texel) {\n"
190 " return texelFetch(u_instanceData, ivec2(texel % " + width +
", texel / " + width +
"), 0);\n"
192 "highp vec4 esDrawEntry() { return esFrameTexel(int(u_instanceBase.x) + ES_DRAW_ID); }\n"
193 "highp vec4 esInstanceTexel(int texel) {\n"
194 " return esFrameTexel((ES_DRAW_RECORD + ES_RECORD_ID) * " + texels +
" + texel);\n"
196 "highp mat4 esInstanceModel() {\n"
200 " return mat4(vec4(r0.x, r1.x, r2.x, 0.0), vec4(r0.y, r1.y, r2.y, 0.0),\n"
201 " vec4(r0.z, r1.z, r2.z, 0.0), vec4(r0.w, r1.w, r2.w, 1.0));\n"
203 "highp mat3 esInstanceNormalMatrix() {\n"
208 "highp vec4 esInstanceTint() { return esInstanceTexel("
210 "highp vec4 esInstanceLightmapRect() { return esInstanceTexel("
222std::string morphHelpersGLSL() {
224 "uniform highp sampler2D u_morphDeltas;\n"
225 "vec3 esMorphDelta(highp float index, highp float width) {\n"
226 " return texelFetch(u_morphDeltas, ivec2(int(mod(index, width)), int(index / width)), 0).xyz;\n"
228 "void esApplyMorph(inout vec3 position, inout vec3 normal) {\n"
229 " int head = int(esDrawEntry().z);\n"
230 " if (head == 0) return;\n"
231 " highp vec4 info = esFrameTexel(head);\n"
232 " int live = int(info.x);\n"
234 " if (i >= live) break;\n"
235 " highp vec4 shape = esFrameTexel(head + 1 + i);\n"
236 " highp float at = (shape.x * info.y + float(gl_VertexID)) * info.z;\n"
237 " position += shape.y * esMorphDelta(at, info.w);\n"
238 " if (info.z > 1.5) normal += shape.y * esMorphDelta(at + 1.0, info.w);\n"
248std::string morphHelpersWGSL() {
251 +
" : texture_2d<f32>;\n"
252 "fn esMorphDelta(index : f32, width : f32) -> vec3f {\n"
254 +
", vec2i(i32(index % width), i32(index / width)), 0).xyz;\n"
256 "fn esApplyMorph(position : ptr<function, vec3f>, normal : ptr<function, vec3f>, vertexIndex : u32) {\n"
257 " let head = i32(esDrawEntry().z);\n"
258 " if (head == 0) { return; }\n"
259 " let info = esFrameTexel(head);\n"
260 " let live = i32(info.x);\n"
262 " if (i >= live) { break; }\n"
263 " let shape = esFrameTexel(head + 1 + i);\n"
264 " let at = (shape.x * info.y + f32(vertexIndex)) * info.z;\n"
265 " *position = *position + shape.y * esMorphDelta(at, info.w);\n"
266 " if (info.z > 1.5) { *normal = *normal + shape.y * esMorphDelta(at + 1.0, info.w); }\n"
272constexpr u32 kMaxIncludeDepth = 16;
274std::string ltrim(
const std::string& s) {
275 usize start = s.find_first_not_of(
" \t");
276 return start == std::string::npos ? std::string() : s.substr(start);
279bool expandIncludes(
const std::string& source,
280 const std::string& currentFile,
282 std::unordered_set<std::string>& active,
285 std::vector<SourceLine>& outMap,
286 std::string& errorMessage) {
287 if (depth > kMaxIncludeDepth) {
288 errorMessage =
"Shader include depth exceeded " + std::to_string(kMaxIncludeDepth);
292 LineReader stream(source);
295 while (stream.next(line)) {
297 const std::string lead = ltrim(line);
298 if (lead.rfind(
"#include", 0) != 0) {
301 outMap.push_back(
SourceLine{currentFile, lineNumber});
305 const usize q1 = lead.find(
'"');
306 const usize q2 = (q1 == std::string::npos) ? std::string::npos : lead.find(
'"', q1 + 1);
307 if (q1 == std::string::npos || q2 == std::string::npos || q2 <= q1 + 1) {
308 errorMessage =
"Malformed #include directive: " + line;
311 const std::string path = lead.substr(q1 + 1, q2 - q1 - 1);
314 errorMessage =
"#include \"" + path +
"\" used but no include resolver was provided";
317 if (active.count(path) != 0) {
318 errorMessage =
"Circular #include of \"" + path +
"\"";
321 std::optional<std::string> contents = resolver(path);
323 errorMessage =
"Could not resolve #include \"" + path +
"\"";
328 if (!expandIncludes(*contents, path, resolver, active, depth + 1, out, outMap, errorMessage)) {
338void fillHook(std::string& src,
const std::string& token,
const std::string& text) {
339 for (
usize at = src.find(token); at != std::string::npos; at = src.find(token, at + text.size())) {
340 src.replace(at, token.size(), text);
348std::string wgslCanonicalVSOut(
bool lit) {
352 " @builtin(position) @invariant pos : vec4f,\n"
353 " @location(0) v_color : vec4f,\n"
354 " @location(1) v_texCoord : vec2f,\n";
356 src +=
" @location(2) v_worldPos : vec2f,\n";
358 src +=
" @location(8) @interpolate(flat) v_lightLayer : f32,\n";
364 "#ifdef MESH_NORMALS\n"
365 " @location(3) v_worldNormal : vec3f,\n"
366 " @location(4) v_worldXYZ : vec3f,\n"
369 " @location(11) v_particle : vec4f,\n"
372 "#ifdef MESH_TANGENTS\n"
373 " @location(7) v_worldTangent : vec4f,\n"
378 "#ifdef MESH_LIGHTMAP\n"
379 " @location(5) v_lightmap : vec3f,\n"
382 " @location(9) v_texCoord1 : vec2f,\n"
386 "#ifdef MESH_LOCAL_POSITION\n"
387 " @location(10) v_localPos : vec3f,\n"
392 src +=
" @location(6) @interpolate(flat) v_probeSlot : f32,\n";
401std::string canonicalVertexStageWGSL(
bool lit,
const std::string& hook = {}) {
402 std::string src = wgslCanonicalVSOut(lit);
408 "struct SkinConstants { bones : array<mat4x4f, " + std::to_string(
MESH_MAX_BONES) +
"> };\n"
409 "@group(0) @binding(5) var<uniform> skin : SkinConstants;\n"
413 + morphHelpersWGSL() +
420 " @location(0) a_position : vec2f,\n"
421 " @location(1) a_texCoord : vec2f,\n"
422 " @location(2) a_inst_position : vec3f,\n"
423 " @location(3) a_inst_size : vec2f,\n"
424 " @location(4) a_inst_rotation : f32,\n"
425 " @location(5) a_inst_color : vec4f,\n"
426 " @location(6) a_inst_uv : vec4f,\n"
427 " @location(7) a_inst_extra : vec4f,\n"
429 " @location(0) a_position : vec3f,\n"
430 " @location(1) a_color : vec4f,\n"
431 " @location(2) a_texCoord : vec2f,\n"
432 "#ifdef MESH_NORMALS\n"
433 " @location(3) a_normal : vec3f,\n"
435 "#ifdef MESH_LIGHTMAP\n"
436 " @location(7) a_texCoord1 : vec2f,\n"
438 "#ifdef MESH_TANGENTS\n"
439 " @location(4) a_tangent : vec4f,\n"
441 + std::string(lit ?
"#if !defined(MESH) && !defined(SKINNED)\n"
442 " @location(4) a_lightLayer : f32,\n"
445 " @location(5) a_joints : vec4u,\n"
446 " @location(6) a_weights : vec4f,\n"
450 " @builtin(vertex_index) vertexIndex : u32,\n"
457 "@vertex fn vs_main(v : VSIn, @builtin(instance_index) instanceId : u32) -> VSOut {\n"
458 " var out : VSOut;\n"
459 " g_instanceId = i32(instanceId);\n"
461 " var local = v.a_position;\n"
462 "#ifdef MESH_NORMALS\n"
463 " var localNormal = v.a_normal;\n"
465 " var localNormal = vec3f(0.0, 0.0, 1.0);\n"
468 " esApplyMorph(&local, &localNormal, v.vertexIndex);\n"
475 " let scaled = v.a_position * v.a_inst_size;\n"
476 " let cosR = cos(v.a_inst_rotation);\n"
477 " let sinR = sin(v.a_inst_rotation);\n"
478 " let rotated = vec2f(scaled.x * cosR - scaled.y * sinR,\n"
479 " scaled.x * sinR + scaled.y * cosR);\n"
480 " let fwd = viewDirection(v.a_inst_position);\n"
482 " var refUp = vec3f(0.0, 1.0, 0.0);\n"
483 " if (abs(fwd.y) > 0.999) { refUp = vec3f(0.0, 0.0, 1.0); }\n"
484 " let right = normalize(cross(refUp, fwd));\n"
485 " let up = cross(fwd, right);\n"
486 " let world = vec4f(v.a_inst_position + right * rotated.x + up * rotated.y, 1.0);\n"
487 " out.v_color = vec4f(v.a_inst_color.rgb * v.a_inst_extra.z, v.a_inst_color.a);\n"
488 " out.v_particle = vec4f(v.a_inst_extra.x, v.a_inst_extra.y, v.a_inst_extra.w, v.a_inst_extra.z);\n"
491 "#elif defined(SKINNED)\n"
492 " let pose = v.a_weights.x * skin.bones[v.a_joints.x]\n"
493 " + v.a_weights.y * skin.bones[v.a_joints.y]\n"
494 " + v.a_weights.z * skin.bones[v.a_joints.z]\n"
495 " + v.a_weights.w * skin.bones[v.a_joints.w];\n"
496 " let world = pose * vec4f(local, 1.0);\n"
497 " out.v_color = v.a_color * esInstanceTint();\n"
498 "#elif defined(MESH)\n"
499 " let world = esInstanceModel() * vec4f(local, 1.0);\n"
500 " out.v_color = @@WGSL_MESH_COLOR@@ * esInstanceTint();\n"
502 " let world = vec4f(v.a_position, 1.0);\n"
503 " out.v_color = v.a_color;\n"
505 " out.pos = frame.projection * world;\n"
508 " out.v_texCoord = v.a_texCoord * v.a_inst_uv.zw + v.a_inst_uv.xy;\n"
510 " out.v_texCoord = v.a_texCoord;\n"
512 "#ifdef MESH_NORMALS\n"
514 "#if defined(PARTICLE)\n"
515 " out.v_worldNormal = fwd;\n"
516 "#elif defined(SKINNED)\n"
517 " out.v_worldNormal = mat3x3f(pose[0].xyz, pose[1].xyz, pose[2].xyz) * localNormal;\n"
519 " out.v_worldNormal = esInstanceNormalMatrix() * localNormal;\n"
521 " out.v_worldXYZ = world.xyz;\n"
522 "#ifdef MESH_TANGENTS\n"
524 " out.v_worldTangent = vec4f(mat3x3f(pose[0].xyz, pose[1].xyz, pose[2].xyz) * v.a_tangent.xyz, v.a_tangent.w);\n"
526 " let tangentModel = mat3x3f(esInstanceModel()[0].xyz, esInstanceModel()[1].xyz, esInstanceModel()[2].xyz);\n"
527 " out.v_worldTangent = vec4f(tangentModel * v.a_tangent.xyz,\n"
528 " select(v.a_tangent.w, -v.a_tangent.w, determinant(tangentModel) < 0.0));\n"
532 "#ifdef MESH_LIGHTMAP\n"
533 " let lmRect = esInstanceLightmapRect();\n"
534 " out.v_lightmap = vec3f(v.a_texCoord1 * lmRect.xy + lmRect.zw,\n"
535 " select(0.0, 1.0, lmRect.x > 0.0));\n"
536 " out.v_texCoord1 = v.a_texCoord1;\n"
538 "#if defined(MESH_LOCAL_POSITION) && defined(MESH)\n"
539 " out.v_localPos = v.a_position;\n"
542 src +=
" out.v_worldPos = world.xy;\n";
543 src +=
"#if !defined(MESH) && !defined(SKINNED) && !defined(PARTICLE)\n out.v_lightLayer = v.a_lightLayer;\n#else\n out.v_lightLayer = 0.0;\n#endif\n";
547 src +=
"#ifdef PARTICLE\n out.v_probeSlot = 0.0;\n#else\n out.v_probeSlot = f32(instanceId);\n#endif\n";
552 " out.pos.y = -out.pos.y;\n"
558 fillHook(src,
"@@WGSL_MESH_COLOR@@", hook.empty() ? std::string(
"v.a_color") : std::string(
"es_vertexColor"));
559 fillHook(src,
"@@WGSL_HOOK@@", hook.empty() ? std::string() :
560 "#ifdef MESH\nvar<private> es_vertexColor : vec4f;\nvar<private> es_vertexUv1 : vec2f;\n" + hook +
"\n#endif\n");
561 fillHook(src,
"@@WGSL_CALL@@", hook.empty() ? std::string() :
562 " es_vertexColor = v.a_color;\n#ifdef MESH_LIGHTMAP\n es_vertexUv1 = v.a_texCoord1;\n#else\n es_vertexUv1 = vec2f(0.0);\n#endif\n"
563 " esMaterialVertex(&local, &localNormal, v.a_texCoord);\n");
569std::string wgslPPVSOut() {
572 " @builtin(position) pos : vec4f,\n"
573 " @location(0) v_texCoord : vec2f,\n"
580std::string canonicalPPVertexStageWGSL() {
581 std::string src = wgslPPVSOut();
585 " @location(0) a_position : vec2f,\n"
586 " @location(1) a_texCoord : vec2f,\n"
589 "@vertex fn vs_main(v : VSIn) -> VSOut {\n"
590 " var out : VSOut;\n"
591 " out.pos = vec4f(v.a_position.x, -v.a_position.y, 0.0, 1.0);\n"
592 " out.v_texCoord = v.a_texCoord;\n"
601std::string canonicalPPVertexStage() {
603 "layout(location = 0) in vec2 a_position;\n"
604 "layout(location = 1) in vec2 a_texCoord;\n"
606 "out vec2 v_texCoord;\n"
609 " v_texCoord = a_texCoord;\n"
610 " gl_Position = vec4(a_position, 0.0, 1.0);\n"
617std::string canonicalVertexStage(
bool lit,
const std::string& hook = {}) {
623 "layout(location = 0) in vec2 a_position;\n"
624 "layout(location = 1) in vec2 a_texCoord;\n"
625 "layout(location = 2) in vec3 a_inst_position;\n"
626 "layout(location = 3) in vec2 a_inst_size;\n"
627 "layout(location = 4) in float a_inst_rotation;\n"
628 "layout(location = 5) in vec4 a_inst_color;\n"
629 "layout(location = 6) in vec4 a_inst_uv;\n"
630 "layout(location = 7) in vec4 a_inst_extra;\n"
632 "layout(location = 0) in vec3 a_position;\n"
633 "layout(location = 1) in vec4 a_color;\n"
634 "layout(location = 2) in vec2 a_texCoord;\n"
635 "#ifdef MESH_NORMALS\n"
636 "layout(location = 3) in vec3 a_normal;\n"
638 "#ifdef MESH_LIGHTMAP\n"
639 "layout(location = 7) in vec2 a_texCoord1;\n"
641 "#ifdef MESH_TANGENTS\n"
642 "layout(location = 4) in vec4 a_tangent;\n"
645 + std::string(lit ?
"#if !defined(MESH) && !defined(SKINNED)\n"
646 "layout(location = 4) in float a_lightLayer;\n"
649 "layout(location = 5) in uvec4 a_joints;\n"
650 "layout(location = 6) in vec4 a_weights;\n"
652 "layout(std140) uniform SkinConstants {\n"
661 + morphHelpersGLSL() +
666 "invariant gl_Position;\n"
667 "out vec4 v_color;\n"
668 "out vec2 v_texCoord;\n"
669 "#ifdef MESH_NORMALS\n"
670 "out highp vec3 v_worldNormal;\n"
671 "out highp vec3 v_worldXYZ;\n"
672 "#ifdef MESH_TANGENTS\n"
673 "out highp vec4 v_worldTangent;\n"
677 "out highp vec4 v_particle;\n"
679 "#ifdef MESH_LIGHTMAP\n"
680 "out highp vec3 v_lightmap;\n"
681 "out highp vec2 v_texCoord1;\n"
684 "#ifdef MESH_LOCAL_POSITION\n"
685 "out highp vec3 v_localPos;\n"
688 src +=
"out highp vec2 v_worldPos;\n";
690 src +=
"flat out highp float v_lightLayer;\n";
701 " vec3 local = a_position;\n"
702 "#ifdef MESH_NORMALS\n"
703 " vec3 localNormal = a_normal;\n"
705 " vec3 localNormal = vec3(0.0, 0.0, 1.0);\n"
708 " esApplyMorph(local, localNormal);\n"
715 " vec2 scaled = a_position * a_inst_size;\n"
716 " float cosR = cos(a_inst_rotation);\n"
717 " float sinR = sin(a_inst_rotation);\n"
718 " vec2 rotated = vec2(scaled.x * cosR - scaled.y * sinR,\n"
719 " scaled.x * sinR + scaled.y * cosR);\n"
720 " highp vec3 fwd = viewDirection(a_inst_position);\n"
722 " highp vec3 refUp = abs(fwd.y) > 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(0.0, 1.0, 0.0);\n"
723 " highp vec3 right = normalize(cross(refUp, fwd));\n"
724 " highp vec3 up = cross(fwd, right);\n"
725 " vec4 world = vec4(a_inst_position + right * rotated.x + up * rotated.y, 1.0);\n"
726 " v_color = vec4(a_inst_color.rgb * a_inst_extra.z, a_inst_color.a);\n"
727 " v_particle = vec4(a_inst_extra.x, a_inst_extra.y, a_inst_extra.w, a_inst_extra.z);\n"
730 "#elif defined(SKINNED)\n"
731 " mat4 skin = a_weights.x * u_bones[a_joints.x]\n"
732 " + a_weights.y * u_bones[a_joints.y]\n"
733 " + a_weights.z * u_bones[a_joints.z]\n"
734 " + a_weights.w * u_bones[a_joints.w];\n"
735 " vec4 world = skin * vec4(local, 1.0);\n"
736 " v_color = a_color * esInstanceTint();\n"
737 "#elif defined(MESH)\n"
738 " vec4 world = esInstanceModel() * vec4(local, 1.0);\n"
739 " v_color = @@GLSL_MESH_COLOR@@ * esInstanceTint();\n"
741 " vec4 world = vec4(a_position, 1.0);\n"
742 " v_color = a_color;\n"
744 " gl_Position = u_projection * world;\n"
747 " v_texCoord = a_texCoord * a_inst_uv.zw + a_inst_uv.xy;\n"
749 " v_texCoord = a_texCoord;\n"
751 "#ifdef MESH_NORMALS\n"
753 "#if defined(PARTICLE)\n"
754 " v_worldNormal = fwd;\n"
755 "#elif defined(SKINNED)\n"
756 " v_worldNormal = mat3(skin) * localNormal;\n"
758 " v_worldNormal = esInstanceNormalMatrix() * localNormal;\n"
760 " v_worldXYZ = world.xyz;\n"
761 "#ifdef MESH_TANGENTS\n"
763 " v_worldTangent = vec4(mat3(skin) * a_tangent.xyz, a_tangent.w);\n"
765 " mat3 tangentModel = mat3(esInstanceModel());\n"
767 " v_worldTangent = vec4(tangentModel * a_tangent.xyz, determinant(tangentModel) < 0.0 ? -a_tangent.w : a_tangent.w);\n"
771 "#ifdef MESH_LIGHTMAP\n"
772 " highp vec4 lmRect = esInstanceLightmapRect();\n"
773 " v_lightmap = vec3(a_texCoord1 * lmRect.xy + lmRect.zw,\n"
774 " lmRect.x > 0.0 ? 1.0 : 0.0);\n"
775 " v_texCoord1 = a_texCoord1;\n"
777 "#if defined(MESH_LOCAL_POSITION) && defined(MESH)\n"
778 " v_localPos = a_position;\n"
781 src +=
" v_worldPos = world.xy;\n";
782 src +=
"#if !defined(MESH) && !defined(SKINNED) && !defined(PARTICLE)\n v_lightLayer = a_lightLayer;\n#else\n v_lightLayer = 0.0;\n#endif\n";
785 src +=
"#ifdef PARTICLE\n v_probeSlot = 0.0;\n#else\n v_probeSlot = float(ES_INSTANCE_ID);\n#endif\n";
788 fillHook(src,
"@@GLSL_MESH_COLOR@@", hook.empty() ? std::string(
"a_color") : std::string(
"es_vertexColor"));
789 fillHook(src,
"@@GLSL_HOOK@@", hook.empty() ? std::string() :
790 "#ifdef MESH\nhighp vec4 es_vertexColor;\nhighp vec2 es_vertexUv1;\n" + hook +
"\n#endif\n");
791 fillHook(src,
"@@GLSL_CALL@@", hook.empty() ? std::string() :
792 " es_vertexColor = a_color;\n#ifdef MESH_LIGHTMAP\n es_vertexUv1 = a_texCoord1;\n#else\n es_vertexUv1 = vec2(0.0);\n#endif\n"
793 " esMaterialVertex(local, localNormal, a_texCoord);\n");
803std::string normalizeDomain(
const std::string& authored) {
804 if (authored ==
"Lit2D")
return "Lit";
805 if (authored ==
"Unlit2D")
return "Unlit";
826bool identChar(
char c) {
return std::isalnum(
static_cast<unsigned char>(c)) || c ==
'_'; }
828std::string declaredName(std::string_view decl) {
829 const size_t bracket = decl.find(
'[');
830 if (bracket != std::string_view::npos) decl = decl.substr(0, bracket);
831 while (!decl.empty() && !identChar(decl.back())) decl.remove_suffix(1);
832 size_t start = decl.size();
833 while (start > 0 && identChar(decl[start - 1])) --start;
834 return std::string(decl.substr(start));
837void collectUniformNames(
const std::string& glsl, std::unordered_map<std::string, std::string>& out) {
839 while ((at = glsl.find(
"uniform ", at)) != std::string::npos) {
840 if (at > 0 &&
identChar(glsl[at - 1])) { at += 8;
continue; }
841 const size_t end = glsl.find_first_of(
"{;", at);
842 if (end == std::string::npos)
break;
843 if (glsl[end] ==
';') {
844 const std::string name = declaredName(std::string_view(glsl).substr(at, end - at));
845 if (!name.empty()) out.emplace(name,
"a uniform");
849 const std::string block = declaredName(std::string_view(glsl).substr(at, end - at));
850 const size_t close = glsl.find(
'}', end);
851 if (close == std::string::npos)
break;
852 size_t member = end + 1;
853 while (member < close) {
854 const size_t semi = glsl.find(
';', member);
855 if (semi == std::string::npos || semi > close)
break;
856 std::string_view line = std::string_view(glsl).substr(member, semi - member);
857 const size_t hash = line.rfind(
'\n');
858 if (hash != std::string_view::npos) line = line.substr(hash + 1);
859 const std::string name = declaredName(line);
860 if (!name.empty() && line.find(
'#') == std::string_view::npos) out.emplace(name, block);
867const std::unordered_map<std::string, std::string>& engineUniformNames(
const ParsedShader& parsed) {
868 static std::mutex lock;
869 static std::unordered_map<std::string, std::unordered_map<std::string, std::string>> byDomain;
870 std::lock_guard<std::mutex> guard(lock);
871 const std::string key = parsed.domain + (parsed.vertexIsCanonical ?
"|canonical" :
"|own");
872 auto found = byDomain.find(key);
873 if (found != byDomain.end())
return found->second;
877 probe.version = parsed.version;
878 probe.domain = parsed.domain;
879 probe.vertexIsCanonical = parsed.vertexIsCanonical;
882 const std::vector<std::string> everything{
883 "MESH",
"MESH_NORMALS",
"MESH_TANGENTS",
"MESH_LIGHTMAP",
"SKINNED",
"ES_RECEIVE_SHADOW",
884 "ES_ENV_MAP",
"ES_SURFACE_3D",
"ES_GBUFFER",
"ES_VELOCITY",
"ES_OPAQUE"};
885 auto& names = byDomain[key];
904 result.
valid =
false;
906 if (source.empty()) {
911 std::string expanded;
913 std::unordered_set<std::string> active;
914 std::string includeError;
915 if (!expandIncludes(source, std::string{}, resolver, active, 0,
922 LineReader stream(expanded);
925 std::string currentVariantName;
926 TextBuilder currentSection;
927 std::vector<SourceLine> currentSectionMap;
928 bool currentSectionIsWGSL =
false;
929 bool currentSectionIsFullWGSL =
false;
932 while (stream.next(line)) {
934 std::string directive, argument;
935 parseDirective(line, directive, argument);
937 if (directive ==
"shader") {
938 if (argument.size() >= 2 && argument.front() ==
'"' && argument.back() ==
'"') {
939 result.
name = argument.substr(1, argument.size() - 2);
941 result.
name = argument;
946 if (directive ==
"version") {
951 if (directive ==
"feature") {
954 if (!argument.empty()) result.
features.push_back(argument);
958 if (directive ==
"param") {
966 if (directive ==
"coverage") {
971 if (directive ==
"tips") {
976 if (directive ==
"hairshadow") {
981 if (directive ==
"gbuffer") {
986 if (directive ==
"lights") {
991 if (directive ==
"highprecision") {
996 if (directive ==
"depthinput") {
1001 if (directive ==
"vertexbounds") {
1003 result.
vertexBounds = std::strtof(argument.c_str(),
nullptr);
1008 if (directive ==
"vertexoffset") {
1010 result.
errorMessage =
"Unexpected #pragma vertexoffset at line " + std::to_string(lineNumber);
1013 if (!argument.empty() && argument !=
"wgsl") {
1014 result.
errorMessage =
"Unknown vertexoffset language '" + argument +
"' at line " +
1015 std::to_string(lineNumber) +
" (expected no tag for GLSL, or 'wgsl')";
1019 currentSectionIsWGSL = !argument.empty();
1020 currentSectionIsFullWGSL =
false;
1021 currentSection.str(
"");
1022 currentSection.clear();
1023 currentSectionMap.clear();
1027 if (directive ==
"domain") {
1028 if (!argument.empty()) result.
domain = normalizeDomain(argument);
1032 if (directive ==
"lighting") {
1038 if (directive ==
"switch") {
1042 decl.
name = nextToken(argument, swPos);
1043 if (!decl.
name.empty()) {
1044 const usize p = argument.find(
"default(");
1045 if (p != std::string::npos) {
1046 const usize open = p + 8;
1047 const usize close = argument.find(
')', open);
1048 if (close != std::string::npos) {
1049 const std::string v = trim(argument.substr(open, close - open));
1050 decl.
defaultOn = (v ==
"on" || v ==
"true" || v ==
"1");
1058 if (directive ==
"properties") {
1060 result.
errorMessage =
"Unexpected #pragma properties at line " + std::to_string(lineNumber);
1067 if (directive ==
"vertex" || directive ==
"fragment") {
1069 result.
errorMessage =
"Unexpected #pragma " + directive +
1070 " at line " + std::to_string(lineNumber);
1077 if (!argument.empty() && argument !=
"wgsl" && argument !=
"wgsl full") {
1078 result.
errorMessage =
"Unknown stage language '" + argument +
1079 "' at line " + std::to_string(lineNumber) +
1080 " (expected no tag for GLSL, 'wgsl', or 'wgsl full')";
1084 currentSectionIsWGSL = !argument.empty();
1085 currentSectionIsFullWGSL = (argument ==
"wgsl full");
1086 currentSection.str(
"");
1087 currentSection.clear();
1088 currentSectionMap.clear();
1092 if (directive ==
"variant") {
1094 result.
errorMessage =
"Unexpected #pragma variant at line " + std::to_string(lineNumber);
1098 currentVariantName = argument;
1099 currentSection.str(
"");
1100 currentSection.clear();
1101 currentSectionMap.clear();
1105 if (directive ==
"end") {
1115 stages[s] = currentSection.str();
1116 maps[s] = std::move(currentSectionMap);
1117 if (currentSectionIsWGSL && currentSectionIsFullWGSL) {
1120 currentSectionMap.clear();
1121 currentSectionIsWGSL =
false;
1122 currentSectionIsFullWGSL =
false;
1127 currentSectionMap.clear();
1128 currentSectionIsWGSL =
false;
1131 result.
variants[currentVariantName] = currentSection.str();
1132 currentVariantName.clear();
1133 currentSectionMap.clear();
1144 if (!trim(line).empty() && line[0] !=
'/' && trim(line).substr(0, 2) !=
"//") {
1150 std::string trimmedLine = trim(line);
1151 if (!trimmedLine.empty() && trimmedLine.find(
"uniform") != std::string::npos) {
1153 if (!prop.
name.empty()) {
1164 currentSection << line <<
"\n";
1168 currentSectionMap.push_back(src);
1175 result.
errorMessage =
"Unexpected end of file - missing #pragma end";
1182 if (result.
domain ==
"Unlit" || result.
domain ==
"Lit") {
1185 }
else if (result.
domain ==
"PostProcess") {
1203 if (result.
domain ==
"Unlit" || result.
domain ==
"Lit") {
1206 }
else if (result.
domain ==
"PostProcess") {
1213 const auto& engine = engineUniformNames(result);
1215 const auto clash = engine.find(prop.name);
1216 if (clash == engine.end())
continue;
1217 result.
errorMessage =
"#pragma param '" + prop.name +
"' is reserved: the engine declares it in " +
1218 (clash->second ==
"a uniform" ? std::string(
"a uniform") :
"the " + clash->second +
" block") +
1219 " of every " + result.
domain +
" shader, and on WebGL two declarations of one name do not compile. " +
1220 (clash->second ==
"TimeConstants"
1221 ?
"Read it directly instead (GLSL: u_time.x = seconds, u_time.y = frame delta, u_viewport.xy = canvas pixels; "
1222 "WGSL: tc.u_time / tc.u_viewport). "
1224 "Give a parameter of your own a different name.";
1229 computeMaterialLayout(result);
1231 result.
valid =
true;
1237 const std::string& platform,
1238 const std::vector<std::string>& features,
1244 std::vector<std::string> sorted(features);
1245 std::sort(sorted.begin(), sorted.end());
1247 for (
const auto& f : sorted) {
1248 if (!key.empty()) key +=
'|';
1255 std::vector<std::string> features;
1256 for (
usize start = 0; start <= csv.size();) {
1257 const usize comma = csv.find(
',', start);
1258 const usize end = comma == std::string::npos ? csv.size() : comma;
1259 const std::string f = trim(csv.substr(start, end - start));
1260 if (!f.empty()) features.push_back(f);
1261 if (comma == std::string::npos)
break;
1269usize wordCount(
const std::string&
text,
const std::string& word) {
1271 for (
usize at =
text.find(word); at != std::string::npos; at =
text.find(word, at + word.size())) {
1272 const bool before = at > 0 && (std::isalnum(
static_cast<unsigned char>(
text[at - 1])) ||
text[at - 1] ==
'_');
1273 const usize end = at + word.size();
1274 const bool after = end <
text.size() && (std::isalnum(
static_cast<unsigned char>(
text[end])) ||
text[end] ==
'_');
1275 if (!before && !after) ++n;
1280std::string withoutDefines(std::string text,
const std::vector<std::string>& names) {
1281 for (
const auto& name : names) {
1282 const std::string line =
"#define " + name +
" 1\n";
1283 if (
const usize at = text.find(line); at != std::string::npos) text.erase(at, line.size());
1291 const std::vector<std::string>& features,
1296 std::vector<std::string> kept, dropped;
1297 for (
const auto& f : features) {
1298 const usize defines = wordCount(vertex,
"#define " + f) + wordCount(fragment,
"#define " + f);
1299 (wordCount(vertex, f) + wordCount(fragment, f) > defines ? kept : dropped).push_back(f);
1301 if (dropped.empty())
return features;
1311u32 countNewlines(
const std::string& s) {
1327 default:
return "float";
1348 default:
return "f32";
1355const char* kFrameHeaderWGSL =
1356 "struct FrameConstants {\n"
1357 " projection : mat4x4f,\n"
1358 " camera : vec4f,\n"
1359 " inverseViewProjection : mat4x4f,\n"
1360 " renderOrigin : vec4f,\n"
1362 "@group(0) @binding(0) var<uniform> frame : FrameConstants;\n"
1363 "fn viewDirection(worldPos : vec3f) -> vec3f {\n"
1364 " if (frame.camera.w > 0.5) { return normalize(frame.camera.xyz - worldPos); }\n"
1365 " return frame.camera.xyz;\n"
1368 "fn worldFromDepth(uv : vec2f, depth : f32) -> vec3f {\n"
1369 " let clip = vec4f(uv * 2.0 - 1.0, depth, 1.0);\n"
1370 " let world = frame.inverseViewProjection * clip;\n"
1371 " return world.xyz / world.w;\n"
1373 "fn distanceToEye(worldPos : vec3f) -> f32 {\n"
1374 " if (frame.camera.w > 0.5) { return length(worldPos - frame.camera.xyz); }\n"
1375 " return -dot(worldPos, frame.camera.xyz);\n"
1377 "fn sceneUv(worldPos : vec3f) -> vec2f {\n"
1378 " let clip = frame.projection * vec4f(worldPos, 1.0);\n"
1379 " let w = max(clip.w, 1e-4);\n"
1380 " return clamp(clip.xy / w * 0.5 + 0.5, vec2f(0.001), vec2f(0.999));\n"
1382 "fn sceneDistance(texel : vec4f) -> f32 {\n"
1383 " return select(texel.b * 1024.0, texel.r, texel.r < 65000.0);\n"
1386const char* kTimeHeaderWGSL =
1387 "struct TimeConstants { u_time : vec4f, u_viewport : vec4f, u_quality : vec4f };\n"
1388 "@group(0) @binding(3) var<uniform> tc : TimeConstants;\n";
1397 for (
const auto& p : parsed.properties) {
1400 mask |= 1u << p.textureUnit;
1406std::string wgslBatchTextureDecls(
bool postProcess,
u32 materialUnits = 0) {
1408 for (
u32 i = 0; i < 8; ++i) {
1410 if ((materialUnits & (1u << i)) != 0)
continue;
1411 const std::string n = std::to_string(i);
1416 src +=
"@group(1) @binding(" + n +
") var t" + n +
" : texture_depth_2d;\n";
1419 src +=
"@group(1) @binding(" + n +
") var t" + n +
" : texture_2d<f32>;\n";
1420 src +=
"@group(1) @binding(" + std::to_string(8 + i) +
") var s" + n +
" : sampler;\n";
1431std::string wgslReachedTextureDecls(
const std::string& source,
bool postProcess) {
1438 const std::string n = std::to_string(unit);
1439 if ((reachedTex & (1u << unit)) != 0
1445 :
" : texture_2d<f32>;\n");
1447 if ((reachedSam & (1u << unit)) != 0
1463std::string wgslMaterialTextureDecls(
const ParsedShader& parsed,
const std::string& body,
const std::string* only =
nullptr) {
1466 for (
const auto& p : parsed.properties) {
1468 if (only && only->find(p.name) == std::string::npos)
continue;
1469 const u32 unit =
static_cast<u32>(p.textureUnit);
1471 (p.layered ?
" : texture_2d_array<f32>;\n" :
" : texture_2d<f32>;\n");
1472 if (body.find(p.name +
"_s") == std::string::npos || (declared & (
u64{1} <<
samplerBindingForUnit(unit))) != 0)
continue;
1485const char* kColorHelpersWGSL = R
"(fn srgbToLinear(c : vec3f) -> vec3f {
1486 return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3f(2.4)), step(vec3f(0.04045), c));
1488fn linearToSrgb(c : vec3f) -> vec3f {
1489 return mix(c * 12.92, 1.055 * pow(c, vec3f(1.0 / 2.4)) - 0.055, step(vec3f(0.0031308), c));
1491fn acesFilmic(x : vec3f) -> vec3f {
1492 return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), vec3f(0.0), vec3f(1.0));
1494fn pbrNeutral(color : vec3f) -> vec3f {
1495 let startCompression = 0.8 - 0.04;
1496 let desaturation = 0.15;
1498 let x = min(c.r, min(c.g, c.b));
1500 if (x < 0.08) { offset = x - 6.25 * x * x; }
1501 c = c - vec3f(offset);
1502 let peak = max(c.r, max(c.g, c.b));
1503 if (peak < startCompression) { return c; }
1504 let d = 1.0 - startCompression;
1505 let newPeak = 1.0 - d * d / (peak + d - startCompression);
1506 c = c * (newPeak / peak);
1507 let g = 1.0 - 1.0 / (desaturation * (peak - newPeak) + 1.0);
1508 return mix(c, vec3f(newPeak), g);
1515const char* kPostLightHeaderWGSL = R
"(struct Light { posDir : vec4f, color : vec4f, spot : vec4f, shadow : vec4f, shadowMap : vec4f, falloff : vec4f };
1516struct LightConstants {
1518 u_lights : array<Light, 16>,
1519 u_mask2DRect : vec4f,
1520 u_shadowMatrix : array<mat4x4f, 16>,
1521 u_shadowTile : array<vec4f, 16>,
1522 u_shadowParams : vec4f,
1523 u_envIrradiance : array<vec4f, 9>,
1524 u_envParams : vec4f,
1526 u_reflParams : vec4f,
1527 u_reflBox : array<vec4f, 30>,
1528 u_bakedTint : vec4f,
1529 tiledLights : array<Light, 96>,
1530 tileMask : array<vec4u, 192>,
1533@group(0) @binding(2) var<uniform> lc : LightConstants;
1534fn unpackDepth(c : vec3f) -> f32 {
1535 return dot(c, vec3f(1.0, 1.0 / 255.0, 1.0 / 65025.0));
1537// The first directional light that shines: xyz = where it stands in the sky, w = 1 (0 = none),
1538// color = its colour and strength, tiles = x first atlas tile, y how many.
1539struct Sun { dir : vec4f, color : vec4f, tiles : vec2i };
1540fn findSun() -> Sun {
1543 s.color = vec4f(0.0);
1544 s.tiles = vec2i(0, 0);
1545 for (var i = 0; i < 16; i++) {
1546 let l = lc.u_lights[i];
1547 if (l.posDir.z > 0.5 && l.posDir.z < 1.5 && l.color.a > 0.0) {
1548 s.dir = vec4f(-normalize(vec3f(l.posDir.x, l.posDir.y, l.posDir.w)), 1.0);
1550 s.tiles = vec2i(i32(l.shadowMap.x), i32(l.shadowMap.y % 8.0));
1556fn sunVisibility(worldPos : vec3f, first : i32, count : i32) -> f32 {
1557 if (lc.u_shadowParams.x < 0.5 || count <= 0) { return 1.0; }
1558 for (var k = 0; k < 16; k++) {
1559 if (k >= count) { break; }
1561 let m = lc.u_shadowMatrix[t];
1562 let c = m * vec4f(worldPos, 1.0);
1563 if (c.w <= 0.0) { continue; }
1564 let proj = c.xyz / c.w;
1565 let uv = proj.xy * 0.5 + 0.5;
1566 if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 || proj.z < 0.0 || proj.z > 1.0) { continue; }
1567 let rect = lc.u_shadowTile[t];
1568 let at = rect.xy + uv * rect.z;
1569 let lo = rect.xy + lc.u_shadowParams.y * 0.5;
1570 let hi = rect.xy + rect.z - lc.u_shadowParams.y * 0.5;
1571 let d = unpackDepth(textureSampleLevel(t2, s2, clamp(at, lo, hi), 0.0).rgb);
1572 return select(1.0, 0.0, d < clamp(proj.z * 0.5 + 0.5, 0.0, 1.0) - 0.0025);
1578const char* kLitHeaderWGSL = R
"(struct Light { posDir : vec4f, color : vec4f, spot : vec4f, shadow : vec4f, shadowMap : vec4f, falloff : vec4f };
1579struct LightConstants {
1581 u_lights : array<Light, 16>,
1582 u_mask2DRect : vec4f,
1583 u_shadowMatrix : array<mat4x4f, 16>,
1584 u_shadowTile : array<vec4f, 16>,
1585 u_shadowParams : vec4f,
1586 u_envIrradiance : array<vec4f, 9>,
1587 u_envParams : vec4f,
1589 u_reflParams : vec4f,
1590 u_reflBox : array<vec4f, 30>,
1591 u_bakedTint : vec4f,
1592 tiledLights : array<Light, 96>,
1593 tileMask : array<vec4u, 192>,
1595 u_ambientGround : vec4f,
1596 u_tileView : mat4x4f,
1597 u_waterRect : vec4f,
1598 u_waterDepth : vec4f,
1601@group(0) @binding(2) var<uniform> lc : LightConstants;
1602struct ProbeConstants { u_probeIrradiance : array<vec4f, 1000>, u_probeTail : vec4f };
1603@group(0) @binding(7) var<uniform> pc : ProbeConstants;
1605#ifndef MESH_LIGHTMAP
1606// The frame's probe atlas, a volume of bricks read per pixel, on the bake's unit: only resident 3D surfaces carry probe runs,
1607// and a variant reading a bake has that unit's 2D atlas instead.
1608@group(1) @binding(5) var t5 : texture_3d<f32>;
1609@group(1) @binding(13) var s5 : sampler;
1612struct PlanarConstants { planarProjection : mat4x4f, planarParams : vec4f };
1613@group(0) @binding(9) var<uniform> planar : PlanarConstants;
1614// Which run of that block this fragment's instance reads. WGSL has no module
1615// varying, so the entry point hands it over — the GLSL twin reads the varying
1616// straight, which is the one place the two stages differ in shape.
1617var<private> g_probeSlot : f32 = 0.0;
1618// Set by a hair shader before it lights: how much of the light a layer of strands takes, per world unit along it (0 = a surface, a hard compare).
1619var<private> g_hairShadow : f32 = 0.0;
1620// Set by a shader that lights a surface the sun seldom shadows (the sea) before it lights: the shadow is read as an edge a source with no size
1621// throws, nine taps, and not as the penumbra of the sun's size, a search and a filter of up to sixty-four.
1622var<private> g_shadowHard : f32 = 0.0;
1623// The GLSL twin's v_lightmap, handed over by the entry point like the slot above.
1624var<private> g_lightmap : vec3f = vec3f(0.0);
1625// Where the surface being lit stands, for a volume read per pixel: set by whatever lights it (the BRDF, envRadiance).
1626var<private> g_probePos : vec3f = vec3f(0.0);
1627// The mesh's own tangent frame, handed over by the entry point like the slot above; zero where the shader never sets it, which
1628// is what sends perturbNormal back to deriving a frame per pixel.
1629var<private> g_worldTangent : vec4f = vec4f(0.0);
1630fn packDepth(d : f32) -> vec3f {
1631 let enc = fract(d * vec3f(1.0, 255.0, 65025.0));
1632 return enc - enc.yzz * vec3f(1.0 / 255.0, 1.0 / 255.0, 0.0);
1634fn unpackDepth(c : vec3f) -> f32 {
1635 return dot(c, vec3f(1.0, 1.0 / 255.0, 1.0 / 65025.0));
1637fn stepFor(texel : f32, slope : f32, reach : f32) -> f32 {
1638 // How far toward the light a lookup has to ask from: one texel of doubt about where
1639 // the map sampled this surface, plus whatever `reach` texels of it are worth at the
1641 return texel * (1.5 * (1.0 + slope) + reach * slope);
1643fn shadowDepth(m : mat4x4f, p : vec3f) -> f32 {
1644 let c = m * vec4f(p, 1.0);
1645 return clamp(c.z / max(c.w, 1e-6) * 0.5 + 0.5, 0.0, 1.0);
1647fn shadowTap(at : vec2f, lo : vec2f, hi : vec2f, here : f32) -> f32 {
1648#ifdef ES_RECEIVE_SHADOW
1649 // A tap that leaves its tile reads another map entirely — a neighbouring cube face,
1650 // which is the least related depth in the atlas.
1651 let d = unpackDepth(textureSampleLevel(t2, s2, clamp(at, lo, hi), 0.0).rgb);
1652 return select(1.0, 0.0, d < here);
1654 // The map's sampler is only declared where a shader receives one.
1658fn diskTap(i : i32, n : i32, radius : f32) -> vec2f {
1659 // A spiral, not a table: the golden angle spreads any number of taps evenly over a
1660 // disc, so the pattern follows the count instead of being pasted in beside it.
1661 let a = f32(i) * 2.3999632;
1662 // Turned over in v for the reason the tile's rect is: an offset in texture space
1663 // follows the axis the texture is sampled along, and this backend's runs the other
1664 // way. A spiral is not its own mirror, so without this the two average other points.
1665 return radius * sqrt((f32(i) + 0.5) / f32(n)) * vec2f(cos(a), -sin(a));
1667// The same spiral turned by `spin` radians: a disc wider than the taps can cover without gaps between them bands where the same spiral
1668// lands on every pixel, and turning it by an angle that differs from one point of the surface to the next makes that grain instead.
1669fn diskTapSpun(i : i32, n : i32, radius : f32, spin : f32) -> vec2f {
1670 let a = f32(i) * 2.3999632 + spin;
1671 return radius * sqrt((f32(i) + 0.5) / f32(n)) * vec2f(cos(a), -sin(a));
1673// A turn for the spiral, fixed to the point of the surface (so it does not crawl as the camera moves).
1674fn shadowSpin(worldPos : vec3f) -> f32 {
1675 return 6.2831853 * fract(sin(dot(worldPos, vec3f(12.9898, 78.233, 37.719))) * 43758.5453);
1679R
"(// The spiral taps for 8, 16 and 32 points, as numbers (see the GLSL twin): each is turned by the pixel's own spin where it is used.
1680const kSpiral8 = array<vec2f, 8>(
1681 vec2f(0.2500000, 0.0000000),
1682 vec2f(-0.3192901, 0.2924959),
1683 vec2f(0.0488724, -0.5568765),
1684 vec2f(0.4024445, 0.5249175),
1685 vec2f(-0.7385351, -0.1306364),
1686 vec2f(0.6996049, -0.4450315),
1687 vec2f(-0.2340040, 0.8704838),
1688 vec2f(-0.4462715, -0.8592682)
1690const kInner5 = array<vec2f, 5>(vec2f(0.0), vec2f(1.5, 0.0), vec2f(-1.5, 0.0), vec2f(0.0, 1.5), vec2f(0.0, -1.5));
1691const kSpiral16 = array<vec2f, 16>(
1692 vec2f(0.1767767, 0.0000000),
1693 vec2f(-0.2257722, 0.2068258),
1694 vec2f(0.0345580, -0.3937712),
1695 vec2f(0.2845713, 0.3711727),
1696 vec2f(-0.5222232, -0.0923739),
1697 vec2f(0.4946953, -0.3146848),
1698 vec2f(-0.1654658, 0.6155250),
1699 vec2f(-0.3155616, -0.6075943),
1700 vec2f(0.6846422, 0.2500301),
1701 vec2f(-0.7122560, 0.2940091),
1702 vec2f(0.3433543, -0.7337287),
1703 vec2f(0.2537305, 0.8089319),
1704 vec2f(-0.7647461, -0.4431856),
1705 vec2f(0.8971339, -0.1972327),
1706 vec2f(-0.5475066, 0.7787725),
1707 vec2f(-0.1264872, -0.9760896)
1709const kSpiral32 = array<vec2f, 32>(
1710 vec2f(0.1250000, 0.0000000),
1711 vec2f(-0.1596450, 0.1462479),
1712 vec2f(0.0244362, -0.2784383),
1713 vec2f(0.2012223, 0.2624588),
1714 vec2f(-0.3692676, -0.0653182),
1715 vec2f(0.3498024, -0.2225157),
1716 vec2f(-0.1170020, 0.4352419),
1717 vec2f(-0.2231357, -0.4296341),
1718 vec2f(0.4841152, 0.1767979),
1719 vec2f(-0.5036411, 0.2078959),
1720 vec2f(0.2427881, -0.5188246),
1721 vec2f(0.1794146, 0.5720012),
1722 vec2f(-0.5407571, -0.3133795),
1723 vec2f(0.6343695, -0.1394646),
1724 vec2f(-0.3871456, 0.5506753),
1725 vec2f(-0.0894400, -0.6901996),
1726 vec2f(0.5490720, 0.4627580),
1727 vec2f(-0.7388785, 0.0305553),
1728 vec2f(0.5389548, -0.5363326),
1729 vec2f(-0.0360577, 0.7797915),
1730 vec2f(-0.5128179, -0.6145265),
1731 vec2f(0.8123597, 0.1093013),
1732 vec2f(-0.6883103, 0.4789091),
1733 vec2f(0.1880855, -0.8360615),
1734 vec2f(0.4350338, 0.7591907),
1735 vec2f(-0.8504486, -0.2713156),
1736 vec2f(0.8261021, -0.3816809),
1737 vec2f(-0.3578875, 0.8551558),
1738 vec2f(-0.3194081, -0.8880335),
1739 vec2f(0.8499090, 0.4466874),
1740 vec2f(-0.9440344, 0.2488453),
1741 vec2f(0.5365950, -0.8345303)
1743// What of the sun a sky's clouds leave at a world point. See the GLSL twin.
1744fn cloudShadow3D(worldPos : vec3f, t : i32) -> f32 {
1745#ifndef ES_RECEIVE_SHADOW
1748 let uv = (lc.u_shadowMatrix[t] * vec4f(worldPos, 1.0)).xy * 0.5 + 0.5;
1749 if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { return 1.0; }
1750 let rect = lc.u_shadowTile[t];
1751 let texel = lc.u_shadowParams.y;
1752 let p = (rect.xy + uv * rect.z) / texel - 0.5;
1754 let at = (floor(p) + 0.5) * texel;
1755 let lo = rect.xy + texel * 0.5;
1756 let hi = rect.xy + rect.z - texel * 0.5;
1757 let a = textureSampleLevel(t2, s2, clamp(at, lo, hi), 0.0).a;
1758 let b = textureSampleLevel(t2, s2, clamp(at + vec2f(texel, 0.0), lo, hi), 0.0).a;
1759 let c = textureSampleLevel(t2, s2, clamp(at + vec2f(0.0, texel), lo, hi), 0.0).a;
1760 let d = textureSampleLevel(t2, s2, clamp(at + vec2f(texel), lo, hi), 0.0).a;
1761 return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
1764fn shadowFactor3D(worldPos : vec3f, N : vec3f, L : vec3f, source : vec2f,
1765 first : i32, count : i32) -> f32 {
1766#ifndef ES_RECEIVE_SHADOW
1769 if (lc.u_shadowParams.x < 0.5) { return 1.0; }
1770 let NoL = clamp(dot(N, L), 0.0, 1.0);
1771 // Nearest tile first: a light's tiles overlap, and the first one covering a
1772 // fragment is the one that spends the most texels on it.
1773 for (var k = 0; k < 16; k++) {
1774 if (k >= count) { break; }
1776 let m = lc.u_shadowMatrix[t];
1777 let lcp = m * vec4f(worldPos, 1.0);
1778 // Behind the light, where a divide by a negative w mirrors the point into the
1779 // map's own square and shadows it against whatever the light sees the other
1780 // way. A cube's six faces have five of themselves behind each one.
1781 if (lcp.w <= 0.0) { continue; }
1782 let proj = lcp.xyz / lcp.w;
1783 let uv = proj.xy * 0.5 + 0.5;
1784 // Depth counts as outside as much as the square does: this matrix and the one
1785 // that wrote the map both run z over [0, 1], so past either end is somewhere
1786 // the map never saw.
1787 if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0
1788 || proj.z < 0.0 || proj.z > 1.0) { continue; }
1789 let rect = lc.u_shadowTile[t];
1790 let biasTexels = floor(rect.w);
1791 let bias = vec2f(biasTexels * (1.0 / 64.0), rect.w - biasTexels);
1792 let slope = sqrt(1.0 - NoL * NoL) / max(NoL, bias.y);
1793 // One texel of this tile in WORLD units where this fragment stands: the matrix's
1794 // x scale is clip per world, w how far away this is (1 where the map has no eye),
1795 // and the rect over one atlas texel how many texels the square holds.
1796 let texels = max(rect.z / max(lc.u_shadowParams.y, 1e-9), 1.0);
1797 let across = length(vec3f(m[0].x, m[1].x, m[2].x));
1798 let texel = 2.0 * lcp.w / max(across * texels, 1e-9);
1799 // A step in world units toward the light, not a shifted answer, so one expression serves a cascade and a cone - but only as far
1800 // as a slope of 1.2 asks, the rest of the clearance along the normal: all of it toward the light is eleven texels on a wall the
1801 // sun grazes, further than a ceiling is thick where a texel is coarse, and the wall's top came out lit.
1802 let lean = min(slope, 1.2);
1803 let biasStep = texel * bias.x;
1804 let aside = worldPos + N * (biasStep * max(sqrt(1.0 - NoL * NoL) - lean * NoL, 0.0));
1805 let lcq = m * vec4f(aside, 1.0);
1806 let uvq = lcq.xy / max(lcq.w, 1e-6) * 0.5 + 0.5;
1807 let here = shadowDepth(m, aside + L * (biasStep * (1.0 + lean)));
1808 let at0 = rect.xy + uvq * rect.z;
1809 let lo = rect.xy + lc.u_shadowParams.y * 0.5;
1810 let hi = rect.xy + rect.z - lc.u_shadowParams.y * 0.5;
1811 // How wide the source is in the unit this map measures depth in: world units
1812 // where its w varies with position, so it has an eye to measure them from, and
1813 // the tangent of the angle it subtends where its w is 1 everywhere.
1814 let hasEye = length(vec3f(m[0].w, m[1].w, m[2].w)) > 0.5;
1815 let src = select(source.y, source.x, hasEye);
1816#ifndef ES_LIGHT_DIRECT
1817 // Hair: layers of strand cards a few millimetres apart are not a wall. The light left after a depth of them falls off with that depth, from the
1818 // nearest card (what the map holds) to this one, the way a deep shadow map reads it. A blocker within a couple of texels toward the light is
1819 // this card's own surface and does not count.
1820 if (g_hairShadow > 0.0) {
1821 let reachHair = shadowDepth(m, worldPos + L * stepFor(texel, slope, 2.0));
1824 for (var i = 0; i < 8; i++) {
1825 let at = clamp(at0 + diskTap(i, 8, 2.0) * lc.u_shadowParams.y, lo, hi);
1826 let d = unpackDepth(textureSampleLevel(t2, s2, at, 0.0).rgb);
1827 if (d < reachHair) { sumHair += d; hitsHair += 1.0; }
1829 if (hitsHair < 0.5) { return 1.0; }
1830 let Ah = length(vec3f(m[0].z, m[1].z, m[2].z));
1831 let zbh = 2.0 * (sumHair / hitsHair) - 1.0;
1832 var spanHair = (proj.z - zbh) / max(Ah, 1e-9);
1833 if (hasEye) { spanHair = lcp.w - lcp.w * (Ah - proj.z) / max(Ah - zbh, 1e-6); }
1834 return mix(1.0, exp(-g_hairShadow * max(spanHair, 0.0)), hitsHair * 0.125);
1837 // A source with no size throws one edge: a tent over the 3x3 texels around the
1838 // point, weighted by where it falls among them. Equal weights step at every
1839 // texel and the map's grid shows along the edge; a 2x2 still stair-steps it.
1840#ifdef ES_LIGHT_DIRECT
1843 if (src <= 0.0 || g_shadowHard > 0.5) {
1845 let texelUv = lc.u_shadowParams.y;
1846 let f = at0 / texelUv - 1.0;
1847 let c = (floor(f) + 0.5) * texelUv;
1849 let wx = array<f32, 3>((1.0 - t.x) * 0.5, 0.5, t.x * 0.5);
1850 let wy = array<f32, 3>((1.0 - t.y) * 0.5, 0.5, t.y * 0.5);
1852 for (var y = 0; y < 3; y++) {
1853 for (var x = 0; x < 3; x++) {
1854 lit += wx[x] * wy[y] * shadowTap(c + vec2f(f32(x), f32(y)) * texelUv, lo, hi, here);
1859#ifndef ES_LIGHT_DIRECT
1860 // What blocks this fragment, over the whole disc an edge can reach across — and
1861 // against a depth that forgives that reach, since a tap r texels away lands r
1862 // texels along the surface and a one-texel bias would call the slope a blocker.
1863 // Each tap forgives as far as it stands from the point: a disc this wide forgiven as a whole would let a blocker touching the
1864 // surface (a box on a floor) through as lit for a hand's width round its foot.
1865 let spin = shadowSpin(worldPos);
1866 let turn = vec2f(cos(spin), sin(spin));
1867 // See the GLSL twin: the matrix is applied to the direction once, and each tap moves the clip position along it.
1868 let toLight = m * vec4f(L, 0.0);
1869 // The taps are round the moved point: the same step as it took, and what each tap's own distance is worth.
1870 let stepBase = biasStep * (1.0 + lean);
1871 let stepPer = texel * slope;
1874 // See the GLSL twin: the fragment's own texel and the four a step and a half round it, before the sparse wide disc.
1875 for (var i = 0; i < 5; i++) {
1877 let off = vec2f(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);
1878 let at = clamp(at0 + off * lc.u_shadowParams.y, lo, hi);
1879 let d = unpackDepth(textureSampleLevel(t2, s2, at, 0.0).rgb);
1880 let cr = lcq + toLight * (stepBase + max(length(off), 1.0) * stepPer);
1881 let reach = clamp(cr.z / max(cr.w, 1e-6) * 0.5 + 0.5, 0.0, 1.0);
1882 if (d < reach) { sum += d; hits += 1.0; }
1884 let fewBlockers = tc.u_quality.y > 0.0 && tc.u_quality.y < 12.0;
1885 let disc = select(24.0, max(tc.u_quality.w, 0.5), tc.u_quality.w > 0.0);
1887 for (var i = 0; i < 8; i++) {
1888 let p = kSpiral8[i];
1889 let off = disc * vec2f(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);
1890 let at = clamp(at0 + off * lc.u_shadowParams.y, lo, hi);
1891 let d = unpackDepth(textureSampleLevel(t2, s2, at, 0.0).rgb);
1892 let cr = lcq + toLight * (stepBase + max(length(off), 1.0) * stepPer);
1893 let reach = clamp(cr.z / max(cr.w, 1e-6) * 0.5 + 0.5, 0.0, 1.0);
1894 if (d < reach) { sum += d; hits += 1.0; }
1897 for (var i = 0; i < 16; i++) {
1898 let p = kSpiral16[i];
1899 let off = disc * vec2f(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);
1900 let at = clamp(at0 + off * lc.u_shadowParams.y, lo, hi);
1901 let d = unpackDepth(textureSampleLevel(t2, s2, at, 0.0).rgb);
1902 let cr = lcq + toLight * (stepBase + max(length(off), 1.0) * stepPer);
1903 let reach = clamp(cr.z / max(cr.w, 1e-6) * 0.5 + 0.5, 0.0, 1.0);
1904 if (d < reach) { sum += d; hits += 1.0; }
1907 if (hits < 0.5) { return 1.0; }
1908 if (hits > select(20.5, 12.5, fewBlockers)) { return 0.0; }
1909 // How far the receiver stands beyond what blocks it, and how far from the light
1910 // that blocker is. A is the length of the map's depth row, and each kind of map
1911 // inverts its own with it: hyperbolic where it has an eye, linear where w is 1.
1912 let A = length(vec3f(m[0].z, m[1].z, m[2].z));
1913 let zb = 2.0 * (sum / hits) - 1.0;
1915 var span = (proj.z - zb) / max(A, 1e-9);
1917 dbw = lcp.w * (A - proj.z) / max(A - zb, 1e-6);
1920 // A source subtending src/dbw at the blocker throws that much penumbra across the
1921 // span beyond it — which is why a shadow hardens as its caster nears what it
1922 // falls on, and why a sun's angle and a lamp's size are the same expression.
1923 let radius = clamp(src * span / max(dbw * texel, 1e-4), 0.5, disc);
1924 let wide = shadowDepth(m, aside + L * (biasStep * (1.0 + lean) + texel * radius * slope));
1926 if (radius < 1.5 || (tc.u_quality.z > 0.0 && tc.u_quality.z < 12.0)) {
1927 for (var i = 0; i < 8; i++) {
1928 let p = kSpiral8[i];
1929 let off = radius * vec2f(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);
1930 soft += shadowTap(at0 + off * lc.u_shadowParams.y, lo, hi, wide);
1932 return soft * (1.0 / 8.0);
1934 if (radius < 4.0 || (tc.u_quality.z > 0.0 && tc.u_quality.z < 24.0)) {
1935 for (var i = 0; i < 16; i++) {
1936 let p = kSpiral16[i];
1937 let off = radius * vec2f(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);
1938 soft += shadowTap(at0 + off * lc.u_shadowParams.y, lo, hi, wide);
1940 return soft * (1.0 / 16.0);
1942 for (var i = 0; i < 32; i++) {
1943 let p = kSpiral32[i];
1944 let off = radius * vec2f(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);
1945 soft += shadowTap(at0 + off * lc.u_shadowParams.y, lo, hi, wide);
1947 return soft * (1.0 / 32.0);
1955R
"(// The coverage a cut-out's alpha gives this pixel: glTF's MASK, kept where alpha reaches the cutoff and gone where it does not, at every
1956// distance. The cut is sharpened to about a pixel (`edge` is fwidth of the alpha), so under multisampling alpha-to-coverage feathers the
1957// edge instead of stair-stepping it, and without it the cut is the hard one. Seen small, the cut-out holds its area because its mips do:
1958// the cook rescales each level's alpha to the share the full image keeps at the cutoff (preserveAlphaCoverage).
1959fn cutoutCoverage(a : f32, cutoff : f32, edge : f32) -> f32 {
1960 return (a - cutoff) / max(edge, 1e-4) + 0.5;
1962fn sampleNormal(map : texture_2d<f32>, samp : sampler, uv : vec2f) -> vec3f {
1963 let xy = textureSampleLevel(map, samp, uv, 0.0).xy * 2.0 - 1.0;
1964 return vec3f(xy, sqrt(max(0.0, 1.0 - dot(xy, xy))));
1966// Through the mip chain, with gradients the caller took before any branch.
1967fn sampleNormalGrad(map : texture_2d<f32>, samp : sampler, uv : vec2f,
1968 ddx : vec2f, ddy : vec2f) -> vec3f {
1969 let xy = textureSampleGrad(map, samp, uv, ddx, ddy).xy * 2.0 - 1.0;
1970 return vec3f(xy, sqrt(max(0.0, 1.0 - dot(xy, xy))));
1972fn scaleNormal(normal : vec3f, scale : f32) -> vec3f {
1973 let n = normal * vec3f(scale, scale, 1.0);
1974 if (dot(n, n) < 1e-12) { return vec3f(0.0, 0.0, 1.0); }
1975 return normalize(n);
1977fn perturbNormal(N : vec3f, worldPos : vec3f, uv : vec2f, tangentNormal : vec3f) -> vec3f {
1978 // The derivatives first: they are only valid in uniform control flow, and the choice below depends on a variable.
1979 let dp1 = dpdx(worldPos);
1980 // A target's rows are bottom-up here as in GL, so dpdy is GLSL's dFdy.
1981 let dp2 = dpdy(worldPos);
1982 let duv1 = dpdx(uv);
1983 let duv2 = dpdy(uv);
1984 let dp2perp = cross(dp2, N);
1985 let dp1perp = cross(N, dp1);
1986 let T = dp2perp * duv1.x + dp1perp * duv2.x;
1987 let B = dp2perp * duv1.y + dp1perp * duv2.y;
1988 let m = max(dot(T, T), dot(B, B));
1989 let scale = max(dot(dp1, dp1), dot(dp2, dp2)) * max(dot(duv1, duv1), dot(duv2, duv2));
1990 // Each axis to unit length on its own: a texture stretched more along one axis than the other (a face unwrapped into an atlas) has
1991 // a short T beside a long B, and scaling both by the longer one would leave the normal map flat along the short one.
1992 let derived = select(N, normalize(mat3x3f(T * inverseSqrt(max(dot(T, T), 1e-20)), B * inverseSqrt(max(dot(B, B), 1e-20)), N) * tangentNormal),
1994 // The frame the normal map was baked in, when the geometry carries it: the tangent made square to the interpolated normal.
1995 // Chosen by select, not by returning early: behind a branch Metal sinks the derivatives above into it, where a quad the
1996 // triangle only partly covers has lost its helpers, and every pixel along an edge lost its normal map (skin-detail).
1997 let Tg = normalize(g_worldTangent.xyz - N * dot(N, g_worldTangent.xyz));
1998 let Bg = cross(N, Tg) * g_worldTangent.w;
1999 let baked = normalize(mat3x3f(Tg, Bg, N) * tangentNormal);
2000 return select(derived, baked, dot(g_worldTangent.xyz, g_worldTangent.xyz) > 1e-8);
2002// Where a world point lands in this camera's part of a screen-space mask: on the Z = 0
2003// plane, which is the plane a 2D occluder hides things in, and through this same camera
2004// so the landing agrees. Negative x = nothing to read.
2005fn mask2DUv(worldPos : vec2f) -> vec2f {
2006 let clip = frame.projection * vec4f(worldPos, 0.0, 1.0);
2007 if (clip.w <= 0.0) { return vec2f(-1.0, -1.0); }
2008 let ndc = clip.xy / clip.w * 0.5 + 0.5;
2009 return lc.u_mask2DRect.xy + ndc * lc.u_mask2DRect.zw;
2011fn mask2DChannel(m : vec4f, channel : f32) -> f32 {
2012 if (channel < 0.5) { return m.r; }
2013 if (channel < 1.5) { return m.g; }
2014 if (channel < 2.5) { return m.b; }
2017fn shadowFactor2D(channel : f32, worldPos : vec2f) -> f32 {
2018 if (channel < 0.0 || lc.u_mask2DRect.z <= 0.0) { return 1.0; }
2019 let uv = mask2DUv(worldPos);
2020 if (uv.x < 0.0) { return 1.0; }
2021 // Channels 4 to 7 live in the second mask, which takes the shape mask's unit in a frame with no cookie.
2023 if (channel < 3.5) { hidden = mask2DChannel(textureSampleLevel(t7, s7, uv, 0.0), channel); }
2024 else { hidden = mask2DChannel(textureSampleLevel(t6, s6, uv, 0.0), channel - 4.0); }
2025 return 1.0 - min(hidden, 1.0);
2027// What the light's own SHAPE covers here — its cookie, drawn into the shape mask at the
2028// light's place. A light with no shape keeps the whole circle it always had.
2029fn shapeFactor2D(channel : f32, worldPos : vec2f) -> f32 {
2030 if (channel < 0.0 || lc.u_mask2DRect.z <= 0.0) { return 1.0; }
2031 let uv = mask2DUv(worldPos);
2032 if (uv.x < 0.0) { return 1.0; }
2033 return min(mask2DChannel(textureSampleLevel(t6, s6, uv, 0.0), channel), 1.0);
2039R
"(fn distributionGGX(NdotH : f32, a : f32) -> f32 {
2041 let d = NdotH * NdotH * (a2 - 1.0) + 1.0;
2042 return a2 / max(3.14159265 * d * d, 1e-7);
2044fn geometrySmith(NdotV : f32, NdotL : f32, roughness : f32) -> f32 {
2045 let k = (roughness + 1.0) * (roughness + 1.0) * 0.125;
2046 return (NdotV / (NdotV * (1.0 - k) + k)) * (NdotL / (NdotL * (1.0 - k) + k));
2048// Smith's masking-shadowing for GGX, height-correlated, folded with the 1 / (4 NdotV NdotL) of the microfacet BRDF (the visibility term),
2049// at alpha = roughness^2: what the environment term above integrates and what Blender's GGX uses. The Schlick-GGX k = (r + 1)^2 / 8 it
2050// replaces shadows too much at a grazing view and a high roughness, which left the rim of a rough metal a quarter darker under a lamp.
2051fn visibilitySmithGGX(NdotV : f32, NdotL : f32, a : f32) -> f32 {
2053 let gv = NdotL * sqrt(NdotV * NdotV * (1.0 - a2) + a2);
2054 let gl = NdotV * sqrt(NdotL * NdotL * (1.0 - a2) + a2);
2055 return 0.5 / max(gv + gl, 1e-5);
2057fn fresnelSchlick(VdotH : f32, F0 : vec3f) -> vec3f {
2058 return F0 + (vec3f(1.0) - F0) * pow(1.0 - VdotH, 5.0);
2060// The split-sum environment term of GGX (height-correlated Smith, alpha = roughness^2): the scale and bias of F0 over the hemisphere,
2061// fitted to the integral by tools/gen-dfg-fit.py (worst 3%, mean under 0.6%; Karis' fit before it was 21% low for a metal at roughness 0.5).
2062fn envBRDFApprox(NdotV : f32, roughness : f32) -> vec2f {
2063 let tx = (2.0 * (clamp(NdotV, 0.02, 1.0) - 0.02) / 0.98 - 1.0);
2064 let ty = 2.0 * clamp(roughness, 0.0, 1.0) - 1.0;
2067 let px2 = (3.0 * tx * px1 - 1.0 * px0) / 2.0;
2068 let px3 = (5.0 * tx * px2 - 2.0 * px1) / 3.0;
2069 let px4 = (7.0 * tx * px3 - 3.0 * px2) / 4.0;
2070 let px5 = (9.0 * tx * px4 - 4.0 * px3) / 5.0;
2071 let px6 = (11.0 * tx * px5 - 5.0 * px4) / 6.0;
2074 let py2 = (3.0 * ty * py1 - 1.0 * py0) / 2.0;
2075 let py3 = (5.0 * ty * py2 - 2.0 * py1) / 3.0;
2076 let py4 = (7.0 * ty * py3 - 3.0 * py2) / 4.0;
2077 let py5 = (9.0 * ty * py4 - 4.0 * py3) / 5.0;
2078 let py6 = (11.0 * ty * py5 - 5.0 * py4) / 6.0;
2079 let g = 1.0 / (clamp(NdotV, 0.02, 1.0) + 0.1);
2080 let sumMetal = (0.7771111 - 0.2780760 * py1 - 0.0654304 * py2 - 0.0705640 * py3 + 0.0859185 * py4 + 0.0016314 * py5 - 0.0014479 * py6) + px1 * (0.0048182 - 0.1346961 * py1 - 0.1342442 * py2 + 0.1115811 * py3 - 0.0497620 * py4 - 0.0098451 * py5 - 0.0004214 * py6) + px2 * (0.0004797 + 0.0654544 * py1 + 0.0215100 * py2 - 0.0948616 * py3 + 0.0774489 * py4 + 0.0139819 * py5 - 0.0151021 * py6) + px3 * (0.0022918 - 0.0244567 * py1 + 0.0056279 * py2 + 0.0393924 * py3 - 0.0613759 * py4 + 0.0099383 * py5 + 0.0092971 * py6) + px4 * (-0.0025728 + 0.0085869 * py1 - 0.0069877 * py2 - 0.0115072 * py3 + 0.0327063 * py4 - 0.0167796 * py5 + 0.0019107 * py6) + px5 * (0.0018089 - 0.0031015 * py1 + 0.0047701 * py2 + 0.0018675 * py3 - 0.0134691 * py4 + 0.0139776 * py5 - 0.0087024 * py6) + px6 * (-0.0008609 + 0.0010956 * py1 - 0.0024048 * py2 + 0.0005262 * py3 + 0.0035639 * py4 - 0.0080487 * py5 + 0.0080563 * py6) + g * (0.0220605 + 0.0049886 * py1 - 0.0108884 * py2 + 0.0359254 * py3 - 0.0336876 * py4);
2081 let sumDielectric = (0.1105178 - 0.1470108 * py1 + 0.0706290 * py2 - 0.0048613 * py3 - 0.0190413 * py4 + 0.0038142 * py5 - 0.0002643 * py6) + px1 * (-0.1400053 + 0.2220226 * py1 - 0.1204309 * py2 + 0.0033027 * py3 + 0.0348652 * py4 - 0.0115348 * py5 + 0.0015711 * py6) + px2 * (0.0993738 - 0.1696809 * py1 + 0.1055418 * py2 - 0.0166890 * py3 - 0.0245166 * py4 + 0.0153020 * py5 - 0.0048468 * py6) + px3 * (-0.0363361 + 0.0724203 * py1 - 0.0631513 * py2 + 0.0261354 * py3 + 0.0041759 * py4 - 0.0092203 * py5 + 0.0054510 * py6) + px4 * (0.0046882 - 0.0144579 * py1 + 0.0238812 * py2 - 0.0200861 * py3 + 0.0078934 * py4 - 0.0001779 * py5 - 0.0024009 * py6) + px5 * (0.0013258 - 0.0006506 * py1 - 0.0049831 * py2 + 0.0084229 * py3 - 0.0075026 * py4 + 0.0046720 * py5 - 0.0007627 * py6) + px6 * (-0.0005364 + 0.0008141 * py1 + 0.0002790 * py2 - 0.0016584 * py3 + 0.0027280 * py4 - 0.0028646 * py5 + 0.0010557 * py6) + g * (-0.0075790 + 0.0243928 * py1 - 0.0212081 * py2 + 0.0063496 * py3 + 0.0036408 * py4);
2082 let scale = (sumMetal - sumDielectric) / 0.96;
2083 return vec2f(scale, sumMetal - scale);
2085// One authority for the environment's orientation: every direction that asks the
2086// environment anything comes through here, so a turned sky cannot disagree with a
2087// turned reflection. The query turns the other way, the world under it.
2088fn envDirection(d : vec3f) -> vec3f {
2089 let a = -lc.u_envTint.a;
2092 return vec3f(c * d.x + s * d.z, d.y, -s * d.x + c * d.z);
2094fn shIrradiance(sh : array<vec4f, 9>, N : vec3f) -> vec3f {
2095 return sh[0].rgb * 0.282095
2096 + sh[1].rgb * (0.488603 * N.y)
2097 + sh[2].rgb * (0.488603 * N.z)
2098 + sh[3].rgb * (0.488603 * N.x)
2099 + sh[4].rgb * (1.092548 * N.x * N.y)
2100 + sh[5].rgb * (1.092548 * N.y * N.z)
2101 + sh[6].rgb * (0.315392 * (3.0 * N.z * N.z - 1.0))
2102 + sh[7].rgb * (1.092548 * N.x * N.z)
2103 + sh[8].rgb * (0.546274 * (N.x * N.x - N.y * N.y));
2105fn ambientFacing(dir : vec3f) -> vec3f {
2106 return lc.u_ambient.rgb + lc.u_ambientGround.rgb * (0.5 - 0.5 * dir.y);
2108fn envIrradiance(Nw : vec3f) -> vec3f {
2109 // Read in place, not passed: an array handed to a function is copied, all nine, for every pixel.
2110 let N = envDirection(Nw);
2111 let sh = lc.u_envIrradiance[0].rgb * 0.282095
2112 + lc.u_envIrradiance[1].rgb * (0.488603 * N.y)
2113 + lc.u_envIrradiance[2].rgb * (0.488603 * N.z)
2114 + lc.u_envIrradiance[3].rgb * (0.488603 * N.x)
2115 + lc.u_envIrradiance[4].rgb * (1.092548 * N.x * N.y)
2116 + lc.u_envIrradiance[5].rgb * (1.092548 * N.y * N.z)
2117 + lc.u_envIrradiance[6].rgb * (0.315392 * (3.0 * N.z * N.z - 1.0))
2118 + lc.u_envIrradiance[7].rgb * (1.092548 * N.x * N.z)
2119 + lc.u_envIrradiance[8].rgb * (0.546274 * (N.x * N.x - N.y * N.y));
2120 return ambientFacing(Nw) + max(sh, vec3f(0.0)) * lc.u_envTint.rgb;
2122// The GLSL twin's indirectIrradiance: a volume replaces the environment, because a
2123// surface has one indirect term and a volume already holds every light and bounce
2124// that reached the point.
2126fn bakedIrradiance() -> vec3f {
2127 let c = textureSampleLevel(t5, s5, g_lightmap.xy, 0.0).rgb;
2132#ifndef MESH_LIGHTMAP
2133// See the GLSL twin: the grid itself, at P, through its indirection cell and the brick that names.
2134fn probeGridIrradiance(N : vec3f, P : vec3f) -> vec4f {
2135 let base = clamp(i32(g_probeSlot), 0, 99) * 10;
2136 let a = pc.u_probeIrradiance[base + 1];
2137 let b = pc.u_probeIrradiance[base + 2];
2138 let c = pc.u_probeIrradiance[base + 3];
2139 let d = pc.u_probeIrradiance[base + 4];
2140 let last = vec3f(a.w, b.w, c.w);
2141 let g = clamp((P - a.xyz) * b.xyz, vec3f(0.0), last);
2142 let cell = min(floor(g * 0.25), max(ceil(last * 0.25) - 1.0, vec3f(0.0)));
2143 let brick = textureLoad(t5, vec3i(c.xyz + cell + 0.5), 0);
2144 let first = floor(cell / brick.w) * brick.w;
2145 let uvw = (brick.xyz + (g - first * 4.0) / brick.w + 0.5) * d.xyz;
2146 var basis = array<f32, 9>(0.282095, 0.488603 * N.y, 0.488603 * N.z, 0.488603 * N.x,
2147 1.092548 * N.x * N.y, 1.092548 * N.y * N.z, 0.315392 * (3.0 * N.z * N.z - 1.0),
2148 1.092548 * N.x * N.z, 0.546274 * (N.x * N.x - N.y * N.y));
2149 var sum = vec4f(0.0);
2150 for (var i = 0; i < 9; i = i + 1) {
2151 sum += textureSampleLevel(t5, s5, uvw + vec3f(f32(i) * d.w * d.x, 0.0, 0.0), 0.0) * basis[i];
2157// See the GLSL twin: how much of the sky a probe sees toward d, 1 where nothing was baked of it.
2158fn skyOcclusion(d : vec3f) -> f32 {
2159 let base = clamp(i32(g_probeSlot), 0, 99) * 10;
2160 var v = pc.u_probeIrradiance[base + 9].y * 0.282095
2161 + pc.u_probeIrradiance[base + 1].w * (0.488603 * d.y)
2162 + pc.u_probeIrradiance[base + 2].w * (0.488603 * d.z)
2163 + pc.u_probeIrradiance[base + 3].w * (0.488603 * d.x)
2164 + pc.u_probeIrradiance[base + 4].w * (1.092548 * d.x * d.y)
2165 + pc.u_probeIrradiance[base + 5].w * (1.092548 * d.y * d.z)
2166 + pc.u_probeIrradiance[base + 6].w * (0.315392 * (3.0 * d.z * d.z - 1.0))
2167 + pc.u_probeIrradiance[base + 7].w * (1.092548 * d.x * d.z)
2168 + pc.u_probeIrradiance[base + 8].w * (0.546274 * (d.x * d.x - d.y * d.y));
2170#ifndef MESH_LIGHTMAP
2171 if (pc.u_probeIrradiance[base].w > 1.5) { v = probeGridIrradiance(d, g_probePos).a; }
2174 return mix(1.0, clamp(v, 0.0, 1.0), step(0.5, pc.u_probeIrradiance[base + 9].z));
2176// See the GLSL twin: one exit, for the shape the two share.
2177)"
R"(fn indirectIrradiance(N : vec3f) -> vec3f {
2178 let base = clamp(i32(g_probeSlot), 0, 99) * 10;
2179 let mode = pc.u_probeIrradiance[base].w;
2182#ifndef MESH_LIGHTMAP
2184 let grid = probeGridIrradiance(N, g_probePos);
2185 let sky = step(0.5, pc.u_probeIrradiance[base + 9].z);
2186 result = max(grid.rgb, vec3f(0.0)) * lc.u_bakedTint.rgb + envIrradiance(N) * (clamp(grid.a, 0.0, 1.0) * sky);
2191 var sh : array<vec4f, 9>;
2192 for (var i = 0; i < 9; i = i + 1) { sh[i] = pc.u_probeIrradiance[base + i]; }
2193 let sky = step(0.5, pc.u_probeIrradiance[base + 9].z);
2194 result = max(shIrradiance(sh, N), vec3f(0.0)) * lc.u_bakedTint.rgb + envIrradiance(N) * (skyOcclusion(N) * sky);
2196 result = envIrradiance(N);
2199 if (g_lightmap.z > 0.5) { result = bakedIrradiance() * lc.u_bakedTint.rgb; }
2203// Which column of the atlas this instance reflects, from the run its own index
2204// names. Zero — an instance inside no probe, or a draw that carries no run at all
2205// — is the environment, which is what every surface reflected before probes.
2206fn reflectionColumn() -> f32 {
2207 let base = clamp(i32(g_probeSlot), 0, 99) * 10;
2208 return pc.u_probeIrradiance[base + 9].x;
2210fn octEncode(d : vec3f) -> vec2f {
2211 var p = d.xz / max(abs(d.x) + abs(d.y) + abs(d.z), 1e-6);
2213 p = (1.0 - abs(vec2f(p.y, p.x)))
2214 * vec2f(select(-1.0, 1.0, p.x >= 0.0), select(-1.0, 1.0, p.y >= 0.0));
2216 return p * 0.5 + 0.5;
2218fn envSampleColumn(R : vec3f, mip : f32, column : f32) -> vec3f {
2222 let face = lc.u_envParams.w;
2223 let size = face * exp2(-mip);
2224 let yOff = 2.0 * face * (1.0 - exp2(-mip)) + 2.0 * mip;
2225 let col = face + 2.0;
2226 let atlasW = col * lc.u_reflParams.x;
2227 let atlasH = 2.0 * face * (1.0 - exp2(-(lc.u_envParams.z + 1.0)))
2228 + 2.0 * (lc.u_envParams.z + 1.0);
2229 // The sky turns with the environment; a baked column does not — it was solved
2230 // in world space, and turning it would spin a room about its own middle.
2231 let uv = octEncode(select(R, envDirection(R), column < 0.5));
2232 // Kept inside this column's own face, border ring included: a tap that leaves
2233 // it reads whatever the sampler's wrap mode says, and the two backends do not
2234 // answer that alike — one repeats to the far edge, the other clamps.
2235 let lo2 = vec2f(column * col + 0.5, yOff + 0.5);
2236 let hi2 = vec2f(column * col + size + 1.5, yOff + size + 1.5);
2237 let px = clamp(vec2f(column * col + 1.0 + uv.x * size, yOff + 1.0 + uv.y * size), lo2, hi2);
2238 let t = textureSampleLevel(t3, s3, px / vec2f(atlasW, atlasH), 0.0);
2239 return t.rgb * t.rgb * (t.a * t.a * lc.u_envParams.y);
2242fn envSampleMip(R : vec3f, mip : f32) -> vec3f { return envSampleColumn(R, mip, 0.0); }
2243// Where the reflected ray LEAVES this column's box, aimed from there rather than
2244// from infinitely far: what makes a reflection slide across a wall as the eye moves
2245// instead of being painted onto it.
2246fn reflectionDirection(R : vec3f, P : vec3f, column : f32) -> vec3f {
2247 if (column < 0.5) { return R; }
2248 let i = i32(column) * 2 - 2;
2249 let lo = lc.u_reflBox[i].xyz;
2250 let hi = lc.u_reflBox[i + 1].xyz;
2251 // Never zero, so a ray parallel to a face divides to an infinity the min
2252 // discards rather than to the NaN that would blacken the pixel.
2253 let d = max(abs(R), vec3f(1e-6)) * (step(vec3f(0.0), R) * 2.0 - vec3f(1.0));
2254 let t = min(min(max((hi.x - P.x) / d.x, (lo.x - P.x) / d.x),
2255 max((hi.y - P.y) / d.y, (lo.y - P.y) / d.y)),
2256 max((hi.z - P.z) / d.z, (lo.z - P.z) / d.z));
2257 if (!(t > 0.0)) { return R; }
2258 return (P + R * t) - (lo + hi) * 0.5;
2260fn envRadiance(R : vec3f, roughness : f32, column : f32, P : vec3f) -> vec3f {
2263 if (planar.planarParams.x > 0.5) {
2264 let clip = planar.planarProjection * vec4f(P, 1.0);
2265 if (clip.w <= 0.0) { return vec3f(0.0); }
2266 let uv = clip.xy / clip.w * vec2f(0.5, 0.5 * planar.planarParams.y) + vec2f(0.5);
2267 if (any(uv < vec2f(0.0)) || any(uv > vec2f(1.0))) { return vec3f(0.0); }
2268 // A small spatial filter, not prefiltered GGX: preserves material roughness
2269 // without allocating a second blur chain or claiming an exact BRDF convolution.
2270 // Blurred by how rough the surface is, a pixel and a half at the least (a mirror is never razor sharp at this size) and
2271 // wider as the roughness grows, so a wet road's reflection softens where a puddle's stays crisp: nine taps, the middle one
2272 // weighted most. The sideways reach follows the target's shape, so the blur is round on screen.
2273 let reach = max(planar.planarParams.z * 1.5, roughness * roughness * 0.04);
2274 let r = vec2f(reach, reach * planar.planarParams.w / planar.planarParams.z);
2276 let seen = textureSampleLevel(t3, s3, uv, 0.0).rgb * 0.2
2277 + (textureSampleLevel(t3, s3, clamp(uv + vec2f(r.x, 0.0), vec2f(0.0), vec2f(1.0)), 0.0).rgb
2278 + textureSampleLevel(t3, s3, clamp(uv - vec2f(r.x, 0.0), vec2f(0.0), vec2f(1.0)), 0.0).rgb
2279 + textureSampleLevel(t3, s3, clamp(uv + vec2f(0.0, r.y), vec2f(0.0), vec2f(1.0)), 0.0).rgb
2280 + textureSampleLevel(t3, s3, clamp(uv - vec2f(0.0, r.y), vec2f(0.0), vec2f(1.0)), 0.0).rgb
2281 + textureSampleLevel(t3, s3, clamp(uv + d, vec2f(0.0), vec2f(1.0)), 0.0).rgb
2282 + textureSampleLevel(t3, s3, clamp(uv - d, vec2f(0.0), vec2f(1.0)), 0.0).rgb
2283 + textureSampleLevel(t3, s3, clamp(uv + vec2f(d.x, -d.y), vec2f(0.0), vec2f(1.0)), 0.0).rgb
2284 + textureSampleLevel(t3, s3, clamp(uv + vec2f(-d.x, d.y), vec2f(0.0), vec2f(1.0)), 0.0).rgb) * 0.1;
2285 // A reflected sun or a sky's hot spot is far brighter than any picture holds, and a mirror shows all of it: the colour is
2286 // brought under a soft ceiling of 1.5 by its brightest channel (a knee from 0.75, so no edge shows where it starts), so a burning orange stays orange instead of clipping toward white.
2287 let peak = max(seen.r, max(seen.g, seen.b));
2288 let held = select(0.75 + 0.75 * (1.0 - exp(-(peak - 0.75) / 0.75)), peak, peak <= 0.75);
2289 return seen * (held / max(peak, 1e-4));
2292 if (lc.u_envParams.x < 0.5) { return ambientFacing(R); }
2293 let dir = reflectionDirection(R, P, column);
2294 let lod = clamp(roughness, 0.0, 1.0) * lc.u_envParams.z;
2295 let lo = floor(lod);
2296 let a = envSampleColumn(dir, lo, column);
2297 let b = envSampleColumn(dir, min(lo + 1.0, lc.u_envParams.z), column);
2298 // A baked column is the WHOLE radiance that reached its probe — the sky, the
2299 // ambient and every bounce. Adding the flat term or the sky's tint on top
2300 // would count the light the capture already saw a second time.
2301 if (column >= 0.5) {
2302 let baked = mix(a, b, lod - lo);
2303 // What the bake saw, as the weather now says it looks: dimmer, and with less of its colour.
2304 let grey = dot(baked, vec3f(0.2126, 0.7152, 0.0722));
2305 return mix(vec3f(grey), baked, lc.u_reflParams.z) * lc.u_reflParams.y;
2307 return (lc.u_ambient.rgb + mix(a, b, lod - lo) * lc.u_envTint.rgb) * skyOcclusion(R);
2309// Which definition of "where is the light" this surface is shaded with. One with a
2310// real third coordinate measures against the light's own; a sprite has no depth to
2311// measure against, so a positional light goes on hovering its radius above it.
2313fn lightVector(pd : vec4f, sh : vec4f, worldPos : vec3f) -> vec3f {
2314 return vec3f(pd.xy, sh.z) - worldPos;
2316fn lightDistance(toLight : vec3f) -> f32 { return length(toLight); }
2317fn spotCone(sp : vec4f, sh : vec4f, toLight : vec3f, dist : f32) -> f32 {
2318 let axis = normalize(vec3f(sp.xy, sh.w));
2320 if (dist > 0.0001) { toFrag = -toLight / dist; }
2321 return smoothstep(sp.w, sp.z, dot(axis, toFrag));
2324fn lightVector(pd : vec4f, sh : vec4f, worldPos : vec3f) -> vec3f {
2325 return vec3f(pd.xy - worldPos.xy, max(pd.w, 1.0));
2327fn lightDistance(toLight : vec3f) -> f32 { return length(toLight.xy); }
2328fn spotCone(sp : vec4f, sh : vec4f, toLight : vec3f, dist : f32) -> f32 {
2329 // A cone aimed out of the plane has no axis IN it, and this half of the shading
2330 // has nowhere else to read one — so it lights the way an unrotated spot always has.
2331 var axis = vec2f(0.0, -1.0);
2332 if (dot(sp.xy, sp.xy) > 1e-8) { axis = normalize(sp.xy); }
2334 if (dist > 0.0001) { toFrag = -toLight.xy / dist; }
2335 return smoothstep(sp.w, sp.z, dot(axis, toFrag));
2338fn towardLight(toLight : vec3f, N : vec3f) -> vec3f {
2339 if (dot(toLight, toLight) > 1e-8) { return normalize(toLight); }
2342// The ramp from a light's reach down to nothing. fo.x holds it at full out to its own
2343// radius; fo.y shapes what is left. The exponent is floored because pow(0, 0) is 1 —
2344// a light that reaches nowhere would light everything.
2345fn distanceFalloff(dist : f32, reach : f32, fo : vec4f) -> f32 {
2346 let ramp = clamp((reach - dist) / max(reach - fo.x, 1e-4), 0.0, 1.0);
2347 let shaped = pow(ramp, max(fo.y, 1e-3));
2348 // See the GLSL twin: fo.y < 0 is an inverse-square light, -fo.y world units to the metre.
2349 let metres = dist / max(-fo.y, 1e-4);
2350 let q = dist / max(reach, 1e-4);
2351 let w = clamp(1.0 - q * q * q * q, 0.0, 1.0);
2352 return select(shaped, w * w / max(metres * metres, 0.01), fo.y < 0.0);
2356R
"(struct SurfaceExt { coat : vec4f, coatN : vec4f, sheen : vec4f, aniso : vec4f, scatter : vec4f, trans : vec4f, film : vec4f, misc : vec4f, strand : vec4f };
2357fn surfaceExtNone(N : vec3f) -> SurfaceExt {
2358 return SurfaceExt(vec4f(0.0), vec4f(N, 0.0), vec4f(0.0), vec4f(0.0), vec4f(0.0), vec4f(0.0), vec4f(0.0),
2359 vec4f(0.04, 0.0, 0.0, 0.0), vec4f(0.6, 0.0, 0.0, 0.0));
2361fn distributionCharlie(NdotH : f32, a : f32) -> f32 {
2362 let invA = 1.0 / max(a, 1e-3);
2363 let sin2 = max(1.0 - NdotH * NdotH, 0.0078125);
2364 return (2.0 + invA) * pow(sin2, invA * 0.5) / 6.28318531;
2366fn visibilityNeubelt(NdotV : f32, NdotL : f32) -> f32 {
2367 return 1.0 / max(4.0 * (NdotL + NdotV - NdotL * NdotV), 1e-4);
2369fn distributionGGXAniso(at : f32, ab : f32, ToH : f32, BoH : f32, NoH : f32) -> f32 {
2371 let d = vec3f(ab * ToH, at * BoH, a2 * NoH);
2372 let b2 = a2 / max(dot(d, d), 1e-7);
2373 return a2 * b2 * b2 / 3.14159265;
2375fn visibilityGGXAniso(at : f32, ab : f32, ToV : f32, BoV : f32, ToL : f32, BoL : f32, NoV : f32, NoL : f32) -> f32 {
2376 let lambdaV = NoL * length(vec3f(at * ToV, ab * BoV, NoV));
2377 let lambdaL = NoV * length(vec3f(at * ToL, ab * BoL, NoL));
2378 return 0.5 / max(lambdaV + lambdaL, 1e-5);
2380fn filmFresnel(F : vec3f, cosTheta : f32, film : vec4f) -> vec3f {
2381 let sinT2 = (1.0 - cosTheta * cosTheta) / (film.y * film.y);
2382 let cosT = sqrt(max(1.0 - sinT2, 0.0));
2383 let opd = 2.0 * film.y * film.z * cosT;
2384 let tint = vec3f(0.5) + vec3f(0.5) * cos(vec3f(6.28318531 * opd) / vec3f(650.0, 510.0, 475.0));
2385 return clamp(F * mix(vec3f(1.0), tint * 2.0, vec3f(film.x)), vec3f(0.0), vec3f(1.0));
2387fn applyLightingSurfaceBRDF(diffuse : vec3f, F0 : vec3f, N : vec3f, worldPos : vec3f, V : vec3f,
2388 roughness : f32, specular : f32, ao : f32, ext : SurfaceExt) -> vec3f {
2389 g_probePos = worldPos;
2390 let a = max(roughness * roughness, 1e-3);
2391 let NdotV = max(dot(N, V), 1e-4);
2392 var lit = indirectIrradiance(N) * ao;
2393 var gloss = vec3f(0.0);
2394 var extra = vec3f(0.0);
2395 // As many as are lit: read for a slot nobody uses, a light's six vectors cost more on a phone than the one light shaded.
2396 let lightCount = i32(lc.u_ambient.a);
2397 // Which of them can reach this point: see the GLSL twin.
2398 var reach3D = 0xFFFFu;
2400 if (lc.tileInfo.w > 0.5) {
2401 let tileView = lc.u_tileView * vec4f(worldPos, 1.0);
2402 let viewNdc = tileView.xy / max(tileView.w, 1e-4);
2403 if (tileView.w > 1e-4 && abs(viewNdc.x) <= 1.0 && abs(viewNdc.y) <= 1.0) {
2404 let viewTiles = vec2i(i32(lc.tileInfo.y), i32(lc.tileInfo.z));
2405 let viewTile = clamp(vec2i(floor((viewNdc * 0.5 + 0.5) * vec2f(viewTiles))), vec2i(0), viewTiles - vec2i(1));
2406 reach3D = lc.tileMask[viewTile.y * viewTiles.x + viewTile.x].w >> 16u;
2410 for (var i = 0; i < lightCount; i++) {
2411 if ((reach3D & (1u << u32(i))) == 0u) { continue; }
2412 var lamp = lc.u_lights[i];
2414 if (lc.u_waterRect.z > 0.0 && f32(i) == lc.u_waterSun.z) { lamp = waterIncidentSun(lamp, worldPos); }
2416 let term = shadeLight(lamp.posDir, lamp.color, lamp.spot, lamp.shadow,
2417 lc.u_lights[i].shadowMap, lc.u_lights[i].falloff, N, V, worldPos, a, F0, NdotV, specular, roughness, ext, true);
2419 gloss += term.gloss;
2420 extra += term.extra;
2422#ifndef ES_LIGHT_DIRECT
2423 // The lights past the sixteen: this pixel's tile is found from where the fragment lands through the camera it was drawn by
2424 // (normalized device coordinates, the same on every backend), and only the lights whose bit is set in its mask are shaded.
2425 let tiledCount = i32(lc.tileInfo.x);
2426 if (tiledCount > 0) {
2427 let tileClip = frame.projection * vec4f(worldPos, 1.0);
2428 let tileNdc = tileClip.xy / max(tileClip.w, 1e-4);
2429 let tileCount = vec2i(i32(lc.tileInfo.y), i32(lc.tileInfo.z));
2430 let tile = clamp(vec2i(floor((tileNdc * 0.5 + 0.5) * vec2f(tileCount))), vec2i(0), tileCount - vec2i(1));
2431 let mask = lc.tileMask[tile.y * tileCount.x + tile.x];
2432 for (var w = 0; w < 3; w++) {
2434 if (w == 1) { bits = mask.y; } else if (w == 2) { bits = mask.z; }
2435 if (bits == 0u) { continue; }
2436 for (var b = 0; b < 32; b++) {
2437 if ((bits & (1u << u32(b))) == 0u) { continue; }
2439 if (k >= tiledCount) { break; }
2440 let term = shadeLight(lc.tiledLights[k].posDir, lc.tiledLights[k].color, lc.tiledLights[k].spot,
2441 lc.tiledLights[k].shadow, lc.tiledLights[k].shadowMap, lc.tiledLights[k].falloff,
2442 N, V, worldPos, a, F0, NdotV, specular, roughness, ext, false);
2444 gloss += term.gloss;
2445 extra += term.extra;
2450 let ab = envBRDFApprox(NdotV, roughness);
2451 // The light a rough microfacet surface loses to bounces between its facets, which single-scattering GGX leaves out (a metal at roughness
2452 // 0.9 came out at half of Blender's brightness): Fdez-Aguera's term for the environment, and the same ratio on the lamps' highlight. What
2453 // the specular reflects is light the diffuse under it does not get, as in the Principled shader. Hair keeps its own lobes as authored.
2454 let Ess = ab.x + ab.y;
2455 let FssEss = F0 * ab.x + vec3f(ab.y);
2456 var FmsEms = vec3f(0.0);
2457 var kd = vec3f(1.0);
2458 if (ext.misc.y <= 0.0 || ext.strand.y > 0.0) {
2459 let Ems = 1.0 - Ess;
2460 let Favg = F0 + (vec3f(1.0) - F0) / 21.0;
2461 FmsEms = FssEss * Favg * Ems / (vec3f(1.0) - Ems * Favg);
2462 gloss *= vec3f(1.0) + F0 * (1.0 / max(Ess, 0.05) - 1.0);
2463 kd = max(vec3f(1.0) - (FssEss + FmsEms) * specular, vec3f(0.0));
2465 var envR = reflect(-V, N);
2466 if (ext.aniso.w != 0.0 || ext.misc.y > 0.0) {
2467 let T = ext.aniso.xyz;
2469 if (ext.aniso.w >= 0.0 && ext.misc.y <= 0.0) { grain = cross(N, T); }
2470 let bent = normalize(cross(cross(grain, V), grain));
2471 var bendBy = abs(ext.aniso.w);
2472 if (ext.misc.y > 0.0) { bendBy = 0.55; }
2473 envR = reflect(-V, normalize(mix(N, bent, vec3f(bendBy))));
2475 var envF = FssEss + FmsEms;
2476 if (ext.film.x > 0.0) { envF = filmFresnel(envF, NdotV, ext.film); }
2477 gloss += envRadiance(envR, roughness, reflectionColumn(), worldPos) * (ao * specular)
2479 let base = diffuse * lit * kd + gloss;
2480 var baseScale = 1.0;
2481 if (ext.coat.x > 0.0) {
2482 let coatNdotV = max(dot(ext.coatN.xyz, V), 1e-4);
2483 let cab = envBRDFApprox(coatNdotV, ext.coat.y);
2484 // coat.z is the coat's reflectance seen straight on; 0 is a varnish's 0.04.
2485 let coatF0 = select(0.04, ext.coat.z, ext.coat.z > 0.0);
2486 let Fc = (coatF0 * cab.x + cab.y) * ext.coat.x;
2487 baseScale *= 1.0 - Fc;
2488 extra += envRadiance(reflect(-V, ext.coatN.xyz), ext.coat.y, reflectionColumn(), worldPos) * (ao * Fc);
2490 if (dot(ext.sheen.rgb, vec3f(1.0)) > 0.0) {
2491 let sheenAlbedo = 0.2 + 0.3 * ext.sheen.a;
2492 baseScale *= 1.0 - max(max(ext.sheen.r, ext.sheen.g), ext.sheen.b) * sheenAlbedo;
2493 extra += ext.sheen.rgb * (indirectIrradiance(N) * ao * sheenAlbedo);
2495 return base * baseScale + extra;
2497fn applyLightingSurface(albedo : vec3f, N : vec3f, worldPos : vec3f, V : vec3f, metallic : f32,
2498 roughness : f32, specular : f32, ao : f32, ext : SurfaceExt) -> vec3f {
2499 return applyLightingSurfaceBRDF(albedo * (1.0 - metallic), mix(vec3f(ext.misc.x), albedo, vec3f(metallic)),
2500 N, worldPos, V, roughness, specular, ao, ext);
2502fn applyLightingPBR(albedo : vec3f, N : vec3f, worldPos : vec3f, V : vec3f, metallic : f32,
2503 roughness : f32, specular : f32, ao : f32) -> vec3f {
2504 return applyLightingSurface(albedo, N, worldPos, V, metallic, roughness, specular, ao, surfaceExtNone(N));
2508R
"(struct LightTerm { lit : vec3f, gloss : vec3f, extra : vec3f };
2509// The layer of the sprite being lit, as its vertex wrote it (the layer plus 129; 0 when the surface has none to test), and whether a light's
2510// range of layers, which rides in shadowMap.y above the tile count, takes it in. See packLightLayerRange.
2511var<private> g_surfaceLayer : f32 = 0.0;
2512fn lightReachesLayer(rangeLane : f32) -> bool {
2513 if (rangeLane < 8.0 || g_surfaceLayer < 0.5) { return true; }
2514 let range = floor(rangeLane / 8.0);
2515 let lo = range % 256.0 - 128.0;
2516 let hi = 127.0 - floor(range / 256.0);
2517 let layer = g_surfaceLayer - 129.0;
2518 return layer >= lo && layer <= hi;
2520fn shadeLight(pd : vec4f, col : vec4f, sp : vec4f, sh : vec4f, sm : vec4f, fo : vec4f, N : vec3f, V : vec3f,
2521 worldPos : vec3f, a : f32, F0 : vec3f, NdotV : f32, specular : f32, roughness : f32,
2522 ext : SurfaceExt, shadow3D : bool) -> LightTerm {
2523 var lit = vec3f(0.0);
2524 var gloss = vec3f(0.0);
2525 var extra = vec3f(0.0);
2526 // A slot nothing lights from adds exactly nothing (see the GLSL twin).
2527 if (col.a == 0.0 || !lightReachesLayer(sm.y)) { return LightTerm(lit, gloss, extra); }
2532 var castShadow = true;
2534 let toL = lightVector(pd, sh, worldPos);
2535 let dist = lightDistance(toL);
2536 atten = distanceFalloff(dist, max(pd.w, 0.0001), fo);
2537 L = towardLight(toL, N);
2538 } else if (pd.z < 1.5) {
2540 L = normalize(-vec3f(pd.xy, pd.w));
2541 var toLight = vec2f(0.0, 0.0);
2542 if (dot(pd.xy, pd.xy) > 1e-8) { toLight = normalize(-pd.xy); }
2543 castShadow = sh.y > 0.0 && dot(toLight, toLight) > 0.5;
2544 aim = worldPos.xy + toLight * sh.y;
2545 if (sp.x > 0.5) { atten = atten * cloudShadow3D(worldPos, i32(sp.x) - 1); }
2547 let toL = lightVector(pd, sh, worldPos);
2548 let dist = lightDistance(toL);
2549 atten = distanceFalloff(dist, max(pd.w, 0.0001), fo);
2550 L = towardLight(toL, N);
2551 atten *= spotCone(sp, sh, toL, dist);
2553 // Facing away, with nothing that takes light from behind: nothing from this light, and no shadow to look up (see the GLSL twin).
2554 if (atten <= 0.0 || (dot(N, L) <= 0.0 && ext.misc.y <= 0.0 && ext.coat.x <= 0.0 && ext.scatter.a <= 0.0
2555 && dot(ext.sheen.rgb, vec3f(1.0)) <= 0.0)) { return LightTerm(lit, gloss, extra); }
2556#ifndef ES_LIGHT_DIRECT
2557 if (col.a > 0.0 && atten > 0.0) {
2558 atten *= shapeFactor2D(fo.w, worldPos.xy);
2560 if (castShadow && col.a > 0.0 && atten > 0.0) {
2561 atten *= mix(1.0, shadowFactor2D(sm.w, worldPos.xy), fo.z);
2564 // See the GLSL twin: a light the tiles carry has no shadow map, and says so.
2565 if (shadow3D && sm.y % 8.0 > 0.0 && atten > 0.0) {
2567 shadowFactor3D(worldPos, N, L, vec2f(sh.x, sm.z), i32(sm.x), i32(sm.y % 8.0)),
2570 var ndotl = max(dot(N, L), 0.0);
2571 // Hair (misc.y above zero; aniso.xyz is the strand): Kajiya-Kay diffuse, which lights a strand by how far light is from along it.
2572 if (ext.misc.y > 0.0) {
2573 let along = dot(ext.aniso.xyz, L);
2574 ndotl = mix(ndotl, sqrt(max(1.0 - along * along, 0.0)) * clamp(dot(N, L) * 0.5 + 0.65, 0.0, 1.0), ext.strand.x);
2576 let radiance = col.rgb * (col.a * ndotl * atten);
2578 if (specular > 0.0 && ext.misc.y > 0.0 && ext.strand.y <= 0.0) {
2579 // Two shifted, narrow lobes along the strand: a white one near the surface and a coloured one under it (scatter.rgb).
2580 let H = normalize(L + V);
2581 let primaryExp = clamp(2.0 / (a * a), 8.0, 900.0);
2582 let strandA = normalize(ext.aniso.xyz + N * ext.misc.z);
2583 let strandB = normalize(ext.aniso.xyz + N * ext.misc.w);
2584 let h1 = dot(strandA, H);
2585 let h2 = dot(strandB, H);
2586 let lobe1 = smoothstep(-1.0, 0.0, h1) * pow(sqrt(max(1.0 - h1 * h1, 0.0)), primaryExp);
2587 let lobe2 = smoothstep(-1.0, 0.0, h2) * pow(sqrt(max(1.0 - h2 * h2, 0.0)), primaryExp * 0.3);
2588 let lightOn = col.rgb * (col.a * atten * clamp(dot(N, L) + 0.35, 0.0, 1.0));
2589 gloss += lightOn * (lobe1 * 0.55 + lobe2 * ext.scatter.rgb * 1.6) * (ext.misc.y * specular);
2590 } else if (specular > 0.0) {
2591 let H = normalize(L + V);
2593 if (ext.misc.y > 0.0) {
2594 // Hair shaded as the Principled shader shades a card with an anisotropy (strand.y): GGX stretched along the strand, as Blender
2595 // stretches it (aspect sqrt(1 - 0.9 anisotropy)). The highlight runs across the strands as a band, the sheen a lock of hair has.
2596 let T = ext.aniso.xyz;
2597 let B = cross(N, T);
2598 let aspect = sqrt(max(1.0 - 0.9 * ext.strand.y, 0.01));
2599 let at = max(a / aspect, 0.002);
2600 let ab = max(a * aspect, 0.002);
2601 brdf = distributionGGXAniso(at, ab, dot(T, H), dot(B, H), max(dot(N, H), 0.0))
2602 * visibilityGGXAniso(at, ab, dot(T, V), dot(B, V), dot(T, L), dot(B, L), NdotV, ndotl);
2603 } else if (ext.aniso.w != 0.0) {
2604 let T = ext.aniso.xyz;
2605 let B = cross(N, T);
2606 let at = max(a * (1.0 + ext.aniso.w), 0.002);
2607 let ab = max(a * (1.0 - ext.aniso.w), 0.002);
2608 brdf = distributionGGXAniso(at, ab, dot(T, H), dot(B, H), max(dot(N, H), 0.0))
2609 * visibilityGGXAniso(at, ab, dot(T, V), dot(B, V), dot(T, L), dot(B, L), NdotV, ndotl);
2611 brdf = distributionGGX(max(dot(N, H), 0.0), a) * visibilitySmithGGX(NdotV, ndotl, a);
2613 var F = fresnelSchlick(max(dot(V, H), 0.0), F0);
2614 if (ext.film.x > 0.0) { F = filmFresnel(F, max(dot(V, H), 0.0), ext.film); }
2615 gloss += radiance * F
2616 * (brdf * 3.14159265 * specular);
2618 if (col.a > 0.0 && atten > 0.0
2619 && (ext.coat.x > 0.0 || ext.scatter.a > 0.0 || dot(ext.sheen.rgb, vec3f(1.0)) > 0.0)) {
2620 let irr = col.rgb * (col.a * atten);
2621 let Hx = normalize(L + V);
2622 let VdotH = max(dot(V, Hx), 0.0);
2623 if (ext.coat.x > 0.0) {
2624 let coatNdotL = max(dot(ext.coatN.xyz, L), 0.0);
2625 let coatA = max(ext.coat.y * ext.coat.y, 1e-3);
2626 let coatF0 = select(0.04, ext.coat.z, ext.coat.z > 0.0);
2627 let Fc = (coatF0 + (1.0 - coatF0) * pow(1.0 - VdotH, 5.0)) * ext.coat.x;
2628 extra += irr * coatNdotL
2629 * (distributionGGX(max(dot(ext.coatN.xyz, Hx), 0.0), coatA) * (0.25 / max(VdotH * VdotH, 1e-4))
2632 if (dot(ext.sheen.rgb, vec3f(1.0)) > 0.0) {
2633 let sheenA = max(ext.sheen.a * ext.sheen.a, 1e-3);
2634 extra += irr * ndotl * ext.sheen.rgb
2635 * (distributionCharlie(max(dot(N, Hx), 0.0), sheenA) * visibilityNeubelt(NdotV, ndotl) * 3.14159265);
2637 if (ext.scatter.a > 0.0) {
2638 // The wrap is per channel once trans.w asks for it: red travels furthest, and every channel further where the
2639 // surface turns sharply (trans.z, a curvature 0..1), as a pre-integrated skin ramp would give.
2640 let wrapWidth = vec3f(ext.scatter.a) * mix(vec3f(1.0), vec3f(1.0, 0.45, 0.25) * (0.3 + 1.7 * ext.trans.z), ext.trans.w);
2641 let wrapped = clamp((vec3f(dot(N, L)) + wrapWidth) / (vec3f(1.0) + wrapWidth), vec3f(0.0), vec3f(1.0));
2642 extra += irr * ext.scatter.rgb * max(wrapped - vec3f(ndotl), vec3f(0.0));
2643 let Hb = normalize(L + N * 0.3);
2644 extra += irr * ext.scatter.rgb
2645 * (pow(clamp(dot(V, -Hb), 0.0, 1.0), 4.0) * ext.trans.x * (1.0 - ext.trans.y));
2649 return LightTerm(lit, gloss, extra);
2653R
"(// A lit sprite's light, written out as only what it is (see the GLSL twin): the general model's sums term for term, with the two 2D masks
2654// read once for the pixel and nothing of the highlight carried along.
2655fn shadeLight2D(pd : vec4f, col : vec4f, sp : vec4f, sh : vec4f, sm : vec4f, fo : vec4f, N : vec3f, worldPos : vec3f,
2656 masked : bool, shadowMask : vec4f, shapeMask : vec4f, shadow3D : bool) -> vec3f {
2657 if (col.a == 0.0 || !lightReachesLayer(sm.y)) { return vec3f(0.0); }
2660 var castShadow = true;
2662 let toL = lightVector(pd, sh, worldPos);
2663 let dist = lightDistance(toL);
2664 atten = distanceFalloff(dist, max(pd.w, 0.0001), fo);
2665 L = towardLight(toL, N);
2666 } else if (pd.z < 1.5) {
2667 L = normalize(-vec3f(pd.xy, pd.w));
2668 var toLight = vec2f(0.0, 0.0);
2669 if (dot(pd.xy, pd.xy) > 1e-8) { toLight = normalize(-pd.xy); }
2670 castShadow = sh.y > 0.0 && dot(toLight, toLight) > 0.5;
2672 let toL = lightVector(pd, sh, worldPos);
2673 let dist = lightDistance(toL);
2674 atten = distanceFalloff(dist, max(pd.w, 0.0001), fo);
2675 L = towardLight(toL, N);
2676 atten *= spotCone(sp, sh, toL, dist);
2678#ifndef ES_LIGHT_DIRECT
2679 if (masked && col.a > 0.0 && atten > 0.0) {
2680 if (fo.w >= 0.0) { atten *= min(mask2DChannel(shapeMask, fo.w), 1.0); }
2681 if (castShadow && sm.w >= 0.0 && atten > 0.0) {
2683 if (sm.w < 3.5) { hidden = mask2DChannel(shadowMask, sm.w); }
2684 else { hidden = mask2DChannel(shapeMask, sm.w - 4.0); }
2685 atten *= mix(1.0, 1.0 - min(hidden, 1.0), fo.z);
2689 if (shadow3D && sm.y % 8.0 > 0.0 && atten > 0.0) {
2691 shadowFactor3D(worldPos, N, L, vec2f(sh.x, sm.z), i32(sm.x), i32(sm.y % 8.0)),
2694 return col.rgb * (col.a * max(dot(N, L), 0.0) * atten);
2696// `reach`: bit i set when loop light i can reach this quad at all (see the GLSL twin); the rest are not worked out.
2697fn applyLighting2DReach(albedo : vec3f, N : vec3f, worldPos : vec2f, ao : f32, reach : u32) -> vec3f {
2698 let P = vec3f(worldPos, 0.0);
2700 var lit = indirectIrradiance(N) * ao;
2702 var shadowMask = vec4f(0.0);
2703 var shapeMask = vec4f(0.0);
2704#ifndef ES_LIGHT_DIRECT
2705 if (lc.u_mask2DRect.z > 0.0) {
2706 let maskUv = mask2DUv(worldPos);
2707 if (!(maskUv.x < 0.0)) {
2709 shadowMask = textureSampleLevel(t7, s7, maskUv, 0.0);
2710 shapeMask = textureSampleLevel(t6, s6, maskUv, 0.0);
2714 // The screen tile this pixel is in says which lights can reach it (see the GLSL twin): the fourth word is the loop's own sixteen.
2715 var reachBits = reach;
2716#ifndef ES_LIGHT_DIRECT
2717 let tiledCount = i32(lc.tileInfo.x);
2718 var tileBits = vec4u(0u);
2719 if (tiledCount > 0 || lc.tileInfo.w > 0.5) {
2720 let tileClip = frame.projection * vec4f(P, 1.0);
2721 let tileNdc = tileClip.xy / max(tileClip.w, 1e-4);
2722 let tileCount = vec2i(i32(lc.tileInfo.y), i32(lc.tileInfo.z));
2723 let tile = clamp(vec2i(floor((tileNdc * 0.5 + 0.5) * vec2f(tileCount))), vec2i(0), tileCount - vec2i(1));
2724 tileBits = lc.tileMask[tile.y * tileCount.x + tile.x];
2725 if (lc.tileInfo.w > 0.5) { reachBits = reachBits & tileBits.w; }
2728 let lightCount = i32(lc.u_ambient.a);
2729 for (var i = 0; i < lightCount; i++) {
2730 if (((reachBits >> u32(i)) & 1u) == 0u) { continue; }
2731 lit += shadeLight2D(lc.u_lights[i].posDir, lc.u_lights[i].color, lc.u_lights[i].spot, lc.u_lights[i].shadow,
2732 lc.u_lights[i].shadowMap, lc.u_lights[i].falloff, N, P, masked, shadowMask, shapeMask, true);
2734#ifndef ES_LIGHT_DIRECT
2735 if (tiledCount > 0) {
2736 for (var w = 0; w < 3; w++) {
2737 var bits = tileBits.x;
2738 if (w == 1) { bits = tileBits.y; } else if (w == 2) { bits = tileBits.z; }
2739 if (bits == 0u) { continue; }
2740 for (var b = 0; b < 32; b++) {
2741 if ((bits & (1u << u32(b))) == 0u) { continue; }
2743 if (k >= tiledCount) { break; }
2744 lit += shadeLight2D(lc.tiledLights[k].posDir, lc.tiledLights[k].color, lc.tiledLights[k].spot,
2745 lc.tiledLights[k].shadow, lc.tiledLights[k].shadowMap, lc.tiledLights[k].falloff,
2746 N, P, masked, shadowMask, shapeMask, false);
2751 return albedo * lit;
2753fn applyLighting2DAO(albedo : vec3f, N : vec3f, worldPos : vec2f, ao : f32) -> vec3f {
2754 return applyLighting2DReach(albedo, N, worldPos, ao, 65535u);
2756fn applyLighting2D(albedo : vec3f, N : vec3f, worldPos : vec2f) -> vec3f {
2757 return applyLighting2DAO(albedo, N, worldPos, 1.0);
2759// The same, for a sprite that knows its layer: layerLane is the varying the vertex stage wrote (v_lightLayer). A negative lane carries,
2760// above the layer, which lights reach the quad (packSpriteLightLane); the sixteenth light has no bit and is always worked out.
2761fn applyLighting2DLayer(albedo : vec3f, N : vec3f, worldPos : vec2f, layerLane : f32) -> vec3f {
2762 let lane = abs(layerLane);
2763 let reachLane = floor(lane * 0.001953125);
2764 g_surfaceLayer = lane - reachLane * 512.0;
2766 if (layerLane < 0.0) { reach = u32(reachLane) + 32768u; }
2767 return applyLighting2DReach(albedo, N, worldPos, 1.0, reach);
2774std::string blankUniformBlock(
const std::string& src,
const std::string& blockName) {
2775 const std::string needle =
"uniform " + blockName;
2776 const usize at = src.find(needle);
2777 if (at == std::string::npos)
return src;
2779 const usize lineStart = src.rfind(
'\n', at) == std::string::npos ? 0 : src.rfind(
'\n', at) + 1;
2781 const std::string prefix = src.substr(lineStart, at - lineStart);
2782 if (prefix.find_first_not_of(
" \t") != std::string::npos
2783 && prefix.find(
"layout") == std::string::npos) {
2786 const usize open = src.find(
'{', at);
2787 if (open == std::string::npos)
return src;
2788 const usize close = src.find(
"};", open);
2789 if (close == std::string::npos)
return src;
2791 std::string out = src;
2792 for (
usize i = lineStart; i < close + 2; ++i) {
2793 if (out[i] !=
'\n') out[i] =
' ';
2798std::string trimWs(
const std::string& s) {
2799 const usize a = s.find_first_not_of(
" \t\r\n");
2800 if (a == std::string::npos)
return {};
2801 const usize b = s.find_last_not_of(
" \t\r\n");
2802 return s.substr(a, b - a + 1);
2808class ConditionParser {
2810 ConditionParser(
const std::string& text,
const std::unordered_set<std::string>& defined)
2811 : s_(text), defined_(defined) {}
2813 bool evaluate() {
return orExpr(); }
2816 void skipWs() {
while (i_ < s_.size() && (s_[i_] ==
' ' || s_[i_] ==
'\t' || s_[i_] ==
'\r')) ++i_; }
2817 bool eat(
const char* tok) {
2819 const usize n = std::strlen(tok);
2820 if (s_.compare(i_, n, tok) != 0)
return false;
2824 std::string ident() {
2826 const usize start = i_;
2827 while (i_ < s_.size() && (std::isalnum(
static_cast<unsigned char>(s_[i_])) || s_[i_] ==
'_')) ++i_;
2828 return s_.substr(start, i_ - start);
2832 while (eat(
"||")) v = andExpr() || v;
2837 while (eat(
"&&")) v = unary() && v;
2841 if (eat(
"!"))
return !unary();
2843 const bool v = orExpr();
2847 const std::string word = ident();
2848 if (word ==
"defined") {
2849 const bool paren = eat(
"(");
2850 const bool v = defined_.count(ident()) != 0;
2851 if (paren) eat(
")");
2854 if (!word.empty() && std::isdigit(
static_cast<unsigned char>(word[0])))
return std::strtol(word.c_str(),
nullptr, 0) != 0;
2855 return defined_.count(word) != 0;
2858 const std::string& s_;
2859 const std::unordered_set<std::string>& defined_;
2865std::string preprocessConditionals(
const std::string& source,
const std::vector<std::string>& features) {
2866 const std::unordered_set<std::string> defined(features.begin(), features.end());
2872 std::vector<Frame> stack;
2873 auto activeNow = [&]() {
return stack.empty() || stack.back().active; };
2876 out.reserve(source.size());
2877 LineReader in(source);
2879 while (in.next(line)) {
2880 const std::string lead = ltrim(line);
2881 if (lead.rfind(
"#ifdef", 0) == 0 || lead.rfind(
"#ifndef", 0) == 0) {
2882 const bool neg = lead.rfind(
"#ifndef", 0) == 0;
2883 const std::string name = trimWs(lead.substr(neg ? 7 : 6));
2884 const bool parent = activeNow();
2885 const bool cond = parent && ((defined.count(name) != 0) != neg);
2886 stack.push_back(Frame{parent, cond, cond});
2889 if (lead.rfind(
"#if", 0) == 0 && (lead.size() == 3 || lead[3] ==
' ' || lead[3] ==
'\t' || lead[3] ==
'(' || lead[3] ==
'!')) {
2890 const bool parent = activeNow();
2891 const bool cond = parent && ConditionParser(lead.substr(3), defined).evaluate();
2892 stack.push_back(Frame{parent, cond, cond});
2895 if (lead.rfind(
"#elif", 0) == 0 && !stack.empty()) {
2896 const bool cond = ConditionParser(lead.substr(5), defined).evaluate();
2897 Frame& f = stack.back();
2898 f.active = f.parentActive && !f.taken && cond;
2899 f.taken = f.taken || f.active;
2902 if (lead.rfind(
"#else", 0) == 0 && !stack.empty()) {
2903 Frame& f = stack.back();
2904 f.active = f.parentActive && !f.taken;
2908 if (lead.rfind(
"#endif", 0) == 0) {
2909 if (!stack.empty()) stack.pop_back();
2929bool hasFeature(
const std::vector<std::string>& features,
const char* name) {
2930 return std::find(features.begin(), features.end(), name) != features.end();
2935 const std::vector<std::string>& features) {
2937 if (!parsed.valid)
return result;
2939 auto bodyIt = parsed.wgslStages.find(stage);
2940 if (bodyIt == parsed.wgslStages.end()) {
2941 ES_LOG_ERROR(
"Shader '{}' has no WGSL twin for the {} stage (add '#pragma {} wgsl')",
2942 parsed.name, stageName(stage), stageName(stage));
2949 auto fullIt = parsed.wgslStageFull.find(stage);
2950 if (fullIt != parsed.wgslStageFull.end() && fullIt->second) {
2951 result.source = preprocessConditionals(bodyIt->second, features);
2952 result.headerLineCount = 0;
2956 TextBuilder assembled;
2957 u32 headerLines = 0;
2958 auto inject = [&](
const std::string& s) {
2960 headerLines += countNewlines(s);
2963 const bool lit = parsed.domain ==
"Lit";
2968 inject(parsed.domain ==
"PostProcess" ? wgslPPVSOut() : wgslCanonicalVSOut(lit));
2970 const bool probeAtlas = lit && hasFeature(features,
"ES_SURFACE_3D") && !hasFeature(features,
"MESH_LIGHTMAP");
2971 inject(wgslBatchTextureDecls(parsed.domain ==
"PostProcess",
2974 inject(kFrameHeaderWGSL);
2975 inject(kTimeHeaderWGSL);
2976 if (parsed.materialBlockSize > 0) {
2977 std::string block =
"struct MaterialConstants {\n";
2978 for (
const auto& p : parsed.properties) {
2979 if (!p.fromParam || p.std140Offset < 0)
continue;
2980 block +=
" " + p.name +
" : " + wgslTypeName(p.type) +
",\n";
2983 "@group(0) @binding(1) var<uniform> mc : MaterialConstants;\n";
2986 std::string bodyText = bodyIt->second;
2990 fillHook(bodyText,
"@@ES_VERTEX_HOOK@@", parsed.wgslVertexHook);
2993 inject(wgslMaterialTextureDecls(parsed, bodyText, &parsed.wgslVertexHook));
2997 inject(wgslMaterialTextureDecls(parsed, bodyText, &bodyText));
3000 inject(wgslMaterialTextureDecls(parsed, bodyIt->second));
3002 if (parsed.domain ==
"PostProcess" && parsed.usesLights) inject(kPostLightHeaderWGSL);
3003 inject(kColorHelpersWGSL);
3009 inject(instanceRecordWGSL());
3014 inject(wgslReachedTextureDecls(preprocessConditionals(assembled.str() + bodyIt->second, features),
3015 parsed.domain ==
"PostProcess"));
3017 assembled << bodyText;
3019 result.source = preprocessConditionals(assembled.str(), features);
3020 result.headerLineCount = headerLines;
3026bool ShaderParser::s_linearColor =
false;
3029 if (!parsed.valid || !parsed.vertexIsCanonical)
return {};
3030 return wgslCanonicalVSOut(parsed.domain ==
"Lit");
3038 const std::string& platform,
3039 const std::vector<std::string>& featuresIn,
3045 std::vector<std::string> features = featuresIn;
3046 if (parsed.
lightingDirect && std::find(features.begin(), features.end(),
"ES_LIGHT_DIRECT") == features.end()) {
3047 features.push_back(
"ES_LIGHT_DIRECT");
3050 && std::find(features.begin(), features.end(),
"ES_LINEAR") == features.end()) {
3051 features.push_back(
"ES_LINEAR");
3057 features.erase(std::remove(features.begin(), features.end(), std::string(
"MESH_TANGENTS")), features.end());
3061 const auto has = [](
const std::vector<std::string>& list,
const char* name) {
return std::find(list.begin(), list.end(), name) != list.end(); };
3062 features.erase(std::remove(features.begin(), features.end(), std::string(
"MESH_LOCAL_POSITION")), features.end());
3064 features.push_back(
"MESH_LOCAL_POSITION");
3067 return assembleWGSLStage(parsed, stage, features);
3071 if (!parsed.
valid)
return result;
3073 auto stageIt = parsed.
stages.find(stage);
3074 if (stageIt == parsed.
stages.end())
return result;
3076 TextBuilder assembled;
3077 u32 headerLines = 0;
3079 if (!parsed.
version.empty()) {
3080 assembled <<
"#version " << parsed.
version <<
"\n";
3085 const auto named = parsed.
stages.find(stage);
3086 if (named != parsed.
stages.end() && namesRecords(named->second)) {
3087 assembled <<
"#ifndef VULKAN\n#extension GL_ANGLE_multi_draw : require\n#endif\n";
3095 for (
const auto& f : features) {
3096 assembled <<
"#define " << f <<
" 1\n";
3104 static const char* kColorHelpers =
3105 "highp vec3 srgbToLinear(highp vec3 c) {\n"
3106 " return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c));\n"
3108 "highp vec3 linearToSrgb(highp vec3 c) {\n"
3109 " return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));\n"
3114 "highp vec3 acesFilmic(highp vec3 x) {\n"
3115 " return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0.0, 1.0);\n"
3119 "highp vec3 pbrNeutral(highp vec3 c) {\n"
3120 " const highp float startCompression = 0.8 - 0.04;\n"
3121 " const highp float desaturation = 0.15;\n"
3122 " highp float x = min(c.r, min(c.g, c.b));\n"
3123 " highp float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n"
3125 " highp float peak = max(c.r, max(c.g, c.b));\n"
3126 " if (peak < startCompression) return c;\n"
3127 " const highp float d = 1.0 - startCompression;\n"
3128 " highp float newPeak = 1.0 - d * d / (peak + d - startCompression);\n"
3129 " c *= newPeak / peak;\n"
3130 " highp float g = 1.0 - 1.0 / (desaturation * (peak - newPeak) + 1.0);\n"
3131 " return mix(c, newPeak * vec3(1.0, 1.0, 1.0), g);\n"
3133 assembled << kColorHelpers;
3134 headerLines += countNewlines(kColorHelpers);
3143 static const char* kFrameHeader =
3144 "layout(std140) uniform FrameConstants {\n"
3145 " highp mat4 u_projection;\n"
3146 " highp vec4 u_camera;\n"
3147 " highp mat4 u_inverseViewProjection;\n"
3148 " highp vec4 u_renderOrigin;\n"
3150 "highp vec3 viewDirection(in highp vec3 worldPos) {\n"
3151 " return u_camera.w > 0.5 ? normalize(u_camera.xyz - worldPos) : u_camera.xyz;\n"
3153 "highp vec3 worldFromDepth(in highp vec2 uv, in highp float depth) {\n"
3154 " highp vec4 clip = vec4(uv * 2.0 - 1.0, depth * 2.0 - 1.0, 1.0);\n"
3155 " highp vec4 world = u_inverseViewProjection * clip;\n"
3156 " return world.xyz / world.w;\n"
3158 "highp float distanceToEye(in highp vec3 worldPos) {\n"
3159 " return u_camera.w > 0.5 ? length(worldPos - u_camera.xyz) : -dot(worldPos, u_camera.xyz);\n"
3161 "highp vec2 sceneUv(in highp vec3 worldPos) {\n"
3162 " highp vec4 clip = u_projection * vec4(worldPos, 1.0);\n"
3163 " return clamp(clip.xy / max(clip.w, 1e-4) * 0.5 + 0.5, vec2(0.001), vec2(0.999));\n"
3165 "highp float sceneDistance(in highp vec4 texel) {\n"
3166 " return texel.r < 65000.0 ? texel.r : texel.b * 1024.0;\n"
3168 assembled << kFrameHeader;
3169 headerLines += countNewlines(kFrameHeader);
3174 static const char* kTimeHeader =
3175 "layout(std140) uniform TimeConstants { highp vec4 u_time; highp vec4 u_viewport; highp vec4 u_quality; };\n";
3176 assembled << kTimeHeader;
3177 headerLines += countNewlines(kTimeHeader);
3187 assembled <<
"layout(std140) uniform MaterialConstants {\n";
3190 if (!p.fromParam || p.std140Offset < 0)
continue;
3191 assembled <<
" highp " << glslTypeName(p.type) <<
" " << p.name <<
";\n";
3194 assembled <<
"};\n";
3199 assembled << (p.layered ?
"uniform highp sampler2DArray " :
"uniform highp sampler2D ") << p.name <<
";\n";
3215 assembled <<
"#ifdef VULKAN\n"
3216 "#define ES_INSTANCE_ID gl_InstanceIndex\n"
3218 "#define ES_INSTANCE_ID gl_InstanceID\n"
3224 if (namesRecords(stageIt->second)) {
3225 const std::string decl = instanceRecordGLSLDecls();
3227 headerLines +=
static_cast<u32>(std::count(decl.begin(), decl.end(),
'\n'));
3233 assembled <<
"flat out highp float v_probeSlot;\n";
3240 static const char* kLitHeader =
3241 "struct Light { highp vec4 posDir; highp vec4 color; highp vec4 spot; highp vec4 shadow;"
3242 " highp vec4 shadowMap; highp vec4 falloff; };\n"
3243 "layout(std140) uniform LightConstants {\n"
3244 " highp vec4 u_ambient;\n"
3245 " Light u_lights[16];\n"
3246 " highp vec4 u_mask2DRect;\n"
3247 " highp mat4 u_shadowMatrix[16];\n"
3248 " highp vec4 u_shadowTile[16];\n"
3249 " highp vec4 u_shadowParams;\n"
3250 " highp vec4 u_envIrradiance[9];\n"
3251 " highp vec4 u_envParams;\n"
3252 " highp vec4 u_envTint;\n"
3253 " highp vec4 u_reflParams;\n"
3254 " highp vec4 u_reflBox[30];\n"
3255 " highp vec4 u_bakedTint;\n"
3256 " Light u_tiledLights[96];\n"
3257 " highp uvec4 u_tileMask[192];\n"
3258 " highp vec4 u_tileInfo;\n"
3259 " highp vec4 u_ambientGround;\n"
3260 " highp mat4 u_tileView;\n"
3261 " highp vec4 u_waterRect, u_waterDepth, u_waterSun;\n"
3266 "layout(std140) uniform ProbeConstants {\n"
3267 " highp vec4 u_probeIrradiance[10 * 100];\n"
3268 " highp vec4 u_probeTail;\n"
3270 "layout(std140) uniform PlanarConstants {\n"
3271 " highp mat4 u_planarProjection; highp vec4 u_planarParams;\n"
3273 "flat in highp float v_probeSlot;\n"
3276 "#ifdef ES_SURFACE_3D\n"
3277 "#ifndef MESH_LIGHTMAP\n"
3278 "uniform highp sampler3D u_probeGrid;\n"
3282 "highp vec3 g_probePos = vec3(0.0);\n"
3286 "#ifdef ES_RECEIVE_SHADOW\n"
3287 "uniform highp sampler2D u_shadowMap;\n"
3289 "#ifdef ES_ENV_MAP\n"
3290 "uniform highp sampler2D u_envMap;\n"
3295 "uniform highp sampler2D u_shadow2D;\n"
3296 "uniform highp sampler2D u_lightShape2D;\n"
3300 "highp vec3 packDepth(in highp float d) {\n"
3301 " highp vec3 enc = fract(d * vec3(1.0, 255.0, 65025.0));\n"
3302 " return enc - enc.yzz * vec3(1.0 / 255.0, 1.0 / 255.0, 0.0);\n"
3304 "highp float unpackDepth(in highp vec3 c) {\n"
3305 " return dot(c, vec3(1.0, 1.0 / 255.0, 1.0 / 65025.0));\n"
3310 "highp float stepFor(in highp float texel, in highp float slope,\n"
3311 " in highp float reach) {\n"
3312 " return texel * (1.5 * (1.0 + slope) + reach * slope);\n"
3314 "highp float shadowDepth(in highp mat4 m, in highp vec3 p) {\n"
3315 " highp vec4 c = m * vec4(p, 1.0);\n"
3316 " return clamp(c.z / max(c.w, 1e-6) * 0.5 + 0.5, 0.0, 1.0);\n"
3320 "highp float shadowTap(in highp vec2 at, in highp vec2 lo, in highp vec2 hi,\n"
3321 " in highp float here) {\n"
3322 "#ifdef ES_RECEIVE_SHADOW\n"
3323 " return unpackDepth(texture(u_shadowMap, clamp(at, lo, hi)).rgb) < here\n"
3330 "highp float g_hairShadow = 0.0;\n"
3332 "highp float g_shadowHard = 0.0;\n"
3335 "highp vec2 diskTap(in int i, in int n, in highp float radius) {\n"
3336 " highp float a = float(i) * 2.3999632;\n"
3337 " return radius * sqrt((float(i) + 0.5) / float(n)) * vec2(cos(a), sin(a));\n"
3340 "highp vec2 diskTapSpun(in int i, in int n, in highp float radius, in highp float spin) {\n"
3341 " highp float a = float(i) * 2.3999632 + spin;\n"
3342 " return radius * sqrt((float(i) + 0.5) / float(n)) * vec2(cos(a), sin(a));\n"
3344 "highp float shadowSpin(in highp vec3 worldPos) {\n"
3345 " return 6.2831853 * fract(sin(dot(worldPos, vec3(12.9898, 78.233, 37.719))) * 43758.5453);\n"
3347 "// The spiral taps for 16 and 32 points, as numbers: the cos, the sin and the root of each tap do not change from one pixel to the next, so they are\n"
3348 "// not worked out in the pixel (a sin, a cos and a sqrt a tap, forty-eight taps). Each is turned by the pixel's own spin where it is used.\n"
3349 "const highp vec2 kInner5[5] = vec2[5](vec2(0.0), vec2(1.5, 0.0), vec2(-1.5, 0.0), vec2(0.0, 1.5), vec2(0.0, -1.5));\n"
3350 "const highp vec2 kSpiral8[8] = vec2[8](\n"
3351 " vec2(0.2500000, 0.0000000),\n"
3352 " vec2(-0.3192901, 0.2924959),\n"
3353 " vec2(0.0488724, -0.5568765),\n"
3354 " vec2(0.4024445, 0.5249175),\n"
3355 " vec2(-0.7385351, -0.1306364),\n"
3356 " vec2(0.6996049, -0.4450315),\n"
3357 " vec2(-0.2340040, 0.8704838),\n"
3358 " vec2(-0.4462715, -0.8592682));\n"
3359 "const highp vec2 kSpiral16[16] = vec2[16](\n"
3360 " vec2(0.1767767, 0.0000000),\n"
3361 " vec2(-0.2257722, 0.2068258),\n"
3362 " vec2(0.0345580, -0.3937712),\n"
3363 " vec2(0.2845713, 0.3711727),\n"
3364 " vec2(-0.5222232, -0.0923739),\n"
3365 " vec2(0.4946953, -0.3146848),\n"
3366 " vec2(-0.1654658, 0.6155250),\n"
3367 " vec2(-0.3155616, -0.6075943),\n"
3368 " vec2(0.6846422, 0.2500301),\n"
3369 " vec2(-0.7122560, 0.2940091),\n"
3370 " vec2(0.3433543, -0.7337287),\n"
3371 " vec2(0.2537305, 0.8089319),\n"
3372 " vec2(-0.7647461, -0.4431856),\n"
3373 " vec2(0.8971339, -0.1972327),\n"
3374 " vec2(-0.5475066, 0.7787725),\n"
3375 " vec2(-0.1264872, -0.9760896));\n"
3376 "const highp vec2 kSpiral32[32] = vec2[32](\n"
3377 " vec2(0.1250000, 0.0000000),\n"
3378 " vec2(-0.1596450, 0.1462479),\n"
3379 " vec2(0.0244362, -0.2784383),\n"
3380 " vec2(0.2012223, 0.2624588),\n"
3381 " vec2(-0.3692676, -0.0653182),\n"
3382 " vec2(0.3498024, -0.2225157),\n"
3383 " vec2(-0.1170020, 0.4352419),\n"
3384 " vec2(-0.2231357, -0.4296341),\n"
3385 " vec2(0.4841152, 0.1767979),\n"
3386 " vec2(-0.5036411, 0.2078959),\n"
3387 " vec2(0.2427881, -0.5188246),\n"
3388 " vec2(0.1794146, 0.5720012),\n"
3389 " vec2(-0.5407571, -0.3133795),\n"
3390 " vec2(0.6343695, -0.1394646),\n"
3391 " vec2(-0.3871456, 0.5506753),\n"
3392 " vec2(-0.0894400, -0.6901996),\n"
3393 " vec2(0.5490720, 0.4627580),\n"
3394 " vec2(-0.7388785, 0.0305553),\n"
3395 " vec2(0.5389548, -0.5363326),\n"
3396 " vec2(-0.0360577, 0.7797915),\n"
3397 " vec2(-0.5128179, -0.6145265),\n"
3398 " vec2(0.8123597, 0.1093013),\n"
3399 " vec2(-0.6883103, 0.4789091),\n"
3400 " vec2(0.1880855, -0.8360615),\n"
3401 " vec2(0.4350338, 0.7591907),\n"
3402 " vec2(-0.8504486, -0.2713156),\n"
3403 " vec2(0.8261021, -0.3816809),\n"
3404 " vec2(-0.3578875, 0.8551558),\n"
3405 " vec2(-0.3194081, -0.8880335),\n"
3406 " vec2(0.8499090, 0.4466874),\n"
3407 " vec2(-0.9440344, 0.2488453),\n"
3408 " vec2(0.5365950, -0.8345303));\n"
3411 "highp float cloudShadow3D(in highp vec3 worldPos, in int t) {\n"
3412 "#ifndef ES_RECEIVE_SHADOW\n"
3415 " highp vec2 uv = (u_shadowMatrix[t] * vec4(worldPos, 1.0)).xy * 0.5 + 0.5;\n"
3416 " if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) return 1.0;\n"
3417 " highp vec4 rect = u_shadowTile[t];\n"
3418 " highp float texel = u_shadowParams.y;\n"
3419 " highp vec2 p = (rect.xy + uv * rect.z) / texel - 0.5;\n"
3420 " highp vec2 f = fract(p);\n"
3421 " highp vec2 at = (floor(p) + 0.5) * texel;\n"
3422 " highp vec2 lo = rect.xy + texel * 0.5;\n"
3423 " highp vec2 hi = rect.xy + rect.z - texel * 0.5;\n"
3424 " highp float a = textureLod(u_shadowMap, clamp(at, lo, hi), 0.0).a;\n"
3425 " highp float b = textureLod(u_shadowMap, clamp(at + vec2(texel, 0.0), lo, hi), 0.0).a;\n"
3426 " highp float c = textureLod(u_shadowMap, clamp(at + vec2(0.0, texel), lo, hi), 0.0).a;\n"
3427 " highp float d = textureLod(u_shadowMap, clamp(at + vec2(texel), lo, hi), 0.0).a;\n"
3428 " return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);\n"
3434 "highp float shadowFactor3D(in highp vec3 worldPos, in highp vec3 N, in highp vec3 L,\n"
3435 " in highp vec2 source, in int first, in int count) {\n"
3436 "#ifndef ES_RECEIVE_SHADOW\n"
3439 " if (u_shadowParams.x < 0.5) return 1.0;\n"
3443 " highp float NoL = clamp(dot(N, L), 0.0, 1.0);\n"
3446 " for (int k = 0; k < 16; ++k) {\n"
3447 " if (k >= count) break;\n"
3448 " int t = first + k;\n"
3449 " highp mat4 m = u_shadowMatrix[t];\n"
3450 " highp vec4 lc = m * vec4(worldPos, 1.0);\n"
3454 " if (lc.w <= 0.0) continue;\n"
3455 " highp vec3 proj = lc.xyz / lc.w;\n"
3456 " highp vec2 uv = proj.xy * 0.5 + 0.5;\n"
3460 " if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0\n"
3461 " || proj.z < 0.0 || proj.z > 1.0) continue;\n"
3464 " highp vec4 rect = u_shadowTile[t];\n"
3465 " highp float biasTexels = floor(rect.w);\n"
3466 " highp vec2 bias = vec2(biasTexels * (1.0 / 64.0), rect.w - biasTexels);\n"
3467 " highp float slope = sqrt(1.0 - NoL * NoL) / max(NoL, bias.y);\n"
3471 " highp float texels = max(rect.z / max(u_shadowParams.y, 1e-9), 1.0);\n"
3472 " highp float across = length(vec3(m[0][0], m[1][0], m[2][0]));\n"
3473 " highp float texel = 2.0 * lc.w / max(across * texels, 1e-9);\n"
3477 " highp float lean = min(slope, 1.2);\n"
3478 " highp float biasStep = texel * bias.x;\n"
3479 " highp vec3 aside = worldPos + N * (biasStep * max(sqrt(1.0 - NoL * NoL) - lean * NoL, 0.0));\n"
3480 " highp vec4 lcq = m * vec4(aside, 1.0);\n"
3481 " highp vec2 uvq = lcq.xy / max(lcq.w, 1e-6) * 0.5 + 0.5;\n"
3482 " highp float here = shadowDepth(m, aside + L * (biasStep * (1.0 + lean)));\n"
3483 " highp vec2 at0 = rect.xy + uvq * rect.z;\n"
3484 " highp vec2 lo = rect.xy + u_shadowParams.y * 0.5;\n"
3485 " highp vec2 hi = rect.xy + rect.z - u_shadowParams.y * 0.5;\n"
3489 " bool hasEye = length(vec3(m[0][3], m[1][3], m[2][3])) > 0.5;\n"
3490 " highp float src = hasEye ? source.x : source.y;\n"
3491 "#ifndef ES_LIGHT_DIRECT\n"
3494 " if (g_hairShadow > 0.0) {\n"
3495 " highp float reachHair = shadowDepth(m, worldPos + L * stepFor(texel, slope, 2.0));\n"
3496 " highp float sumHair = 0.0;\n"
3497 " highp float hitsHair = 0.0;\n"
3498 " for (int i = 0; i < 8; ++i) {\n"
3499 " highp vec2 at = clamp(at0 + diskTap(i, 8, 2.0) * u_shadowParams.y, lo, hi);\n"
3500 " highp float d = unpackDepth(texture(u_shadowMap, at).rgb);\n"
3501 " if (d < reachHair) { sumHair += d; hitsHair += 1.0; }\n"
3503 " if (hitsHair < 0.5) return 1.0;\n"
3504 " highp float Ah = length(vec3(m[0][2], m[1][2], m[2][2]));\n"
3505 " highp float zbh = 2.0 * (sumHair / hitsHair) - 1.0;\n"
3506 " highp float spanHair = (proj.z - zbh) / max(Ah, 1e-9);\n"
3507 " if (hasEye) spanHair = lc.w - lc.w * (Ah - proj.z) / max(Ah - zbh, 1e-6);\n"
3508 " return mix(1.0, exp(-g_hairShadow * max(spanHair, 0.0)), hitsHair * 0.125);\n"
3514 "#ifdef ES_LIGHT_DIRECT\n"
3517 " if (src <= 0.0 || g_shadowHard > 0.5) {\n"
3519 " highp float texelUv = u_shadowParams.y;\n"
3520 " highp vec2 f = at0 / texelUv - 1.0;\n"
3521 " highp vec2 c = (floor(f) + 0.5) * texelUv;\n"
3522 " highp vec2 t = fract(f);\n"
3523 " highp vec3 wx = vec3((1.0 - t.x) * 0.5, 0.5, t.x * 0.5);\n"
3524 " highp vec3 wy = vec3((1.0 - t.y) * 0.5, 0.5, t.y * 0.5);\n"
3525 " highp float lit = 0.0;\n"
3526 " for (int y = 0; y < 3; ++y) {\n"
3527 " for (int x = 0; x < 3; ++x) {\n"
3528 " lit += wx[x] * wy[y] * shadowTap(c + vec2(float(x), float(y)) * texelUv,\n"
3534 "#ifndef ES_LIGHT_DIRECT\n"
3539 " highp float spin = shadowSpin(worldPos);\n"
3540 " highp vec2 turn = vec2(cos(spin), sin(spin));\n"
3541 " // The depth a tap forgives to is that of the point a step toward the light, and the step is linear in how far the tap stands: so the\n"
3542 " // matrix is applied to the direction once, and a tap moves the clip position along it instead of going through the matrix again.\n"
3543 " highp vec4 toLight = m * vec4(L, 0.0);\n"
3544 " highp float stepBase = biasStep * (1.0 + lean);\n"
3545 " highp float stepPer = texel * slope;\n"
3546 " highp float sum = 0.0;\n"
3547 " highp float hits = 0.0;\n"
3548 " for (int i = 0; i < 5; ++i) {\n"
3549 " highp vec2 p = kInner5[i];\n"
3550 " highp vec2 off = vec2(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);\n"
3551 " highp vec2 at = clamp(at0 + off * u_shadowParams.y, lo, hi);\n"
3552 " highp float d = unpackDepth(texture(u_shadowMap, at).rgb);\n"
3553 " highp vec4 cr = lcq + toLight * (stepBase + max(length(off), 1.0) * stepPer);\n"
3554 " highp float reach = clamp(cr.z / max(cr.w, 1e-6) * 0.5 + 0.5, 0.0, 1.0);\n"
3555 " if (d < reach) { sum += d; hits += 1.0; }\n"
3557 " bool fewBlockers = u_quality.y > 0.0 && u_quality.y < 12.0;\n"
3558 " highp float disc = u_quality.w > 0.0 ? max(u_quality.w, 0.5) : 24.0;\n"
3559 " if (fewBlockers) {\n"
3560 " for (int i = 0; i < 8; ++i) {\n"
3561 " highp vec2 p = kSpiral8[i];\n"
3562 " highp vec2 off = disc * vec2(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);\n"
3563 " highp vec2 at = clamp(at0 + off * u_shadowParams.y, lo, hi);\n"
3564 " highp float d = unpackDepth(texture(u_shadowMap, at).rgb);\n"
3565 " highp vec4 cr = lcq + toLight * (stepBase + max(length(off), 1.0) * stepPer);\n"
3566 " highp float reach = clamp(cr.z / max(cr.w, 1e-6) * 0.5 + 0.5, 0.0, 1.0);\n"
3567 " if (d < reach) { sum += d; hits += 1.0; }\n"
3570 " for (int i = 0; i < 16; ++i) {\n"
3571 " highp vec2 p = kSpiral16[i];\n"
3572 " highp vec2 off = disc * vec2(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);\n"
3573 " highp vec2 at = clamp(at0 + off * u_shadowParams.y, lo, hi);\n"
3574 " highp float d = unpackDepth(texture(u_shadowMap, at).rgb);\n"
3575 " highp vec4 cr = lcq + toLight * (stepBase + max(length(off), 1.0) * stepPer);\n"
3576 " highp float reach = clamp(cr.z / max(cr.w, 1e-6) * 0.5 + 0.5, 0.0, 1.0);\n"
3577 " if (d < reach) { sum += d; hits += 1.0; }\n"
3580 " if (hits < 0.5) return 1.0;\n"
3581 " if (hits > (fewBlockers ? 12.5 : 20.5)) return 0.0;\n"
3586 " highp float A = length(vec3(m[0][2], m[1][2], m[2][2]));\n"
3587 " highp float zb = 2.0 * (sum / hits) - 1.0;\n"
3588 " highp float dbw = 1.0;\n"
3589 " highp float span = (proj.z - zb) / max(A, 1e-9);\n"
3591 " dbw = lc.w * (A - proj.z) / max(A - zb, 1e-6);\n"
3592 " span = lc.w - dbw;\n"
3597 " highp float radius = clamp(src * span / max(dbw * texel, 1e-4),\n"
3599 " highp float wide = shadowDepth(m, aside + L * (biasStep * (1.0 + lean) + texel * radius * slope));\n"
3600 " highp float soft = 0.0;\n"
3601 " if (radius < 1.5 || (u_quality.z > 0.0 && u_quality.z < 12.0)) {\n"
3602 " for (int i = 0; i < 8; ++i) {\n"
3603 " highp vec2 p = kSpiral8[i];\n"
3604 " highp vec2 off = radius * vec2(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);\n"
3605 " soft += shadowTap(at0 + off * u_shadowParams.y, lo, hi, wide);\n"
3607 " return soft * (1.0 / 8.0);\n"
3609 " if (radius < 4.0 || (u_quality.z > 0.0 && u_quality.z < 24.0)) {\n"
3610 " for (int i = 0; i < 16; ++i) {\n"
3611 " highp vec2 p = kSpiral16[i];\n"
3612 " highp vec2 off = radius * vec2(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);\n"
3613 " soft += shadowTap(at0 + off * u_shadowParams.y, lo, hi, wide);\n"
3615 " return soft * (1.0 / 16.0);\n"
3617 " for (int i = 0; i < 32; ++i) {\n"
3618 " highp vec2 p = kSpiral32[i];\n"
3619 " highp vec2 off = radius * vec2(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);\n"
3620 " soft += shadowTap(at0 + off * u_shadowParams.y, lo, hi, wide);\n"
3622 " return soft * (1.0 / 32.0);\n"
3630 "highp float cutoutCoverage(in highp float a, in highp float cutoff, in highp float edge) {\n"
3631 " return (a - cutoff) / max(edge, 1e-4) + 0.5;\n"
3636 "highp vec3 sampleNormal(in highp sampler2D map, in highp vec2 uv) {\n"
3637 " highp vec2 xy = texture(map, uv).xy * 2.0 - 1.0;\n"
3638 " return vec3(xy, sqrt(max(0.0, 1.0 - dot(xy, xy))));\n"
3640 "highp vec3 sampleNormalGrad(in highp sampler2D map, in highp vec2 uv,\n"
3641 " in highp vec2 ddx, in highp vec2 ddy) {\n"
3642 " highp vec2 xy = textureGrad(map, uv, ddx, ddy).xy * 2.0 - 1.0;\n"
3643 " return vec3(xy, sqrt(max(0.0, 1.0 - dot(xy, xy))));\n"
3645 "highp vec3 scaleNormal(in highp vec3 normal, in highp float scale) {\n"
3646 " highp vec3 n = normal * vec3(scale, scale, 1.0);\n"
3647 " return dot(n, n) < 1e-12 ? vec3(0.0, 0.0, 1.0) : normalize(n);\n"
3654 "#ifdef MESH_TANGENTS\n"
3655 "in highp vec4 v_worldTangent;\n"
3657 "highp vec3 perturbNormal(in highp vec3 N, in highp vec3 worldPos,\n"
3658 " in highp vec2 uv, in highp vec3 tangentNormal) {\n"
3659 "#ifdef MESH_TANGENTS\n"
3661 " highp vec3 Tg = normalize(v_worldTangent.xyz - N * dot(N, v_worldTangent.xyz));\n"
3662 " highp vec3 Bg = cross(N, Tg) * v_worldTangent.w;\n"
3663 " return normalize(mat3(Tg, Bg, N) * tangentNormal);\n"
3665 " highp vec3 dp1 = dFdx(worldPos);\n"
3666 " highp vec3 dp2 = dFdy(worldPos);\n"
3667 " highp vec2 duv1 = dFdx(uv);\n"
3668 " highp vec2 duv2 = dFdy(uv);\n"
3669 " highp vec3 dp2perp = cross(dp2, N);\n"
3670 " highp vec3 dp1perp = cross(N, dp1);\n"
3671 " highp vec3 T = dp2perp * duv1.x + dp1perp * duv2.x;\n"
3672 " highp vec3 B = dp2perp * duv1.y + dp1perp * duv2.y;\n"
3675 " highp float m = max(dot(T, T), dot(B, B));\n"
3676 " highp float scale = max(dot(dp1, dp1), dot(dp2, dp2)) * max(dot(duv1, duv1), dot(duv2, duv2));\n"
3677 " if (!(m > scale * 1e-6)) return N;\n"
3678 " return normalize(mat3(T * inversesqrt(max(dot(T, T), 1e-20)), B * inversesqrt(max(dot(B, B), 1e-20)), N) * tangentNormal);\n"
3684 "highp vec2 mask2DUv(in highp vec2 worldPos) {\n"
3685 " highp vec4 clip = u_projection * vec4(worldPos, 0.0, 1.0);\n"
3686 " if (clip.w <= 0.0) return vec2(-1.0);\n"
3687 " highp vec2 ndc = clip.xy / clip.w * 0.5 + 0.5;\n"
3688 " return u_mask2DRect.xy + ndc * u_mask2DRect.zw;\n"
3690 "highp float mask2DChannel(in highp vec4 m, in highp float channel) {\n"
3691 " return (channel < 0.5) ? m.r : (channel < 1.5) ? m.g\n"
3692 " : (channel < 2.5) ? m.b : m.a;\n"
3697 "highp float shadowFactor2D(in highp float channel, in highp vec2 worldPos) {\n"
3698 " if (channel < 0.0 || u_mask2DRect.z <= 0.0) return 1.0;\n"
3699 " highp vec2 uv = mask2DUv(worldPos);\n"
3700 " if (uv.x < 0.0) return 1.0;\n"
3704 " highp float hidden = (channel < 3.5)\n"
3705 " ? mask2DChannel(textureLod(u_shadow2D, uv, 0.0), channel)\n"
3706 " : mask2DChannel(textureLod(u_lightShape2D, uv, 0.0), channel - 4.0);\n"
3707 " return 1.0 - min(hidden, 1.0);\n"
3711 "highp float shapeFactor2D(in highp float channel, in highp vec2 worldPos) {\n"
3712 " if (channel < 0.0 || u_mask2DRect.z <= 0.0) return 1.0;\n"
3713 " highp vec2 uv = mask2DUv(worldPos);\n"
3714 " if (uv.x < 0.0) return 1.0;\n"
3715 " return min(mask2DChannel(textureLod(u_lightShape2D, uv, 0.0), channel), 1.0);\n"
3720 "highp float distributionGGX(in highp float NdotH, in highp float a) {\n"
3721 " highp float a2 = a * a;\n"
3722 " highp float d = NdotH * NdotH * (a2 - 1.0) + 1.0;\n"
3723 " return a2 / max(3.14159265 * d * d, 1e-7);\n"
3725 "highp float geometrySmith(in highp float NdotV, in highp float NdotL,\n"
3726 " in highp float roughness) {\n"
3727 " highp float k = (roughness + 1.0) * (roughness + 1.0) * 0.125;\n"
3728 " return (NdotV / (NdotV * (1.0 - k) + k)) * (NdotL / (NdotL * (1.0 - k) + k));\n"
3731 "highp float visibilitySmithGGX(in highp float NdotV, in highp float NdotL, in highp float a) {\n"
3732 " highp float a2 = a * a;\n"
3733 " highp float gv = NdotL * sqrt(NdotV * NdotV * (1.0 - a2) + a2);\n"
3734 " highp float gl = NdotV * sqrt(NdotL * NdotL * (1.0 - a2) + a2);\n"
3735 " return 0.5 / max(gv + gl, 1e-5);\n"
3737 "highp vec3 fresnelSchlick(in highp float VdotH, in highp vec3 F0) {\n"
3738 " return F0 + (vec3(1.0) - F0) * pow(1.0 - VdotH, 5.0);\n"
3741 "highp vec2 envBRDFApprox(in highp float NdotV, in highp float roughness) {\n"
3742 " highp float tx = (2.0 * (clamp(NdotV, 0.02, 1.0) - 0.02) / 0.98 - 1.0);\n"
3743 " highp float ty = 2.0 * clamp(roughness, 0.0, 1.0) - 1.0;\n"
3744 " highp float px0 = 1.0;\n"
3745 " highp float px1 = tx;\n"
3746 " highp float px2 = (3.0 * tx * px1 - 1.0 * px0) / 2.0;\n"
3747 " highp float px3 = (5.0 * tx * px2 - 2.0 * px1) / 3.0;\n"
3748 " highp float px4 = (7.0 * tx * px3 - 3.0 * px2) / 4.0;\n"
3749 " highp float px5 = (9.0 * tx * px4 - 4.0 * px3) / 5.0;\n"
3750 " highp float px6 = (11.0 * tx * px5 - 5.0 * px4) / 6.0;\n"
3751 " highp float py0 = 1.0;\n"
3752 " highp float py1 = ty;\n"
3753 " highp float py2 = (3.0 * ty * py1 - 1.0 * py0) / 2.0;\n"
3754 " highp float py3 = (5.0 * ty * py2 - 2.0 * py1) / 3.0;\n"
3755 " highp float py4 = (7.0 * ty * py3 - 3.0 * py2) / 4.0;\n"
3756 " highp float py5 = (9.0 * ty * py4 - 4.0 * py3) / 5.0;\n"
3757 " highp float py6 = (11.0 * ty * py5 - 5.0 * py4) / 6.0;\n"
3758 " highp float g = 1.0 / (clamp(NdotV, 0.02, 1.0) + 0.1);\n"
3759 " highp float sumMetal = (0.7771111 - 0.2780760 * py1 - 0.0654304 * py2 - 0.0705640 * py3 + 0.0859185 * py4 + 0.0016314 * py5 - 0.0014479 * py6) + px1 * (0.0048182 - 0.1346961 * py1 - 0.1342442 * py2 + 0.1115811 * py3 - 0.0497620 * py4 - 0.0098451 * py5 - 0.0004214 * py6) + px2 * (0.0004797 + 0.0654544 * py1 + 0.0215100 * py2 - 0.0948616 * py3 + 0.0774489 * py4 + 0.0139819 * py5 - 0.0151021 * py6) + px3 * (0.0022918 - 0.0244567 * py1 + 0.0056279 * py2 + 0.0393924 * py3 - 0.0613759 * py4 + 0.0099383 * py5 + 0.0092971 * py6) + px4 * (-0.0025728 + 0.0085869 * py1 - 0.0069877 * py2 - 0.0115072 * py3 + 0.0327063 * py4 - 0.0167796 * py5 + 0.0019107 * py6) + px5 * (0.0018089 - 0.0031015 * py1 + 0.0047701 * py2 + 0.0018675 * py3 - 0.0134691 * py4 + 0.0139776 * py5 - 0.0087024 * py6) + px6 * (-0.0008609 + 0.0010956 * py1 - 0.0024048 * py2 + 0.0005262 * py3 + 0.0035639 * py4 - 0.0080487 * py5 + 0.0080563 * py6) + g * (0.0220605 + 0.0049886 * py1 - 0.0108884 * py2 + 0.0359254 * py3 - 0.0336876 * py4);\n"
3760 " highp float sumDielectric = (0.1105178 - 0.1470108 * py1 + 0.0706290 * py2 - 0.0048613 * py3 - 0.0190413 * py4 + 0.0038142 * py5 - 0.0002643 * py6) + px1 * (-0.1400053 + 0.2220226 * py1 - 0.1204309 * py2 + 0.0033027 * py3 + 0.0348652 * py4 - 0.0115348 * py5 + 0.0015711 * py6) + px2 * (0.0993738 - 0.1696809 * py1 + 0.1055418 * py2 - 0.0166890 * py3 - 0.0245166 * py4 + 0.0153020 * py5 - 0.0048468 * py6) + px3 * (-0.0363361 + 0.0724203 * py1 - 0.0631513 * py2 + 0.0261354 * py3 + 0.0041759 * py4 - 0.0092203 * py5 + 0.0054510 * py6) + px4 * (0.0046882 - 0.0144579 * py1 + 0.0238812 * py2 - 0.0200861 * py3 + 0.0078934 * py4 - 0.0001779 * py5 - 0.0024009 * py6) + px5 * (0.0013258 - 0.0006506 * py1 - 0.0049831 * py2 + 0.0084229 * py3 - 0.0075026 * py4 + 0.0046720 * py5 - 0.0007627 * py6) + px6 * (-0.0005364 + 0.0008141 * py1 + 0.0002790 * py2 - 0.0016584 * py3 + 0.0027280 * py4 - 0.0028646 * py5 + 0.0010557 * py6) + g * (-0.0075790 + 0.0243928 * py1 - 0.0212081 * py2 + 0.0063496 * py3 + 0.0036408 * py4);\n"
3761 " highp float scale = (sumMetal - sumDielectric) / 0.96;\n"
3762 " return vec2(scale, sumMetal - scale);\n"
3765 "highp vec3 envDirection(in highp vec3 d) {\n"
3766 " highp float a = -u_envTint.a;\n"
3767 " highp float s = sin(a);\n"
3768 " highp float c = cos(a);\n"
3769 " return vec3(c * d.x + s * d.z, d.y, -s * d.x + c * d.z);\n"
3773 "highp vec3 shIrradiance(in highp vec4 sh[9], in highp vec3 N) {\n"
3774 " return sh[0].rgb * 0.282095\n"
3775 " + sh[1].rgb * (0.488603 * N.y)\n"
3776 " + sh[2].rgb * (0.488603 * N.z)\n"
3777 " + sh[3].rgb * (0.488603 * N.x)\n"
3778 " + sh[4].rgb * (1.092548 * N.x * N.y)\n"
3779 " + sh[5].rgb * (1.092548 * N.y * N.z)\n"
3780 " + sh[6].rgb * (0.315392 * (3.0 * N.z * N.z - 1.0))\n"
3781 " + sh[7].rgb * (1.092548 * N.x * N.z)\n"
3782 " + sh[8].rgb * (0.546274 * (N.x * N.x - N.y * N.y));\n"
3788 "highp vec3 ambientFacing(in highp vec3 dir) {\n"
3789 " return u_ambient.rgb + u_ambientGround.rgb * (0.5 - 0.5 * dir.y);\n"
3791 "highp vec3 envIrradiance(in highp vec3 Nw) {\n"
3793 " highp vec3 N = envDirection(Nw);\n"
3794 " highp vec3 sh = u_envIrradiance[0].rgb * 0.282095\n"
3795 " + u_envIrradiance[1].rgb * (0.488603 * N.y)\n"
3796 " + u_envIrradiance[2].rgb * (0.488603 * N.z)\n"
3797 " + u_envIrradiance[3].rgb * (0.488603 * N.x)\n"
3798 " + u_envIrradiance[4].rgb * (1.092548 * N.x * N.y)\n"
3799 " + u_envIrradiance[5].rgb * (1.092548 * N.y * N.z)\n"
3800 " + u_envIrradiance[6].rgb * (0.315392 * (3.0 * N.z * N.z - 1.0))\n"
3801 " + u_envIrradiance[7].rgb * (1.092548 * N.x * N.z)\n"
3802 " + u_envIrradiance[8].rgb * (0.546274 * (N.x * N.x - N.y * N.y));\n"
3803 " return ambientFacing(Nw) + max(sh, vec3(0.0)) * u_envTint.rgb;\n"
3808 "highp int probeRun() { return clamp(int(v_probeSlot), 0, 99) * 10; }\n"
3812 "highp float reflectionColumn() { return u_probeIrradiance[probeRun() + 9].x; }\n"
3818 "#ifdef ES_SURFACE_3D\n"
3819 "#ifndef MESH_LIGHTMAP\n"
3820 "highp vec4 probeGridIrradiance(in highp vec3 N, in highp vec3 P) {\n"
3821 " highp int base = probeRun();\n"
3822 " highp vec4 a = u_probeIrradiance[base + 1];\n"
3823 " highp vec4 b = u_probeIrradiance[base + 2];\n"
3824 " highp vec4 c = u_probeIrradiance[base + 3];\n"
3825 " highp vec4 d = u_probeIrradiance[base + 4];\n"
3826 " highp vec3 last = vec3(a.w, b.w, c.w);\n"
3827 " highp vec3 g = clamp((P - a.xyz) * b.xyz, vec3(0.0), last);\n"
3828 " highp vec3 cell = min(floor(g * 0.25), max(ceil(last * 0.25) - 1.0, vec3(0.0)));\n"
3829 " highp vec4 brick = texelFetch(u_probeGrid, ivec3(c.xyz + cell + 0.5), 0);\n"
3830 " highp vec3 first = floor(cell / brick.w) * brick.w;\n"
3831 " highp vec3 uvw = (brick.xyz + (g - first * 4.0) / brick.w + 0.5) * d.xyz;\n"
3832 " highp float basis[9];\n"
3833 " basis[0] = 0.282095;\n"
3834 " basis[1] = 0.488603 * N.y;\n"
3835 " basis[2] = 0.488603 * N.z;\n"
3836 " basis[3] = 0.488603 * N.x;\n"
3837 " basis[4] = 1.092548 * N.x * N.y;\n"
3838 " basis[5] = 1.092548 * N.y * N.z;\n"
3839 " basis[6] = 0.315392 * (3.0 * N.z * N.z - 1.0);\n"
3840 " basis[7] = 1.092548 * N.x * N.z;\n"
3841 " basis[8] = 0.546274 * (N.x * N.x - N.y * N.y);\n"
3842 " highp vec4 sum = vec4(0.0);\n"
3843 " for (int i = 0; i < 9; i++) {\n"
3844 " sum += textureLod(u_probeGrid, uvw + vec3(float(i) * d.w * d.x, 0.0, 0.0), 0.0) * basis[i];\n"
3855 "highp float skyOcclusion(in highp vec3 d) {\n"
3856 " highp int base = probeRun();\n"
3857 " highp float v = u_probeIrradiance[base + 9].y * 0.282095\n"
3858 " + u_probeIrradiance[base + 1].w * (0.488603 * d.y)\n"
3859 " + u_probeIrradiance[base + 2].w * (0.488603 * d.z)\n"
3860 " + u_probeIrradiance[base + 3].w * (0.488603 * d.x)\n"
3861 " + u_probeIrradiance[base + 4].w * (1.092548 * d.x * d.y)\n"
3862 " + u_probeIrradiance[base + 5].w * (1.092548 * d.y * d.z)\n"
3863 " + u_probeIrradiance[base + 6].w * (0.315392 * (3.0 * d.z * d.z - 1.0))\n"
3864 " + u_probeIrradiance[base + 7].w * (1.092548 * d.x * d.z)\n"
3865 " + u_probeIrradiance[base + 8].w * (0.546274 * (d.x * d.x - d.y * d.y));\n"
3866 "#ifdef ES_SURFACE_3D\n"
3867 "#ifndef MESH_LIGHTMAP\n"
3868 " if (u_probeIrradiance[base].w > 1.5) v = probeGridIrradiance(d, g_probePos).a;\n"
3871 " return mix(1.0, clamp(v, 0.0, 1.0), step(0.5, u_probeIrradiance[base + 9].z));\n"
3880 "highp vec3 indirectIrradiance(in highp vec3 N) {\n"
3881 " highp int base = probeRun();\n"
3882 " highp float mode = u_probeIrradiance[base].w;\n"
3883 " highp vec3 result;\n"
3884 "#ifdef ES_SURFACE_3D\n"
3885 "#ifndef MESH_LIGHTMAP\n"
3886 " if (mode > 1.5) {\n"
3887 " highp vec4 grid = probeGridIrradiance(N, g_probePos);\n"
3888 " highp float sky = step(0.5, u_probeIrradiance[base + 9].z);\n"
3889 " result = max(grid.rgb, vec3(0.0)) * u_bakedTint.rgb + envIrradiance(N) * (clamp(grid.a, 0.0, 1.0) * sky);\n"
3893 " if (mode > 0.5) {\n"
3894 " highp vec4 sh[9];\n"
3895 " for (int i = 0; i < 9; i++) sh[i] = u_probeIrradiance[base + i];\n"
3896 " highp float sky = step(0.5, u_probeIrradiance[base + 9].z);\n"
3897 " result = max(shIrradiance(sh, N), vec3(0.0)) * u_bakedTint.rgb + envIrradiance(N) * (skyOcclusion(N) * sky);\n"
3899 " result = envIrradiance(N);\n"
3901 "#ifdef MESH_LIGHTMAP\n"
3902 " if (v_lightmap.z > 0.5) result = bakedIrradiance() * u_bakedTint.rgb;\n"
3908 "highp vec2 octEncode(in highp vec3 d) {\n"
3909 " highp vec2 p = d.xz / max(abs(d.x) + abs(d.y) + abs(d.z), 1e-6);\n"
3910 " if (d.y < 0.0) {\n"
3911 " p = (1.0 - abs(p.yx)) * vec2(p.x >= 0.0 ? 1.0 : -1.0, p.y >= 0.0 ? 1.0 : -1.0);\n"
3913 " return p * 0.5 + 0.5;\n"
3918 "highp vec3 envSampleColumn(in highp vec3 R, in highp float mip,\n"
3919 " in highp float column) {\n"
3920 "#ifndef ES_ENV_MAP\n"
3921 " return vec3(0.0);\n"
3923 " highp float face = u_envParams.w;\n"
3924 " highp float size = face * exp2(-mip);\n"
3925 " highp float yOff = 2.0 * face * (1.0 - exp2(-mip)) + 2.0 * mip;\n"
3926 " highp float col = face + 2.0;\n"
3927 " highp float atlasW = col * u_reflParams.x;\n"
3928 " highp float atlasH = 2.0 * face * (1.0 - exp2(-(u_envParams.z + 1.0)))\n"
3929 " + 2.0 * (u_envParams.z + 1.0);\n"
3932 " highp vec2 uv = octEncode(column < 0.5 ? envDirection(R) : R);\n"
3936 " highp vec2 lo = vec2(column * col + 0.5, yOff + 0.5);\n"
3937 " highp vec2 hi = vec2(column * col + size + 1.5, yOff + size + 1.5);\n"
3938 " highp vec2 px = clamp(vec2(column * col + 1.0 + uv.x * size,\n"
3939 " yOff + 1.0 + uv.y * size), lo, hi);\n"
3943 " highp vec4 t = textureLod(u_envMap, px / vec2(atlasW, atlasH), 0.0);\n"
3944 " return t.rgb * t.rgb * (t.a * t.a * u_envParams.y);\n"
3947 "highp vec3 envSampleMip(in highp vec3 R, in highp float mip) {\n"
3948 " return envSampleColumn(R, mip, 0.0);\n"
3953 "highp vec3 reflectionDirection(in highp vec3 R, in highp vec3 P,\n"
3954 " in highp float column) {\n"
3955 " if (column < 0.5) return R;\n"
3956 " highp int i = int(column) * 2 - 2;\n"
3957 " highp vec3 lo = u_reflBox[i].xyz;\n"
3958 " highp vec3 hi = u_reflBox[i + 1].xyz;\n"
3961 " highp vec3 d = max(abs(R), vec3(1e-6)) * (step(vec3(0.0), R) * 2.0 - 1.0);\n"
3962 " highp vec3 far = max((hi - P) / d, (lo - P) / d);\n"
3963 " highp float t = min(min(far.x, far.y), far.z);\n"
3964 " if (!(t > 0.0)) return R;\n"
3965 " return (P + R * t) - (lo + hi) * 0.5;\n"
3969 "highp vec3 envRadiance(in highp vec3 R, in highp float roughness,\n"
3970 " in highp float column, in highp vec3 P) {\n"
3971 " g_probePos = P;\n"
3972 "#ifdef ES_ENV_MAP\n"
3973 " if (u_planarParams.x > 0.5) {\n"
3974 " highp vec4 clip = u_planarProjection * vec4(P, 1.0);\n"
3975 " if (clip.w <= 0.0) return vec3(0.0);\n"
3976 " highp vec2 uv = clip.xy / clip.w * vec2(0.5, 0.5 * u_planarParams.y) + 0.5;\n"
3977 " if (any(lessThan(uv, vec2(0.0))) || any(greaterThan(uv, vec2(1.0)))) return vec3(0.0);\n"
3979 " highp float reach = max(u_planarParams.z * 1.5, roughness * roughness * 0.04);\n"
3980 " highp vec2 r = vec2(reach, reach * u_planarParams.w / u_planarParams.z);\n"
3981 " highp vec2 d = r * 0.7071;\n"
3982 " highp vec3 seen = textureLod(u_envMap, uv, 0.0).rgb * 0.2\n"
3983 " + (textureLod(u_envMap, clamp(uv + vec2(r.x, 0.0), 0.0, 1.0), 0.0).rgb\n"
3984 " + textureLod(u_envMap, clamp(uv - vec2(r.x, 0.0), 0.0, 1.0), 0.0).rgb\n"
3985 " + textureLod(u_envMap, clamp(uv + vec2(0.0, r.y), 0.0, 1.0), 0.0).rgb\n"
3986 " + textureLod(u_envMap, clamp(uv - vec2(0.0, r.y), 0.0, 1.0), 0.0).rgb\n"
3987 " + textureLod(u_envMap, clamp(uv + d, 0.0, 1.0), 0.0).rgb\n"
3988 " + textureLod(u_envMap, clamp(uv - d, 0.0, 1.0), 0.0).rgb\n"
3989 " + textureLod(u_envMap, clamp(uv + vec2(d.x, -d.y), 0.0, 1.0), 0.0).rgb\n"
3990 " + textureLod(u_envMap, clamp(uv + vec2(-d.x, d.y), 0.0, 1.0), 0.0).rgb) * 0.1;\n"
3992 " highp float peak = max(seen.r, max(seen.g, seen.b));\n"
3993 " highp float held = peak <= 0.75 ? peak : 0.75 + 0.75 * (1.0 - exp(-(peak - 0.75) / 0.75));\n"
3994 " return seen * (held / max(peak, 1e-4));\n"
3997 " if (u_envParams.x < 0.5) return ambientFacing(R);\n"
3998 " highp vec3 dir = reflectionDirection(R, P, column);\n"
3999 " highp float lod = clamp(roughness, 0.0, 1.0) * u_envParams.z;\n"
4000 " highp float lo = floor(lod);\n"
4001 " highp vec3 a = envSampleColumn(dir, lo, column);\n"
4002 " highp vec3 b = envSampleColumn(dir, min(lo + 1.0, u_envParams.z), column);\n"
4006 " if (column >= 0.5) {\n"
4007 " highp vec3 baked = mix(a, b, lod - lo);\n"
4009 " highp float grey = dot(baked, vec3(0.2126, 0.7152, 0.0722));\n"
4010 " return mix(vec3(grey), baked, u_reflParams.z) * u_reflParams.y;\n"
4013 " return (u_ambient.rgb + mix(a, b, lod - lo) * u_envTint.rgb) * skyOcclusion(R);\n"
4021 "#ifdef ES_SURFACE_3D\n"
4022 "highp vec3 lightVector(in highp vec4 pd, in highp vec4 sh, in highp vec3 worldPos) {\n"
4023 " return vec3(pd.xy, sh.z) - worldPos;\n"
4025 "highp float lightDistance(in highp vec3 toLight) { return length(toLight); }\n"
4026 "highp float spotCone(in highp vec4 sp, in highp vec4 sh, in highp vec3 toLight,\n"
4027 " in highp float dist) {\n"
4028 " highp vec3 axis = normalize(vec3(sp.xy, sh.w));\n"
4029 " highp vec3 toFrag = (dist > 0.0001) ? -toLight / dist : axis;\n"
4030 " return smoothstep(sp.w, sp.z, dot(axis, toFrag));\n"
4033 "highp vec3 lightVector(in highp vec4 pd, in highp vec4 sh, in highp vec3 worldPos) {\n"
4034 " return vec3(pd.xy - worldPos.xy, max(pd.w, 1.0));\n"
4036 "highp float lightDistance(in highp vec3 toLight) { return length(toLight.xy); }\n"
4037 "highp float spotCone(in highp vec4 sp, in highp vec4 sh, in highp vec3 toLight,\n"
4038 " in highp float dist) {\n"
4042 " highp vec2 axis = dot(sp.xy, sp.xy) > 1e-8 ? normalize(sp.xy) : vec2(0.0, -1.0);\n"
4043 " highp vec2 toFrag = (dist > 0.0001) ? -toLight.xy / dist : axis;\n"
4044 " return smoothstep(sp.w, sp.z, dot(axis, toFrag));\n"
4050 "highp vec3 towardLight(in highp vec3 toLight, in highp vec3 N) {\n"
4051 " return dot(toLight, toLight) > 1e-8 ? normalize(toLight) : N;\n"
4056 "highp float distanceFalloff(in highp float dist, in highp float reach,\n"
4057 " in highp vec4 fo) {\n"
4058 " highp float ramp = clamp((reach - dist) / max(reach - fo.x, 1e-4), 0.0, 1.0);\n"
4059 " highp float shaped = pow(ramp, max(fo.y, 1e-3));\n"
4063 " highp float metres = dist / max(-fo.y, 1e-4);\n"
4064 " highp float q = dist / max(reach, 1e-4);\n"
4065 " highp float w = clamp(1.0 - q * q * q * q, 0.0, 1.0);\n"
4066 " return fo.y < 0.0 ? w * w / max(metres * metres, 0.01) : shaped;\n"
4077 "#ifdef ES_SURFACE_3D\n"
4078 "void waterIncidentSun(inout Light lamp, highp vec3 position);\n"
4080 "struct SurfaceExt {\n"
4081 " highp vec4 coat;\n"
4082 " highp vec4 coatN;\n"
4083 " highp vec4 sheen;\n"
4084 " highp vec4 aniso;\n"
4085 " highp vec4 scatter;\n"
4086 " highp vec4 trans;\n"
4087 " highp vec4 film;\n"
4088 " highp vec4 misc;\n"
4089 " highp vec4 strand;\n"
4091 "SurfaceExt surfaceExtNone(in highp vec3 N) {\n"
4092 " return SurfaceExt(vec4(0.0), vec4(N, 0.0), vec4(0.0), vec4(0.0), vec4(0.0), vec4(0.0), vec4(0.0),\n"
4093 " vec4(0.04, 0.0, 0.0, 0.0), vec4(0.6, 0.0, 0.0, 0.0));\n"
4095 "highp float distributionCharlie(in highp float NdotH, in highp float a) {\n"
4096 " highp float invA = 1.0 / max(a, 1e-3);\n"
4097 " highp float sin2 = max(1.0 - NdotH * NdotH, 0.0078125);\n"
4098 " return (2.0 + invA) * pow(sin2, invA * 0.5) / 6.28318531;\n"
4100 "highp float visibilityNeubelt(in highp float NdotV, in highp float NdotL) {\n"
4101 " return 1.0 / max(4.0 * (NdotL + NdotV - NdotL * NdotV), 1e-4);\n"
4103 "highp float distributionGGXAniso(in highp float at, in highp float ab, in highp float ToH,\n"
4104 " in highp float BoH, in highp float NoH) {\n"
4105 " highp float a2 = at * ab;\n"
4106 " highp vec3 d = vec3(ab * ToH, at * BoH, a2 * NoH);\n"
4107 " highp float b2 = a2 / max(dot(d, d), 1e-7);\n"
4108 " return a2 * b2 * b2 / 3.14159265;\n"
4110 "highp float visibilityGGXAniso(in highp float at, in highp float ab, in highp float ToV, in highp float BoV,\n"
4111 " in highp float ToL, in highp float BoL, in highp float NoV, in highp float NoL) {\n"
4112 " highp float lambdaV = NoL * length(vec3(at * ToV, ab * BoV, NoV));\n"
4113 " highp float lambdaL = NoV * length(vec3(at * ToL, ab * BoL, NoL));\n"
4114 " return 0.5 / max(lambdaV + lambdaL, 1e-5);\n"
4116 "highp vec3 filmFresnel(in highp vec3 F, in highp float cosTheta, in highp vec4 film) {\n"
4117 " highp float sinT2 = (1.0 - cosTheta * cosTheta) / (film.y * film.y);\n"
4118 " highp float cosT = sqrt(max(1.0 - sinT2, 0.0));\n"
4119 " highp float opd = 2.0 * film.y * film.z * cosT;\n"
4120 " highp vec3 tint = vec3(0.5) + 0.5 * cos(6.28318531 * opd / vec3(650.0, 510.0, 475.0));\n"
4121 " return clamp(F * mix(vec3(1.0), tint * 2.0, film.x), vec3(0.0), vec3(1.0));\n"
4126 "highp float g_surfaceLayer = 0.0;\n"
4127 "bool lightReachesLayer(in highp float rangeLane) {\n"
4128 " if (rangeLane < 8.0 || g_surfaceLayer < 0.5) return true;\n"
4129 " highp float range = floor(rangeLane / 8.0);\n"
4130 " highp float lo = mod(range, 256.0) - 128.0;\n"
4131 " highp float hi = 127.0 - floor(range / 256.0);\n"
4132 " highp float layer = g_surfaceLayer - 129.0;\n"
4133 " return layer >= lo && layer <= hi;\n"
4135 "void shadeLight(in highp vec4 pd, in highp vec4 col, in highp vec4 sp, in highp vec4 sh, in highp vec4 sm,\n"
4136 " in highp vec4 fo, in highp vec3 N, in highp vec3 V, in highp vec3 worldPos,\n"
4137 " in highp float a, in highp vec3 F0, in highp float NdotV, in highp float specular,\n"
4138 " in highp float roughness, in SurfaceExt ext, inout highp vec3 lit, inout highp vec3 gloss,\n"
4139 " inout highp vec3 extra, in bool shadow3D);\n"
4143 "highp vec3 applyLightingSurfaceBRDF(in highp vec3 diffuse, in highp vec3 F0, in highp vec3 N,\n"
4144 " in highp vec3 worldPos, in highp vec3 V,\n"
4145 " in highp float roughness, in highp float specular,\n"
4146 " in highp float ao, in SurfaceExt ext) {\n"
4147 " g_probePos = worldPos;\n"
4150 " highp float a = max(roughness * roughness, 1e-3);\n"
4151 " highp float NdotV = max(dot(N, V), 1e-4);\n"
4154 " highp vec3 lit = indirectIrradiance(N) * ao;\n"
4155 " highp vec3 gloss = vec3(0.0);\n"
4156 " highp vec3 extra = vec3(0.0);\n"
4160 " int lightCount = int(u_ambient.a);\n"
4164 " highp uint reach3D = 0xFFFFu;\n"
4165 "#ifdef ES_SURFACE_3D\n"
4166 " if (u_tileInfo.w > 0.5) {\n"
4167 " highp vec4 tileClip = u_tileView * vec4(worldPos, 1.0);\n"
4168 " highp vec2 tileNdc = tileClip.xy / max(tileClip.w, 1e-4);\n"
4169 " if (tileClip.w > 1e-4 && abs(tileNdc.x) <= 1.0 && abs(tileNdc.y) <= 1.0) {\n"
4170 " ivec2 tileCount = ivec2(int(u_tileInfo.y), int(u_tileInfo.z));\n"
4171 " ivec2 tile = clamp(ivec2(floor((tileNdc * 0.5 + 0.5) * vec2(tileCount))), ivec2(0), tileCount - ivec2(1));\n"
4172 " reach3D = u_tileMask[tile.y * tileCount.x + tile.x].w >> 16u;\n"
4176 " for (int i = 0; i < lightCount; ++i) {\n"
4177 " if ((reach3D & (1u << uint(i))) == 0u) continue;\n"
4178 " Light lamp = u_lights[i];\n"
4179 "#ifdef ES_SURFACE_3D\n"
4180 " if (u_waterRect.z > 0.0 && float(i) == u_waterSun.z) waterIncidentSun(lamp, worldPos);\n"
4182 " shadeLight(lamp.posDir, lamp.color, lamp.spot, lamp.shadow,\n"
4183 " u_lights[i].shadowMap, u_lights[i].falloff, N, V, worldPos, a, F0, NdotV,\n"
4184 " specular, roughness, ext, lit, gloss, extra, true);\n"
4186 "#ifndef ES_LIGHT_DIRECT\n"
4189 " int tiledCount = int(u_tileInfo.x);\n"
4190 " if (tiledCount > 0) {\n"
4191 " highp vec4 tileClip = u_projection * vec4(worldPos, 1.0);\n"
4192 " highp vec2 tileNdc = tileClip.xy / max(tileClip.w, 1e-4);\n"
4193 " ivec2 tileCount = ivec2(int(u_tileInfo.y), int(u_tileInfo.z));\n"
4194 " ivec2 tile = clamp(ivec2(floor((tileNdc * 0.5 + 0.5) * vec2(tileCount))), ivec2(0), tileCount - ivec2(1));\n"
4195 " highp uvec4 mask = u_tileMask[tile.y * tileCount.x + tile.x];\n"
4196 " for (int w = 0; w < 3; ++w) {\n"
4197 " highp uint bits = w == 0 ? mask.x : (w == 1 ? mask.y : mask.z);\n"
4198 " if (bits == 0u) continue;\n"
4199 " for (int b = 0; b < 32; ++b) {\n"
4200 " if ((bits & (1u << uint(b))) == 0u) continue;\n"
4201 " int k = w * 32 + b;\n"
4202 " if (k >= tiledCount) break;\n"
4203 " shadeLight(u_tiledLights[k].posDir, u_tiledLights[k].color, u_tiledLights[k].spot,\n"
4204 " u_tiledLights[k].shadow, u_tiledLights[k].shadowMap, u_tiledLights[k].falloff,\n"
4205 " N, V, worldPos, a, F0, NdotV, specular, roughness, ext, lit, gloss, extra, false);\n"
4213 " highp vec2 ab = envBRDFApprox(NdotV, roughness);\n"
4215 " highp float Ess = ab.x + ab.y;\n"
4216 " highp vec3 FssEss = F0 * ab.x + ab.y;\n"
4217 " highp vec3 FmsEms = vec3(0.0);\n"
4218 " highp vec3 kd = vec3(1.0);\n"
4219 " if (ext.misc.y <= 0.0 || ext.strand.y > 0.0) {\n"
4220 " highp float Ems = 1.0 - Ess;\n"
4221 " highp vec3 Favg = F0 + (vec3(1.0) - F0) / 21.0;\n"
4222 " FmsEms = FssEss * Favg * Ems / (vec3(1.0) - Ems * Favg);\n"
4223 " gloss *= vec3(1.0) + F0 * (1.0 / max(Ess, 0.05) - 1.0);\n"
4224 " kd = max(vec3(1.0) - (FssEss + FmsEms) * specular, vec3(0.0));\n"
4226 " highp vec3 envR = reflect(-V, N);\n"
4227 " if (ext.aniso.w != 0.0 || ext.misc.y > 0.0) {\n"
4228 " highp vec3 T = ext.aniso.xyz;\n"
4229 " highp vec3 grain = (ext.aniso.w >= 0.0 && ext.misc.y <= 0.0) ? cross(N, T) : T;\n"
4230 " highp vec3 bent = normalize(cross(cross(grain, V), grain));\n"
4231 " envR = reflect(-V, normalize(mix(N, bent, ext.misc.y > 0.0 ? 0.55 : abs(ext.aniso.w))));\n"
4233 " highp vec3 envF = FssEss + FmsEms;\n"
4234 " if (ext.film.x > 0.0) envF = filmFresnel(envF, NdotV, ext.film);\n"
4235 " gloss += envRadiance(envR, roughness, reflectionColumn(), worldPos)\n"
4236 " * (ao * specular)\n"
4238 " highp vec3 base = diffuse * lit * kd + gloss;\n"
4239 " highp float baseScale = 1.0;\n"
4240 " if (ext.coat.x > 0.0) {\n"
4241 " highp float coatNdotV = max(dot(ext.coatN.xyz, V), 1e-4);\n"
4242 " highp vec2 cab = envBRDFApprox(coatNdotV, ext.coat.y);\n"
4243 " highp float coatF0 = ext.coat.z > 0.0 ? ext.coat.z : 0.04;\n"
4244 " highp float Fc = (coatF0 * cab.x + cab.y) * ext.coat.x;\n"
4245 " baseScale *= 1.0 - Fc;\n"
4246 " extra += envRadiance(reflect(-V, ext.coatN.xyz), ext.coat.y, reflectionColumn(), worldPos) * (ao * Fc);\n"
4248 " if (dot(ext.sheen.rgb, vec3(1.0)) > 0.0) {\n"
4249 " highp float sheenAlbedo = 0.2 + 0.3 * ext.sheen.a;\n"
4250 " baseScale *= 1.0 - max(max(ext.sheen.r, ext.sheen.g), ext.sheen.b) * sheenAlbedo;\n"
4251 " extra += ext.sheen.rgb * (indirectIrradiance(N) * ao * sheenAlbedo);\n"
4253 " return base * baseScale + extra;\n"
4255 "highp vec3 applyLightingSurface(in highp vec3 albedo, in highp vec3 N, in highp vec3 worldPos,\n"
4256 " in highp vec3 V, in highp float metallic, in highp float roughness,\n"
4257 " in highp float specular, in highp float ao, in SurfaceExt ext) {\n"
4258 " return applyLightingSurfaceBRDF(albedo * (1.0 - metallic), mix(vec3(ext.misc.x), albedo, metallic),\n"
4259 " N, worldPos, V, roughness, specular, ao, ext);\n"
4261 "highp vec3 applyLightingPBR(in highp vec3 albedo, in highp vec3 N, in highp vec3 worldPos,\n"
4262 " in highp vec3 V, in highp float metallic,\n"
4263 " in highp float roughness, in highp float specular,\n"
4264 " in highp float ao) {\n"
4265 " return applyLightingSurface(albedo, N, worldPos, V, metallic, roughness, specular, ao, surfaceExtNone(N));\n"
4267 "void shadeLight(in highp vec4 pd, in highp vec4 col, in highp vec4 sp, in highp vec4 sh, in highp vec4 sm,\n"
4268 " in highp vec4 fo, in highp vec3 N, in highp vec3 V, in highp vec3 worldPos,\n"
4269 " in highp float a, in highp vec3 F0, in highp float NdotV, in highp float specular,\n"
4270 " in highp float roughness, in SurfaceExt ext, inout highp vec3 lit, inout highp vec3 gloss,\n"
4271 " inout highp vec3 extra, in bool shadow3D) {\n"
4274 " if (col.a == 0.0 || !lightReachesLayer(sm.y)) return;\n"
4276 " highp float atten;\n"
4277 " highp vec2 target = pd.xy;\n"
4278 " bool castShadow = true;\n"
4279 " if (pd.z < 0.5) {\n"
4280 " highp vec3 toL = lightVector(pd, sh, worldPos);\n"
4281 " highp float dist = lightDistance(toL);\n"
4282 " atten = distanceFalloff(dist, max(pd.w, 0.0001), fo);\n"
4283 " L = towardLight(toL, N);\n"
4284 " } else if (pd.z < 1.5) {\n"
4287 " L = normalize(-vec3(pd.xy, pd.w));\n"
4290 " highp vec2 toLight = (dot(pd.xy, pd.xy) > 1e-8) ? normalize(-pd.xy) : vec2(0.0);\n"
4291 " castShadow = sh.y > 0.0 && dot(toLight, toLight) > 0.5;\n"
4292 " target = worldPos.xy + toLight * sh.y;\n"
4294 " if (sp.x > 0.5) atten *= cloudShadow3D(worldPos, int(sp.x) - 1);\n"
4296 " highp vec3 toL = lightVector(pd, sh, worldPos);\n"
4297 " highp float dist = lightDistance(toL);\n"
4298 " atten = distanceFalloff(dist, max(pd.w, 0.0001), fo);\n"
4299 " L = towardLight(toL, N);\n"
4300 " atten *= spotCone(sp, sh, toL, dist);\n"
4307 " if (atten <= 0.0 || (dot(N, L) <= 0.0 && ext.misc.y <= 0.0 && ext.coat.x <= 0.0 && ext.scatter.a <= 0.0\n"
4308 " && dot(ext.sheen.rgb, vec3(1.0)) <= 0.0)) return;\n"
4311 "#ifndef ES_LIGHT_DIRECT\n"
4312 " if (col.a > 0.0 && atten > 0.0) {\n"
4313 " atten *= shapeFactor2D(fo.w, worldPos.xy);\n"
4315 " if (castShadow && col.a > 0.0 && atten > 0.0) {\n"
4316 " atten *= mix(1.0, shadowFactor2D(sm.w, worldPos.xy), fo.z);\n"
4324 " if (shadow3D && mod(sm.y, 8.0) > 0.0 && atten > 0.0) {\n"
4325 " atten *= mix(1.0, shadowFactor3D(worldPos, N, L, vec2(sh.x, sm.z),\n"
4326 " int(sm.x), int(mod(sm.y, 8.0))), fo.z);\n"
4328 " highp float ndotl = max(dot(N, L), 0.0);\n"
4330 " if (ext.misc.y > 0.0) {\n"
4331 " highp float along = dot(ext.aniso.xyz, L);\n"
4332 " ndotl = mix(ndotl, sqrt(max(1.0 - along * along, 0.0)) * clamp(dot(N, L) * 0.5 + 0.65, 0.0, 1.0), ext.strand.x);\n"
4334 " highp vec3 radiance = col.rgb * (col.a * ndotl * atten);\n"
4335 " lit += radiance;\n"
4338 " if (specular > 0.0 && ext.misc.y > 0.0 && ext.strand.y <= 0.0) {\n"
4339 " highp vec3 H = normalize(L + V);\n"
4340 " highp float primaryExp = clamp(2.0 / (a * a), 8.0, 900.0);\n"
4341 " highp vec3 t1 = normalize(ext.aniso.xyz + N * ext.misc.z);\n"
4342 " highp vec3 t2 = normalize(ext.aniso.xyz + N * ext.misc.w);\n"
4343 " highp float h1 = dot(t1, H);\n"
4344 " highp float h2 = dot(t2, H);\n"
4345 " highp float lobe1 = smoothstep(-1.0, 0.0, h1) * pow(sqrt(max(1.0 - h1 * h1, 0.0)), primaryExp);\n"
4346 " highp float lobe2 = smoothstep(-1.0, 0.0, h2) * pow(sqrt(max(1.0 - h2 * h2, 0.0)), primaryExp * 0.3);\n"
4347 " highp vec3 lightOn = col.rgb * (col.a * atten * clamp(dot(N, L) + 0.35, 0.0, 1.0));\n"
4348 " gloss += lightOn * (lobe1 * 0.55 + lobe2 * ext.scatter.rgb * 1.6) * (ext.misc.y * specular);\n"
4349 " } else if (specular > 0.0) {\n"
4350 " highp vec3 H = normalize(L + V);\n"
4352 " highp float brdf;\n"
4353 " if (ext.misc.y > 0.0) {\n"
4354 " highp vec3 T = ext.aniso.xyz;\n"
4355 " highp vec3 B = cross(N, T);\n"
4356 " highp float aspect = sqrt(max(1.0 - 0.9 * ext.strand.y, 0.01));\n"
4357 " highp float at = max(a / aspect, 0.002);\n"
4358 " highp float ab = max(a * aspect, 0.002);\n"
4359 " brdf = distributionGGXAniso(at, ab, dot(T, H), dot(B, H), max(dot(N, H), 0.0))\n"
4360 " * visibilityGGXAniso(at, ab, dot(T, V), dot(B, V), dot(T, L), dot(B, L), NdotV, ndotl);\n"
4361 " } else if (ext.aniso.w != 0.0) {\n"
4362 " highp vec3 T = ext.aniso.xyz;\n"
4363 " highp vec3 B = cross(N, T);\n"
4364 " highp float at = max(a * (1.0 + ext.aniso.w), 0.002);\n"
4365 " highp float ab = max(a * (1.0 - ext.aniso.w), 0.002);\n"
4366 " brdf = distributionGGXAniso(at, ab, dot(T, H), dot(B, H), max(dot(N, H), 0.0))\n"
4367 " * visibilityGGXAniso(at, ab, dot(T, V), dot(B, V), dot(T, L), dot(B, L), NdotV, ndotl);\n"
4369 " brdf = distributionGGX(max(dot(N, H), 0.0), a) * visibilitySmithGGX(NdotV, ndotl, a);\n"
4371 " highp vec3 F = fresnelSchlick(max(dot(V, H), 0.0), F0);\n"
4372 " if (ext.film.x > 0.0) F = filmFresnel(F, max(dot(V, H), 0.0), ext.film);\n"
4373 " gloss += radiance * F\n"
4374 " * (brdf * 3.14159265 * specular);\n"
4376 " if (col.a > 0.0 && atten > 0.0\n"
4377 " && (ext.coat.x > 0.0 || ext.scatter.a > 0.0 || dot(ext.sheen.rgb, vec3(1.0)) > 0.0)) {\n"
4378 " highp vec3 irr = col.rgb * (col.a * atten);\n"
4379 " highp vec3 Hx = normalize(L + V);\n"
4380 " highp float VdotH = max(dot(V, Hx), 0.0);\n"
4381 " if (ext.coat.x > 0.0) {\n"
4382 " highp float coatNdotL = max(dot(ext.coatN.xyz, L), 0.0);\n"
4383 " highp float coatA = max(ext.coat.y * ext.coat.y, 1e-3);\n"
4384 " highp float coatF0 = ext.coat.z > 0.0 ? ext.coat.z : 0.04;\n"
4385 " highp float Fc = (coatF0 + (1.0 - coatF0) * pow(1.0 - VdotH, 5.0)) * ext.coat.x;\n"
4386 " extra += irr * coatNdotL\n"
4387 " * (distributionGGX(max(dot(ext.coatN.xyz, Hx), 0.0), coatA) * (0.25 / max(VdotH * VdotH, 1e-4))\n"
4388 " * Fc * 3.14159265);\n"
4390 " if (dot(ext.sheen.rgb, vec3(1.0)) > 0.0) {\n"
4391 " highp float sheenA = max(ext.sheen.a * ext.sheen.a, 1e-3);\n"
4392 " extra += irr * ndotl * ext.sheen.rgb\n"
4393 " * (distributionCharlie(max(dot(N, Hx), 0.0), sheenA) * visibilityNeubelt(NdotV, ndotl) * 3.14159265);\n"
4395 " if (ext.scatter.a > 0.0) {\n"
4396 " highp vec3 wrapWidth = vec3(ext.scatter.a) * mix(vec3(1.0), vec3(1.0, 0.45, 0.25) * (0.3 + 1.7 * ext.trans.z), ext.trans.w);\n"
4397 " highp vec3 wrapped = clamp((vec3(dot(N, L)) + wrapWidth) / (vec3(1.0) + wrapWidth), vec3(0.0), vec3(1.0));\n"
4398 " extra += irr * ext.scatter.rgb * max(wrapped - vec3(ndotl), vec3(0.0));\n"
4399 " highp vec3 Hb = normalize(L + N * 0.3);\n"
4400 " extra += irr * ext.scatter.rgb\n"
4401 " * (pow(clamp(dot(V, -Hb), 0.0, 1.0), 4.0) * ext.trans.x * (1.0 - ext.trans.y));\n"
4411 "void shadeLight2D(in highp vec4 pd, in highp vec4 col, in highp vec4 sp, in highp vec4 sh, in highp vec4 sm,\n"
4412 " in highp vec4 fo, in highp vec3 N, in highp vec3 worldPos, in bool masked,\n"
4413 " in highp vec4 shadowMask, in highp vec4 shapeMask, inout highp vec3 lit, in bool shadow3D) {\n"
4414 " if (col.a == 0.0 || !lightReachesLayer(sm.y)) return;\n"
4416 " highp float atten = 1.0;\n"
4417 " bool castShadow = true;\n"
4418 " if (pd.z < 0.5) {\n"
4419 " highp vec3 toL = lightVector(pd, sh, worldPos);\n"
4420 " highp float dist = lightDistance(toL);\n"
4421 " atten = distanceFalloff(dist, max(pd.w, 0.0001), fo);\n"
4422 " L = towardLight(toL, N);\n"
4423 " } else if (pd.z < 1.5) {\n"
4424 " L = normalize(-vec3(pd.xy, pd.w));\n"
4425 " highp vec2 toLight = (dot(pd.xy, pd.xy) > 1e-8) ? normalize(-pd.xy) : vec2(0.0);\n"
4426 " castShadow = sh.y > 0.0 && dot(toLight, toLight) > 0.5;\n"
4428 " highp vec3 toL = lightVector(pd, sh, worldPos);\n"
4429 " highp float dist = lightDistance(toL);\n"
4430 " atten = distanceFalloff(dist, max(pd.w, 0.0001), fo);\n"
4431 " L = towardLight(toL, N);\n"
4432 " atten *= spotCone(sp, sh, toL, dist);\n"
4434 "#ifndef ES_LIGHT_DIRECT\n"
4435 " if (masked && col.a > 0.0 && atten > 0.0) {\n"
4436 " if (fo.w >= 0.0) atten *= min(mask2DChannel(shapeMask, fo.w), 1.0);\n"
4437 " if (castShadow && sm.w >= 0.0 && atten > 0.0) {\n"
4438 " highp float hidden = (sm.w < 3.5) ? mask2DChannel(shadowMask, sm.w) : mask2DChannel(shapeMask, sm.w - 4.0);\n"
4439 " atten *= mix(1.0, 1.0 - min(hidden, 1.0), fo.z);\n"
4443 " if (shadow3D && mod(sm.y, 8.0) > 0.0 && atten > 0.0) {\n"
4444 " atten *= mix(1.0, shadowFactor3D(worldPos, N, L, vec2(sh.x, sm.z),\n"
4445 " int(sm.x), int(mod(sm.y, 8.0))), fo.z);\n"
4447 " lit += col.rgb * (col.a * max(dot(N, L), 0.0) * atten);\n"
4451 "highp vec3 applyLighting2DReach(highp vec3 albedo, highp vec3 N, highp vec2 worldPos,\n"
4452 " highp float ao, int reach) {\n"
4453 " highp vec3 P = vec3(worldPos, 0.0);\n"
4454 " g_probePos = P;\n"
4455 " highp vec3 lit = indirectIrradiance(N) * ao;\n"
4456 " bool masked = false;\n"
4457 " highp vec4 shadowMask = vec4(0.0);\n"
4458 " highp vec4 shapeMask = vec4(0.0);\n"
4459 "#ifndef ES_LIGHT_DIRECT\n"
4460 " if (u_mask2DRect.z > 0.0) {\n"
4461 " highp vec2 maskUv = mask2DUv(worldPos);\n"
4462 " if (!(maskUv.x < 0.0)) {\n"
4464 " shadowMask = textureLod(u_shadow2D, maskUv, 0.0);\n"
4465 " shapeMask = textureLod(u_lightShape2D, maskUv, 0.0);\n"
4471 "#ifndef ES_LIGHT_DIRECT\n"
4472 " int tiledCount = int(u_tileInfo.x);\n"
4473 " highp uvec4 tileBits = uvec4(0u);\n"
4474 " if (tiledCount > 0 || u_tileInfo.w > 0.5) {\n"
4475 " highp vec4 tileClip = u_projection * vec4(P, 1.0);\n"
4476 " highp vec2 tileNdc = tileClip.xy / max(tileClip.w, 1e-4);\n"
4477 " ivec2 tileCount = ivec2(int(u_tileInfo.y), int(u_tileInfo.z));\n"
4478 " ivec2 tile = clamp(ivec2(floor((tileNdc * 0.5 + 0.5) * vec2(tileCount))), ivec2(0), tileCount - ivec2(1));\n"
4479 " tileBits = u_tileMask[tile.y * tileCount.x + tile.x];\n"
4480 " if (u_tileInfo.w > 0.5) reach = reach & int(tileBits.w);\n"
4483 " int lightCount = int(u_ambient.a);\n"
4484 " for (int i = 0; i < lightCount; ++i) {\n"
4485 " if (((reach >> i) & 1) == 0) continue;\n"
4486 " shadeLight2D(u_lights[i].posDir, u_lights[i].color, u_lights[i].spot, u_lights[i].shadow,\n"
4487 " u_lights[i].shadowMap, u_lights[i].falloff, N, P, masked, shadowMask, shapeMask, lit, true);\n"
4489 "#ifndef ES_LIGHT_DIRECT\n"
4490 " if (tiledCount > 0) {\n"
4491 " for (int w = 0; w < 3; ++w) {\n"
4492 " highp uint bits = w == 0 ? tileBits.x : (w == 1 ? tileBits.y : tileBits.z);\n"
4493 " if (bits == 0u) continue;\n"
4494 " for (int b = 0; b < 32; ++b) {\n"
4495 " if ((bits & (1u << uint(b))) == 0u) continue;\n"
4496 " int k = w * 32 + b;\n"
4497 " if (k >= tiledCount) break;\n"
4498 " shadeLight2D(u_tiledLights[k].posDir, u_tiledLights[k].color, u_tiledLights[k].spot,\n"
4499 " u_tiledLights[k].shadow, u_tiledLights[k].shadowMap, u_tiledLights[k].falloff,\n"
4500 " N, P, masked, shadowMask, shapeMask, lit, false);\n"
4505 " return albedo * lit;\n"
4507 "highp vec3 applyLighting2DAO(highp vec3 albedo, highp vec3 N, highp vec2 worldPos,\n"
4508 " highp float ao) {\n"
4509 " return applyLighting2DReach(albedo, N, worldPos, ao, 65535);\n"
4511 "highp vec3 applyLighting2D(highp vec3 albedo, highp vec3 N, highp vec2 worldPos) {\n"
4512 " return applyLighting2DAO(albedo, N, worldPos, 1.0);\n"
4517 "highp vec3 applyLighting2DLayer(highp vec3 albedo, highp vec3 N, highp vec2 worldPos, highp float layerLane) {\n"
4518 " highp float lane = abs(layerLane);\n"
4519 " highp float reach = floor(lane * 0.001953125);\n"
4520 " g_surfaceLayer = lane - reach * 512.0;\n"
4521 " return applyLighting2DReach(albedo, N, worldPos, 1.0, layerLane < 0.0 ? int(reach) + 32768 : 65535);\n"
4526 if (std::find(features.begin(), features.end(),
"MESH_LIGHTMAP") != features.end()) {
4530 static const char* kLightmapHeader =
4531 "in highp vec3 v_lightmap;\n"
4532 "uniform highp sampler2D u_lightmap;\n"
4533 "highp vec3 bakedIrradiance() {\n"
4534 " highp vec3 c = textureLod(u_lightmap, v_lightmap.xy, 0.0).rgb;\n"
4535 " return c * c * 8.0;\n"
4537 assembled << kLightmapHeader;
4538 headerLines += countNewlines(kLightmapHeader);
4542 headerLines += countNewlines(kLitHeader);
4547 static const char* kPostLightHeader =
4548 "struct Light { highp vec4 posDir; highp vec4 color; highp vec4 spot; highp vec4 shadow;"
4549 " highp vec4 shadowMap; highp vec4 falloff; };\n"
4550 "layout(std140) uniform LightConstants {\n"
4551 " highp vec4 u_ambient;\n"
4552 " Light u_lights[16];\n"
4553 " highp vec4 u_mask2DRect;\n"
4554 " highp mat4 u_shadowMatrix[16];\n"
4555 " highp vec4 u_shadowTile[16];\n"
4556 " highp vec4 u_shadowParams;\n"
4557 " highp vec4 u_envIrradiance[9];\n"
4558 " highp vec4 u_envParams;\n"
4559 " highp vec4 u_envTint;\n"
4560 " highp vec4 u_reflParams;\n"
4561 " highp vec4 u_reflBox[30];\n"
4562 " highp vec4 u_bakedTint;\n"
4563 " Light u_tiledLights[96];\n"
4564 " highp uvec4 u_tileMask[192];\n"
4565 " highp vec4 u_tileInfo;\n"
4567 "uniform highp sampler2D u_shadowMap;\n"
4568 "highp float unpackDepth(in highp vec3 c) {\n"
4569 " return dot(c, vec3(1.0, 1.0 / 255.0, 1.0 / 65025.0));\n"
4572 "void findSun(out highp vec4 dir, out highp vec4 color, out ivec2 tiles) {\n"
4573 " dir = vec4(0.0);\n"
4574 " color = vec4(0.0);\n"
4575 " tiles = ivec2(0);\n"
4576 " for (int i = 0; i < 16; ++i) {\n"
4577 " Light l = u_lights[i];\n"
4578 " if (l.posDir.z > 0.5 && l.posDir.z < 1.5 && l.color.a > 0.0) {\n"
4579 " dir = vec4(-normalize(vec3(l.posDir.x, l.posDir.y, l.posDir.w)), 1.0);\n"
4580 " color = l.color;\n"
4581 " tiles = ivec2(int(l.shadowMap.x), int(mod(l.shadowMap.y, 8.0)));\n"
4587 "highp float sunVisibility(in highp vec3 worldPos, in int first, in int count) {\n"
4588 " if (u_shadowParams.x < 0.5 || count <= 0) return 1.0;\n"
4589 " for (int k = 0; k < 16; ++k) {\n"
4590 " if (k >= count) break;\n"
4591 " int t = first + k;\n"
4592 " highp mat4 m = u_shadowMatrix[t];\n"
4593 " highp vec4 c = m * vec4(worldPos, 1.0);\n"
4594 " if (c.w <= 0.0) continue;\n"
4595 " highp vec3 proj = c.xyz / c.w;\n"
4596 " highp vec2 uv = proj.xy * 0.5 + 0.5;\n"
4597 " if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 || proj.z < 0.0 || proj.z > 1.0) continue;\n"
4598 " highp vec4 rect = u_shadowTile[t];\n"
4599 " highp vec2 at = rect.xy + uv * rect.z;\n"
4600 " highp vec2 lo = rect.xy + u_shadowParams.y * 0.5;\n"
4601 " highp vec2 hi = rect.xy + rect.z - u_shadowParams.y * 0.5;\n"
4602 " highp float d = unpackDepth(texture(u_shadowMap, clamp(at, lo, hi)).rgb);\n"
4603 " return d < clamp(proj.z * 0.5 + 0.5, 0.0, 1.0) - 0.0025 ? 0.0 : 1.0;\n"
4607 assembled << kPostLightHeader;
4608 headerLines += countNewlines(kPostLightHeader);
4611 if (!platform.empty()) {
4612 auto variantIt = parsed.
variants.find(platform);
4613 if (variantIt != parsed.
variants.end()) {
4614 assembled << variantIt->second;
4615 headerLines += countNewlines(variantIt->second);
4621 headerLines += countNewlines(parsed.
sharedCode);
4626 std::string bodyText = stageIt->second;
4628 fillHook(bodyText,
"@@ES_VERTEX_HOOK@@", parsed.
vertexHook);
4632 assembled << blankUniformBlock(bodyText,
"FrameConstants");
4634 assembled << instanceRecordGLSLBodies();
4637 result.
source = assembled.str();
4644std::string formatRemap(
u32 logLine,
4645 const std::vector<SourceLine>& stageMap,
4646 u32 headerLineOffset,
4648 if (logLine <= headerLineOffset)
return {};
4649 const u32 bodyLine = logLine - headerLineOffset;
4650 if (bodyLine == 0 || bodyLine > stageMap.size())
return {};
4651 const SourceLine& src = stageMap[bodyLine - 1];
4652 const std::string file = src.file.empty() ? std::string(
"<main>") : src.file;
4655 out = file +
"(" + std::to_string(src.line) +
")";
4657 out = file +
":" + std::to_string(src.line) +
":";
4662bool scanNumber(
const std::string& log,
usize start,
usize& outEnd,
u32& outNumber) {
4666 while (j < log.size() && std::isdigit(
static_cast<unsigned char>(log[j]))) {
4667 num = num * 10 +
static_cast<u32>(log[j] -
'0');
4671 if (!any)
return false;
4680 const std::vector<SourceLine>& stageMap,
4681 u32 headerLineOffset) {
4682 if (log.empty() || stageMap.empty())
return log;
4684 auto isWordChar = [](
char c) {
4685 return std::isalnum(
static_cast<unsigned char>(c)) || c ==
'_';
4689 out.reserve(log.size());
4690 const usize n = log.size();
4693 const bool boundary = (i == 0) || !isWordChar(log[i - 1]);
4694 if (boundary && i + 2 < n && log[i] ==
'0' && log[i + 1] ==
':') {
4697 if (scanNumber(log, i + 2, end, num) && end < n && log[end] ==
':') {
4698 std::string rep = formatRemap(num, stageMap, headerLineOffset,
false);
4706 if (boundary && i + 2 < n && log[i] ==
'0' && log[i + 1] ==
'(') {
4709 if (scanNumber(log, i + 2, end, num) && end < n && log[end] ==
')') {
4710 std::string rep = formatRemap(num, stageMap, headerLineOffset,
true);
4727void ShaderParser::parseDirective(
const std::string& line,
4728 std::string& directive,
4729 std::string& argument) {
4733 std::string trimmedLine = trim(line);
4734 if (trimmedLine.substr(0, 7) !=
"#pragma") {
4738 std::string rest = trim(trimmedLine.substr(7));
4743 usize spacePos = rest.find_first_of(
" \t");
4744 if (spacePos == std::string::npos) {
4747 directive = rest.substr(0, spacePos);
4748 argument = trim(rest.substr(spacePos + 1));
4752ShaderProperty ShaderParser::parseParamDirective(
const std::string& argument) {
4753 ShaderProperty prop;
4757 std::string typeStr;
4758 prop.name = nextToken(argument, ssPos);
4759 typeStr = nextToken(argument, ssPos);
4760 if (prop.name.empty() || typeStr.empty()) {
4764 prop.layered = typeStr ==
"textureArray";
4768 auto clause = [&](
const char* key) -> std::optional<std::string> {
4769 const std::string token = std::string(key) +
"(";
4770 usize p = argument.find(token);
4771 if (p == std::string::npos)
return std::nullopt;
4772 usize open = p + token.size();
4773 usize close = argument.find(
')', open);
4774 if (close == std::string::npos)
return std::nullopt;
4775 return trim(argument.substr(open, close - open));
4778 if (
auto d = clause(
"default")) prop.defaultValue = *d;
4779 if (
auto u = clause(
"ui")) prop.ui = *u;
4780 if (
auto u = clause(
"unit")) prop.worldUnits = *u ==
"length" ? 1 : *u ==
"perLength" ? -1 : 0;
4781 if (
auto r = clause(
"range")) {
4782 usize comma = r->find(
',');
4783 if (comma != std::string::npos) {
4784 prop.rangeMin =
static_cast<f32>(std::atof(trim(r->substr(0, comma)).c_str()));
4785 prop.rangeMax =
static_cast<f32>(std::atof(trim(r->substr(comma + 1)).c_str()));
4786 prop.hasRange =
true;
4791 prop.displayName = prop.name;
4792 if (prop.displayName.size() > 2 && prop.displayName.substr(0, 2) ==
"u_") {
4793 prop.displayName = prop.displayName.substr(2);
4795 if (!prop.displayName.empty()) {
4796 prop.displayName[0] =
static_cast<char>(std::toupper(prop.displayName[0]));
4804bool namesIdentifier(
const std::string& text, std::string_view word) {
4805 const auto isIdent = [](
char c) {
return std::isalnum(
static_cast<unsigned char>(c)) || c ==
'_'; };
4806 for (
usize at = text.find(word); at != std::string::npos; at = text.find(word, at + 1)) {
4807 const bool startOk = at == 0 || !isIdent(text[at - 1]);
4808 const usize end = at + word.size();
4809 if (startOk && (end >= text.size() || !isIdent(text[end])))
return true;
4818u32 batchUnitsRead(
const std::string& text) {
4819 constexpr std::string_view word =
"u_textures";
4820 const auto isIdent = [](
char c) {
return std::isalnum(
static_cast<unsigned char>(c)) || c ==
'_'; };
4822 for (
usize at = text.find(word); at != std::string::npos; at = text.find(word, at + 1)) {
4823 usize i = at + word.size();
4824 if ((at > 0 && isIdent(text[at - 1])) || (i < text.size() && isIdent(text[i])))
continue;
4827 while (before > 0 && std::isspace(
static_cast<unsigned char>(text[before - 1]))) --before;
4828 if (before > 0 && before < at && isIdent(text[before - 1]))
continue;
4829 while (i < text.size() && std::isspace(
static_cast<unsigned char>(text[i]))) ++i;
4830 if (i >= text.size() || text[i] !=
'[')
return 0xFFu;
4831 const usize close = text.find(
']', i);
4832 if (close == std::string::npos)
return 0xFFu;
4834 bool literal = close > i + 1;
4835 for (
usize c = i + 1; c < close && literal; ++c) {
4836 if (std::isdigit(
static_cast<unsigned char>(text[c]))) index = std::min(index * 10u +
static_cast<u32>(text[c] -
'0'), 255u);
4837 else if (!std::isspace(
static_cast<unsigned char>(text[c]))) literal =
false;
4839 if (!literal)
return 0xFFu;
4855 if (shader.domain ==
"Lit") {
4858 }
else if (shader.domain ==
"Unlit") {
4860 }
else if (shader.domain ==
"PostProcess") {
4870 std::string glsl = shader.sharedCode + shader.vertexHook;
4871 for (
const auto& [stage, source] : shader.stages) glsl += source;
4872 for (
const auto& [platform, source] : shader.variants) glsl += source;
4873 std::string wgsl = shader.wgslVertexHook;
4874 for (
const auto& [stage, source] : shader.wgslStages) wgsl += source;
4875 const std::string both = glsl + wgsl;
4877 reads |= batchUnitsRead(both);
4878 static constexpr struct {
const char* name;
u32 unit; } kEngine[] = {
4883 for (
const auto& e : kEngine) {
4884 if (namesIdentifier(both, e.name)) reads |= 1u << e.unit;
4889 reads |= reachedTex | reachedSam;
4895i32 ShaderParser::takeOverflowUnit(
u32& free) {
4897 if ((free & (1u << unit)) == 0)
continue;
4898 free &= ~(1u << unit);
4904void ShaderParser::computeMaterialLayout(
ParsedShader& shader) {
4914 default: size = 0; align = 0;
break;
4917 auto alignUp = [](
u32 v,
u32 a) ->
u32 {
return a == 0 ? v : (v + a - 1) & ~(a - 1); };
4926 for (
auto& p : shader.properties) {
4927 if (!p.fromParam)
continue;
4929 p.std140Offset = -1;
4934 p.textureUnit =
static_cast<i32>(textureUnit++);
4937 const i32 low = takeOverflowUnit(overflowFree);
4939 p.textureUnit = low;
4942 ES_LOG_ERROR(
"shader {}: texture param \"{}\" finds no free texture unit: units {}..{} are"
4943 " taken, and the {} domain leaves none of the engine's units below {} that this"
4944 " shader does not read",
4950 u32 size = 0, align = 0;
4951 sizeAlign(p.type, size, align);
4952 if (size == 0) { p.std140Offset = -1;
continue; }
4953 offset = alignUp(offset, align);
4954 p.std140Offset =
static_cast<i32>(offset);
4958 shader.materialBlockSize = (offset == 0) ? 0 : alignUp(offset, 16);
4961ShaderProperty ShaderParser::parsePropertyAnnotation(
const std::string& line) {
4962 ShaderProperty prop;
4964 usize uniformPos = line.find(
"uniform");
4965 if (uniformPos == std::string::npos) {
4969 std::string afterUniform = trim(line.substr(uniformPos + 7));
4970 usize spacePos = afterUniform.find_first_of(
" \t");
4971 if (spacePos == std::string::npos) {
4975 std::string glslType = afterUniform.substr(0, spacePos);
4976 std::string rest = trim(afterUniform.substr(spacePos));
4978 usize semicolonPos = rest.find(
';');
4979 if (semicolonPos == std::string::npos) {
4983 prop.name = trim(rest.substr(0, semicolonPos));
4985 if (glslType ==
"float") {
4987 }
else if (glslType ==
"vec2") {
4989 }
else if (glslType ==
"vec3") {
4991 }
else if (glslType ==
"vec4") {
4993 }
else if (glslType ==
"int") {
4995 }
else if (glslType ==
"sampler2D") {
5001 usize propStart = line.find(
"@property");
5002 if (propStart != std::string::npos) {
5003 usize parenStart = line.find(
'(', propStart);
5004 usize parenEnd = line.find(
')', parenStart);
5005 if (parenStart != std::string::npos && parenEnd != std::string::npos) {
5006 std::string params = line.substr(parenStart + 1, parenEnd - parenStart - 1);
5008 usize typePos = params.find(
"type");
5009 if (typePos != std::string::npos) {
5010 usize eqPos = params.find(
'=', typePos);
5011 if (eqPos != std::string::npos) {
5012 usize valStart = params.find_first_not_of(
" \t", eqPos + 1);
5013 usize valEnd = params.find_first_of(
" \t,)", valStart);
5014 if (valStart != std::string::npos) {
5015 std::string typeVal = params.substr(valStart, valEnd - valStart);
5016 prop.type = stringToPropertyType(typeVal);
5021 usize defaultPos = params.find(
"default");
5022 if (defaultPos != std::string::npos) {
5023 usize eqPos = params.find(
'=', defaultPos);
5024 if (eqPos != std::string::npos) {
5025 usize valStart = params.find_first_not_of(
" \t", eqPos + 1);
5026 usize valEnd = params.find_first_of(
",)", valStart);
5027 if (valStart != std::string::npos) {
5028 prop.defaultValue = trim(params.substr(valStart, valEnd - valStart));
5033 usize namePos = params.find(
"name");
5034 if (namePos != std::string::npos) {
5035 usize quoteStart = params.find(
'"', namePos);
5036 usize quoteEnd = params.find(
'"', quoteStart + 1);
5037 if (quoteStart != std::string::npos && quoteEnd != std::string::npos) {
5038 prop.displayName = params.substr(quoteStart + 1, quoteEnd - quoteStart - 1);
5044 if (prop.displayName.empty()) {
5045 prop.displayName = prop.name;
5046 if (prop.displayName.size() > 2 && prop.displayName.substr(0, 2) ==
"u_") {
5047 prop.displayName = prop.displayName.substr(2);
5049 if (!prop.displayName.empty()) {
5050 prop.displayName[0] =
static_cast<char>(std::toupper(prop.displayName[0]));
5068std::string ShaderParser::trim(
const std::string& str) {
5069 const char* whitespace =
" \t\r\n";
5070 usize start = str.find_first_not_of(whitespace);
5071 if (start == std::string::npos) {
5074 usize end = str.find_last_not_of(whitespace);
5075 return str.substr(start, end - start + 1);
The samplers the engine injects into a shader, and the texture unit each is pinned to.
Backend-agnostic graphics enumerations.
WHERE one draw's entry is in the frame's per-object record texture, and what an entry says.
Logging utilities for ESEngine.
#define ES_LOG_ERROR(...)
Logs an error message.
Binding points for per-material shader constants — the second tier of the engine's constant-buffer la...
Parser for unified .esshader file format.
std::ostream & operator<<(std::ostream &os, esengine::Entity e)
What a texture unit is called in WGSL, and what a WGSL source says about the group-1 bindings it hold...
static void setLinearColorSpace(bool linear)
Process-global color-space mode. When linear, every assembled stage compiles with ES_LINEAR defined (...
static std::vector< std::string > splitFeatures(const std::string &csv)
Split a comma-separated feature/switch list into trimmed, non-empty entries — the form the boundary c...
static ParsedShader parse(const std::string &source)
Parses shader source into structured format (no include support).
static std::string canonicalVaryingsWGSL(const ParsedShader &parsed)
The WGSL varying struct the engine's vertex stage emits for parsed, or empty when the shader writes i...
static std::string variantKey(const std::vector< std::string > &features)
Stable cache key for a feature set (order-independent), e.g. "GRAYSCALE|TINT". Consumers key their co...
static std::string remapCompilerLog(const std::string &log, const std::vector< SourceLine > &stageMap, u32 headerLineOffset)
Rewrites GL compile-log line references back to original files.
static u32 materialOverflowUnits(const ParsedShader &shader)
The units below the material base a texture param may take on shader (a mask): the ones it never read...
static bool linearColorSpace()
static std::string assembleStage(const ParsedShader &parsed, ShaderStage stage, const std::string &platform="", const std::vector< std::string > &features={}, ShaderTargetLanguage target=ShaderTargetLanguage::GLSL_ES300)
Assembles final GLSL source for a specific stage.
static std::vector< std::string > featuresRead(const ParsedShader &parsed, const std::vector< std::string > &features, ShaderTargetLanguage target=ShaderTargetLanguage::GLSL_ES300)
static AssembledStage assembleStageEx(const ParsedShader &parsed, ShaderStage stage, const std::string &platform="", const std::vector< std::string > &features={}, ShaderTargetLanguage target=ShaderTargetLanguage::GLSL_ES300)
std::function< std::optional< std::string >(const std::string &)> ShaderIncludeResolver
Resolves an include path to its file contents.
ShaderTargetLanguage
Target language for stage assembly (REARCH_WGSL dual emission).
std::int32_t i32
Signed 32-bit integer.
u64 scanWGSLBindingMask(const char *source, u32 group)
Bit mask of the @group(N) @binding(i) indices a WGSL source declares.
constexpr const char * LIGHTMAP_SAMPLER
The baked-light atlas, and the unit a lightmapped mesh samples it from.
constexpr const char * MORPH_DELTA_SAMPLER
The sampler a mesh's morph deltas arrive through, and the unit it is pinned to.
constexpr u32 SHADOW_2D_TEXTURE_UNIT
constexpr u32 samplerBindingForUnit(u32 unit)
Group-1 binding of a texture unit's sampler (see textureBindingForUnit).
std::uint64_t u64
Unsigned 64-bit integer.
constexpr u32 textureBindingForUnit(u32 unit)
Group-1 binding of a texture unit. Units 0-7 are the batch stream and take bindings 0-7; a material's...
static constexpr u32 MESH_INSTANCE_TEXELS
void scanWGSLReachedUnits(const char *source, u32 &textures, u32 &samplers)
The tN / sN names a WGSL source REACHES, by unit.
constexpr u32 LIGHTMAP_TEXTURE_UNIT
std::size_t usize
Size type for indexing and sizes.
static constexpr u32 MESH_INSTANCE_TEXEL_LIGHTMAP
constexpr u32 MATERIAL_TEXTURE_UNIT_BASE
First sampler unit a material texture parameter may use (batch owns units 0..7).
constexpr u32 SHADOW_MAP_TEXTURE_UNIT
static constexpr u32 MESH_INSTANCE_TEXEL_TINT
constexpr u32 kGBufferUnit
The unit a PostProcess pass reads the scene's surface record at: what a surface IS — octahedral norma...
constexpr char WATER_SUN_GLSL[]
bool & glslMultiDraw()
Whether this process's GLSL mesh programs count through a run's entries by gl_DrawID.
constexpr u32 MORPH_DELTA_TEXTURE_UNIT
constexpr u32 kSceneDepthUnit
The unit a PostProcess pass reads the scene's DEPTH at.
constexpr const char * SHADOW_MAP_SAMPLER
The injected shadow-map sampler, and the texture unit Shader::compile pins it to.
constexpr const char * SHADOW_2D_SAMPLER
The 2D shadow mask, and the texture unit every Lit shader samples it from.
constexpr const char * ENV_MAP_SAMPLER
The injected reflection sampler, one unit past the shadow map's.
std::uint32_t u32
Unsigned 32-bit integer.
static constexpr u32 MESH_INSTANCE_TEXTURE_WIDTH
static constexpr u32 MESH_INSTANCE_TEXTURE_UNIT
constexpr u32 SHAPE_2D_TEXTURE_UNIT
static constexpr u32 MESH_MAX_ACTIVE_MORPHS
constexpr u32 ENV_MAP_TEXTURE_UNIT
static constexpr u32 MESH_INSTANCE_TEXEL_NORMAL
constexpr char WATER_SUN_WGSL[]
static constexpr u32 MESH_INSTANCE_TEXEL_MODEL
constexpr u32 WGSL_MAX_TEXTURE_UNITS
Units a tN / sN name can carry — the batch stream and a material's own.
constexpr const char * SHAPE_2D_SAMPLER
The 2D light-shape mask, and the unit below the shadow mask's.
constexpr u32 INSTANCE_CONSTANTS_BINDING
Indexed UBO binding point for the per-draw InstanceConstants block. Nine and not four: slot 4 is DRAW...
float f32
32-bit floating point
static constexpr u32 MESH_MAX_BONES
Result of parsing an .esshader file.
std::string version
GLSL version.
std::string errorMessage
Parse error if any.
std::unordered_map< ShaderStage, std::vector< SourceLine > > wgslStageLineMaps
Line maps for wgslStages, same convention as stageLineMaps.
std::unordered_map< ShaderStage, std::vector< SourceLine > > stageLineMaps
Per-stage line maps, parallel to stages[].
std::unordered_map< ShaderStage, std::string > stages
Stage source code.
std::unordered_map< ShaderStage, std::string > wgslStages
WGSL twin stage bodies (#pragma vertex wgsl / #pragma fragment wgsl sections), keyed like stages[].
bool valid
True if parsing succeeded.
std::vector< SourceLine > expandedLineMap
Line map for the expanded pre-parse source.
std::vector< std::string > features
std::string sharedCode
Code shared by all stages.
std::string hairShadowParam
std::string coverageParam
std::string name
Shader name.
std::unordered_map< ShaderStage, bool > wgslStageFull
Stages whose WGSL twin is a SELF-CONTAINED program (#pragma vertex wgsl full / #pragma fragment wgsl ...
bool wgslVertexIsCanonical
True when the WGSL vertex stage is the injected canonical one. The WGSL fragment assembly then also i...
bool vertexIsCanonical
True when the GLSL vertex stage is the injected canonical one.
std::vector< ShaderSwitch > switches
Material-controlled pragma switch toggles (name + default).
std::string wgslVertexHook
std::unordered_map< std::string, std::string > variants
Platform variants.
std::vector< ShaderProperty > properties
Exposed material params (pragma param / properties block).
Like assembleStage, but also reports the line count of the assembled prefix (version + variant + shar...
std::string name
Uniform name.
A material-controlled static switch (pragma switch): a boolean the material sets, selecting a compile...
A (file, line) pair identifying an original source location.