@margoengine/terrain 0.0.0-stage → 0.1.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.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +1808 -3
- package/dist/blend.d.ts +70 -0
- package/dist/blend.js +159 -0
- package/dist/colors.d.ts +164 -0
- package/dist/deform.d.ts +103 -0
- package/dist/deform.js +322 -0
- package/dist/displace.d.ts +60 -0
- package/dist/displace.js +254 -0
- package/dist/dunes.d.ts +86 -0
- package/dist/dunes.js +88 -0
- package/dist/errors-fc4i1pSL.js +7 -0
- package/dist/grid.d.ts +11 -0
- package/dist/ground-change-settings.d.ts +29 -0
- package/dist/ground-change-settings.js +69 -0
- package/dist/ground-change.d.ts +227 -0
- package/dist/ground-change.js +1291 -0
- package/dist/ground-model.d.ts +290 -0
- package/dist/hdr-format-DRhzGS7G.js +30 -0
- package/dist/height-grid.d.ts +65 -0
- package/dist/height-grid.js +74 -0
- package/dist/heightfield.d.ts +38 -0
- package/dist/holes.d.ts +37 -0
- package/dist/holes.js +97 -0
- package/dist/imagery.d.ts +109 -0
- package/dist/imagery.js +472 -0
- package/dist/index.d.ts +297 -0
- package/dist/index.js +1 -0
- package/dist/layers-pbr.d.ts +78 -0
- package/dist/layers-pbr.js +128 -0
- package/dist/lighting-layout-CaDtDa5G.js +34 -0
- package/dist/lighting-layout.d.ts +5 -0
- package/dist/mesh-patch-BThCHCeS.js +21 -0
- package/dist/mesh-patch.d.ts +14 -0
- package/dist/noise3-sQdnbz4B.js +11 -0
- package/dist/noise3.d.ts +3 -0
- package/dist/overlays.d.ts +74 -0
- package/dist/overlays.js +297 -0
- package/dist/planet-craters.d.ts +55 -0
- package/dist/planet-recipes.d.ts +75 -0
- package/dist/planet-recipes.js +216 -0
- package/dist/planet.d.ts +139 -0
- package/dist/planet.js +602 -0
- package/dist/query.d.ts +150 -0
- package/dist/query.js +243 -0
- package/dist/relief-lighting.d.ts +46 -0
- package/dist/relief-lighting.js +208 -0
- package/dist/require-webgpu--tUXPsmA.js +7 -0
- package/dist/rock-settings.d.ts +39 -0
- package/dist/rock-settings.js +84 -0
- package/dist/rock-surface.d.ts +111 -0
- package/dist/rock-surface.js +368 -0
- package/dist/rocks.d.ts +258 -0
- package/dist/rocks.js +488 -0
- package/dist/rvt.d.ts +136 -0
- package/dist/rvt.js +518 -0
- package/dist/sculpt.d.ts +103 -0
- package/dist/sculpt.js +361 -0
- package/dist/settings-B9BSdnhD.js +72 -0
- package/dist/settings.d.ts +81 -0
- package/dist/settings.js +152 -0
- package/dist/shader.d.ts +61 -0
- package/dist/shared/settings.d.ts +89 -0
- package/dist/src-C6dtSaAb.js +1155 -0
- package/dist/stream.d.ts +100 -0
- package/dist/stream.js +339 -0
- package/dist/surface-height.d.ts +16 -0
- package/dist/wet-ground.d.ts +82 -0
- package/dist/wet-ground.js +147 -0
- package/package.json +148 -6
package/dist/deform.js
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
// @margo/core-built 0.1.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
const e=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
|
|
4
|
+
import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
|
|
5
|
+
import { MargoError as t } from "@margoengine/math/errors";
|
|
6
|
+
//#region src/deform.ts
|
|
7
|
+
var n = [
|
|
8
|
+
0,
|
|
9
|
+
0,
|
|
10
|
+
0
|
|
11
|
+
], r = 110, i = 1024, a = "\nstruct Window {origin:vec2i,previous:vec2i,size:u32,first:u32,fade:f32,texel:f32,rim:f32,count:u32,pad:vec2f}\nstruct Stamp {shape:vec4f,ends:vec4f,turn:vec4f,box:vec4i}\n@group(0) @binding(0) var<uniform> w:Window;\n@group(0) @binding(1) var<storage,read_write> marks:array<atomic<u32>>;\n@group(0) @binding(2) var<storage,read> stamps:array<Stamp>;\n@group(0) @binding(3) var relief:texture_storage_2d<rgba16float,write>;\nfn slot(world:vec2i)->u32 {let s=i32(w.size);let m=((world%s)+s)%s;return u32(m.y)*w.size+u32(m.x);}\nfn inside(world:vec2i,origin:vec2i)->bool {return all(world>=origin)&&all(world<origin+vec2i(i32(w.size)));}\n@compute @workgroup_size(8,8) fn age(@builtin(global_invocation_id) id:vec3u) {\n if(any(id.xy>=vec2u(w.size))){return;}\n let k=id.y*w.size+id.x;let n=w.size*w.size;let s=i32(w.size);\n let world=w.origin+(((vec2i(id.xy)-w.origin)%s)+s)%s;\n if(w.first==1u||!inside(world,w.previous)){atomicStore(&marks[k],0u);atomicStore(&marks[n+k],0u);return;}\n if(w.fade>0.0){\n atomicStore(&marks[k],bitcast<u32>(max(bitcast<f32>(atomicLoad(&marks[k]))-w.fade,0.0)));\n atomicStore(&marks[n+k],bitcast<u32>(max(bitcast<f32>(atomicLoad(&marks[n+k]))-w.fade*w.rim,0.0)));\n }\n}\n@compute @workgroup_size(8,8) fn stamp(@builtin(global_invocation_id) id:vec3u) {\n if(id.z>=w.count){return;}\n let s=stamps[id.z];if(any(vec2i(id.xy)>=s.box.zw)){return;}\n let world=s.box.xy+vec2i(id.xy);if(!inside(world,w.origin)){return;}\n let p=(vec2f(id.xy)+0.5)*w.texel;var t:f32;\n if(s.shape.x<0.5){let d=p-s.ends.xy;t=length(vec2f(d.x*s.turn.x+d.y*s.turn.y,d.y*s.turn.x-d.x*s.turn.y)/s.shape.wz);}\n else{let ab=s.ends.zw-s.ends.xy;let h=clamp(dot(p-s.ends.xy,ab)/max(dot(ab,ab),1e-12),0.0,1.0);t=length(p-s.ends.xy-ab*h)/s.shape.z;}\n let depth=s.shape.y*(1.0-smoothstep(0.55,1.0,t));let raised=s.shape.y*w.rim*(1.0-smoothstep(0.0,0.45,abs(t-1.2)));\n let k=slot(world);\n if(depth>0.0){atomicMax(&marks[k],bitcast<u32>(depth));}\n if(raised>0.0){atomicMax(&marks[w.size*w.size+k],bitcast<u32>(raised));}\n}\nfn heightAt(c:vec2i)->f32 {\n let s=i32(w.size);let m=((c%s)+s)%s;let k=u32(m.y)*w.size+u32(m.x);\n let d=bitcast<f32>(atomicLoad(&marks[k]));let r=bitcast<f32>(atomicLoad(&marks[w.size*w.size+k]));\n return r*(1.0-smoothstep(0.0,0.02,d))-d;\n}\n@compute @workgroup_size(8,8) fn resolve(@builtin(global_invocation_id) id:vec3u) {\n if(any(id.xy>=vec2u(w.size))){return;}\n let c=vec2i(id.xy);let d=bitcast<f32>(atomicLoad(&marks[id.y*w.size+id.x]));\n let gx=(heightAt(c+vec2i(1,0))-heightAt(c-vec2i(1,0)))/(2.0*w.texel);\n let gz=(heightAt(c+vec2i(0,1))-heightAt(c-vec2i(0,1)))/(2.0*w.texel);\n textureStore(relief,c,vec4f(heightAt(c),gx,gz,clamp(d/0.02,0.0,1.0)));\n}", o = (e, t) => `
|
|
12
|
+
struct TerrainDeformFrame {window:vec4f,params:vec4f,extra:vec4f,softness:array<vec4f,4>,layers:array<vec4f,4>}
|
|
13
|
+
@group(${e}) @binding(${r}) var<uniform> terrainDeform:TerrainDeformFrame;
|
|
14
|
+
@group(${e}) @binding(111) var terrainDeformMap:texture_2d<f32>;
|
|
15
|
+
var<private> terrainDeformTint:f32=1.0;
|
|
16
|
+
fn terrainDeformAt(xz:vec2f)->vec4f {
|
|
17
|
+
let f=terrainDeform.window;let d=max(abs(xz.x-f.x),abs(xz.y-f.y))*2.0/f.z;
|
|
18
|
+
return textureSampleLevel(terrainDeformMap,terrainSampler,xz/f.z,0.0)*(1.0-smoothstep(1.0-8.0/f.w,1.0-2.0/f.w,d));
|
|
19
|
+
}
|
|
20
|
+
fn terrainDeformSoftness(xz:vec2f)->f32 {${t ? `
|
|
21
|
+
let dd=vec2f(textureDimensions(terrainWeights0));let uv=clamp((xz-frame.map.xy)/frame.map.zw,vec2f(0.5)/dd,vec2f(1)-vec2f(0.5)/dd);var soft=0.0;var total=0.0;
|
|
22
|
+
${Array.from({ length: t }, (e, t) => `{let wv=textureSampleLevel(terrainWeights${t},terrainSampler,uv,0.0);soft+=dot(wv,terrainDeform.softness[${t}]);total+=dot(wv,terrainDeform.layers[${t}]);}`).join("")}
|
|
23
|
+
return select(terrainDeform.extra.y,soft/total,total>0.00001);` : "\n return terrainDeform.extra.y;"}
|
|
24
|
+
}
|
|
25
|
+
fn terrainDeformShift(i:Output)->Output {
|
|
26
|
+
var j=i;let n=normalize(i.normal);let reach=terrainDeform.params.x;let dist=distance(frame.eye.xyz,i.position);
|
|
27
|
+
if(dist>=reach||n.y<0.2){return j;}
|
|
28
|
+
let soft=terrainDeformSoftness(i.position.xz)*(1.0-smoothstep(reach*0.75,reach,dist));if(soft<=0.0){return j;}
|
|
29
|
+
let v=normalize(i.position-frame.eye.xyz);let vn=min(dot(v,n),-0.05);
|
|
30
|
+
let top=terrainDeform.extra.x*soft;let bottom=-terrainDeform.params.w*soft;let t0=top/vn;
|
|
31
|
+
let span=min(bottom/vn-t0,8.0*(top-bottom)/max(sqrt(max(1.0-vn*vn,0.0)),0.0001));let steps=terrainDeform.params.y;
|
|
32
|
+
var before=t0;var gap0=top-terrainDeformAt((i.position+v*t0).xz).x*soft;var hit=t0+span;
|
|
33
|
+
for(var k=1.0;k<=steps;k+=1.0){
|
|
34
|
+
let t=t0+span*k/steps;let gap=t*vn-terrainDeformAt((i.position+v*t).xz).x*soft;
|
|
35
|
+
if(gap<=0.0){hit=mix(before,t,gap0/max(gap0-gap,0.000001));break;}
|
|
36
|
+
before=t;gap0=gap;
|
|
37
|
+
}
|
|
38
|
+
let p=i.position+v*hit;let delta=p.xz-i.position.xz;let sample=terrainDeformAt(p.xz);
|
|
39
|
+
j.position=vec3f(p.x,i.position.y-(n.x*delta.x+n.z*delta.y)/n.y,p.z);
|
|
40
|
+
let g=vec3f(sample.y,0.0,sample.z)*soft;j.normal=normalize(n-(g-n*dot(n,g)));
|
|
41
|
+
terrainDeformTint=1.0-terrainDeform.params.z*sample.w*soft;
|
|
42
|
+
return j;
|
|
43
|
+
}
|
|
44
|
+
`, s = "@fragment fn fragment(i:Output)->@location(0) vec4f {", c = "fn terrainColor(position:vec3f,normal:vec3f)->vec3f {", l = 0, u = class u {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
|
|
45
|
+
#e;
|
|
46
|
+
#t;
|
|
47
|
+
#n;
|
|
48
|
+
#r;
|
|
49
|
+
#i;
|
|
50
|
+
#a;
|
|
51
|
+
#o;
|
|
52
|
+
#s;
|
|
53
|
+
#c;
|
|
54
|
+
#l;
|
|
55
|
+
#u;
|
|
56
|
+
#d;
|
|
57
|
+
#f;
|
|
58
|
+
#p;
|
|
59
|
+
#m;
|
|
60
|
+
#h;
|
|
61
|
+
constructor(e, t = {}) {
|
|
62
|
+
this.terrain = e, this.options = t, this.name = "terrain-deform:" + l++, this.disposed = !1, this.#s = [], this.#u = /* @__PURE__ */ new Float64Array(3), this.#d = [], this.#f = !0, this.#p = /* @__PURE__ */ new Map(), this.#m = /* @__PURE__ */ new ArrayBuffer(48), this.#h = /* @__PURE__ */ new ArrayBuffer(i * 64);
|
|
63
|
+
let n = e?.options?.layers?.length;
|
|
64
|
+
if (!n || typeof e.addLighting != "function") throw TypeError("Invalid terrain deformation; pass a Terrain");
|
|
65
|
+
let r = t ?? {}, a = (e) => typeof e == "number" && e >= 0 && e <= 1, o = (e) => typeof e == "number" && e > 0 && Number.isFinite(e);
|
|
66
|
+
if (!Number.isInteger(r.size ?? 1024) || (r.size ?? 1024) < 64 || (r.size ?? 1024) > 2048 || !o(r.texel ?? .025) || !o(r.depth ?? .15) || !a(r.rim ?? .25) || !(typeof (r.fade ?? 120) == "number" && (r.fade ?? 120) >= 0 && Number.isFinite(r.fade ?? 120)) || !a(r.softness ?? 1) || !(r.layers === void 0 || Array.isArray(r.layers) && r.layers.length <= n && r.layers.every(a)) || !a(r.darken ?? .25) || !o(r.distance ?? 40) || !Number.isInteger(r.steps ?? 12) || (r.steps ?? 12) < 4 || (r.steps ?? 12) > 32 || r.follow !== void 0 && typeof r.follow != "function") throw RangeError("Invalid terrain deformation; give size 64..2048, texel, depth and distance above 0, rim, softness, darken and each layers entry 0..1 (at most one per terrain layer), fade 0 or more, steps 4..32 and follow as a function.");
|
|
67
|
+
this.size = r.size ?? 1024, this.texel = e.options.floatingOrigin ? Math.fround(this.size * (r.texel ?? .025)) / this.size : r.texel ?? .025, this.depth = r.depth ?? .15;
|
|
68
|
+
}
|
|
69
|
+
static attach(t, n, r = {}) {__margoAssertCore(t,__margoCoreRequirement("0.1.0",import.meta.url));
|
|
70
|
+
let i = new u(n, r);
|
|
71
|
+
return e(t).use(i), i;
|
|
72
|
+
}
|
|
73
|
+
footprint(e, t, n = {}) {
|
|
74
|
+
let r = n.length ?? .28, i = n.width ?? .11, a = n.angle ?? 0;
|
|
75
|
+
this.#g([
|
|
76
|
+
e,
|
|
77
|
+
t,
|
|
78
|
+
a
|
|
79
|
+
], r, i, n.depth);
|
|
80
|
+
let o = Math.max(r, i) * .85, s = Math.floor((e - o) / this.texel), c = Math.floor((t - o) / this.texel), l = Math.ceil(2 * o / this.texel) + 2;
|
|
81
|
+
return this.#v([
|
|
82
|
+
0,
|
|
83
|
+
this.#_(n.depth),
|
|
84
|
+
i / 2,
|
|
85
|
+
r / 2,
|
|
86
|
+
e - s * this.texel,
|
|
87
|
+
t - c * this.texel,
|
|
88
|
+
0,
|
|
89
|
+
0,
|
|
90
|
+
Math.cos(a),
|
|
91
|
+
Math.sin(a),
|
|
92
|
+
0,
|
|
93
|
+
0,
|
|
94
|
+
s,
|
|
95
|
+
c,
|
|
96
|
+
l,
|
|
97
|
+
l
|
|
98
|
+
]), this;
|
|
99
|
+
}
|
|
100
|
+
track(e, t, n = {}) {
|
|
101
|
+
let r = n.width ?? .25;
|
|
102
|
+
this.#g([
|
|
103
|
+
e?.[0],
|
|
104
|
+
e?.[1],
|
|
105
|
+
t?.[0],
|
|
106
|
+
t?.[1]
|
|
107
|
+
], r, r, n.depth);
|
|
108
|
+
let i = this.#_(n.depth), a = r * .85, o = 188 * this.texel - 2 * a, s = Math.hypot(t[0] - e[0], t[1] - e[1]), c = Math.max(1, Math.ceil(s / o));
|
|
109
|
+
for (let n = 0; n < c; n++) {
|
|
110
|
+
let o = [e[0] + (t[0] - e[0]) * n / c, e[1] + (t[1] - e[1]) * n / c], s = [e[0] + (t[0] - e[0]) * (n + 1) / c, e[1] + (t[1] - e[1]) * (n + 1) / c], l = Math.floor((Math.min(o[0], s[0]) - a) / this.texel), u = Math.floor((Math.min(o[1], s[1]) - a) / this.texel), d = Math.ceil((Math.max(o[0], s[0]) + a) / this.texel), f = Math.ceil((Math.max(o[1], s[1]) + a) / this.texel), p = l * this.texel, m = u * this.texel;
|
|
111
|
+
this.#v([
|
|
112
|
+
1,
|
|
113
|
+
i,
|
|
114
|
+
r / 2,
|
|
115
|
+
0,
|
|
116
|
+
o[0] - p,
|
|
117
|
+
o[1] - m,
|
|
118
|
+
s[0] - p,
|
|
119
|
+
s[1] - m,
|
|
120
|
+
1,
|
|
121
|
+
0,
|
|
122
|
+
0,
|
|
123
|
+
0,
|
|
124
|
+
l,
|
|
125
|
+
u,
|
|
126
|
+
d - l + 1,
|
|
127
|
+
f - u + 1
|
|
128
|
+
]);
|
|
129
|
+
}
|
|
130
|
+
return this;
|
|
131
|
+
}
|
|
132
|
+
trail(e, t = {}) {
|
|
133
|
+
if (!Array.isArray(e)) throw RangeError("Invalid terrain trail; pass an array of [x, z] points");
|
|
134
|
+
for (let n = 1; n < e.length; n++) this.track(e[n - 1], e[n], t);
|
|
135
|
+
return e.length === 1 && this.track(e[0], e[0], t), this;
|
|
136
|
+
}
|
|
137
|
+
clear() {
|
|
138
|
+
return this.#d = [], this.#f = !0, this;
|
|
139
|
+
}
|
|
140
|
+
get texture() {
|
|
141
|
+
return this.#i;
|
|
142
|
+
}
|
|
143
|
+
get pending() {
|
|
144
|
+
return this.#d.length;
|
|
145
|
+
}
|
|
146
|
+
#g(e, t, n, r) {
|
|
147
|
+
let i = 188 * this.texel * .5;
|
|
148
|
+
if (!e.every((e) => typeof e == "number" && Number.isFinite(e)) || !(t > 0 && t <= i) || !(n > 0 && n <= i) || !(r === void 0 || typeof r == "number" && r >= 0 && Number.isFinite(r))) throw RangeError(`Invalid terrain print; give finite positions, length and width above 0 up to ${i.toFixed(3)} world units and depth 0 or more.`);
|
|
149
|
+
}
|
|
150
|
+
#_(e) {
|
|
151
|
+
return Math.min(e ?? this.depth, this.depth);
|
|
152
|
+
}
|
|
153
|
+
#v(e) {
|
|
154
|
+
this.#d.push(e);
|
|
155
|
+
}
|
|
156
|
+
setup(e) {
|
|
157
|
+
if (this.disposed || !e.gpu) throw new t(this.disposed ? "disposed" : "unsupported", "Terrain deformation requires WebGPU and a live module; attach a new one to a WebGPU engine; see https://margoengine.com/errors#webgpu");
|
|
158
|
+
let n = e.gpu, o = this.size, s = 8 * o * o;
|
|
159
|
+
if (o > n.limits.maxTextureDimension2D || s > n.limits.maxStorageBufferBindingSize) throw new t("unsupported", "The terrain deformation map is larger than this device allows; pass a smaller size");
|
|
160
|
+
this.owner = e, this.#e = n.createBuffer({
|
|
161
|
+
size: s,
|
|
162
|
+
usage: 128
|
|
163
|
+
}), this.#t = n.createBuffer({
|
|
164
|
+
size: i * 64,
|
|
165
|
+
usage: 136
|
|
166
|
+
}), this.#n = n.createBuffer({
|
|
167
|
+
size: 48,
|
|
168
|
+
usage: 72
|
|
169
|
+
}), this.#r = n.createBuffer({
|
|
170
|
+
size: 176,
|
|
171
|
+
usage: 72
|
|
172
|
+
}), this.#i = n.createTexture({
|
|
173
|
+
size: [o, o],
|
|
174
|
+
format: "rgba16float",
|
|
175
|
+
usage: 13
|
|
176
|
+
});
|
|
177
|
+
let c = n.createBindGroupLayout({ entries: [
|
|
178
|
+
{
|
|
179
|
+
binding: 0,
|
|
180
|
+
visibility: 4,
|
|
181
|
+
buffer: { type: "uniform" }
|
|
182
|
+
},
|
|
183
|
+
{
|
|
184
|
+
binding: 1,
|
|
185
|
+
visibility: 4,
|
|
186
|
+
buffer: { type: "storage" }
|
|
187
|
+
},
|
|
188
|
+
{
|
|
189
|
+
binding: 2,
|
|
190
|
+
visibility: 4,
|
|
191
|
+
buffer: { type: "read-only-storage" }
|
|
192
|
+
},
|
|
193
|
+
{
|
|
194
|
+
binding: 3,
|
|
195
|
+
visibility: 4,
|
|
196
|
+
storageTexture: {
|
|
197
|
+
access: "write-only",
|
|
198
|
+
format: "rgba16float"
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
] }), l = n.createShaderModule({ code: a }), u = n.createPipelineLayout({ bindGroupLayouts: [c] }), d = (e) => n.createComputePipeline({
|
|
202
|
+
layout: u,
|
|
203
|
+
compute: {
|
|
204
|
+
module: l,
|
|
205
|
+
entryPoint: e
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
this.#o = {
|
|
209
|
+
age: d("age"),
|
|
210
|
+
stamp: d("stamp"),
|
|
211
|
+
resolve: d("resolve")
|
|
212
|
+
}, this.#a = n.createBindGroup({
|
|
213
|
+
layout: c,
|
|
214
|
+
entries: [
|
|
215
|
+
{
|
|
216
|
+
binding: 0,
|
|
217
|
+
resource: { buffer: this.#n }
|
|
218
|
+
},
|
|
219
|
+
{
|
|
220
|
+
binding: 1,
|
|
221
|
+
resource: { buffer: this.#e }
|
|
222
|
+
},
|
|
223
|
+
{
|
|
224
|
+
binding: 2,
|
|
225
|
+
resource: { buffer: this.#t }
|
|
226
|
+
},
|
|
227
|
+
{
|
|
228
|
+
binding: 3,
|
|
229
|
+
resource: this.#i.createView()
|
|
230
|
+
}
|
|
231
|
+
]
|
|
232
|
+
});
|
|
233
|
+
let f = this.options, p = /* @__PURE__ */ new Float32Array(44), m = this.terrain.options.layers.length;
|
|
234
|
+
p.set([
|
|
235
|
+
1e30,
|
|
236
|
+
1e30,
|
|
237
|
+
o * this.texel,
|
|
238
|
+
o
|
|
239
|
+
], 0), p.set([
|
|
240
|
+
f.distance ?? 40,
|
|
241
|
+
f.steps ?? 12,
|
|
242
|
+
f.darken ?? .25,
|
|
243
|
+
this.depth
|
|
244
|
+
], 4), p.set([
|
|
245
|
+
this.depth * (f.rim ?? .25),
|
|
246
|
+
f.softness ?? 1,
|
|
247
|
+
0,
|
|
248
|
+
0
|
|
249
|
+
], 8);
|
|
250
|
+
for (let e = 0; e < m; e++) p[12 + e] = f.layers?.[e] ?? f.softness ?? 1, p[28 + e] = 1;
|
|
251
|
+
n.queue.writeBuffer(this.#r, 0, p), this.#l = void 0, this.#f = !0, this.#s = [{
|
|
252
|
+
binding: r,
|
|
253
|
+
resource: { buffer: this.#r }
|
|
254
|
+
}, {
|
|
255
|
+
binding: 111,
|
|
256
|
+
resource: this.#i.createView()
|
|
257
|
+
}], this.#c ??= this.terrain.addLighting(this);
|
|
258
|
+
}
|
|
259
|
+
registerPasses(e) {
|
|
260
|
+
e.add({
|
|
261
|
+
name: this.name,
|
|
262
|
+
order: -5,
|
|
263
|
+
execute: (e) => {
|
|
264
|
+
e.backend === "webgpu" && !(e.view?.index ?? 0) && this.#y(e);
|
|
265
|
+
}
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
#y(e) {
|
|
269
|
+
if (this.disposed || !this.#o) return;
|
|
270
|
+
let t = this.size, r = !!this.terrain.options.floatingOrigin, a = r ? this.terrain.shift : n, o = this.options.follow?.() ?? (r ? [e.camera.position[0] + a[0], e.camera.position[2] + a[2]] : [e.camera.position[0], e.camera.position[2]]);
|
|
271
|
+
if (!Number.isFinite(o[0]) || !Number.isFinite(o[1])) return;
|
|
272
|
+
let s = [Math.floor(o[0] / this.texel) - t / 2, Math.floor(o[1] / this.texel) - t / 2], c = this.#l ?? s, l = this.#f, u = r && (this.#u[0] !== a[0] || this.#u[2] !== a[2]), d = c[0] !== s[0] || c[1] !== s[1] || !this.#l, f = this.options.fade ?? 120, p = f > 0 ? this.depth * Math.max(e.delta, 0) / f : 0, m = Math.min(this.#d.length, i);
|
|
273
|
+
if (u || d && r) {
|
|
274
|
+
let n = t * this.texel, r = (e) => e - Math.floor(e / n) * n;
|
|
275
|
+
e.device.queue.writeBuffer(this.#r, 0, new Float32Array([(s[0] + t / 2) * this.texel - a[0], (s[1] + t / 2) * this.texel - a[2]])), e.device.queue.writeBuffer(this.#r, 40, new Float32Array([r(a[0]), r(a[2])])), this.#u.set([
|
|
276
|
+
a[0],
|
|
277
|
+
a[1],
|
|
278
|
+
a[2]
|
|
279
|
+
]);
|
|
280
|
+
}
|
|
281
|
+
if (!l && !d && !p && !m) return;
|
|
282
|
+
let h = new Int32Array(this.#m), g = new Float32Array(this.#m), _ = new Uint32Array(this.#m);
|
|
283
|
+
h.set([
|
|
284
|
+
s[0],
|
|
285
|
+
s[1],
|
|
286
|
+
c[0],
|
|
287
|
+
c[1]
|
|
288
|
+
]), _[4] = t, _[5] = +l, g[6] = p, g[7] = this.texel, g[8] = this.options.rim ?? .25, _[9] = m, e.device.queue.writeBuffer(this.#n, 0, this.#m), d && !r && e.device.queue.writeBuffer(this.#r, 0, new Float32Array([(s[0] + t / 2) * this.texel, (s[1] + t / 2) * this.texel])), d && (this.#l = s);
|
|
289
|
+
let v = e.encoder.beginComputePass(), y = Math.ceil(t / 8);
|
|
290
|
+
if (v.setBindGroup(0, this.#a), (l || d || p) && (v.setPipeline(this.#o.age), v.dispatchWorkgroups(y, y)), m) {
|
|
291
|
+
let t = this.#d.splice(0, m), n = new Float32Array(this.#h), r = new Int32Array(this.#h), i = 1;
|
|
292
|
+
t.forEach((e, t) => {
|
|
293
|
+
n.set(e.slice(0, 12), t * 16), r.set(e.slice(12), t * 16 + 12), i = Math.max(i, e[14], e[15]);
|
|
294
|
+
}), e.device.queue.writeBuffer(this.#t, 0, this.#h, 0, m * 64), v.setPipeline(this.#o.stamp), v.dispatchWorkgroups(Math.ceil(i / 8), Math.ceil(i / 8), m);
|
|
295
|
+
}
|
|
296
|
+
v.setPipeline(this.#o.resolve), v.dispatchWorkgroups(y, y), v.end(), this.#f = !1;
|
|
297
|
+
}
|
|
298
|
+
bindings() {
|
|
299
|
+
return this.#s;
|
|
300
|
+
}
|
|
301
|
+
shader(e, n) {
|
|
302
|
+
let r = n + e, i = this.#p.get(r);
|
|
303
|
+
if (i) return i;
|
|
304
|
+
if (e.split(s).length !== 2) throw new t("unsupported", "Terrain deformation needs the terrain's lit fragment shader; attach it before effects that replace it");
|
|
305
|
+
let a = [...e.matchAll(/var terrainWeights(\d):texture_2d<f32>;/g)].length, l = e.replace(s, "fn terrainDeformInner(i:Output)->vec4f {");
|
|
306
|
+
return l.split(c).length === 2 && (l = l.replace(c, "fn terrainColorUndeformed(position:vec3f,normal:vec3f)->vec3f {")), l = (this.terrain.options.floatingOrigin ? o(n, a).replace("xz/f.z,0.0)", "(xz+terrainDeform.extra.zw)/f.z,0.0)") : o(n, a)) + l + (l.includes("terrainColorUndeformed") ? `\n${c}return terrainColorUndeformed(position,normal)*terrainDeformTint;}` : "") + `\n${s}return terrainDeformInner(terrainDeformShift(i));}`, this.#p.size >= 16 && this.#p.clear(), this.#p.set(r, l), l;
|
|
307
|
+
}
|
|
308
|
+
onDeviceRestored(e) {
|
|
309
|
+
this.#b(), this.setup(e);
|
|
310
|
+
}
|
|
311
|
+
#b() {
|
|
312
|
+
this.#e?.destroy(), this.#t?.destroy(), this.#n?.destroy(), this.#r?.destroy(), this.#i?.destroy(), this.#e = this.#t = this.#n = this.#r = this.#i = void 0, this.#a = this.#o = void 0, this.#s = [];
|
|
313
|
+
}
|
|
314
|
+
dispose() {
|
|
315
|
+
this.disposed || (this.disposed = !0, this.#c?.(), this.#c = void 0, this.owner?.sceneOf(this)?.removePlugin(this.name), this.#b(), this.#p.clear(), this.#d = [], this.owner = void 0);
|
|
316
|
+
}
|
|
317
|
+
[Symbol.dispose ?? Symbol()]() {
|
|
318
|
+
this.dispose();
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
//#endregion
|
|
322
|
+
export { u as TerrainDeformation };
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/// <reference lib="esnext.disposable" preserve="true" />
|
|
2
|
+
import type { EngineKernel } from '@margoengine/core';
|
|
3
|
+
import { type Engine, type EnginePlugin } from '@margoengine/core/extension';
|
|
4
|
+
import type { Terrain, TerrainLighting } from './index.js';
|
|
5
|
+
import type { TerrainMaterials } from './layers-pbr.js';
|
|
6
|
+
/** One layer's relief. */
|
|
7
|
+
export interface TerrainLayerRelief {
|
|
8
|
+
/** World depth from the height map's 1 (top) to its 0, 0 to 1. Default the displacement's `depth`. */
|
|
9
|
+
depth?: number;
|
|
10
|
+
}
|
|
11
|
+
/** Settings of {@link TerrainDisplacement.attach}, fixed at attachment. Invalid values throw RangeError. */
|
|
12
|
+
export interface TerrainDisplacementOptions {
|
|
13
|
+
/** World depth of every layer's relief, 0 to 1. Default 0.05 (5 cm). */
|
|
14
|
+
depth?: number;
|
|
15
|
+
/** Per layer depths, in the order of `TerrainOptions.layers` (fewer: the rest take `depth`). */
|
|
16
|
+
layers?: readonly TerrainLayerRelief[];
|
|
17
|
+
/** World distance from the camera within which the relief shows, fading out over its last quarter, above 0. Default 30. */
|
|
18
|
+
distance?: number;
|
|
19
|
+
/** Most search steps a fragment takes (a quarter of them facing the surface), 4 to 64. Default 24. */
|
|
20
|
+
steps?: number;
|
|
21
|
+
/**
|
|
22
|
+
* Whether the relief shadows itself from the sun. Needs square, power-of-two surface maps; adds a maximum mipmap of
|
|
23
|
+
* them (4 bytes per texel per layer, plus a third for its smaller levels). Default true.
|
|
24
|
+
*/
|
|
25
|
+
shadows?: boolean;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Near displacement (parallax occlusion) of a terrain's layer height maps, for a terrain with `TerrainMaterials`:
|
|
29
|
+
* `TerrainDisplacement.attach(engine, terrain, materials, options)` after `TerrainMaterials.attach`; WebGPU only.
|
|
30
|
+
* Ground within `distance` of the camera and no steeper than about 57 degrees shows its relief's depth, occlusion and
|
|
31
|
+
* self-shadow; the outline of the ground against the sky stays the clipmap's (no real geometry moves).
|
|
32
|
+
* @throws RangeError when an option is out of range.
|
|
33
|
+
* @throws MargoError `'unsupported'` when the terrain's shader has no layer materials, or shadows meet surface maps
|
|
34
|
+
* that are not square and a power of two; `'disposed'` after dispose.
|
|
35
|
+
*/
|
|
36
|
+
export declare class TerrainDisplacement implements EnginePlugin, TerrainLighting {
|
|
37
|
+
#private;
|
|
38
|
+
private readonly terrain;
|
|
39
|
+
private readonly materials;
|
|
40
|
+
readonly options: TerrainDisplacementOptions;
|
|
41
|
+
readonly name: string;
|
|
42
|
+
disposed: boolean;
|
|
43
|
+
owner?: Engine;
|
|
44
|
+
private constructor();
|
|
45
|
+
/** Attaches displacement to `terrain`, after its `materials`. `dispose()` removes it. */
|
|
46
|
+
static attach(engine: EngineKernel, terrain: Terrain, materials: TerrainMaterials, options?: TerrainDisplacementOptions): TerrainDisplacement;
|
|
47
|
+
setup(engine: Engine): void;
|
|
48
|
+
/** The group-1 entries the patched shader reads. */
|
|
49
|
+
bindings(): GPUBindGroupEntry[];
|
|
50
|
+
/** The terrain's lit shader (with layer materials) shading the point each near view ray hits (bindings in `group`). */
|
|
51
|
+
shader(source: string, group: number): string;
|
|
52
|
+
/**
|
|
53
|
+
* Moves the sun shadow lookups that effects attached after it added (`@margoengine/shadows` `Shadows` and
|
|
54
|
+
* `VirtualShadows`) to where each displaced point's ray toward the sun leaves the clipmap surface.
|
|
55
|
+
*/
|
|
56
|
+
finish(source: string): string;
|
|
57
|
+
onDeviceRestored(engine: Engine): void;
|
|
58
|
+
dispose(): void;
|
|
59
|
+
[Symbol.dispose]: () => void;
|
|
60
|
+
}
|
package/dist/displace.js
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
// @margo/core-built 0.1.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
const e=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
|
|
4
|
+
import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
|
|
5
|
+
import { MargoError as t } from "@margoengine/math/errors";
|
|
6
|
+
//#region src/displace.ts
|
|
7
|
+
var n = 108, r = 160, i = .02, a = 4, o = "@fragment fn fragment(i:Output)->@location(0) vec4f {return terrainPbrShade(i);}", s = "let dx=dpdx(position);let dy=dpdy(position);", c = "let direct=(", l = `
|
|
8
|
+
@group(GROUP) @binding(109) var terrainDisplaceMax:texture_2d_array<f32>;
|
|
9
|
+
var<private> terrainDisplaceO:array<vec2f,16>;
|
|
10
|
+
fn terrainDisplaceRelief(xz:vec2f)->f32 {
|
|
11
|
+
var sum=0.0;var total=0.0;
|
|
12
|
+
for(var layer=0u;layer<u32(frame.heights.z);layer++){
|
|
13
|
+
let w=terrainDisplaceW[layer];if(w<=0.0){continue;}
|
|
14
|
+
let a=textureSampleLevel(terrainPbrSurfaces,terrainSampler,xz*layerRules[layer].params.x,i32(layer),0.0).a;
|
|
15
|
+
let b=w*exp2(terrainPbrRules[layer].w*(a-1.0));sum+=b*a;total+=b;
|
|
16
|
+
}
|
|
17
|
+
return sum/max(total,0.00001);
|
|
18
|
+
}
|
|
19
|
+
fn terrainDisplaceBound(lo:vec2f,hi:vec2f,reference:f32,top:i32)->f32 {
|
|
20
|
+
var m=0.0;
|
|
21
|
+
for(var layer=0u;layer<u32(frame.heights.z);layer++){
|
|
22
|
+
if(terrainDisplaceW[layer]<=0.0){continue;}
|
|
23
|
+
let r=layerRules[layer].params.x/reference;let a=terrainDisplaceO[layer]+lo*r+0.001;let b=terrainDisplaceO[layer]+hi*r-0.001;
|
|
24
|
+
let level=clamp(i32(ceil(log2(max(max(b.x-a.x,b.y-a.y),1.0)))),0,top);
|
|
25
|
+
let c=exp2(f32(level));let n=vec2i(textureDimensions(terrainDisplaceMax,level));
|
|
26
|
+
let c0=vec2i(floor(a/c));let c1=vec2i(floor(b/c));
|
|
27
|
+
for(var y=c0.y;y<=c1.y;y++){for(var x=c0.x;x<=c1.x;x++){
|
|
28
|
+
m=max(m,textureLoad(terrainDisplaceMax,((vec2i(x,y)%n)+n)%n,i32(layer),level).r);
|
|
29
|
+
}}
|
|
30
|
+
}
|
|
31
|
+
return m;
|
|
32
|
+
}
|
|
33
|
+
fn terrainDisplaceSun(p:vec3f,normal:vec3f,depth:f32)->f32 {
|
|
34
|
+
let l=frame.light.xyz;let up=dot(l,normal);let t=l-normal*up;let run=length(t.xz);
|
|
35
|
+
if(up<=0.0||run<0.0001){return 1.0;}
|
|
36
|
+
let dir=t.xz/run;let side=f32(textureDimensions(terrainDisplaceMax).x);let top=i32(textureNumLevels(terrainDisplaceMax))-1;
|
|
37
|
+
var reference=0.0;var first=0u;var root=0.0;
|
|
38
|
+
for(var layer=0u;layer<u32(frame.heights.z);layer++){
|
|
39
|
+
if(terrainDisplaceW[layer]<=0.0){continue;}
|
|
40
|
+
let s=layerRules[layer].params.x;if(s>reference){reference=s;first=layer;}
|
|
41
|
+
terrainDisplaceO[layer]=fract(p.xz*s)*side-0.5;
|
|
42
|
+
root=max(root,textureLoad(terrainDisplaceMax,vec2i(0),i32(layer),top).r);
|
|
43
|
+
}
|
|
44
|
+
if(reference<=0.0){return 1.0;}
|
|
45
|
+
|
|
46
|
+
let k=reference*side;let rise=up/run/(depth*k);let margin=${i}/(depth*k);let o=terrainDisplaceO[first];
|
|
47
|
+
let h0=terrainDisplaceRelief(p.xz);
|
|
48
|
+
var level=0;var tau=0.0;var lowest=${i};
|
|
49
|
+
for(var i=0;i<${r};i++){
|
|
50
|
+
let ray=h0+rise*tau;if(ray>=root){break;}
|
|
51
|
+
let w=o+dir*tau;let c=exp2(f32(level));let cell=floor((w+dir*0.001)/c)*c;
|
|
52
|
+
let across=select((select(cell,cell+c,dir>vec2f(0.0))-w)/dir,vec2f(1e9),abs(dir)<vec2f(0.000001));
|
|
53
|
+
let exit=tau+max(min(across.x,across.y),0.001);
|
|
54
|
+
if(ray-terrainDisplaceBound(cell-o,cell+c-o,reference,top)>=margin*exit){tau=exit;level=min(level+1,top);continue;}
|
|
55
|
+
if(level>0){level--;continue;}
|
|
56
|
+
for(var j=1;j<=2;j++){
|
|
57
|
+
let at=mix(tau,exit,0.5*f32(j));
|
|
58
|
+
if(at>=0.25){lowest=min(lowest,(h0+rise*at-terrainDisplaceRelief(p.xz+dir*(at/k)))*depth*k/at);}
|
|
59
|
+
}
|
|
60
|
+
if(lowest<=-${i}){break;}
|
|
61
|
+
tau=exit;
|
|
62
|
+
}
|
|
63
|
+
return smoothstep(-${i},${i},lowest);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
fn terrainDisplaceSunArea(p:vec3f,normal:vec3f,depth:f32)->f32 {
|
|
72
|
+
var reference=0.0;
|
|
73
|
+
for(var layer=0u;layer<u32(frame.heights.z);layer++){if(terrainDisplaceW[layer]>0.0){reference=max(reference,layerRules[layer].params.x);}}
|
|
74
|
+
let ax=terrainDisplaceDx.xz;let ay=terrainDisplaceDy.xz;
|
|
75
|
+
let n=clamp(round(max(length(ax),length(ay))*reference*f32(textureDimensions(terrainDisplaceMax).x)),1.0,${a}.0);
|
|
76
|
+
if(n<=1.0){return terrainDisplaceSun(p,normal,depth);}
|
|
77
|
+
var sum=0.0;
|
|
78
|
+
for(var y=0.0;y<n;y+=1.0){for(var x=0.0;x<n;x+=1.0){
|
|
79
|
+
let o=ax*((x+0.5)/n-0.5)+ay*((y+0.5)/n-0.5);sum+=terrainDisplaceSun(p+vec3f(o.x,0.0,o.y),normal,depth);
|
|
80
|
+
}}
|
|
81
|
+
return sum/(n*n);
|
|
82
|
+
}`, u = (e, t, r) => `
|
|
83
|
+
@group(${e}) @binding(${n}) var<uniform> terrainDisplaceRules:array<vec4f,17>;
|
|
84
|
+
var<private> terrainDisplaced:bool;var<private> terrainDisplaceDx:vec3f;var<private> terrainDisplaceDy:vec3f;
|
|
85
|
+
var<private> terrainDisplaceShadow:f32=1.0;var<private> terrainDisplaceW:array<f32,16>;var<private> terrainDisplaceLift:vec3f;
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
fn terrainDisplaceShadowPoint(p:vec3f)->vec3f {return select(p,terrainDisplaceLift,terrainDisplaced);}
|
|
90
|
+
fn terrainDisplaceWeights(position:vec3f,normal:vec3f)->f32 {
|
|
91
|
+
var total=0.0;var depth=0.0;let count=u32(frame.heights.z);${t ? `
|
|
92
|
+
let d=vec2f(textureDimensions(terrainWeights0));let uv=clamp((position.xz-frame.map.xy)/frame.map.zw,vec2f(0.5)/d,vec2f(1)-vec2f(0.5)/d);
|
|
93
|
+
let packed=array<vec4f,4>(${[
|
|
94
|
+
0,
|
|
95
|
+
1,
|
|
96
|
+
2,
|
|
97
|
+
3
|
|
98
|
+
].map((e) => e < t ? `textureSampleLevel(terrainWeights${e},terrainSampler,uv,0)` : "vec4f(0)").join(",")});
|
|
99
|
+
for(var layer=0u;layer<count;layer++){let w=packed[layer/4u][layer%4u];terrainDisplaceW[layer]=w;total+=w;depth+=w*terrainDisplaceRules[layer].x;}` : "\n let slope=1-clamp(normal.y,0.0,1.0);\n for(var layer=0u;layer<count;layer++){\n let rule=layerRules[layer];let hs=rule.heightSlope;let h=rule.params.y;let s=rule.params.z;\n let w=smoothstep(hs.x-h,hs.x+h,position.y)*(1-smoothstep(hs.y-h,hs.y+h,position.y))*smoothstep(hs.z-s,hs.z+s,slope)*(1-smoothstep(hs.w-s,hs.w+s,slope));\n terrainDisplaceW[layer]=w;total+=w;depth+=w*terrainDisplaceRules[layer].x;\n }"}
|
|
100
|
+
if(total<=0.00001){for(var layer=0u;layer<count;layer++){terrainDisplaceW[layer]=0.0;}terrainDisplaceW[0]=1.0;return terrainDisplaceRules[0].x;}
|
|
101
|
+
return depth/total;
|
|
102
|
+
}
|
|
103
|
+
fn terrainDisplaceHeight(xz:vec2f)->f32 {
|
|
104
|
+
var sum=0.0;var total=0.0;
|
|
105
|
+
for(var layer=0u;layer<u32(frame.heights.z);layer++){
|
|
106
|
+
let w=terrainDisplaceW[layer];if(w<=0.0){continue;}
|
|
107
|
+
let s=layerRules[layer].params.x;
|
|
108
|
+
let a=textureSampleGrad(terrainPbrSurfaces,terrainSampler,xz*s,i32(layer),terrainDisplaceDx.xz*s,terrainDisplaceDy.xz*s).a;
|
|
109
|
+
let b=w*exp2(terrainPbrRules[layer].w*(a-1.0));sum+=b*a;total+=b;
|
|
110
|
+
}
|
|
111
|
+
return sum/max(total,0.00001);
|
|
112
|
+
}${r ? l.replace("GROUP", String(e)) : ""}
|
|
113
|
+
fn terrainDisplace(position:vec3f,normal:vec3f)->vec3f {
|
|
114
|
+
terrainDisplaceDx=dpdx(position);terrainDisplaceDy=dpdy(position);
|
|
115
|
+
let settings=terrainDisplaceRules[16];let v=frame.eye.xyz-position;let far=length(v);
|
|
116
|
+
if(far>=settings.x||normal.y<0.55){return position;}
|
|
117
|
+
let depth=terrainDisplaceWeights(position,normal)*(1.0-smoothstep(0.75*settings.x,settings.x,far))*smoothstep(0.55,0.85,normal.y);
|
|
118
|
+
if(depth<=0.0){return position;}
|
|
119
|
+
let e=v/far;let facing=max(dot(e,normal),0.2);let ray=-e/facing;
|
|
120
|
+
let steps=max(round(mix(settings.y,settings.y*0.25,facing)),2.0);let dd=depth/steps;
|
|
121
|
+
var d0=0.0;var f0=-depth*(1.0-terrainDisplaceHeight(position.xz));var d1=0.0;var f1=f0;
|
|
122
|
+
for(var k=1.0;k<=steps;k+=1.0){
|
|
123
|
+
d1=dd*k;f1=d1-depth*(1.0-terrainDisplaceHeight((position+ray*d1).xz));
|
|
124
|
+
if(f1>=0.0){break;}
|
|
125
|
+
d0=d1;f0=f1;
|
|
126
|
+
}
|
|
127
|
+
var hit=d1;if(f1>=0.0&&f1>f0){hit=d0+(d1-d0)*(-f0)/(f1-f0);}
|
|
128
|
+
let p=position+ray*hit;terrainDisplaced=true;
|
|
129
|
+
let l=frame.light.xyz;terrainDisplaceLift=p+l*max(dot(position-p,normal),0.0)/max(dot(l,normal),0.05);${r ? "terrainDisplaceShadow=terrainDisplaceSunArea(p,normal,depth);" : ""}
|
|
130
|
+
return p;
|
|
131
|
+
}`, d = (e) => `
|
|
132
|
+
@group(0) @binding(0) var relief:texture_2d_array<f32>;
|
|
133
|
+
@group(0) @binding(1) var maxima:texture_storage_2d_array<r32float,write>;
|
|
134
|
+
@compute @workgroup_size(8,8) fn main(@builtin(global_invocation_id) id:vec3u) {
|
|
135
|
+
let n=textureDimensions(maxima);if(id.x>=n.x||id.y>=n.y){return;}
|
|
136
|
+
let m=vec2i(textureDimensions(relief));var h=0.0;
|
|
137
|
+
for(var y=0;y<2;y++){for(var x=0;x<2;x++){
|
|
138
|
+
h=max(h,textureLoad(relief,(vec2i(id.xy)*${e ? 1 : 2}+vec2i(x,y))%m,i32(id.z),0).${e ? "a" : "r"});
|
|
139
|
+
}}
|
|
140
|
+
textureStore(maxima,vec2i(id.xy),i32(id.z),vec4f(h));
|
|
141
|
+
}`, f = 0, p = class r {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
|
|
142
|
+
#e;
|
|
143
|
+
#t;
|
|
144
|
+
#n;
|
|
145
|
+
#r;
|
|
146
|
+
#i;
|
|
147
|
+
constructor(e, t, n) {
|
|
148
|
+
this.terrain = e, this.materials = t, this.options = n, this.name = "terrain-displace:" + f++, this.disposed = !1, this.#n = [], this.#i = /* @__PURE__ */ new Map();
|
|
149
|
+
let r = e?.options?.layers?.length;
|
|
150
|
+
if (!r || typeof e.addLighting != "function") throw TypeError("Invalid terrain displacement; pass a Terrain");
|
|
151
|
+
if (typeof t?.bindings != "function" || !("surface" in t)) throw TypeError("Invalid terrain displacement; pass the TerrainMaterials attached to the terrain");
|
|
152
|
+
let i = n ?? {}, a = i.layers ?? [], o = (e) => typeof e == "number" && e >= 0 && e <= 1;
|
|
153
|
+
if (!o(i.depth ?? .05) || !Array.isArray(a) || a.length > r || !a.every((e) => o(e?.depth ?? 0)) || !((i.distance ?? 30) > 0 && Number.isFinite(i.distance ?? 30)) || !Number.isInteger(i.steps ?? 24) || (i.steps ?? 24) < 4 || (i.steps ?? 24) > 64 || typeof (i.shadows ?? !0) != "boolean") throw RangeError("Invalid terrain displacement; give depth 0..1, at most one layers entry per terrain layer with depth 0..1, distance above 0, steps 4..64 and shadows true or false.");
|
|
154
|
+
}
|
|
155
|
+
static attach(t, n, i, a = {}) {__margoAssertCore(t,__margoCoreRequirement("0.1.0",import.meta.url));
|
|
156
|
+
let o = new r(n, i, a);
|
|
157
|
+
return e(t).use(o), o;
|
|
158
|
+
}
|
|
159
|
+
setup(e) {
|
|
160
|
+
if (this.disposed || !e.gpu) throw new t(this.disposed ? "disposed" : "unsupported", "Terrain displacement requires WebGPU and a live module; attach a new one to a WebGPU engine");
|
|
161
|
+
this.owner = e;
|
|
162
|
+
let r = this.options, i = e.gpu, a = /* @__PURE__ */ new Float32Array(68);
|
|
163
|
+
for (let e = 0; e < 16; e++) a[e * 4] = r.layers?.[e]?.depth ?? r.depth ?? .05;
|
|
164
|
+
a.set([
|
|
165
|
+
r.distance ?? 30,
|
|
166
|
+
r.steps ?? 24,
|
|
167
|
+
+(r.shadows ?? !0),
|
|
168
|
+
0
|
|
169
|
+
], 64), this.#e = i.createBuffer({
|
|
170
|
+
size: a.byteLength,
|
|
171
|
+
usage: 72
|
|
172
|
+
}), i.queue.writeBuffer(this.#e, 0, a), this.#n = [{
|
|
173
|
+
binding: n,
|
|
174
|
+
resource: { buffer: this.#e }
|
|
175
|
+
}], (r.shadows ?? !0) && (this.#t = this.#a(i), this.#n.push({
|
|
176
|
+
binding: 109,
|
|
177
|
+
resource: this.#t.createView({ dimension: "2d-array" })
|
|
178
|
+
})), this.#r ??= this.terrain.addLighting(this);
|
|
179
|
+
}
|
|
180
|
+
#a(e) {
|
|
181
|
+
let n = this.materials.surface, r = n?.width ?? 0;
|
|
182
|
+
if (!n) throw new t("unsupported", "Terrain displacement needs live TerrainMaterials; attach TerrainMaterials first");
|
|
183
|
+
if (n.height !== r || r < 1 || r & r - 1) throw new t("unsupported", "Terrain displacement shadows need square, power-of-two surface maps; resize them or pass shadows: false");
|
|
184
|
+
let i = Math.log2(r) + 1, a = n.depthOrArrayLayers, o = e.createTexture({
|
|
185
|
+
size: [
|
|
186
|
+
r,
|
|
187
|
+
r,
|
|
188
|
+
a
|
|
189
|
+
],
|
|
190
|
+
format: "r32float",
|
|
191
|
+
mipLevelCount: i,
|
|
192
|
+
usage: 12
|
|
193
|
+
}), s = [!0, !1].map((t) => e.createComputePipeline({
|
|
194
|
+
layout: "auto",
|
|
195
|
+
compute: {
|
|
196
|
+
module: e.createShaderModule({ code: d(t) }),
|
|
197
|
+
entryPoint: "main"
|
|
198
|
+
}
|
|
199
|
+
})), c = e.createCommandEncoder(), l = c.beginComputePass();
|
|
200
|
+
for (let t = 0; t < i; t++) {
|
|
201
|
+
let i = s[+!!t], c = Math.ceil((r >> t) / 8);
|
|
202
|
+
l.setPipeline(i), l.setBindGroup(0, e.createBindGroup({
|
|
203
|
+
layout: i.getBindGroupLayout(0),
|
|
204
|
+
entries: [{
|
|
205
|
+
binding: 0,
|
|
206
|
+
resource: (t ? o : n).createView({
|
|
207
|
+
dimension: "2d-array",
|
|
208
|
+
baseMipLevel: Math.max(t - 1, 0),
|
|
209
|
+
mipLevelCount: 1
|
|
210
|
+
})
|
|
211
|
+
}, {
|
|
212
|
+
binding: 1,
|
|
213
|
+
resource: o.createView({
|
|
214
|
+
dimension: "2d-array",
|
|
215
|
+
baseMipLevel: t,
|
|
216
|
+
mipLevelCount: 1
|
|
217
|
+
})
|
|
218
|
+
}]
|
|
219
|
+
})), l.dispatchWorkgroups(c, c, a);
|
|
220
|
+
}
|
|
221
|
+
return l.end(), e.queue.submit([c.finish()]), o;
|
|
222
|
+
}
|
|
223
|
+
bindings() {
|
|
224
|
+
return this.#n;
|
|
225
|
+
}
|
|
226
|
+
shader(e, n) {
|
|
227
|
+
let r = n + e, i = this.#i.get(r);
|
|
228
|
+
if (i) return i;
|
|
229
|
+
if (!e.includes("terrainPbrSurfaces") || [
|
|
230
|
+
o,
|
|
231
|
+
s,
|
|
232
|
+
c
|
|
233
|
+
].some((t) => e.split(t).length !== 2)) throw new t("unsupported", "Terrain displacement needs the terrain lit shader with TerrainMaterials; attach TerrainMaterials first");
|
|
234
|
+
let a = [...e.matchAll(/var terrainWeights(\d):texture_2d<f32>;/g)].length, l = u(n, a, this.options.shadows ?? !0), d = (e.includes("wrap:vec4f") ? l.replace("fract(p.xz*s)", "fract((p.xz+layerRules[layer].wrap.xz)*s)").replace("xz*s,i32(layer)", "(xz+layerRules[layer].wrap.xz)*s,i32(layer)").replace("xz*layerRules[layer].params.x,i32(layer)", "(xz+layerRules[layer].wrap.xz)*layerRules[layer].params.x,i32(layer)") : l) + e.replace(o, "@fragment fn fragment(i:Output)->@location(0) vec4f {var j=i;j.position=terrainDisplace(i.position,normalize(i.normal));return terrainPbrShade(j);}").replace(s, "var dx=dpdx(position);var dy=dpdy(position);if(terrainDisplaced){dx=terrainDisplaceDx;dy=terrainDisplaceDy;}").replace(c, "let direct=terrainDisplaceShadow*(");
|
|
235
|
+
return this.#i.size >= 16 && this.#i.clear(), this.#i.set(r, d), d;
|
|
236
|
+
}
|
|
237
|
+
finish(e) {
|
|
238
|
+
return e.includes("fn terrainDisplaceShadowPoint") ? e.replace(/shadowLit\(([^,()]+),i\.position,/g, "shadowLit($1,terrainDisplaceShadowPoint(i.position),") : e;
|
|
239
|
+
}
|
|
240
|
+
onDeviceRestored(e) {
|
|
241
|
+
this.#o(), this.setup(e);
|
|
242
|
+
}
|
|
243
|
+
#o() {
|
|
244
|
+
this.#e?.destroy(), this.#t?.destroy(), this.#e = this.#t = void 0, this.#n = [];
|
|
245
|
+
}
|
|
246
|
+
dispose() {
|
|
247
|
+
this.disposed || (this.disposed = !0, this.#r?.(), this.#r = void 0, this.owner?.sceneOf(this)?.removePlugin(this.name), this.#o(), this.#i.clear(), this.owner = void 0);
|
|
248
|
+
}
|
|
249
|
+
[Symbol.dispose ?? Symbol()]() {
|
|
250
|
+
this.dispose();
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
//#endregion
|
|
254
|
+
export { p as TerrainDisplacement };
|