@holoscript/core 8.0.12 → 8.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/README.md +14 -0
  2. package/bin/holo-decision.mjs +133 -0
  3. package/dist/{GLTFPipeline-L76YTXKA.js → GLTFPipeline-6LS3UDYX.js} +6 -6
  4. package/dist/{GLTFPipeline-ZWJN7GI6.cjs → GLTFPipeline-VTI6PRRQ.cjs} +10 -10
  5. package/dist/{HoloCompositionParser-FLBZKFD3.js → HoloCompositionParser-GILABNN3.js} +5 -5
  6. package/dist/{HoloCompositionParser-3XEC7IJC.cjs → HoloCompositionParser-ZVRYVEA5.cjs} +12 -12
  7. package/dist/{HoloScriptPlusParser-RNUCHOAJ.cjs → HoloScriptPlusParser-WTPRPRPR.cjs} +8 -8
  8. package/dist/{HoloScriptPlusParser-55AY4MUF.js → HoloScriptPlusParser-ZP53ECSL.js} +5 -5
  9. package/dist/{SceneIRCompiler-KWUFHZ4O.cjs → SceneIRCompiler-7KQ5NKAU.cjs} +11 -11
  10. package/dist/{SceneIRCompiler-63KA3M2F.js → SceneIRCompiler-VX75RB6H.js} +6 -6
  11. package/dist/{chunk-EM2OGPYE.js → chunk-2GKF7JQ6.js} +3 -3
  12. package/dist/{chunk-HVX7QQYK.js → chunk-3KHRZTNW.js} +3 -3
  13. package/dist/{chunk-UTUD6GJI.js → chunk-42Z3SVHQ.js} +3 -3
  14. package/dist/{chunk-Z4IUBW46.js → chunk-47XZ62KM.js} +112 -55
  15. package/dist/{chunk-GGR7QUKK.cjs → chunk-4CRMVEON.cjs} +37 -37
  16. package/dist/{chunk-QBY7LRN2.js → chunk-4NEPHK2K.js} +3 -3
  17. package/dist/{chunk-65S62L4D.cjs → chunk-5B2AJKA5.cjs} +20 -20
  18. package/dist/{chunk-PJFTTSKE.js → chunk-5T6BWIB7.js} +4 -4
  19. package/dist/{chunk-KFVNCW4Q.js → chunk-62OYZT6Q.js} +3 -3
  20. package/dist/{chunk-3KMANSQJ.cjs → chunk-645EWDZW.cjs} +4 -4
  21. package/dist/{chunk-BP4KTMLY.js → chunk-6FCNMTL5.js} +4 -4
  22. package/dist/{chunk-77QI552M.js → chunk-73EDVY5D.js} +3 -3
  23. package/dist/{chunk-7IDJDMPU.cjs → chunk-7FYSSI3C.cjs} +27 -2
  24. package/dist/{chunk-WNYXT4TE.cjs → chunk-7ITJP33Q.cjs} +3 -3
  25. package/dist/chunk-7ZKQ32XK.js +1571 -0
  26. package/dist/{chunk-P7JEKJTZ.cjs → chunk-B6JHTTMR.cjs} +25 -14
  27. package/dist/{chunk-FG6PYGIZ.js → chunk-BLCWQ225.js} +4 -4
  28. package/dist/{chunk-7NPZZZD7.js → chunk-C73GVAYC.js} +16 -9
  29. package/dist/{chunk-RMOEL2GD.cjs → chunk-CESMPUEZ.cjs} +3794 -1137
  30. package/dist/{chunk-SQXAZHDG.js → chunk-CHIZSMWD.js} +3 -3
  31. package/dist/{chunk-G35CAQ7I.cjs → chunk-D44CEFY4.cjs} +5 -5
  32. package/dist/chunk-ERYKKPHW.cjs +1884 -0
  33. package/dist/{chunk-TYNRXRHF.js → chunk-EYHPTJ3F.js} +3695 -1045
  34. package/dist/{chunk-J3UHV5T4.cjs → chunk-FGXJPJ3W.cjs} +4 -4
  35. package/dist/{chunk-IJU6AS67.cjs → chunk-FHR2AVMA.cjs} +23 -23
  36. package/dist/{chunk-LMB555QB.cjs → chunk-FOM36K5I.cjs} +18 -18
  37. package/dist/{chunk-JBYBMBMW.js → chunk-FWKEY4LD.js} +3 -2
  38. package/dist/{chunk-ZRPALBQB.cjs → chunk-GGH3ZYDB.cjs} +5 -5
  39. package/dist/{chunk-2BYAUHBO.js → chunk-GI5YYZH6.js} +3 -3
  40. package/dist/{chunk-VTEXJOSD.cjs → chunk-GYJLP4BO.cjs} +30 -30
  41. package/dist/{chunk-OC6GV5QH.cjs → chunk-HCONR4J6.cjs} +38 -38
  42. package/dist/{chunk-B3CWTCK2.js → chunk-IA7FCSRY.js} +27 -2
  43. package/dist/{chunk-5FYMCVBY.js → chunk-IXFNA5TT.js} +4 -4
  44. package/dist/{chunk-G6KACNMO.js → chunk-JCVSCKUH.js} +4 -4
  45. package/dist/{chunk-FHVPN7BN.js → chunk-JQCXLKAU.js} +3 -3
  46. package/dist/{chunk-F3YT6GUF.cjs → chunk-KLM6QD6D.cjs} +14 -14
  47. package/dist/{chunk-UGQ3QNV6.js → chunk-KOGPVAP6.js} +24 -8
  48. package/dist/{chunk-CKV5NYAE.js → chunk-KYJD2UMV.js} +4 -4
  49. package/dist/{chunk-LB3ZZMKT.cjs → chunk-L4DBUX3N.cjs} +10 -10
  50. package/dist/{chunk-RXQNRZ5F.js → chunk-LGRKBTPM.js} +3 -3
  51. package/dist/{chunk-OMNHTCS4.cjs → chunk-LHUDAJQT.cjs} +3 -2
  52. package/dist/{chunk-PDXX5UI4.cjs → chunk-LQNL3IYV.cjs} +38 -38
  53. package/dist/{chunk-WWNCM473.js → chunk-M7XR3F53.js} +4 -4
  54. package/dist/{chunk-IFW5IW4L.cjs → chunk-ML4V5PVU.cjs} +670 -627
  55. package/dist/{chunk-656IAS7B.cjs → chunk-N7IYRAFG.cjs} +21 -14
  56. package/dist/chunk-N7MIIDLI.cjs +1605 -0
  57. package/dist/{chunk-USOUXQYD.js → chunk-NWKARJM2.js} +130 -22
  58. package/dist/{chunk-VVAAZITA.cjs → chunk-OOP4S3GU.cjs} +5 -5
  59. package/dist/{chunk-TX6ZBIF4.js → chunk-ORBVCOTC.js} +3 -3
  60. package/dist/{chunk-RRQIAJLQ.cjs → chunk-OSKGCXAQ.cjs} +5 -5
  61. package/dist/{chunk-QEDMOGF3.cjs → chunk-P65OIMJT.cjs} +7 -7
  62. package/dist/{chunk-QM7FJB5W.js → chunk-PSWCJQS4.js} +4 -4
  63. package/dist/{chunk-7N63JHUN.cjs → chunk-PZ46WRHX.cjs} +8 -8
  64. package/dist/{chunk-AATYYLYK.js → chunk-Q4J2K7FI.js} +16 -5
  65. package/dist/chunk-QLPRI3QW.js +1875 -0
  66. package/dist/{chunk-WTH23ISI.js → chunk-R5VKLUMR.js} +4 -4
  67. package/dist/{chunk-NQN5LFN4.cjs → chunk-REN3LHO6.cjs} +19 -19
  68. package/dist/{chunk-JEJ7TT54.js → chunk-RVN7OPCP.js} +4 -4
  69. package/dist/{chunk-ZK7KX5CD.cjs → chunk-SE2Y5BSL.cjs} +6 -6
  70. package/dist/{chunk-2X3IPCBK.cjs → chunk-SKVBUGMC.cjs} +7 -7
  71. package/dist/{chunk-GZPUA2TL.cjs → chunk-SNMQUWIO.cjs} +10 -10
  72. package/dist/{chunk-OIBRWLPY.cjs → chunk-TKDDIE3T.cjs} +54 -3
  73. package/dist/{chunk-5H5GFBMG.cjs → chunk-TMNAKNV2.cjs} +112 -55
  74. package/dist/{chunk-5LVFTGKH.js → chunk-TZQKJOPC.js} +3 -3
  75. package/dist/{chunk-TSTFYGGX.js → chunk-UKEK2NZJ.js} +3 -3
  76. package/dist/{chunk-3IUHTGDD.cjs → chunk-VA7THINF.cjs} +38 -38
  77. package/dist/{chunk-Z557DVYN.js → chunk-VMCR5QVI.js} +4 -4
  78. package/dist/{chunk-IS7NTKY5.cjs → chunk-VTFLKSJL.cjs} +14 -14
  79. package/dist/{chunk-VO52AJD5.js → chunk-VXHB6ZHY.js} +4 -4
  80. package/dist/{chunk-S4O7CFHQ.cjs → chunk-VZI7S7P6.cjs} +7 -7
  81. package/dist/{chunk-BQJ3YBF3.js → chunk-W4AJMMQR.js} +667 -628
  82. package/dist/{chunk-2KKOYZYI.cjs → chunk-XZC75AJ4.cjs} +5 -5
  83. package/dist/{chunk-FWCHPCD4.js → chunk-Y2OCKXVD.js} +4 -4
  84. package/dist/{chunk-EI5G5JLY.cjs → chunk-YBM34FUJ.cjs} +134 -22
  85. package/dist/{chunk-DUG3OQAS.js → chunk-YDSNDCV3.js} +3 -3
  86. package/dist/{chunk-566ZB4LZ.cjs → chunk-YM7UUYR5.cjs} +5 -5
  87. package/dist/{chunk-BCP4E7MD.cjs → chunk-YMI3ED3B.cjs} +26 -10
  88. package/dist/{chunk-CP7V3ATL.js → chunk-Z7NUL73U.js} +51 -4
  89. package/dist/cli/holoscript-runner.cjs +11 -11
  90. package/dist/cli/holoscript-runner.js +4 -4
  91. package/dist/compiler/agent-inference.cjs +8 -8
  92. package/dist/compiler/agent-inference.js +4 -4
  93. package/dist/compiler/android-xr.cjs +7 -7
  94. package/dist/compiler/android-xr.js +5 -5
  95. package/dist/compiler/android.cjs +6 -6
  96. package/dist/compiler/android.js +4 -4
  97. package/dist/compiler/context.cjs +6 -6
  98. package/dist/compiler/context.js +3 -3
  99. package/dist/compiler/daimon-seed.cjs +9 -9
  100. package/dist/compiler/daimon-seed.js +4 -4
  101. package/dist/compiler/domain-block-utils.cjs +165 -165
  102. package/dist/compiler/domain-block-utils.js +4 -4
  103. package/dist/compiler/dtdl.cjs +7 -7
  104. package/dist/compiler/dtdl.js +4 -4
  105. package/dist/compiler/gltf-pipeline.cjs +8 -8
  106. package/dist/compiler/gltf-pipeline.js +1 -1
  107. package/dist/compiler/godot.cjs +6 -6
  108. package/dist/compiler/godot.js +5 -5
  109. package/dist/compiler/incremental.cjs +8 -8
  110. package/dist/compiler/incremental.js +3 -3
  111. package/dist/compiler/index.cjs +871 -207
  112. package/dist/compiler/index.d.ts +21 -1
  113. package/dist/compiler/index.js +696 -60
  114. package/dist/compiler/ios.cjs +6 -6
  115. package/dist/compiler/ios.js +4 -4
  116. package/dist/compiler/llm-provider-capabilities.cjs +6 -6
  117. package/dist/compiler/llm-provider-capabilities.js +3 -3
  118. package/dist/compiler/openxr.cjs +6 -6
  119. package/dist/compiler/openxr.js +5 -5
  120. package/dist/compiler/sdf.cjs +7 -7
  121. package/dist/compiler/sdf.js +5 -5
  122. package/dist/compiler/state.cjs +6 -6
  123. package/dist/compiler/state.js +4 -4
  124. package/dist/compiler/trait-composition.cjs +7 -7
  125. package/dist/compiler/trait-composition.js +3 -3
  126. package/dist/compiler/unity.cjs +6 -6
  127. package/dist/compiler/unity.js +5 -5
  128. package/dist/compiler/unreal.cjs +7 -7
  129. package/dist/compiler/unreal.js +5 -5
  130. package/dist/compiler/urdf.cjs +14 -14
  131. package/dist/compiler/urdf.js +5 -5
  132. package/dist/compiler/usd-physics.cjs +7 -7
  133. package/dist/compiler/usd-physics.js +4 -4
  134. package/dist/compiler/visionos.cjs +6 -6
  135. package/dist/compiler/visionos.js +5 -5
  136. package/dist/compiler/vrchat.cjs +7 -7
  137. package/dist/compiler/vrchat.js +5 -5
  138. package/dist/compiler/wasm.cjs +10 -10
  139. package/dist/compiler/wasm.js +5 -5
  140. package/dist/compiler/webgpu.cjs +6 -6
  141. package/dist/compiler/webgpu.js +5 -5
  142. package/dist/constants.cjs +3 -3
  143. package/dist/constants.js +1 -1
  144. package/dist/entries/scripting.cjs +6 -6
  145. package/dist/entries/scripting.js +2 -2
  146. package/dist/evolution/index.cjs +21 -17
  147. package/dist/evolution/index.d.ts +9 -0
  148. package/dist/evolution/index.js +6 -6
  149. package/dist/index.cjs +930 -703
  150. package/dist/index.d.ts +70 -5
  151. package/dist/index.js +192 -109
  152. package/dist/parser.cjs +19 -19
  153. package/dist/parser.js +5 -5
  154. package/dist/reconstruction/index.cjs +127 -38
  155. package/dist/reconstruction/index.d.ts +159 -0
  156. package/dist/reconstruction/index.js +11 -2
  157. package/dist/runtime.d.ts +1 -0
  158. package/dist/traitDocs/traitDocs.cjs +8 -8
  159. package/dist/traitDocs/traitDocs.js +2 -2
  160. package/dist/traits/index.cjs +566 -471
  161. package/dist/traits/index.js +93 -11
  162. package/package.json +25 -41
  163. package/dist/chunk-G3BM3CT4.cjs +0 -639
  164. package/dist/chunk-KEYG7HGY.js +0 -1062
  165. package/dist/chunk-QX34ELJ7.js +0 -625
  166. package/dist/chunk-W2GA3EQB.cjs +0 -1065
@@ -1,1065 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkQEDMOGF3_cjs = require('./chunk-QEDMOGF3.cjs');
4
- var chunkZK7KX5CD_cjs = require('./chunk-ZK7KX5CD.cjs');
5
- var chunkZHPMP447_cjs = require('./chunk-ZHPMP447.cjs');
6
- var ans = require('@holoscript/core-types/ans');
7
-
8
- // src/compiler/WebGPUCompiler.ts
9
- var WebGPUCompiler_exports = {};
10
- chunkZHPMP447_cjs.__export(WebGPUCompiler_exports, {
11
- WebGPUCompiler: () => exports.WebGPUCompiler
12
- });
13
- function isGpuParticleTraitName(name) {
14
- return typeof name === "string" && (name === "gpu_particle" || name.startsWith("vfx_particle_"));
15
- }
16
- function findGpuParticleTrait(traits) {
17
- return traits?.find((t) => isGpuParticleTraitName(t.name));
18
- }
19
- exports.WebGPUCompiler = void 0;
20
- var init_WebGPUCompiler = chunkZHPMP447_cjs.__esm({
21
- "src/compiler/WebGPUCompiler.ts"() {
22
- chunkZK7KX5CD_cjs.init_CompilerBase();
23
- chunkQEDMOGF3_cjs.init_DomainBlockCompilerMixin();
24
- exports.WebGPUCompiler = class extends chunkZK7KX5CD_cjs.CompilerBase {
25
- constructor(options = {}) {
26
- super();
27
- this.compilerName = "WebGPUCompiler";
28
- this.lines = [];
29
- this.indentLevel = 0;
30
- this.objectIndex = 0;
31
- this.options = {
32
- entryPoint: options.entryPoint || "main",
33
- enableCompute: options.enableCompute ?? true,
34
- msaa: options.msaa || 4,
35
- indent: options.indent || " ",
36
- provenanceHash: options.provenanceHash ?? ""
37
- };
38
- }
39
- getRequiredCapability() {
40
- return ans.ANSCapabilityPath.WEBGPU;
41
- }
42
- compile(composition, agentToken, outputPath) {
43
- this.validateCompilerAccess(agentToken, outputPath);
44
- this.lines = [];
45
- this.indentLevel = 0;
46
- this.objectIndex = 0;
47
- this.emit("// Auto-generated by HoloScript WebGPUCompiler");
48
- this.emit(
49
- `// Source: composition "${this.escapeStringValue(composition.name, "TypeScript")}"`
50
- );
51
- this.emit("// Do not edit manually \u2014 regenerate from .holo source");
52
- if (this.options.provenanceHash) {
53
- this.emit(`// Provenance Hash: ${this.options.provenanceHash}`);
54
- }
55
- this.emit("");
56
- this.emitDeviceInit();
57
- this.emitGeometryHelpers();
58
- this.emitShaderSources();
59
- if (composition.environment) this.emitEnvironment(composition.environment);
60
- this.emitCamera(composition.camera);
61
- if (composition.objects) {
62
- for (const obj of composition.objects) this.emitObject(obj);
63
- }
64
- if (composition.spatialGroups) {
65
- for (const group of composition.spatialGroups) this.emitGroup(group);
66
- }
67
- if (composition.lights) {
68
- for (const light of composition.lights) this.emitLight(light);
69
- }
70
- if (this.options.enableCompute) this.emitComputeShaders(composition);
71
- this.emitWebGPUDomainBlocks(composition);
72
- this.emitRenderLoop(composition);
73
- return this.lines.join("\n");
74
- }
75
- emitWebGPUDomainBlocks(composition) {
76
- const domainBlocks = composition.domainBlocks ?? [];
77
- if (domainBlocks.length === 0) return;
78
- this.emit("");
79
- this.emit("// === v4.2 Domain Blocks ===");
80
- for (let i = 0; i < domainBlocks.length; i++) {
81
- const block = domainBlocks[i];
82
- const prefix = this.domainBlockVar(block, i);
83
- switch (block.domain) {
84
- case "material":
85
- this.emitMaterialDomainBlock(block, prefix);
86
- break;
87
- case "dataviz":
88
- this.emitMultiline(chunkQEDMOGF3_cjs.datavizToWebGPU(chunkQEDMOGF3_cjs.compileDataVizBlock(block), prefix));
89
- break;
90
- case "vfx":
91
- this.emitParticleDomainBlock(block, prefix);
92
- break;
93
- case "postfx":
94
- this.emitPostFXDomainBlock(block, prefix);
95
- break;
96
- case "procedural":
97
- this.emitProceduralDomainBlock(block, prefix);
98
- break;
99
- default:
100
- this.emitDomainMetadataBlock(block, prefix);
101
- break;
102
- }
103
- this.emit("");
104
- }
105
- }
106
- emitMaterialDomainBlock(block, prefix) {
107
- const mat = chunkQEDMOGF3_cjs.compileMaterialBlock(block);
108
- this.emitMultiline(chunkQEDMOGF3_cjs.materialToWebGPU(mat, prefix));
109
- if (Object.keys(mat.textureMaps).length > 0) {
110
- this.emit(`const ${prefix}TextureMaps = ${this.json(mat.textureMaps)};`);
111
- this.emit(`const ${prefix}Textures = await loadMaterialTextureSet(${prefix}TextureMaps);`);
112
- this.emit(
113
- `const ${prefix}TextureReceipt = { name: "${this.escapeStringValue(mat.name, "TypeScript")}", maps: Object.keys(${prefix}TextureMaps), loaded: Object.values(${prefix}Textures).filter((t) => t.loaded).length };`
114
- );
115
- }
116
- }
117
- emitParticleDomainBlock(block, prefix) {
118
- const ps = chunkQEDMOGF3_cjs.compileParticleBlock(block);
119
- const count = Math.max(
120
- 1,
121
- Math.floor(
122
- this.numberProp(block, ["max_particles", "maxParticles", "count", "rate"], 512)
123
- )
124
- );
125
- const seed = this.hashSeed(`${ps.name}:${ps.keyword}:${count}`);
126
- this.emit(`// Domain particles: ${this.escapeStringValue(ps.name, "TypeScript")}`);
127
- this.emit(`const ${prefix}ParticleConfig = ${this.json({
128
- name: ps.name,
129
- keyword: ps.keyword,
130
- traits: ps.traits,
131
- properties: ps.properties,
132
- modules: ps.modules
133
- })};`);
134
- this.emit(`const ${prefix}ParticleCount = ${count};`);
135
- this.emit(`const ${prefix}ParticleData = makeParticleCloud(${prefix}ParticleCount, ${seed});`);
136
- this.emit(
137
- `const ${prefix}ParticleBuf = createBuffer(device, ${prefix}ParticleData, GPUBufferUsage.VERTEX | GPUBufferUsage.STORAGE);`
138
- );
139
- this.emit(`const ${prefix}ParticlePipeline = device.createRenderPipeline({`);
140
- this.indent();
141
- this.emit('layout: "auto",');
142
- this.emit(
143
- 'vertex: { module: device.createShaderModule({ code: WGSL_PARTICLE_RENDER }), entryPoint: "vs_particle",'
144
- );
145
- this.emit(
146
- ' buffers: [{ arrayStride: 32, attributes: [{ shaderLocation: 0, offset: 0, format: "float32x3" }, { shaderLocation: 1, offset: 12, format: "float32x3" }, { shaderLocation: 2, offset: 24, format: "float32" }] }] },'
147
- );
148
- this.emit(
149
- 'fragment: { module: device.createShaderModule({ code: WGSL_PARTICLE_RENDER }), entryPoint: "fs_particle",'
150
- );
151
- this.emit(
152
- ' targets: [{ format, blend: { color: { srcFactor: "src-alpha", dstFactor: "one", operation: "add" }, alpha: { srcFactor: "zero", dstFactor: "one", operation: "add" } } }] },'
153
- );
154
- this.emit(
155
- 'primitive: { topology: "point-list" }, depthStencil: { format: "depth24plus", depthWriteEnabled: false, depthCompare: "less" },'
156
- );
157
- this.dedent();
158
- this.emit("});");
159
- }
160
- emitPostFXDomainBlock(block, prefix) {
161
- const pp = chunkQEDMOGF3_cjs.compilePostProcessingBlock(block);
162
- this.emit(`// Domain post-processing: ${this.escapeStringValue(pp.name ?? block.name, "TypeScript")}`);
163
- this.emit(`const ${prefix}PostFXConfig = ${this.json({
164
- name: pp.name,
165
- keyword: pp.keyword,
166
- effects: pp.effects
167
- })};`);
168
- this.emit(`const ${prefix}PostFXPipeline = device.createRenderPipeline({`);
169
- this.indent();
170
- this.emit('layout: "auto",');
171
- this.emit(
172
- 'vertex: { module: device.createShaderModule({ code: WGSL_POSTFX }), entryPoint: "vs_postfx" },'
173
- );
174
- this.emit(
175
- 'fragment: { module: device.createShaderModule({ code: WGSL_POSTFX }), entryPoint: "fs_postfx", targets: [{ format, blend: { color: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" }, alpha: { srcFactor: "one", dstFactor: "one-minus-src-alpha", operation: "add" } } }] },'
176
- );
177
- this.emit('primitive: { topology: "triangle-list" }, multisample: { count: MSAA_COUNT },');
178
- this.dedent();
179
- this.emit("});");
180
- }
181
- emitProceduralDomainBlock(block, prefix) {
182
- const proc = chunkQEDMOGF3_cjs.compileProceduralBlock(block);
183
- this.emit(`// Domain procedural: ${this.escapeStringValue(proc.name, "TypeScript")}`);
184
- this.emit(`const ${prefix}ProceduralConfig = ${this.json({
185
- name: proc.name,
186
- keyword: proc.keyword,
187
- genType: proc.genType,
188
- seed: proc.seed,
189
- density: proc.density,
190
- scaleRange: proc.scaleRange,
191
- noise: proc.noise,
192
- sourceMesh: proc.sourceMesh,
193
- traits: proc.traits,
194
- properties: proc.properties
195
- })};`);
196
- this.emit(
197
- `const ${prefix}ProceduralUniform = createBuffer(device, new Float32Array([${proc.seed ?? 1}, ${proc.density ?? 1}, ${this.numberProp(block, ["count"], 1)}, 0]), GPUBufferUsage.UNIFORM);`
198
- );
199
- if (block.keyword === "scatter" || block.keyword === "distribute" || block.properties?.count) {
200
- const count = Math.max(1, Math.floor(this.numberProp(block, ["count"], 128)));
201
- this.emit(`const ${prefix}ScatterInstanceCount = ${count};`);
202
- this.emit(`const ${prefix}ScatterVertices = generateConeVertices(0.08, 0.36, 8);`);
203
- this.emit(`const ${prefix}ScatterVBO = createBuffer(device, ${prefix}ScatterVertices, GPUBufferUsage.VERTEX);`);
204
- this.emit(`const ${prefix}ScatterVertexCount = ${prefix}ScatterVertices.length / 6;`);
205
- this.emit(`const ${prefix}ScatterPipeline = device.createRenderPipeline({`);
206
- this.indent();
207
- this.emit('layout: "auto",');
208
- this.emit(
209
- 'vertex: { module: device.createShaderModule({ code: WGSL_SCATTER }), entryPoint: "vs_scatter",'
210
- );
211
- this.emit(
212
- ' buffers: [{ arrayStride: 24, attributes: [{ shaderLocation: 0, offset: 0, format: "float32x3" }, { shaderLocation: 1, offset: 12, format: "float32x3" }] }] },'
213
- );
214
- this.emit(
215
- 'fragment: { module: device.createShaderModule({ code: WGSL_SCATTER }), entryPoint: "fs_scatter", targets: [{ format }] },'
216
- );
217
- this.emit(
218
- 'primitive: { topology: "triangle-list", cullMode: "back" }, depthStencil: { format: "depth24plus", depthWriteEnabled: true, depthCompare: "less" }, multisample: { count: MSAA_COUNT },'
219
- );
220
- this.dedent();
221
- this.emit("});");
222
- }
223
- }
224
- emitDomainMetadataBlock(block, prefix) {
225
- this.emit(`const ${prefix}DomainBlock = ${this.json({
226
- domain: block.domain,
227
- keyword: block.keyword,
228
- name: block.name,
229
- traits: block.traits,
230
- properties: block.properties,
231
- childCount: block.children?.length ?? 0
232
- })};`);
233
- }
234
- // ─── Device Init ──────────────────────────────────────────────────────────
235
- emitDeviceInit() {
236
- this.emit("// === WebGPU Device Initialization ===");
237
- this.emit('const canvas = document.querySelector("canvas") as HTMLCanvasElement;');
238
- this.emit("const adapter = await navigator.gpu.requestAdapter();");
239
- this.emit('if (!adapter) throw new Error("WebGPU not supported");');
240
- this.emit("const device = await adapter.requestDevice();");
241
- this.emit('document.body.dataset.holoscriptWebgpu = "device-ready";');
242
- this.emit('const context = canvas.getContext("webgpu") as GPUCanvasContext;');
243
- this.emit("const format = navigator.gpu.getPreferredCanvasFormat();");
244
- this.emit('context.configure({ device, format, alphaMode: "premultiplied" });');
245
- this.emit(`const MSAA_COUNT = ${this.options.msaa};`);
246
- this.emit(
247
- "const msaaTexture = device.createTexture({ size: [canvas.width, canvas.height], sampleCount: MSAA_COUNT, format, usage: GPUTextureUsage.RENDER_ATTACHMENT });"
248
- );
249
- this.emit(
250
- 'const depthTexture = device.createTexture({ size: [canvas.width, canvas.height], sampleCount: MSAA_COUNT, format: "depth24plus", usage: GPUTextureUsage.RENDER_ATTACHMENT });'
251
- );
252
- this.emit("");
253
- this.emit(
254
- "function createBuffer(device: GPUDevice, data: Float32Array, usage: number): GPUBuffer {"
255
- );
256
- this.indent();
257
- this.emit(
258
- "const buf = device.createBuffer({ size: data.byteLength, usage: usage | GPUBufferUsage.COPY_DST });"
259
- );
260
- this.emit("device.queue.writeBuffer(buf, 0, data); return buf;");
261
- this.dedent();
262
- this.emit("}");
263
- this.emit("function createStorageBuffer(device: GPUDevice, size: number): GPUBuffer {");
264
- this.indent();
265
- this.emit(
266
- "return device.createBuffer({ size, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });"
267
- );
268
- this.dedent();
269
- this.emit("}");
270
- this.emit("function createFallbackTexture(device, rgba) {");
271
- this.indent();
272
- this.emit('const tex = device.createTexture({ size: [1, 1, 1], format: "rgba8unorm", usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST });');
273
- this.emit("device.queue.writeTexture({ texture: tex }, new Uint8Array(rgba), { bytesPerRow: 4 }, [1, 1, 1]);");
274
- this.emit("return tex;");
275
- this.dedent();
276
- this.emit("}");
277
- this.emit("async function loadTexture2D(src) {");
278
- this.indent();
279
- this.emit('const sampler = device.createSampler({ magFilter: "linear", minFilter: "linear", mipmapFilter: "linear", addressModeU: "repeat", addressModeV: "repeat" });');
280
- this.emit("try {");
281
- this.indent();
282
- this.emit("const resp = await fetch(src);");
283
- this.emit("if (!resp.ok) throw new Error(`texture fetch ${resp.status}`);");
284
- this.emit("const bitmap = await createImageBitmap(await resp.blob());");
285
- this.emit('const texture = device.createTexture({ size: [bitmap.width, bitmap.height, 1], format: "rgba8unorm", usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT });');
286
- this.emit("device.queue.copyExternalImageToTexture({ source: bitmap }, { texture }, [bitmap.width, bitmap.height]);");
287
- this.emit("return { src, texture, view: texture.createView(), sampler, loaded: true };");
288
- this.dedent();
289
- this.emit("} catch {");
290
- this.indent();
291
- this.emit("const texture = createFallbackTexture(device, [255, 255, 255, 255]);");
292
- this.emit("return { src, texture, view: texture.createView(), sampler, loaded: false };");
293
- this.dedent();
294
- this.emit("}");
295
- this.dedent();
296
- this.emit("}");
297
- this.emit("async function loadMaterialTextureSet(maps) {");
298
- this.indent();
299
- this.emit("const entries = await Promise.all(Object.entries(maps).map(async ([kind, src]) => [kind, await loadTexture2D(src)]));");
300
- this.emit("return Object.fromEntries(entries);");
301
- this.dedent();
302
- this.emit("}");
303
- this.emit("const assetLoader = {");
304
- this.indent();
305
- this.emit("async load(src) {");
306
- this.indent();
307
- this.emit('return { src, kind: "external-model", loaded: false };');
308
- this.dedent();
309
- this.emit("},");
310
- this.dedent();
311
- this.emit("};");
312
- this.emit("function makeParticleCloud(count, seed) {");
313
- this.indent();
314
- this.emit("let s = seed || 1;");
315
- this.emit("const rnd = () => { s = (s * 1664525 + 1013904223) >>> 0; return s / 4294967296; };");
316
- this.emit("const data = new Float32Array(count * 8);");
317
- this.emit("for (let i = 0; i < count; i++) {");
318
- this.indent();
319
- this.emit("const o = i * 8;");
320
- this.emit("data[o + 0] = rnd() * 1.8 - 0.9; data[o + 1] = rnd() * 1.2 - 0.6; data[o + 2] = rnd() * 1.8 - 0.9;");
321
- this.emit("data[o + 3] = 0.0; data[o + 4] = 0.25 + rnd(); data[o + 5] = 0.0; data[o + 6] = rnd(); data[o + 7] = 0.0;");
322
- this.dedent();
323
- this.emit("}");
324
- this.emit("return data;");
325
- this.dedent();
326
- this.emit("}");
327
- this.emit("");
328
- }
329
- emitGeometryHelpers() {
330
- this.emit("// === Geometry Helpers ===");
331
- this.emit("function generateCubeVertices(size) {");
332
- this.indent();
333
- this.emit("const s = size / 2;");
334
- this.emit("return new Float32Array([");
335
- this.indent();
336
- this.emit("-s,-s, s, 0,0,1, s,-s, s, 0,0,1, s, s, s, 0,0,1, -s,-s, s, 0,0,1, s, s, s, 0,0,1, -s, s, s, 0,0,1,");
337
- this.emit(" s,-s,-s, 0,0,-1, -s,-s,-s, 0,0,-1, -s, s,-s, 0,0,-1, s,-s,-s, 0,0,-1, -s, s,-s, 0,0,-1, s, s,-s, 0,0,-1,");
338
- this.emit("-s,-s,-s, -1,0,0, -s,-s, s, -1,0,0, -s, s, s, -1,0,0, -s,-s,-s, -1,0,0, -s, s, s, -1,0,0, -s, s,-s, -1,0,0,");
339
- this.emit(" s,-s, s, 1,0,0, s,-s,-s, 1,0,0, s, s,-s, 1,0,0, s,-s, s, 1,0,0, s, s,-s, 1,0,0, s, s, s, 1,0,0,");
340
- this.emit("-s, s, s, 0,1,0, s, s, s, 0,1,0, s, s,-s, 0,1,0, -s, s, s, 0,1,0, s, s,-s, 0,1,0, -s, s,-s, 0,1,0,");
341
- this.emit("-s,-s,-s, 0,-1,0, s,-s,-s, 0,-1,0, s,-s, s, 0,-1,0, -s,-s,-s, 0,-1,0, s,-s, s, 0,-1,0, -s,-s, s, 0,-1,0");
342
- this.dedent();
343
- this.emit("]);");
344
- this.dedent();
345
- this.emit("}");
346
- this.emit("function generatePlaneVertices(width, depth) {");
347
- this.indent();
348
- this.emit("const x = width / 2, z = depth / 2;");
349
- this.emit("return new Float32Array([-x,0,-z,0,1,0, x,0,-z,0,1,0, x,0,z,0,1,0, -x,0,-z,0,1,0, x,0,z,0,1,0, -x,0,z,0,1,0]);");
350
- this.dedent();
351
- this.emit("}");
352
- this.emit("function generateSphereVertices(radius, lat, lon) {");
353
- this.indent();
354
- this.emit("const rings = Math.max(3, lat | 0), segs = Math.max(3, lon | 0); const out = [];");
355
- this.emit("const P = (ri, si) => {");
356
- this.emit(" const phi = Math.PI * ri / rings, theta = 2 * Math.PI * si / segs;");
357
- this.emit(" const nx = Math.sin(phi) * Math.cos(theta), ny = Math.cos(phi), nz = Math.sin(phi) * Math.sin(theta);");
358
- this.emit(" return [nx * radius, ny * radius, nz * radius, nx, ny, nz];");
359
- this.emit("};");
360
- this.emit("for (let ri = 0; ri < rings; ri++) { for (let si = 0; si < segs; si++) {");
361
- this.emit(" const a = P(ri, si), b = P(ri + 1, si), c = P(ri + 1, si + 1), d = P(ri, si + 1);");
362
- this.emit(" out.push(...a, ...b, ...c, ...a, ...c, ...d);");
363
- this.emit("} } return new Float32Array(out);");
364
- this.dedent();
365
- this.emit("}");
366
- this.emit("function generateCylinderVertices(radius, height, segments) {");
367
- this.indent();
368
- this.emit("const segs = Math.max(3, segments | 0), hy = height / 2, out = [];");
369
- this.emit("for (let i = 0; i < segs; i++) {");
370
- this.emit(" const t0 = 2*Math.PI*i/segs, t1 = 2*Math.PI*(i+1)/segs;");
371
- this.emit(" const c0 = Math.cos(t0), s0 = Math.sin(t0), c1 = Math.cos(t1), s1 = Math.sin(t1);");
372
- this.emit(" const b0 = [radius*c0, -hy, radius*s0, c0, 0, s0], t0v = [radius*c0, hy, radius*s0, c0, 0, s0];");
373
- this.emit(" const b1 = [radius*c1, -hy, radius*s1, c1, 0, s1], t1v = [radius*c1, hy, radius*s1, c1, 0, s1];");
374
- this.emit(" out.push(...b0, ...b1, ...t1v, ...b0, ...t1v, ...t0v);");
375
- this.emit(" out.push(0, hy, 0, 0, 1, 0, radius*c0, hy, radius*s0, 0, 1, 0, radius*c1, hy, radius*s1, 0, 1, 0);");
376
- this.emit(" out.push(0, -hy, 0, 0, -1, 0, radius*c1, -hy, radius*s1, 0, -1, 0, radius*c0, -hy, radius*s0, 0, -1, 0);");
377
- this.emit("} return new Float32Array(out);");
378
- this.dedent();
379
- this.emit("}");
380
- this.emit("function generateConeVertices(radius, height, segments) {");
381
- this.indent();
382
- this.emit("const segs = Math.max(3, segments | 0), hy = height / 2, out = [];");
383
- this.emit("const ny = radius / Math.hypot(radius, height) || 0, nyx = height / Math.hypot(radius, height) || 1;");
384
- this.emit("for (let i = 0; i < segs; i++) {");
385
- this.emit(" const t0 = 2*Math.PI*i/segs, t1 = 2*Math.PI*(i+1)/segs;");
386
- this.emit(" const c0 = Math.cos(t0), s0 = Math.sin(t0), c1 = Math.cos(t1), s1 = Math.sin(t1);");
387
- this.emit(" out.push(0, hy, 0, (c0+c1)*0.5*nyx, ny, (s0+s1)*0.5*nyx);");
388
- this.emit(" out.push(radius*c0, -hy, radius*s0, c0*nyx, ny, s0*nyx);");
389
- this.emit(" out.push(radius*c1, -hy, radius*s1, c1*nyx, ny, s1*nyx);");
390
- this.emit(" out.push(0, -hy, 0, 0, -1, 0, radius*c1, -hy, radius*s1, 0, -1, 0, radius*c0, -hy, radius*s0, 0, -1, 0);");
391
- this.emit("} return new Float32Array(out);");
392
- this.dedent();
393
- this.emit("}");
394
- this.emit("function generateTorusVertices(radius, tube, radial, tubular) {");
395
- this.indent();
396
- this.emit("const R = Math.max(3, radial | 0), T = Math.max(3, tubular | 0), out = [];");
397
- this.emit("const P = (ri, ti) => {");
398
- this.emit(" const u = 2*Math.PI*ri/R, v = 2*Math.PI*ti/T;");
399
- this.emit(" const cu = Math.cos(u), su = Math.sin(u), cv = Math.cos(v), sv = Math.sin(v);");
400
- this.emit(" const x = (radius + tube*cv)*cu, y = tube*sv, z = (radius + tube*cv)*su;");
401
- this.emit(" return [x, y, z, cv*cu, sv, cv*su];");
402
- this.emit("};");
403
- this.emit("for (let ri = 0; ri < R; ri++) { for (let ti = 0; ti < T; ti++) {");
404
- this.emit(" const a = P(ri, ti), b = P(ri + 1, ti), c = P(ri + 1, ti + 1), d = P(ri, ti + 1);");
405
- this.emit(" out.push(...a, ...b, ...c, ...a, ...c, ...d);");
406
- this.emit("} } return new Float32Array(out);");
407
- this.dedent();
408
- this.emit("}");
409
- this.emit("");
410
- }
411
- // ─── Environment ──────────────────────────────────────────────────────────
412
- emitEnvironment(env) {
413
- this.emit("// === Environment ===");
414
- const envData = {};
415
- for (const prop of env.properties) envData[prop.key] = prop.value;
416
- const bg = envData.background || envData.skybox || "#000000";
417
- const bgColor = this.parseColor(bg);
418
- this.emit(
419
- `const clearColor: GPUColor = { r: ${bgColor[0]}, g: ${bgColor[1]}, b: ${bgColor[2]}, a: 1.0 };`
420
- );
421
- if (envData.fog && typeof envData.fog === "object") {
422
- const fog = envData.fog;
423
- const fc = this.parseColor(fog.color || "#cccccc");
424
- this.emit(
425
- `const fogUniforms = createBuffer(device, new Float32Array([${fc[0]}, ${fc[1]}, ${fc[2]}, 1.0, ${fog.near ?? 10}, ${fog.far ?? 100}, 0.0, 0.0]), GPUBufferUsage.UNIFORM);`
426
- );
427
- }
428
- if (envData.ambient_light !== void 0) {
429
- this.emit(
430
- `const ambientIntensity = ${typeof envData.ambient_light === "number" ? envData.ambient_light : 0.5};`
431
- );
432
- }
433
- this.emit("");
434
- }
435
- // ─── Object ───────────────────────────────────────────────────────────────
436
- emitObject(obj) {
437
- this.objectIndex++;
438
- const v = this.sanitizeName(obj.name);
439
- const meshType = this.findObjProp(obj, "geometry") || this.findObjProp(obj, "mesh") || this.findObjProp(obj, "type") || "cube";
440
- const modelSrc = this.findObjProp(obj, "source") || this.findObjProp(obj, "src") || this.findObjProp(obj, "model");
441
- const isModel = meshType === "model" || !!modelSrc;
442
- const traits = obj.traits || [];
443
- this.emit(`// Object: ${this.escapeStringValue(obj.name, "TypeScript")}`);
444
- const isGaussianSplat = traits.some((t) => t.name === "gaussian_splat");
445
- const isPointCloud = traits.some((t) => t.name === "point_cloud");
446
- const isGpuParticle = traits.some((t) => isGpuParticleTraitName(t.name));
447
- if (isModel && modelSrc) {
448
- this.emit(`const ${v}Asset = await assetLoader.load("${modelSrc}");`);
449
- this.emit(
450
- `// Model asset "${this.escapeStringValue(modelSrc, "TypeScript")}" is tracked in ${v}Asset; fallback mesh keeps the render path defined.`
451
- );
452
- this.emitMeshObject(v, obj, "cube");
453
- } else if (isModel) {
454
- this.emit(`// WARNING: geometry "model" without source URL \u2014 placeholder cube`);
455
- this.emitMeshObject(v, obj, "cube");
456
- } else if (isGaussianSplat) {
457
- this.emitGaussianSplatObject(v, obj);
458
- } else if (isPointCloud) {
459
- this.emitPointCloudObject(v, obj);
460
- } else if (isGpuParticle) {
461
- this.emitGpuParticleObject(v, obj);
462
- } else {
463
- this.emitMeshObject(v, obj, meshType);
464
- }
465
- if (traits.some((t) => t.name === "gpu_physics")) {
466
- this.emit(`const ${v}PhysicsBuf = createStorageBuffer(device, 1024 * 16); // gpu_physics`);
467
- }
468
- if (traits.some((t) => t.name === "compute" || t.name === "gpu_buffer")) {
469
- const ct = traits.find((t) => t.name === "compute" || t.name === "gpu_buffer");
470
- this.emit(
471
- `const ${v}ComputeBuf = createStorageBuffer(device, ${ct?.config?.buffer_size || 4096});`
472
- );
473
- }
474
- this.emit("");
475
- if (obj.children) {
476
- for (const child of obj.children) this.emitObject(child);
477
- }
478
- }
479
- emitMeshObject(v, obj, meshType) {
480
- this.emit(`const ${v}Vertices = ${this.geometryVertexDataFn(meshType)};`);
481
- this.emit(`const ${v}VBO = createBuffer(device, ${v}Vertices, GPUBufferUsage.VERTEX);`);
482
- this.emit(`const ${v}VertexCount = ${v}Vertices.length / 6;`);
483
- const pos = this.findObjProp(obj, "position");
484
- const scale = this.findObjProp(obj, "scale") || this.findObjProp(obj, "size");
485
- const [px, py, pz] = Array.isArray(pos) ? pos : [0, 0, 0];
486
- const [sx, sy, sz] = Array.isArray(scale) ? scale : typeof scale === "number" ? [scale, scale, scale] : [1, 1, 1];
487
- this.emit(
488
- `const ${v}Model = createBuffer(device, new Float32Array([${sx},0,0,0, 0,${sy},0,0, 0,0,${sz},0, ${px},${py},${pz},1]), GPUBufferUsage.UNIFORM);`
489
- );
490
- const material = this.findObjProp(obj, "material");
491
- const color = this.findObjProp(obj, "color");
492
- const [cr, cg, cb] = this.extractMaterialColor(material, color);
493
- const rough = this.extractMaterialProp(material, "roughness", 0.5);
494
- const metal = this.extractMaterialProp(material, "metalness", 0);
495
- const [er, eg, eb] = this.extractEmissive(material, obj);
496
- const emissiveStrength = this.extractMaterialProp(material, "emissive_intensity", 1);
497
- this.emit(
498
- `const ${v}Mat = createBuffer(device, new Float32Array([${cr},${cg},${cb},1.0, ${rough},${metal},${emissiveStrength},0, ${er},${eg},${eb},0]), GPUBufferUsage.UNIFORM);`
499
- );
500
- this.emit(`const ${v}Pipeline = device.createRenderPipeline({`);
501
- this.indent();
502
- this.emit('layout: "auto",');
503
- this.emit(
504
- 'vertex: { module: device.createShaderModule({ code: WGSL_VERTEX }), entryPoint: "vs_main",'
505
- );
506
- this.emit(
507
- ' buffers: [{ arrayStride: 24, attributes: [{ shaderLocation: 0, offset: 0, format: "float32x3" }, { shaderLocation: 1, offset: 12, format: "float32x3" }] }] },'
508
- );
509
- this.emit(
510
- 'fragment: { module: device.createShaderModule({ code: WGSL_FRAGMENT }), entryPoint: "fs_main", targets: [{ format }] },'
511
- );
512
- this.emit('primitive: { topology: "triangle-list", cullMode: "back" },');
513
- this.emit(
514
- `depthStencil: { format: "depth24plus", depthWriteEnabled: true, depthCompare: "less" }, multisample: { count: MSAA_COUNT },`
515
- );
516
- this.dedent();
517
- this.emit("});");
518
- this.emit(
519
- `const ${v}Bind = device.createBindGroup({ layout: ${v}Pipeline.getBindGroupLayout(0), entries: [`
520
- );
521
- this.emit(
522
- ` { binding: 0, resource: { buffer: ${v}Model } }, { binding: 1, resource: { buffer: ${v}Mat } }, { binding: 2, resource: { buffer: vpUniform } }] });`
523
- );
524
- }
525
- emitGaussianSplatObject(v, obj) {
526
- const trait = obj.traits?.find((t) => t.name === "gaussian_splat");
527
- const src = trait?.config?.src || "scene.ply";
528
- const max = trait?.config?.max_splats || 5e5;
529
- const sorted = trait?.config?.sorted !== false;
530
- this.emit(`// Gaussian Splat \u2014 source: ${src} (${sorted ? "radix-sorted" : "unsorted"})`);
531
- if (sorted) {
532
- this.emit(
533
- `// === Wait-Free Radix Sort Pipeline (4x 8-bit Blelloch scan, no global atomics) ===`
534
- );
535
- this.emit(`import { GaussianSplatSorter } from '@holoscript/core/gpu/GaussianSplatSorter';`);
536
- this.emit(`const ${v}Sorter = new GaussianSplatSorter(device, {`);
537
- this.indent();
538
- this.emit(`maxSplats: ${max},`);
539
- this.emit(`canvasWidth: canvas.width,`);
540
- this.emit(`canvasHeight: canvas.height,`);
541
- this.dedent();
542
- this.emit(`});`);
543
- this.emit(`await ${v}Sorter.initialize();`);
544
- this.emit(`const ${v}SplatCount = { value: 0 };`);
545
- } else {
546
- this.emit(`const ${v}SplatBuf = createStorageBuffer(device, ${max} * 32);`);
547
- this.emit(`const ${v}SplatCount = { value: 0 };`);
548
- this.emit(`const ${v}SplatPipeline = device.createRenderPipeline({`);
549
- this.indent();
550
- this.emit('layout: "auto",');
551
- this.emit(
552
- 'vertex: { module: device.createShaderModule({ code: WGSL_SPLAT }), entryPoint: "vs_splat", buffers: [] },'
553
- );
554
- this.emit(
555
- 'fragment: { module: device.createShaderModule({ code: WGSL_SPLAT }), entryPoint: "fs_splat",'
556
- );
557
- this.emit(
558
- ' targets: [{ format, blend: { color: { srcFactor: "one", dstFactor: "one-minus-src-alpha", operation: "add" }, alpha: { srcFactor: "one", dstFactor: "one-minus-src-alpha", operation: "add" } } }] },'
559
- );
560
- this.emit('primitive: { topology: "triangle-strip" },');
561
- this.emit(
562
- 'depthStencil: { format: "depth24plus", depthWriteEnabled: false, depthCompare: "less" },'
563
- );
564
- this.dedent();
565
- this.emit("});");
566
- }
567
- }
568
- emitPointCloudObject(v, obj) {
569
- const trait = obj.traits?.find((t) => t.name === "point_cloud");
570
- const max = trait?.config?.max_points || 1e5;
571
- this.emit(`// Point Cloud (${max} max points)`);
572
- this.emit(`const ${v}PointBuf = createStorageBuffer(device, ${max} * 16);`);
573
- this.emit(`const ${v}PointCount = { value: 0 };`);
574
- this.emit(`const ${v}PointPipeline = device.createRenderPipeline({`);
575
- this.indent();
576
- this.emit('layout: "auto",');
577
- this.emit(
578
- 'vertex: { module: device.createShaderModule({ code: WGSL_POINT }), entryPoint: "vs_point",'
579
- );
580
- this.emit(
581
- ' buffers: [{ arrayStride: 16, attributes: [{ shaderLocation: 0, offset: 0, format: "float32x3" }, { shaderLocation: 1, offset: 12, format: "unorm8x4" }] }] },'
582
- );
583
- this.emit(
584
- 'fragment: { module: device.createShaderModule({ code: WGSL_POINT }), entryPoint: "fs_point", targets: [{ format }] },'
585
- );
586
- this.emit(
587
- `primitive: { topology: "point-list" }, depthStencil: { format: "depth24plus", depthWriteEnabled: true, depthCompare: "less" }, multisample: { count: MSAA_COUNT },`
588
- );
589
- this.dedent();
590
- this.emit("});");
591
- }
592
- emitGpuParticleObject(v, obj) {
593
- const trait = findGpuParticleTrait(obj.traits);
594
- const count = trait?.config?.count || 1e4;
595
- this.emit(`// GPU Particles (${count}) from @${trait?.name ?? "gpu_particle"}`);
596
- this.emit(`const ${v}ParticleCount = ${count};`);
597
- this.emit(`const ${v}ParticleBufA = createStorageBuffer(device, ${v}ParticleCount * 32);`);
598
- this.emit(`const ${v}ParticleBufB = createStorageBuffer(device, ${v}ParticleCount * 32);`);
599
- this.emit(`const ${v}ParticlePipeline = device.createRenderPipeline({`);
600
- this.indent();
601
- this.emit('layout: "auto",');
602
- this.emit(
603
- 'vertex: { module: device.createShaderModule({ code: WGSL_PARTICLE_RENDER }), entryPoint: "vs_particle",'
604
- );
605
- this.emit(
606
- ' buffers: [{ arrayStride: 32, attributes: [{ shaderLocation: 0, offset: 0, format: "float32x3" }, { shaderLocation: 1, offset: 12, format: "float32x3" }, { shaderLocation: 2, offset: 24, format: "float32" }] }] },'
607
- );
608
- this.emit(
609
- 'fragment: { module: device.createShaderModule({ code: WGSL_PARTICLE_RENDER }), entryPoint: "fs_particle",'
610
- );
611
- this.emit(
612
- ' targets: [{ format, blend: { color: { srcFactor: "src-alpha", dstFactor: "one", operation: "add" }, alpha: { srcFactor: "zero", dstFactor: "one", operation: "add" } } }] },'
613
- );
614
- this.emit(
615
- 'primitive: { topology: "point-list" }, depthStencil: { format: "depth24plus", depthWriteEnabled: false, depthCompare: "less" },'
616
- );
617
- this.dedent();
618
- this.emit("});");
619
- }
620
- // ─── Spatial Group ────────────────────────────────────────────────────────
621
- emitGroup(group) {
622
- const v = this.sanitizeName(group.name);
623
- this.emit(`// Spatial Group: ${this.escapeStringValue(group.name, "TypeScript")}`);
624
- const pos = group.properties.find((p) => p.key === "position")?.value;
625
- const [px, py, pz] = Array.isArray(pos) ? pos : [0, 0, 0];
626
- this.emit(
627
- `const ${v}GroupXform = createBuffer(device, new Float32Array([1,0,0,0, 0,1,0,0, 0,0,1,0, ${px},${py},${pz},1]), GPUBufferUsage.UNIFORM);`
628
- );
629
- for (const obj of group.objects) this.emitObject(obj);
630
- if (group.groups) {
631
- for (const sub of group.groups) this.emitGroup(sub);
632
- }
633
- this.emit("");
634
- }
635
- // ─── Light ────────────────────────────────────────────────────────────────
636
- emitLight(light) {
637
- const v = this.sanitizeName(light.name);
638
- let color = [1, 1, 1], intensity = 1, pos = [0, 10, 0], dir = [0, -1, 0];
639
- for (const prop of light.properties) {
640
- if (prop.key === "color") color = this.parseColor(prop.value);
641
- else if (prop.key === "intensity") intensity = prop.value;
642
- else if (prop.key === "position" && Array.isArray(prop.value)) pos = prop.value;
643
- else if (prop.key === "direction" && Array.isArray(prop.value)) dir = prop.value;
644
- }
645
- const ti = { directional: 0, point: 1, spot: 2, hemisphere: 3, ambient: 4, area: 5 }[light.lightType] ?? 0;
646
- this.emit(
647
- `// Light: ${this.escapeStringValue(light.name, "TypeScript")} (${light.lightType})`
648
- );
649
- this.emit(
650
- `const ${v}Light = createBuffer(device, new Float32Array([${color[0] * intensity},${color[1] * intensity},${color[2] * intensity},${ti}, ${pos[0]},${pos[1]},${pos[2]},0, ${dir[0]},${dir[1]},${dir[2]},0]), GPUBufferUsage.UNIFORM);`
651
- );
652
- this.emit("");
653
- }
654
- // ─── Camera ───────────────────────────────────────────────────────────────
655
- emitCamera(cam) {
656
- this.emit("// === Camera ===");
657
- let fov = 60, near = 0.1, far = 1e3, pos = [4, 3, 6], lookAt = [0, 0, 0];
658
- for (const prop of cam?.properties ?? []) {
659
- if (prop.key === "fov" || prop.key === "field_of_view") fov = prop.value;
660
- else if (prop.key === "near") near = prop.value;
661
- else if (prop.key === "far") far = prop.value;
662
- else if (prop.key === "position" && Array.isArray(prop.value)) pos = prop.value;
663
- else if ((prop.key === "look_at" || prop.key === "lookAt") && Array.isArray(prop.value))
664
- lookAt = prop.value;
665
- }
666
- this.emit(`const cameraFov = ${fov} * Math.PI / 180;`);
667
- this.emit(`const cameraNear = ${near}, cameraFar = ${far};`);
668
- this.emit(`const cameraPos = new Float32Array([${pos.join(",")}]);`);
669
- this.emit(`const cameraTarget = new Float32Array([${lookAt.join(",")}]);`);
670
- this.emit("const cameraUp = new Float32Array([0, 1, 0]);");
671
- this.emit("const aspect = (canvas.width || 1) / (canvas.height || 1);");
672
- this.emit("function mat4Multiply(a: Float32Array, b: Float32Array): Float32Array {");
673
- this.indent();
674
- this.emit("const o = new Float32Array(16);");
675
- this.emit("for (let c = 0; c < 4; c++) { for (let r = 0; r < 4; r++) {");
676
- this.emit(" o[c*4+r] = a[0*4+r]*b[c*4+0] + a[1*4+r]*b[c*4+1] + a[2*4+r]*b[c*4+2] + a[3*4+r]*b[c*4+3];");
677
- this.emit("} } return o;");
678
- this.dedent();
679
- this.emit("}");
680
- this.emit("function lookAtMatrix(eye: Float32Array, target: Float32Array, up: Float32Array): Float32Array {");
681
- this.indent();
682
- this.emit("const zx = eye[0]-target[0], zy = eye[1]-target[1], zz = eye[2]-target[2];");
683
- this.emit("let zl = Math.hypot(zx, zy, zz) || 1; const fz = [zx/zl, zy/zl, zz/zl];");
684
- this.emit("const xx = up[1]*fz[2]-up[2]*fz[1], xy = up[2]*fz[0]-up[0]*fz[2], xz = up[0]*fz[1]-up[1]*fz[0];");
685
- this.emit("let xl = Math.hypot(xx, xy, xz) || 1; const rx = [xx/xl, xy/xl, xz/xl];");
686
- this.emit("const uy = [fz[1]*rx[2]-fz[2]*rx[1], fz[2]*rx[0]-fz[0]*rx[2], fz[0]*rx[1]-fz[1]*rx[0]];");
687
- this.emit("return new Float32Array([");
688
- this.emit(" rx[0], uy[0], fz[0], 0,");
689
- this.emit(" rx[1], uy[1], fz[1], 0,");
690
- this.emit(" rx[2], uy[2], fz[2], 0,");
691
- this.emit(" -(rx[0]*eye[0]+rx[1]*eye[1]+rx[2]*eye[2]),");
692
- this.emit(" -(uy[0]*eye[0]+uy[1]*eye[1]+uy[2]*eye[2]),");
693
- this.emit(" -(fz[0]*eye[0]+fz[1]*eye[1]+fz[2]*eye[2]), 1]);");
694
- this.dedent();
695
- this.emit("}");
696
- this.emit("function buildViewProjection(): Float32Array {");
697
- this.indent();
698
- this.emit("const f = 1.0 / Math.tan(cameraFov / 2), ri = 1.0 / (cameraNear - cameraFar);");
699
- this.emit("const proj = new Float32Array([f/aspect,0,0,0, 0,f,0,0, 0,0,cameraFar*ri,-1, 0,0,cameraNear*cameraFar*ri,0]);");
700
- this.emit("const view = lookAtMatrix(cameraPos, cameraTarget, cameraUp);");
701
- this.emit("return mat4Multiply(proj, view);");
702
- this.dedent();
703
- this.emit("}");
704
- this.emit(
705
- "const vpUniform = createBuffer(device, buildViewProjection(), GPUBufferUsage.UNIFORM);"
706
- );
707
- this.emit("");
708
- }
709
- // ─── Compute Pipelines ────────────────────────────────────────────────────
710
- emitComputeShaders(composition) {
711
- const gpuObjs = (composition.objects || []).filter(
712
- (o) => o.traits?.some(
713
- (t) => isGpuParticleTraitName(t.name) || t.name === "gpu_physics" || t.name === "compute"
714
- )
715
- );
716
- if (gpuObjs.length === 0) return;
717
- this.emit("// === Compute Pipelines ===");
718
- for (const obj of gpuObjs) {
719
- const v = this.sanitizeName(obj.name);
720
- const traits = obj.traits || [];
721
- if (traits.some((t) => isGpuParticleTraitName(t.name))) {
722
- const count = findGpuParticleTrait(traits)?.config?.count || 1e4;
723
- this.emit(
724
- `const ${v}ParticleCompute = device.createComputePipeline({ layout: "auto", compute: { module: device.createShaderModule({ code: WGSL_PARTICLE_COMPUTE }), entryPoint: "cs_particle_update" } });`
725
- );
726
- this.emit(`const ${v}ComputeDispatches = ${Math.ceil(count / 64)};`);
727
- }
728
- if (traits.some((t) => t.name === "gpu_physics")) {
729
- this.emit(
730
- `const ${v}PhysicsCompute = device.createComputePipeline({ layout: "auto", compute: { module: device.createShaderModule({ code: WGSL_PHYSICS_COMPUTE }), entryPoint: "cs_physics_step" } });`
731
- );
732
- }
733
- if (traits.some((t) => t.name === "compute")) {
734
- const ct = traits.find((t) => t.name === "compute");
735
- const entry = ct?.config?.shader || "custom_compute";
736
- const wg = ct?.config?.workgroups || [64, 1, 1];
737
- this.emit(
738
- `const ${v}CustomCompute = device.createComputePipeline({ layout: "auto", compute: { module: device.createShaderModule({ code: WGSL_CUSTOM_${v.toUpperCase()} }), entryPoint: "${entry}" } });`
739
- );
740
- this.emit(`const ${v}Workgroups = [${wg}];`);
741
- }
742
- }
743
- this.emit("");
744
- }
745
- // ─── WGSL Shader Sources ──────────────────────────────────────────────────
746
- emitShaderSources() {
747
- this.emit("// === WGSL Shader Sources ===");
748
- this.emit("const WGSL_VERTEX = /* wgsl */`");
749
- this.emit("struct Uniforms { model: mat4x4<f32> };");
750
- this.emit("struct Camera { viewProj: mat4x4<f32> };");
751
- this.emit("@group(0) @binding(0) var<uniform> u: Uniforms;");
752
- this.emit("@group(0) @binding(2) var<uniform> cam: Camera;");
753
- this.emit("struct VIn { @location(0) pos: vec3<f32>, @location(1) norm: vec3<f32> };");
754
- this.emit(
755
- "struct VOut { @builtin(position) clip: vec4<f32>, @location(0) wNorm: vec3<f32>, @location(1) wPos: vec3<f32> };"
756
- );
757
- this.emit("@vertex fn vs_main(i: VIn) -> VOut {");
758
- this.emit(" var o: VOut; let w = u.model * vec4<f32>(i.pos, 1.0);");
759
- this.emit(
760
- " o.clip = cam.viewProj * w; o.wNorm = normalize((u.model * vec4<f32>(i.norm, 0.0)).xyz); o.wPos = w.xyz; return o; }`;"
761
- );
762
- this.emit("");
763
- this.emit("const WGSL_FRAGMENT = /* wgsl */`");
764
- this.emit("struct Mat { color: vec4<f32>, rm: vec4<f32>, emissive: vec4<f32> };");
765
- this.emit("@group(0) @binding(1) var<uniform> mat: Mat;");
766
- this.emit("struct FIn { @location(0) wNorm: vec3<f32>, @location(1) wPos: vec3<f32> };");
767
- this.emit("@fragment fn fs_main(i: FIn) -> @location(0) vec4<f32> {");
768
- this.emit(" let N = normalize(i.wNorm); let L = normalize(vec3<f32>(1.0, 2.0, 1.5));");
769
- this.emit(" let d = max(dot(N, L), 0.0) * (1.0 - mat.rm[0] * 0.5);");
770
- this.emit(" let lit = mat.color.rgb * (0.15 + d);");
771
- this.emit(" let emit = mat.emissive.rgb * mat.rm[2];");
772
- this.emit(" return vec4<f32>(lit + emit, mat.color.a); }`;");
773
- this.emit("");
774
- this.emit("const WGSL_SPLAT = /* wgsl */`");
775
- this.emit(
776
- "struct Splat { center: vec3<f32>, opacity: f32, cov: array<f32,6>, sh: vec3<f32> };"
777
- );
778
- this.emit("@group(0) @binding(0) var<storage, read> splats: array<Splat>;");
779
- this.emit(
780
- "struct SO { @builtin(position) p: vec4<f32>, @location(0) c: vec4<f32>, @location(1) uv: vec2<f32> };"
781
- );
782
- this.emit(
783
- "@vertex fn vs_splat(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> SO {"
784
- );
785
- this.emit(" var q = array<vec2<f32>,4>(vec2(-1,-1),vec2(1,-1),vec2(-1,1),vec2(1,1));");
786
- this.emit(
787
- " var o: SO; let s = splats[ii]; o.p = vec4<f32>(s.center.xy + q[vi]*0.01, s.center[2], 1.0);"
788
- );
789
- this.emit(" o.c = vec4<f32>(s.sh, s.opacity); o.uv = q[vi]; return o; }");
790
- this.emit("@fragment fn fs_splat(i: SO) -> @location(0) vec4<f32> {");
791
- this.emit(" let a = i.c.a * exp(-dot(i.uv, i.uv) * 4.0); if (a < 0.01) { discard; }");
792
- this.emit(" return vec4<f32>(i.c.rgb * a, a); }`;");
793
- this.emit("");
794
- this.emit("const WGSL_POINT = /* wgsl */`");
795
- this.emit("struct PO { @builtin(position) p: vec4<f32>, @location(0) c: vec4<f32> };");
796
- this.emit(
797
- "@vertex fn vs_point(@location(0) pos: vec3<f32>, @location(1) col: vec4<f32>) -> PO { var o: PO; o.p = vec4<f32>(pos, 1.0); o.c = col; return o; }"
798
- );
799
- this.emit("@fragment fn fs_point(i: PO) -> @location(0) vec4<f32> { return i.c; }`;");
800
- this.emit("");
801
- this.emit("const WGSL_PARTICLE_RENDER = /* wgsl */`");
802
- this.emit("struct PVO { @builtin(position) p: vec4<f32>, @location(0) life: f32 };");
803
- this.emit(
804
- "@vertex fn vs_particle(@location(0) pos: vec3<f32>, @location(1) vel: vec3<f32>, @location(2) life: f32) -> PVO { var o: PVO; o.p = vec4<f32>(pos, 1.0); o.life = life; return o; }"
805
- );
806
- this.emit("@fragment fn fs_particle(i: PVO) -> @location(0) vec4<f32> {");
807
- this.emit(
808
- " let t = clamp(i.life, 0.0, 1.0); return vec4<f32>(mix(vec3(1.0,0.2,0.0), vec3(1.0,1.0,0.5), t), t*0.8); }`;"
809
- );
810
- this.emit("");
811
- this.emit("const WGSL_SCATTER = /* wgsl */`");
812
- this.emit("struct VIn { @location(0) pos: vec3<f32>, @location(1) norm: vec3<f32> };");
813
- this.emit("struct VOut { @builtin(position) clip: vec4<f32>, @location(0) shade: f32 };");
814
- this.emit("fn hash11(v: f32) -> f32 { return fract(sin(v * 12.9898) * 43758.5453); }");
815
- this.emit("@vertex fn vs_scatter(i: VIn, @builtin(instance_index) instance: u32) -> VOut {");
816
- this.emit(" let id = f32(instance);");
817
- this.emit(" let x = hash11(id + 1.0) * 1.8 - 0.9; let z = hash11(id + 7.0) * 1.8 - 0.9;");
818
- this.emit(" let scale = 0.35 + hash11(id + 13.0) * 0.45;");
819
- this.emit(" var o: VOut; o.clip = vec4<f32>(i.pos.x * scale + x, i.pos.y * scale - 0.65, i.pos.z * scale + z, 1.0);");
820
- this.emit(" o.shade = 0.45 + max(i.norm.y, 0.0) * 0.45; return o; }");
821
- this.emit("@fragment fn fs_scatter(i: VOut) -> @location(0) vec4<f32> { return vec4<f32>(0.08 * i.shade, 0.34 * i.shade, 0.12 * i.shade, 1.0); }`;");
822
- this.emit("");
823
- this.emit("const WGSL_POSTFX = /* wgsl */`");
824
- this.emit("struct VO { @builtin(position) pos: vec4<f32> };");
825
- this.emit("@vertex fn vs_postfx(@builtin(vertex_index) vi: u32) -> VO {");
826
- this.emit(" var p = array<vec2<f32>,3>(vec2(-1.0,-1.0), vec2(3.0,-1.0), vec2(-1.0,3.0));");
827
- this.emit(" var o: VO; o.pos = vec4<f32>(p[vi], 0.0, 1.0); return o; }");
828
- this.emit("@fragment fn fs_postfx() -> @location(0) vec4<f32> { return vec4<f32>(0.04, 0.08, 0.05, 0.18); }`;");
829
- this.emit("");
830
- this.emit("const WGSL_PARTICLE_COMPUTE = /* wgsl */`");
831
- this.emit("struct P { pos: vec3<f32>, _p0: f32, vel: vec3<f32>, life: f32 };");
832
- this.emit("@group(0) @binding(0) var<storage, read> pin: array<P>;");
833
- this.emit("@group(0) @binding(1) var<storage, read_write> pout: array<P>;");
834
- this.emit("@group(0) @binding(2) var<uniform> dt: f32;");
835
- this.emit(
836
- "@compute @workgroup_size(64) fn cs_particle_update(@builtin(global_invocation_id) gid: vec3<u32>) {"
837
- );
838
- this.emit(" let i = gid[0]; if (i >= arrayLength(&pin)) { return; } var p = pin[i];");
839
- this.emit(" p.vel[1] -= 9.81 * dt; p.pos += p.vel * dt; p.life -= dt;");
840
- this.emit(
841
- " if (p.life <= 0.0) { p.pos = vec3(0.0); p.vel = vec3(0.0, 5.0, 0.0); p.life = 2.0; }"
842
- );
843
- this.emit(" pout[i] = p; }`;");
844
- this.emit("");
845
- this.emit("const WGSL_PHYSICS_COMPUTE = /* wgsl */`");
846
- this.emit("struct Body { pos: vec3<f32>, mass: f32, vel: vec3<f32>, _p: f32 };");
847
- this.emit("@group(0) @binding(0) var<storage, read_write> bodies: array<Body>;");
848
- this.emit("@group(0) @binding(1) var<uniform> dt: f32;");
849
- this.emit(
850
- "@compute @workgroup_size(64) fn cs_physics_step(@builtin(global_invocation_id) gid: vec3<u32>) {"
851
- );
852
- this.emit(" let i = gid[0]; if (i >= arrayLength(&bodies)) { return; } var b = bodies[i];");
853
- this.emit(" b.vel[1] -= 9.81 * dt; b.pos += b.vel * dt;");
854
- this.emit(
855
- " if (b.pos[1] < 0.0) { b.pos[1] = 0.0; b.vel[1] = -b.vel[1] * 0.6; } bodies[i] = b; }`;"
856
- );
857
- this.emit("");
858
- }
859
- // ─── Render Loop ──────────────────────────────────────────────────────────
860
- emitRenderLoop(composition) {
861
- this.emit("// === Render Loop ===");
862
- this.emit("let frameCount = 0;");
863
- this.emit("const t0 = performance.now();");
864
- this.emit("function frame() {");
865
- this.indent();
866
- this.emit("frameCount++;");
867
- this.emit("const time = (performance.now() - t0) / 1000.0;");
868
- this.emit("const enc = device.createCommandEncoder();");
869
- const gpuObjs = (composition.objects || []).filter(
870
- (o) => o.traits?.some(
871
- (t) => isGpuParticleTraitName(t.name) || t.name === "gpu_physics" || t.name === "compute"
872
- )
873
- );
874
- if (gpuObjs.length > 0 && this.options.enableCompute) {
875
- this.emit("const cp = enc.beginComputePass();");
876
- for (const obj of gpuObjs) {
877
- const v = this.sanitizeName(obj.name);
878
- if (obj.traits?.some((t) => isGpuParticleTraitName(t.name))) {
879
- this.emit(
880
- `cp.setPipeline(${v}ParticleCompute); cp.dispatchWorkgroups(${v}ComputeDispatches);`
881
- );
882
- }
883
- if (obj.traits?.some((t) => t.name === "gpu_physics")) {
884
- this.emit(`cp.setPipeline(${v}PhysicsCompute); cp.dispatchWorkgroups(16);`);
885
- }
886
- if (obj.traits?.some((t) => t.name === "compute")) {
887
- this.emit(`cp.setPipeline(${v}CustomCompute); cp.dispatchWorkgroups(...${v}Workgroups);`);
888
- }
889
- }
890
- this.emit("cp.end();");
891
- }
892
- this.emit("const rp = enc.beginRenderPass({");
893
- this.indent();
894
- this.emit(
895
- 'colorAttachments: [{ view: msaaTexture.createView(), resolveTarget: context.getCurrentTexture().createView(), clearValue: clearColor, loadOp: "clear", storeOp: "store" }],'
896
- );
897
- this.emit(
898
- 'depthStencilAttachment: { view: depthTexture.createView(), depthClearValue: 1.0, depthLoadOp: "clear", depthStoreOp: "store" },'
899
- );
900
- this.dedent();
901
- this.emit("});");
902
- if (composition.objects) {
903
- for (const obj of composition.objects) this.emitDrawCall(obj);
904
- }
905
- if (composition.spatialGroups) {
906
- for (const group of composition.spatialGroups) {
907
- for (const obj of group.objects) this.emitDrawCall(obj);
908
- }
909
- }
910
- this.emitDomainBlockDrawCalls(composition, false);
911
- this.emitDomainBlockDrawCalls(composition, true);
912
- this.emit("rp.end();");
913
- this.emit("device.queue.submit([enc.finish()]);");
914
- this.emit("document.body.dataset.holoscriptWebgpuFrame = String(frameCount);");
915
- this.emit("requestAnimationFrame(frame);");
916
- this.dedent();
917
- this.emit("}");
918
- this.emit("requestAnimationFrame(frame);");
919
- }
920
- emitDrawCall(obj) {
921
- const v = this.sanitizeName(obj.name);
922
- const traits = obj.traits || [];
923
- if (traits.some((t) => t.name === "gaussian_splat")) {
924
- this.emit(`rp.setPipeline(${v}SplatPipeline); rp.draw(4, ${v}SplatCount.value);`);
925
- } else if (traits.some((t) => t.name === "point_cloud")) {
926
- this.emit(`rp.setPipeline(${v}PointPipeline); rp.draw(${v}PointCount.value);`);
927
- } else if (traits.some((t) => isGpuParticleTraitName(t.name))) {
928
- this.emit(
929
- `rp.setPipeline(${v}ParticlePipeline); rp.setVertexBuffer(0, ${v}ParticleBufA); rp.draw(${v}ParticleCount);`
930
- );
931
- } else {
932
- this.emit(
933
- `rp.setPipeline(${v}Pipeline); rp.setBindGroup(0, ${v}Bind); rp.setVertexBuffer(0, ${v}VBO); rp.draw(${v}VertexCount);`
934
- );
935
- }
936
- if (obj.children) {
937
- for (const child of obj.children) this.emitDrawCall(child);
938
- }
939
- }
940
- emitDomainBlockDrawCalls(composition, postFxOnly) {
941
- const blocks = composition.domainBlocks ?? [];
942
- for (let i = 0; i < blocks.length; i++) {
943
- const block = blocks[i];
944
- const prefix = this.domainBlockVar(block, i);
945
- if (block.domain === "postfx") {
946
- if (postFxOnly) {
947
- this.emit(`rp.setPipeline(${prefix}PostFXPipeline); rp.draw(3);`);
948
- }
949
- continue;
950
- }
951
- if (postFxOnly) continue;
952
- if (block.domain === "vfx") {
953
- this.emit(
954
- `rp.setPipeline(${prefix}ParticlePipeline); rp.setVertexBuffer(0, ${prefix}ParticleBuf); rp.draw(${prefix}ParticleCount);`
955
- );
956
- }
957
- if (block.domain === "procedural" && (block.keyword === "scatter" || block.keyword === "distribute" || block.properties?.count)) {
958
- this.emit(
959
- `rp.setPipeline(${prefix}ScatterPipeline); rp.setVertexBuffer(0, ${prefix}ScatterVBO); rp.draw(${prefix}ScatterVertexCount, ${prefix}ScatterInstanceCount);`
960
- );
961
- }
962
- }
963
- }
964
- // ─── Helpers ──────────────────────────────────────────────────────────────
965
- emit(line) {
966
- this.lines.push(this.options.indent.repeat(this.indentLevel) + line);
967
- }
968
- emitMultiline(code) {
969
- for (const line of code.split("\n")) this.emit(line);
970
- }
971
- indent() {
972
- this.indentLevel++;
973
- }
974
- dedent() {
975
- this.indentLevel = Math.max(0, this.indentLevel - 1);
976
- }
977
- sanitizeName(name) {
978
- return name.replace(/[^a-zA-Z0-9_]/g, "_");
979
- }
980
- domainBlockVar(block, index) {
981
- const raw = `${block.domain}_${block.keyword}_${block.name || index}`;
982
- const safe = this.sanitizeName(raw);
983
- return `db${index}_${safe || "domain"}`;
984
- }
985
- json(value) {
986
- return JSON.stringify(value).replace(/</g, "\\u003c");
987
- }
988
- numberProp(block, keys, fallback) {
989
- for (const key of keys) {
990
- const value = block.properties?.[key];
991
- if (typeof value === "number" && Number.isFinite(value)) return value;
992
- if (typeof value === "string" && value.trim() !== "") {
993
- const parsed = Number(value);
994
- if (Number.isFinite(parsed)) return parsed;
995
- }
996
- }
997
- return fallback;
998
- }
999
- hashSeed(value) {
1000
- let h = 2166136261;
1001
- for (let i = 0; i < value.length; i++) {
1002
- h ^= value.charCodeAt(i);
1003
- h = Math.imul(h, 16777619);
1004
- }
1005
- return h >>> 0;
1006
- }
1007
- findObjProp(obj, key) {
1008
- return obj.properties?.find((p) => p.key === key)?.value;
1009
- }
1010
- parseColor(value) {
1011
- if (typeof value === "string" && value.startsWith("#")) {
1012
- const h = value.slice(1);
1013
- return [
1014
- parseFloat((parseInt(h.substring(0, 2), 16) / 255).toFixed(4)),
1015
- parseFloat((parseInt(h.substring(2, 4), 16) / 255).toFixed(4)),
1016
- parseFloat((parseInt(h.substring(4, 6), 16) / 255).toFixed(4))
1017
- ];
1018
- }
1019
- if (Array.isArray(value) && value.length >= 3) return [value[0], value[1], value[2]];
1020
- return [1, 1, 1];
1021
- }
1022
- extractMaterialColor(material, color) {
1023
- if (color) return this.parseColor(color);
1024
- if (material && typeof material === "object" && !Array.isArray(material)) {
1025
- const m = material;
1026
- if (m.color) return this.parseColor(m.color);
1027
- }
1028
- return [0.8, 0.8, 0.8];
1029
- }
1030
- extractMaterialProp(material, key, fallback) {
1031
- if (material && typeof material === "object" && !Array.isArray(material)) {
1032
- const m = material;
1033
- if (m[key] !== void 0) return m[key];
1034
- }
1035
- return fallback;
1036
- }
1037
- extractEmissive(material, obj) {
1038
- const objEmissive = this.findObjProp(obj, "emissive");
1039
- if (objEmissive !== void 0) return this.parseColor(objEmissive);
1040
- if (material && typeof material === "object" && !Array.isArray(material)) {
1041
- const m = material;
1042
- if (m.emissive !== void 0) return this.parseColor(m.emissive);
1043
- }
1044
- return [0, 0, 0];
1045
- }
1046
- geometryVertexDataFn(meshType) {
1047
- const map = {
1048
- sphere: "generateSphereVertices(0.5, 16, 16)",
1049
- orb: "generateSphereVertices(0.5, 16, 16)",
1050
- plane: "generatePlaneVertices(1.0, 1.0)",
1051
- cylinder: "generateCylinderVertices(0.5, 1.0, 16)",
1052
- cone: "generateConeVertices(0.5, 1.0, 16)",
1053
- pyramid: "generateConeVertices(0.5, 1.0, 16)",
1054
- torus: "generateTorusVertices(0.5, 0.15, 16, 32)"
1055
- };
1056
- return map[meshType] || "generateCubeVertices(1.0)";
1057
- }
1058
- };
1059
- }
1060
- });
1061
-
1062
- exports.WebGPUCompiler_exports = WebGPUCompiler_exports;
1063
- exports.init_WebGPUCompiler = init_WebGPUCompiler;
1064
- //# sourceMappingURL=chunk-W2GA3EQB.cjs.map
1065
- //# sourceMappingURL=chunk-W2GA3EQB.cjs.map