@margoengine/creative 0.0.0-stage → 1.0.0

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 (47) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +310 -2
  4. package/dist/display-C6RC-F2-.js +3 -0
  5. package/dist/errors-XvcwUnU4.js +7 -0
  6. package/dist/gpu-DaSofAeP.js +30 -0
  7. package/dist/grass-OkjgCaF7.js +450 -0
  8. package/dist/grass-settings.d.ts +63 -0
  9. package/dist/grass-settings.js +131 -0
  10. package/dist/grass-terrain.d.ts +33 -0
  11. package/dist/grass-terrain.js +185 -0
  12. package/dist/grass.d.ts +106 -0
  13. package/dist/grass.js +1 -0
  14. package/dist/hdr-format-DXpjc3bW.js +4 -0
  15. package/dist/index.d.ts +7 -0
  16. package/dist/index.js +8 -0
  17. package/dist/msaa-8hWFieoE.js +220 -0
  18. package/dist/paint-aniso.d.ts +36 -0
  19. package/dist/paint-aniso.js +217 -0
  20. package/dist/paint.d.ts +56 -0
  21. package/dist/paint.js +167 -0
  22. package/dist/particles.d.ts +38 -0
  23. package/dist/particles.js +79 -0
  24. package/dist/pass-B5mPip-t.js +27 -0
  25. package/dist/planet-BYTix5S1.js +505 -0
  26. package/dist/planet-atmosphere.d.ts +37 -0
  27. package/dist/planet-atmosphere.js +196 -0
  28. package/dist/planet-pass.d.ts +47 -0
  29. package/dist/planet.d.ts +76 -0
  30. package/dist/planet.js +1 -0
  31. package/dist/post.d.ts +108 -0
  32. package/dist/post.js +265 -0
  33. package/dist/quality-DFm-cQWC.js +7 -0
  34. package/dist/shared/settings.d.ts +89 -0
  35. package/dist/stars-C0SH8-aJ.js +90 -0
  36. package/dist/stars.d.ts +34 -0
  37. package/dist/stars.js +1 -0
  38. package/dist/targets-depth.d.ts +35 -0
  39. package/dist/targets-depth.js +169 -0
  40. package/dist/targets.d.ts +35 -0
  41. package/dist/targets.js +42 -0
  42. package/dist/texture-target-CGqE9pOa.js +131 -0
  43. package/dist/texture-target.d.ts +49 -0
  44. package/dist/toon.d.ts +32 -0
  45. package/dist/toon.js +58 -0
  46. package/dist/view-rect-TO68f_UR.js +48 -0
  47. package/package.json +124 -4
@@ -0,0 +1,450 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const a=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { n as e } from "./view-rect-TO68f_UR.js";
5
+ import { t } from "./quality-DFm-cQWC.js";
6
+ import { t as n } from "./display-C6RC-F2-.js";
7
+ import { t as r } from "./pass-B5mPip-t.js";
8
+ import { t as i } from "./hdr-format-DXpjc3bW.js";
9
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
10
+ import { MargoError as o } from "@margoengine/math/errors";
11
+ import { finiteVector as s } from "@margoengine/math/validate";
12
+ import { createLcgRandom as c } from "@margoengine/math/mathutils";
13
+ //#region src/shaders/grass-frame.wgsl?raw
14
+ var l = "struct Frame {\n camera: mat4x4f,\n planes: array<vec4f, 6>,\n eye: vec4f,\n light: vec4f,\n radiance: vec4f,\n wind: vec4f,\n field: vec4f,\n settings: vec4f,\n right: vec4f,\n up: vec4f,\n root: vec4f,\n tip: vec4f,\n tipVariant: vec4f,\n translucency: vec4f,\n}\nstruct Blade {\n posX: f32, posY: f32, posZ: f32,\n rotationY: f32, scale: f32, stiffness: f32,\n}\n@group(0) @binding(0) var<uniform> frame: Frame;\n@group(0) @binding(1) var<storage, read> blades: array<Blade>;\n\nfn gust(root: vec2f) -> f32 {\n let p = root * 0.08 + frame.field.w * frame.wind.z * vec2f(0.45, 0.2);\n return 0.5 + 0.25 * sin(p.x * 2.1 + sin(p.y * 1.7)) + 0.25 * sin(p.y * 3.1 - p.x * 0.8);\n}\nfn displayColor(linear: vec3f) -> vec3f {\n if (frame.settings.z > 0.5) { return linear; }\n return toDisplay(linear);\n}\n", u = "@group(0) @binding(2) var<storage, read_write> visible: array<u32>;\nstruct Draw { vertices: u32, instances: atomic<u32>, firstVertex: u32, firstInstance: u32 }\n@group(0) @binding(3) var<storage, read_write> draws: array<Draw, 2>;\n\n\nfn bladeHash(seed: u32) -> f32 {\n var n = seed * 747796405u + 2891336453u;\n n = ((n >> ((n >> 28u) + 4u)) ^ n) * 277803737u;\n return f32((n >> 22u) ^ n) / 4294967296.0;\n}\n\n@compute @workgroup_size(64)\nfn cull(@builtin(global_invocation_id) id: vec3u) {\n let count = u32(frame.settings.y);\n if (id.x >= count) { return; }\n if (frame.settings.w < 1.0 && bladeHash(id.x) >= frame.settings.w) { return; }\n let b = blades[id.x];\n let height = frame.field.z * b.scale;\n let root = vec3f(b.posX, b.posY, b.posZ);\n let center = root + vec3f(0, height * 0.5, 0);\n let radius = height * 0.95;\n let distance = length(center - frame.eye.xyz);\n if (distance - radius > frame.settings.x) { return; }\n for (var i = 0u; i < 6u; i++) {\n if (dot(frame.planes[i].xyz, center) + frame.planes[i].w < -radius) { return; }\n }\n let lod = select(0u, 1u, distance > frame.settings.x * 0.45);\n if (distance > frame.settings.x * 0.7 && id.x % 4u != 0u) { return; }\n let slot = atomicAdd(&draws[lod].instances, 1u);\n visible[lod * count + slot] = id.x;\n}\n", d = "@group(0) @binding(2) var<storage, read> visible: array<u32>;\nstruct Output {\n @builtin(position) clip: vec4f,\n @location(0) uv: vec2f,\n @location(1) world: vec3f,\n @location(2) normal: vec3f,\n @location(3) variation: f32,\n}\n\nfn bladeVertex(position: vec3f, uv: vec2f, id: u32) -> Output {\n let b = blades[id];\n let root = vec3f(b.posX, b.posY, b.posZ);\n let height = frame.field.z * b.scale;\n let bend = clamp(frame.wind.w * (0.35 + 0.65 * gust(root.xz)) / b.stiffness, 0.0, 0.58);\n let sideways = vec3f(cos(b.rotationY), 0, sin(b.rotationY));\n let direction = vec3f(frame.wind.x, 0, frame.wind.y);\n var vertical = 0.0;\n var tangent = vec2f(0);\n\n for (var segment = 0; segment < 3; segment++) {\n let start = f32(segment) / 3.0;\n let end = f32(segment + 1) / 3.0;\n let dx = bend * (pow(end, 1.8) - pow(start, 1.8));\n let dy = sqrt(1.0 / 9.0 - dx * dx);\n vertical += dy * clamp(uv.y * 3.0 - f32(segment), 0.0, 1.0);\n if (abs(uv.y - start) < 0.001 || abs(uv.y - end) < 0.001) { tangent += vec2f(dx, dy); }\n }\n let curve = direction * height * bend * pow(uv.y, 1.8) + vec3f(0, height * vertical, 0);\n let along = direction * tangent.x + vec3f(0, tangent.y, 0);\n var o: Output;\n o.world = root + curve + sideways * position.x * height * 0.075;\n o.clip = frame.camera * vec4f(o.world, 1);\n o.uv = uv;\n o.normal = normalize(cross(sideways, along));\n o.variation = fract(b.rotationY * 7.13);\n return o;\n}\n@vertex fn nearVertex(@location(0) position: vec3f, @location(1) uv: vec2f, @builtin(instance_index) instance: u32) -> Output {\n return bladeVertex(position, uv, visible[instance]);\n}\n@vertex fn farVertex(@location(0) position: vec3f, @location(1) uv: vec2f, @builtin(instance_index) instance: u32) -> Output {\n return bladeVertex(position, uv, visible[u32(frame.settings.y) + instance]);\n}\n@fragment fn fragment(i: Output, @builtin(front_facing) front: bool) -> @location(0) vec4f {\n let n = normalize(i.normal) * select(-1.0, 1.0, front);\n let lightDir = frame.light.xyz;\n let viewDir = normalize(frame.eye.xyz - i.world);\n\n let height = clamp(i.uv.y, 0.0, 1.0);\n let wrap = max(dot(n, lightDir) + 0.45, 0.0) / 1.45;\n let sss = pow(max(dot(-lightDir, viewDir), 0.0), 2.0) * height * frame.translucency.w;\n let root = frame.root.xyz;\n let tip = mix(frame.tip.xyz, frame.tipVariant.xyz, i.variation);\n let color = mix(root, tip, pow(height, 0.7));\n let light = frame.radiance.xyz * frame.light.w;\n let linear = color * (frame.radiance.w + wrap * light) + frame.translucency.xyz * sss * light;\n return vec4f(displayColor(linear), 1);\n}\n\nstruct SporeOutput { @builtin(position) clip: vec4f, @location(0) uv: vec2f }\nfn random(seed: u32) -> f32 {\n var n = seed * 747796405u + 2891336453u;\n n = ((n >> ((n >> 28u) + 4u)) ^ n) * 277803737u;\n return f32((n >> 22u) ^ n) / 4294967296.0;\n}\n@vertex fn sporeVertex(@builtin(vertex_index) vertex: u32, @builtin(instance_index) id: u32) -> SporeOutput {\n let corners = array<vec2f, 6>(vec2f(-1,-1), vec2f(1,-1), vec2f(1,1), vec2f(-1,-1), vec2f(1,1), vec2f(-1,1));\n let seed = vec2f(random(id * 3u), random(id * 3u + 1u));\n let phase = random(id * 3u + 2u);\n let drift = frame.wind.xy * frame.field.w * frame.wind.z * (0.25 + gust(seed * frame.field.xy) * 0.2);\n let xz = (fract(seed + drift / frame.field.xy) - 0.5) * frame.field.xy;\n let y = frame.field.z + phase * 4.0 + sin(frame.field.w * 0.6 + phase * 6.283) * 0.25;\n let q = corners[vertex];\n let world = vec3f(xz.x, y, xz.y) + (frame.right.xyz * q.x + frame.up.xyz * q.y) * (0.035 + phase * 0.025);\n var o: SporeOutput; o.clip = frame.camera * vec4f(world, 1); o.uv = q; return o;\n}\n@fragment fn sporeFragment(i: SporeOutput) -> @location(0) vec4f {\n let radius = length(i.uv);\n let spokes = pow(abs(cos(atan2(i.uv.y, i.uv.x) * 6.0)), 18.0);\n let alpha = (1.0 - smoothstep(0.0, 0.22, radius)) + spokes * (1.0 - smoothstep(0.25, 1.0, radius)) * 0.55;\n if (alpha < 0.015) { discard; }\n return vec4f(displayColor(vec3f(2.5, 2.4, 2.1)), min(alpha, 0.85));\n}\n";
15
+ //#endregion
16
+ //#region ../shared/unit-light.js
17
+ function f(e, t, n) {
18
+ let r = Math.hypot(n[0], n[1], n[2]);
19
+ e[t] = n[0] / r, e[t + 1] = n[1] / r, e[t + 2] = n[2] / r, e[t + 3] = n[3];
20
+ }
21
+ //#endregion
22
+ //#region src/grass.ts
23
+ var p = 0, m = class m {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
24
+ static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
25
+ return new m({ engine: e }, t);
26
+ }
27
+ constructor(t, n = {}) {
28
+ this.name = `grass-field:${++p}`, this.variants = /* @__PURE__ */ new Map(), this.frame = /* @__PURE__ */ new Float32Array(88), this.time = 0, this.pass = r(), this.color = this.pass.colorAttachments[0], this.depth = this.pass.depthStencilAttachment, this.sporeDepth = {
29
+ view: void 0,
30
+ depthReadOnly: !0,
31
+ stencilReadOnly: !0
32
+ }, this.sporePass = {
33
+ colorAttachments: [this.color],
34
+ depthStencilAttachment: this.sporeDepth
35
+ }, this.update = (e) => {
36
+ if (e.backend !== "webgpu") throw new o("unsupported", "GrassField requires WebGPU; use a WebGPU engine");
37
+ this.windTime = this.time + e.delta;
38
+ let t = this.frame, n = e.camera;
39
+ t.set(n.matrix), t.set(n.planes, 16), t.set(n.position, 40), f(t, 44, this.engine.lighting.direction), t.set(this.engine.lighting.radiance, 48), t[59] = this.time, t[62] = +i(e.format);
40
+ let r = n.target[0] - n.position[0], a = n.target[1] - n.position[1], s = n.target[2] - n.position[2], c = Math.hypot(r, a, s), l = Math.hypot(r, s), u = l > 1e-12 ? -s / l : 1, d = l > 1e-12 ? r / l : 0;
41
+ t[64] = u, t[66] = d, t[68] = -d * a / c, t[69] = (d * r - u * s) / c, t[70] = u * a / c, e.device.queue.writeBuffer(this.uniform, 0, t), e.encoder.clearBuffer(this.indirect, 4, 4), e.encoder.clearBuffer(this.indirect, 20, 4);
42
+ let p = e.encoder.beginComputePass();
43
+ p.setPipeline(this.compute), p.setBindGroup(0, this.computeGroup), p.dispatchWorkgroups(Math.ceil(this.blades / 64)), p.end();
44
+ }, this.draw = (t) => {
45
+ if (t.backend !== "webgpu") return;
46
+ let n = this.variant(t.format, t.descriptor.multisample?.count ?? 1, t.descriptor.depthStencil?.format);
47
+ this.color.view = t.color, this.depth.view = t.depth;
48
+ let r = t.encoder.beginRenderPass(this.pass);
49
+ e(r, t), r.setBindGroup(0, n.group), r.setVertexBuffer(0, this.vertices), r.setPipeline(n.near), r.drawIndirect(this.indirect, 0), r.setPipeline(n.far), r.drawIndirect(this.indirect, 16), r.end();
50
+ }, this.drawSpores = (e) => {
51
+ if (e.backend !== "webgpu") return;
52
+ let t = this.variant(e.format, e.descriptor.multisample?.count ?? 1, e.descriptor.depthStencil?.format);
53
+ this.color.view = e.color, this.sporeDepth.view = e.depth;
54
+ let n = e.encoder.beginRenderPass(this.sporePass);
55
+ n.setPipeline(t.spores), n.setBindGroup(0, t.sporeGroup), n.draw(6, 240), n.end();
56
+ };
57
+ let { blades: c = 1e5, area: l = [50, 50], bladeHeight: u = 1.2, windSpeed: d = 1.2, windStrength: m = .45, windDirection: h = [1, .35], drawDistance: g = 100, spores: _ = !1 } = n;
58
+ if (s(l, 2, "Grass area"), s(h, 2, "Wind direction"), s([u, g], 2, "Grass dimensions"), !Number.isSafeInteger(c) || c < 1 || c > 16777216 || l.some((e) => Math.fround(e) <= 0 || e > 1e5) || Math.fround(u) <= 0 || u > 100 || Math.fround(g) <= 0 || g > 1e5 || !Math.hypot(...h) || typeof _ != "boolean") throw RangeError("Invalid grass options; use integer blades 1..16777216, positive area, bladeHeight (max 100) and drawDistance (max 100000), a nonzero windDirection and boolean spores");
59
+ this.blades = c, this.spores = _, this.windSpeed = d, this.windStrength = m;
60
+ let v = Math.hypot(...h);
61
+ this.frame[52] = h[0] / v, this.frame[53] = h[1] / v, this.frame.set(l, 56), this.frame[58] = u, this.frame[60] = g, this.frame[61] = c, this.frame[63] = 1, this.frame.set([
62
+ .025,
63
+ .065,
64
+ .012,
65
+ 0
66
+ ], 72), this.frame.set([
67
+ .25,
68
+ .46,
69
+ .045,
70
+ 0
71
+ ], 76), this.frame.set([
72
+ .38,
73
+ .57,
74
+ .085,
75
+ 0
76
+ ], 80), this.frame.set([
77
+ .34,
78
+ .5,
79
+ .09,
80
+ .4
81
+ ], 84), a(t.engine).use(this);
82
+ }
83
+ get windSpeed() {
84
+ return this.frame[54];
85
+ }
86
+ set windSpeed(e) {
87
+ if (typeof e != "number" || !Number.isFinite(e) || e < 0 || e > 100) throw RangeError("Wind speed must be 0..100");
88
+ this.frame[54] = e;
89
+ }
90
+ get windStrength() {
91
+ return this.frame[55];
92
+ }
93
+ set windStrength(e) {
94
+ if (typeof e != "number" || !Number.isFinite(e) || e < 0 || e > 2) throw RangeError("Wind strength must be 0..2");
95
+ this.frame[55] = e;
96
+ }
97
+ get windDirection() {
98
+ return [this.frame[52], this.frame[53]];
99
+ }
100
+ set windDirection(e) {
101
+ s(e, 2, "Wind direction");
102
+ let t = Math.hypot(e[0], e[1]);
103
+ if (!t) throw RangeError("Wind direction must be nonzero");
104
+ this.frame[52] = e[0] / t, this.frame[53] = e[1] / t;
105
+ }
106
+ get bladeHeight() {
107
+ return this.frame[58];
108
+ }
109
+ set bladeHeight(e) {
110
+ if (typeof e != "number" || !Number.isFinite(Math.fround(e)) || Math.fround(e) <= 0 || e > 100) throw RangeError("Blade height must be above 0 and at most 100");
111
+ this.frame[58] = e;
112
+ }
113
+ get drawDistance() {
114
+ return this.frame[60];
115
+ }
116
+ set drawDistance(e) {
117
+ if (typeof e != "number" || !Number.isFinite(Math.fround(e)) || Math.fround(e) <= 0 || e > 1e5) throw RangeError("Draw distance must be above 0 and at most 100000");
118
+ this.frame[60] = e;
119
+ }
120
+ get density() {
121
+ return this.frame[63];
122
+ }
123
+ set density(e) {
124
+ if (typeof e != "number" || !(e >= 0 && e <= 1)) throw RangeError("Grass density must be 0..1");
125
+ this.frame[63] = e;
126
+ }
127
+ get rootColor() {
128
+ return [
129
+ this.frame[72],
130
+ this.frame[73],
131
+ this.frame[74]
132
+ ];
133
+ }
134
+ set rootColor(e) {
135
+ this.colour(e, 72, "rootColor");
136
+ }
137
+ get tipColor() {
138
+ return [
139
+ this.frame[76],
140
+ this.frame[77],
141
+ this.frame[78]
142
+ ];
143
+ }
144
+ set tipColor(e) {
145
+ this.colour(e, 76, "tipColor");
146
+ }
147
+ get tipVariantColor() {
148
+ return [
149
+ this.frame[80],
150
+ this.frame[81],
151
+ this.frame[82]
152
+ ];
153
+ }
154
+ set tipVariantColor(e) {
155
+ this.colour(e, 80, "tipVariantColor");
156
+ }
157
+ get translucencyColor() {
158
+ return [
159
+ this.frame[84],
160
+ this.frame[85],
161
+ this.frame[86]
162
+ ];
163
+ }
164
+ set translucencyColor(e) {
165
+ this.colour(e, 84, "translucencyColor");
166
+ }
167
+ get translucency() {
168
+ return this.frame[87];
169
+ }
170
+ set translucency(e) {
171
+ if (typeof e != "number" || !(e >= 0 && e <= 4)) throw RangeError("Grass translucency must be 0..4");
172
+ this.frame[87] = e;
173
+ }
174
+ colour(e, t, n) {
175
+ if (!Array.isArray(e) || e.length !== 3 || !e.every((e) => typeof e == "number" && e >= 0 && e <= 1)) throw RangeError(`Grass ${n} must be three numbers from 0 to 1`);
176
+ this.frame.set(e, t);
177
+ }
178
+ get windTime() {
179
+ return this.time;
180
+ }
181
+ set windTime(e) {
182
+ if (typeof e != "number" || !Number.isFinite(Math.fround(e)) || e < 0) throw RangeError("Wind time must be finite and nonnegative");
183
+ this.time = e;
184
+ }
185
+ setup(e) {
186
+ if (this.device) throw new o("attached", "Grass field already attached; create a new GrassField");
187
+ let r = e.gpu;
188
+ if (!r) throw new o("unsupported", "GrassField requires WebGPU; use a WebGPU engine; see https://margoengine.com/errors#webgpu");
189
+ if (this.blades * 24 > Math.min(r.limits.maxStorageBufferBindingSize, r.limits.maxBufferSize) || Math.ceil(this.blades / 64) > r.limits.maxComputeWorkgroupsPerDimension) throw RangeError("Grass storage or dispatch exceeds GPU limits; lower blades or use a device with larger storage buffers");
190
+ this.engine = e, this.device = r, this.instances = r.createBuffer({
191
+ label: "grass:instances",
192
+ size: this.blades * 24,
193
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
194
+ }), this.visible = r.createBuffer({
195
+ label: "grass:visible",
196
+ size: this.blades * 8,
197
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC
198
+ }), this.indirect = r.createBuffer({
199
+ label: "grass:indirect",
200
+ size: 32,
201
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC
202
+ }), this.uniform = r.createBuffer({
203
+ label: "grass:frame",
204
+ size: this.frame.byteLength,
205
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
206
+ }), this.vertices = r.createBuffer({
207
+ label: "grass:blade",
208
+ size: 200,
209
+ usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST
210
+ });
211
+ let i = new Float32Array(this.blades * 6), a = Math.min(this.blades, Math.ceil(Math.sqrt(this.blades * this.frame[56] / this.frame[57]))), s = Math.ceil(this.blades / a), f = c(305419896);
212
+ for (let e = 0; e < this.blades; e++) i[e * 6] = ((e % a + f()) / a - .5) * this.frame[56], i[e * 6 + 2] = ((Math.floor(e / a) + f()) / s - .5) * this.frame[57], i[e * 6 + 3] = f() * Math.PI * 2, i[e * 6 + 4] = .7 + f() * .55, i[e * 6 + 5] = .75 + f() * .5;
213
+ r.queue.writeBuffer(this.instances, 0, i), r.queue.writeBuffer(this.indirect, 0, new Uint32Array([
214
+ 7,
215
+ 0,
216
+ 0,
217
+ 0,
218
+ 3,
219
+ 0,
220
+ 7,
221
+ 0
222
+ ])), r.queue.writeBuffer(this.vertices, 0, new Float32Array([
223
+ -.5,
224
+ 0,
225
+ 0,
226
+ 0,
227
+ 0,
228
+ .5,
229
+ 0,
230
+ 0,
231
+ 1,
232
+ 0,
233
+ -.34,
234
+ 1 / 3,
235
+ 0,
236
+ 0,
237
+ 1 / 3,
238
+ .34,
239
+ 1 / 3,
240
+ 0,
241
+ 1,
242
+ 1 / 3,
243
+ -.17,
244
+ 2 / 3,
245
+ 0,
246
+ 0,
247
+ 2 / 3,
248
+ .17,
249
+ 2 / 3,
250
+ 0,
251
+ 1,
252
+ 2 / 3,
253
+ 0,
254
+ 1,
255
+ 0,
256
+ .5,
257
+ 1,
258
+ -.5,
259
+ 0,
260
+ 0,
261
+ 0,
262
+ 0,
263
+ .5,
264
+ 0,
265
+ 0,
266
+ 1,
267
+ 0,
268
+ 0,
269
+ 1,
270
+ 0,
271
+ .5,
272
+ 1
273
+ ]));
274
+ let p = r.createShaderModule({
275
+ label: "grass:cull",
276
+ code: n + l + u
277
+ });
278
+ this.compute = r.createComputePipeline({
279
+ layout: "auto",
280
+ compute: {
281
+ module: p,
282
+ entryPoint: "cull"
283
+ }
284
+ });
285
+ let m = [
286
+ {
287
+ binding: 0,
288
+ resource: { buffer: this.uniform }
289
+ },
290
+ {
291
+ binding: 1,
292
+ resource: { buffer: this.instances }
293
+ },
294
+ {
295
+ binding: 2,
296
+ resource: { buffer: this.visible }
297
+ }
298
+ ];
299
+ this.computeGroup = r.createBindGroup({
300
+ layout: this.compute.getBindGroupLayout(0),
301
+ entries: [...m, {
302
+ binding: 3,
303
+ resource: { buffer: this.indirect }
304
+ }]
305
+ }), this.module = r.createShaderModule({
306
+ label: "grass:render",
307
+ code: n + l + d
308
+ }), this.canvasFormat = navigator.gpu.getPreferredCanvasFormat();
309
+ let h = r.createBindGroupLayout({ entries: [
310
+ {
311
+ binding: 0,
312
+ visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
313
+ buffer: { type: "uniform" }
314
+ },
315
+ {
316
+ binding: 1,
317
+ visibility: GPUShaderStage.VERTEX,
318
+ buffer: { type: "read-only-storage" }
319
+ },
320
+ {
321
+ binding: 2,
322
+ visibility: GPUShaderStage.VERTEX,
323
+ buffer: { type: "read-only-storage" }
324
+ }
325
+ ] });
326
+ this.pipelineLayout = r.createPipelineLayout({ bindGroupLayouts: [h] }), this.group = r.createBindGroup({
327
+ layout: h,
328
+ entries: m
329
+ });
330
+ let g = r.features.has("depth32float-stencil8") ? "depth32float-stencil8" : "depth32float";
331
+ this.variant(this.canvasFormat, t(e), g);
332
+ }
333
+ registerPasses(e) {
334
+ e.add({
335
+ name: this.name + ":cull",
336
+ order: -10,
337
+ execute: this.update
338
+ }), e.add({
339
+ name: this.name + ":draw",
340
+ order: 5,
341
+ execute: this.draw
342
+ }), this.spores && e.add({
343
+ name: this.name + ":spores",
344
+ order: 11,
345
+ execute: this.drawSpores
346
+ });
347
+ }
348
+ variant(e, n, r = this.device.features.has("depth32float-stencil8") ? "depth32float-stencil8" : "depth32float") {
349
+ if (e !== this.canvasFormat && e !== "rgba8unorm" && e !== "bgra8unorm" && e !== "rgba16float" && e !== "rg11b10ufloat" || n !== 1 && (n !== 4 || t() === 1)) throw new o("unsupported", "Unsupported grass target format; draw into rgba8unorm, bgra8unorm or rgba16float, at 1 or 4 samples");
350
+ let i = e + ":" + n + ":" + r, a = this.variants.get(i);
351
+ if (a) return a;
352
+ let s = this.device, c = this.module, l = [{
353
+ arrayStride: 20,
354
+ attributes: [{
355
+ shaderLocation: 0,
356
+ offset: 0,
357
+ format: "float32x3"
358
+ }, {
359
+ shaderLocation: 1,
360
+ offset: 12,
361
+ format: "float32x2"
362
+ }]
363
+ }], u = (t) => s.createRenderPipeline({
364
+ layout: this.pipelineLayout,
365
+ vertex: {
366
+ module: c,
367
+ entryPoint: t,
368
+ buffers: l
369
+ },
370
+ fragment: {
371
+ module: c,
372
+ entryPoint: "fragment",
373
+ targets: [{ format: e }]
374
+ },
375
+ primitive: {
376
+ topology: "triangle-strip",
377
+ cullMode: "none"
378
+ },
379
+ multisample: { count: n },
380
+ depthStencil: {
381
+ format: r,
382
+ depthWriteEnabled: !0,
383
+ depthCompare: "greater-equal"
384
+ }
385
+ });
386
+ return a = {
387
+ near: u("nearVertex"),
388
+ far: u("farVertex"),
389
+ group: this.group
390
+ }, this.spores && (a.spores = s.createRenderPipeline({
391
+ layout: "auto",
392
+ vertex: {
393
+ module: c,
394
+ entryPoint: "sporeVertex"
395
+ },
396
+ fragment: {
397
+ module: c,
398
+ entryPoint: "sporeFragment",
399
+ targets: [{
400
+ format: e,
401
+ blend: {
402
+ color: {
403
+ srcFactor: "src-alpha",
404
+ dstFactor: "one"
405
+ },
406
+ alpha: {
407
+ srcFactor: "one",
408
+ dstFactor: "one-minus-src-alpha"
409
+ }
410
+ }
411
+ }]
412
+ },
413
+ multisample: { count: n },
414
+ depthStencil: {
415
+ format: r,
416
+ depthWriteEnabled: !1,
417
+ depthCompare: "greater-equal"
418
+ }
419
+ }), a.sporeGroup = s.createBindGroup({
420
+ layout: a.spores.getBindGroupLayout(0),
421
+ entries: [{
422
+ binding: 0,
423
+ resource: { buffer: this.uniform }
424
+ }]
425
+ })), this.variants.set(i, a), a;
426
+ }
427
+ release() {
428
+ this.instances?.destroy(), this.visible?.destroy(), this.indirect?.destroy(), this.vertices?.destroy(), this.uniform?.destroy(), this.instances = this.visible = this.indirect = this.vertices = this.uniform = void 0, this.device = void 0, this.compute = void 0, this.computeGroup = void 0, this.variants.clear(), this.module = this.pipelineLayout = this.group = void 0, this.canvasFormat = void 0;
429
+ }
430
+ onDeviceRestored(e) {
431
+ this.release();
432
+ try {
433
+ this.setup(e);
434
+ } catch (e) {
435
+ throw this.release(), e;
436
+ }
437
+ }
438
+ destroy() {
439
+ this.dispose();
440
+ }
441
+ dispose() {
442
+ let e = this.engine?.sceneOf(this);
443
+ e ? e.removePlugin(this.name) : (this.release(), this.engine = void 0);
444
+ }
445
+ [Symbol.dispose ?? Symbol()]() {
446
+ this.dispose();
447
+ }
448
+ };
449
+ //#endregion
450
+ export { m as t };
@@ -0,0 +1,63 @@
1
+ import { type SettingRow } from './shared/settings.js';
2
+ /** A colour value: three numbers, linear RGB. */
3
+ export type GrassSettingColor = readonly [number, number, number];
4
+ /** One value of a setting: a number or a colour. */
5
+ export type GrassSettingValue = number | GrassSettingColor;
6
+ /** Values by setting name; a name left out takes its default. */
7
+ export type GrassSettingValues = Readonly<Record<string, GrassSettingValue>>;
8
+ /** The panel a setting sits in. */
9
+ export type GrassSettingGroup = 'field' | 'wind' | 'color' | 'translucency';
10
+ /** One control: the shared row shape with the grass groups. */
11
+ export interface GrassSetting extends SettingRow {
12
+ readonly group: GrassSettingGroup;
13
+ readonly default: GrassSettingValue;
14
+ }
15
+ /** A `GrassField`: the setters the rows write. */
16
+ export interface GrassSettingTarget {
17
+ bladeHeight: number;
18
+ drawDistance: number;
19
+ density: number;
20
+ windSpeed: number;
21
+ windStrength: number;
22
+ windDirection: readonly [number, number];
23
+ rootColor: GrassSettingColor;
24
+ tipColor: GrassSettingColor;
25
+ tipVariantColor: GrassSettingColor;
26
+ translucencyColor: GrassSettingColor;
27
+ translucency: number;
28
+ }
29
+ /** Every grass look control, in panel order. Defaults are the values a GrassField uses without the option. */
30
+ export declare const GRASS_SETTINGS: readonly GrassSetting[];
31
+ /** The rows that can change every frame without a rebuild: all of them. */
32
+ export declare const GRASS_LIVE_SETTINGS: readonly GrassSetting[];
33
+ /** Every setting at its default, as a fresh object to edit (a slider panel's state). */
34
+ export declare function grassSettingDefaults(): Record<string, GrassSettingValue>;
35
+ /** Named looks, each only values of {@link GRASS_SETTINGS}. */
36
+ export declare const GRASS_LOOKS: {
37
+ /** Today's defaults. */
38
+ readonly natural: {};
39
+ /** Dry summer grass, short and thin, with a hot back-light. */
40
+ readonly dry: {
41
+ readonly 'field.bladeHeight': 0.7;
42
+ readonly 'field.density': 0.7;
43
+ readonly 'color.root': readonly [0.08, 0.06, 0.02];
44
+ readonly 'color.tip': readonly [0.5, 0.4, 0.12];
45
+ readonly 'color.tipVariant': readonly [0.62, 0.5, 0.18];
46
+ readonly 'translucency.color': readonly [0.6, 0.45, 0.12];
47
+ };
48
+ /** Tall green meadow grass in a gale. */
49
+ readonly windy: {
50
+ readonly 'field.bladeHeight': 1.8;
51
+ readonly 'wind.speed': 3;
52
+ readonly 'wind.strength': 1.2;
53
+ };
54
+ };
55
+ /** The name of a look in {@link GRASS_LOOKS}. */
56
+ export type GrassLookName = keyof typeof GRASS_LOOKS;
57
+ /**
58
+ * Writes `values` onto the GrassField (a name left out takes its default), read from the next frame.
59
+ * @throws TypeError for a name not in {@link GRASS_SETTINGS}; RangeError for a value outside its row's range, or a wind
60
+ * direction of 0 and 0.
61
+ * @example applyGrassSettings(grass, GRASS_LOOKS.dry);
62
+ */
63
+ export declare function applyGrassSettings(grass: GrassSettingTarget, values?: GrassSettingValues): void;
@@ -0,0 +1,131 @@
1
+ //#region ../shared/settings.js
2
+ var e = (e, t, n) => typeof e == "number" && e >= t && e <= n, t = (t, n, r) => Array.isArray(t) && t.length === 3 && t.every((t) => e(t, n, r)), n = (e) => e.stopKey ?? "elevation", r = (e, t, n, r, i, a, o, s, c = !0) => ({
3
+ name: e,
4
+ group: t,
5
+ kind: "number",
6
+ default: n,
7
+ min: r,
8
+ max: i,
9
+ step: a,
10
+ unit: o,
11
+ about: s,
12
+ live: c
13
+ }), i = (e, t, n, r, i, a, o = !0) => ({
14
+ name: e,
15
+ group: t,
16
+ kind: "color",
17
+ default: n,
18
+ min: r,
19
+ max: i,
20
+ step: .01,
21
+ unit: "",
22
+ about: a,
23
+ live: o
24
+ });
25
+ function a(e) {
26
+ return Array.isArray(e) ? typeof e[0] == "object" ? e.map((e) => ({
27
+ ...e,
28
+ color: [...e.color]
29
+ })) : [...e] : e;
30
+ }
31
+ function o(e) {
32
+ return Object.fromEntries(e.map((e) => [e.name, a(e.default)]));
33
+ }
34
+ var s = (e) => e.filter((e) => e.live), c = (e) => new Map(e.map((e) => [e.name, e]));
35
+ function l(r, i, a) {
36
+ let o = r.min ?? -Infinity, s = r.max ?? Infinity, c;
37
+ if (i === null) c = !!r.nullable;
38
+ else if (r.kind === "number") c = e(i, o, s);
39
+ else if (r.kind === "color") c = t(i, o, s);
40
+ else if (r.kind === "choice") c = r.choices.includes(i);
41
+ else {
42
+ let a = n(r);
43
+ c = Array.isArray(i) && i.length >= 2 && i.length <= 8 && i.every((n, r) => typeof n == "object" && !!n && e(n[a], o, s) && t(n.color, 0, 1) && (r === 0 || n[a] > i[r - 1][a]));
44
+ }
45
+ if (c) return;
46
+ let l = r.nullable ? r.weather ? ` or null (follow the weather's ${r.weather})` : " or null" : "", u = r.kind === "number" ? `a number from ${o} to ${s}${l}` : r.kind === "color" ? `three numbers from ${o} to ${s} (linear RGB)${l}` : r.kind === "choice" ? r.choices.map((e) => `'${e}'`).join(" or ") + l : `2 to 8 stops {${n(r)}, color}, ${n(r)} ${o} to ${s} rising, colours 0 to 1${l}`;
47
+ throw RangeError(`Invalid ${a} setting ${r.name}; use ${u}`);
48
+ }
49
+ function u(e, t, n, r = `the rows in @margoengine/${n}/settings`) {
50
+ let i = e instanceof Map ? e : c(e);
51
+ for (let e of Object.keys(t)) {
52
+ let a = i.get(e);
53
+ if (!a) throw TypeError(`Unknown ${n} setting ${e}; use a name from ${r}`);
54
+ l(a, t[e], n);
55
+ }
56
+ }
57
+ //#endregion
58
+ //#region src/grass-settings.ts
59
+ var d = (e, t, n, i, a, o, s, c) => r(e, t, n, i, a, o, s, c), f = (e, t, n, r) => i(e, t, n, 0, 1, r), p = [
60
+ d("field.bladeHeight", "field", 1.2, .01, 10, .01, "m", "Blade height in metres; each blade varies 0.7 to 1.25 times this."),
61
+ d("field.drawDistance", "field", 100, 1, 1e3, 1, "m", "Distance beyond which blades are culled; the far third of it draws a quarter of the blades."),
62
+ d("field.density", "field", 1, 0, 1, .01, "", "Fraction of the blades drawn. The kept ones are the same blades each time (a hash of the blade number), so lowering it only thins the field."),
63
+ d("wind.speed", "wind", 1.2, 0, 100, .1, "", "Speed of the gust noise scrolling over the field and of the spores."),
64
+ d("wind.strength", "wind", .45, 0, 2, .01, "", "How far the blades bend."),
65
+ d("wind.directionX", "wind", 1, -1, 1, .01, "", "X of the wind direction (normalised with directionZ; both 0 is refused)."),
66
+ d("wind.directionZ", "wind", .35, -1, 1, .01, "", "Z of the wind direction."),
67
+ f("color.root", "color", [
68
+ .025,
69
+ .065,
70
+ .012
71
+ ], "Blade colour at the root, linear RGB."),
72
+ f("color.tip", "color", [
73
+ .25,
74
+ .46,
75
+ .045
76
+ ], "Blade colour at the tip, linear RGB."),
77
+ f("color.tipVariant", "color", [
78
+ .38,
79
+ .57,
80
+ .085
81
+ ], "Tip colour of the most varied blades: each blade mixes the tip toward this by its own number."),
82
+ f("translucency.color", "translucency", [
83
+ .34,
84
+ .5,
85
+ .09
86
+ ], "Colour of sunlight seen through the blades, linear RGB."),
87
+ d("translucency.strength", "translucency", .4, 0, 4, .01, "", "Strength of the glow of blades against a low sun; 0 is none.")
88
+ ], m = s(p), h = c(p);
89
+ function g() {
90
+ return o(p);
91
+ }
92
+ var _ = {
93
+ natural: {},
94
+ dry: {
95
+ "field.bladeHeight": .7,
96
+ "field.density": .7,
97
+ "color.root": [
98
+ .08,
99
+ .06,
100
+ .02
101
+ ],
102
+ "color.tip": [
103
+ .5,
104
+ .4,
105
+ .12
106
+ ],
107
+ "color.tipVariant": [
108
+ .62,
109
+ .5,
110
+ .18
111
+ ],
112
+ "translucency.color": [
113
+ .6,
114
+ .45,
115
+ .12
116
+ ]
117
+ },
118
+ windy: {
119
+ "field.bladeHeight": 1.8,
120
+ "wind.speed": 3,
121
+ "wind.strength": 1.2
122
+ }
123
+ };
124
+ function v(e, t = {}) {
125
+ u(h, t, "grass", "GRASS_SETTINGS in @margoengine/creative/grass-settings");
126
+ let n = (e) => e in t ? t[e] : h.get(e).default, r = n("wind.directionX"), i = n("wind.directionZ");
127
+ if (!Math.hypot(r, i)) throw RangeError("Invalid grass setting wind.directionX; use a direction other than 0 and 0");
128
+ e.bladeHeight = n("field.bladeHeight"), e.drawDistance = n("field.drawDistance"), e.density = n("field.density"), e.windSpeed = n("wind.speed"), e.windStrength = n("wind.strength"), e.windDirection = [r, i], e.rootColor = n("color.root"), e.tipColor = n("color.tip"), e.tipVariantColor = n("color.tipVariant"), e.translucencyColor = n("translucency.color"), e.translucency = n("translucency.strength");
129
+ }
130
+ //#endregion
131
+ export { m as GRASS_LIVE_SETTINGS, _ as GRASS_LOOKS, p as GRASS_SETTINGS, v as applyGrassSettings, g as grassSettingDefaults };
@@ -0,0 +1,33 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import { Geometry, type EngineKernel } from '@margoengine/core';
3
+ // @ts-ignore optional peer: its types apply when it is installed
4
+ import type { ScatterOptions } from '@margoengine/scatter';
5
+ // @ts-ignore optional peer: its types apply when it is installed
6
+ import type { TrampledScatter, TrampleOptions } from '@margoengine/scatter/interact';
7
+ /** Linear RGBA colour raster, sampled bilinearly at cell centres in world XZ. Alpha is retained but unused. */
8
+ export interface GrassColorMap {
9
+ /** Integer 1..4096, with at most 1048576 pixels total. */
10
+ readonly width: number;
11
+ /** Integer 1..4096. */
12
+ readonly height: number;
13
+ /** Four finite components in 0..1 per texel, row-major. Snapshotted at creation. */
14
+ readonly data: Float32Array;
15
+ /** World [minX,minZ,maxX,maxZ]. Default: the scatter bounds or its area about centre. */
16
+ readonly bounds?: readonly [number, number, number, number];
17
+ }
18
+ /** Scatter placement, rooted wind and sphere interaction, with a three-segment blade by default. */
19
+ export interface TerrainGrassOptions extends Omit<ScatterOptions, 'material'> {
20
+ /** Optional custom blade geometry/LOD triplet. Defaults to a 1 m tall, 8 cm wide segmented blade. */
21
+ geometry?: Geometry | readonly [Geometry, Geometry, Geometry];
22
+ /** World colour map multiplied by the grass colour; omitted gives white. */
23
+ colorMap?: GrassColorMap;
24
+ /** Sphere field/recovery settings; defaults to scatter/interact's settings. */
25
+ interaction?: TrampleOptions;
26
+ /** Abort before import, creation or attachment. */
27
+ signal?: AbortSignal;
28
+ }
29
+ /**
30
+ * Creates terrain-rooted grass using scatter's existing height/density sampling, LODs, wind and moving spheres.
31
+ * The scatter package loads only when called. Call setInteractors each frame; dispose the returned field to detach.
32
+ */
33
+ export declare function createTerrainGrass(engine: EngineKernel, options?: TerrainGrassOptions): Promise<TrampledScatter>;