@zaisma/effects 1.1.0 → 2.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.
package/batches/shared.js CHANGED
@@ -1,6 +1,9 @@
1
1
  // What every batch's shader reads: the effects' clock, the wind, the scene's light and the flash lights, the weather's
2
- // boxes and the shelter map. One set of values, written once a frame, shared by reference by every batch's material.
3
- import * as THREE from "three";
2
+ // boxes and the shelter map. One set of values, written once a frame and sent once a frame (three's render group),
3
+ // shared by every batch's material. Written in three's shading language (TSL), so the same code draws on WebGPU and
4
+ // on WebGL 2.
5
+ import * as THREE from "three/webgpu";
6
+ import { Fn, If, Loop, cameraPosition, dot, exp, float, int, inverseSqrt, ivec2, length, mix, mrt, output, renderGroup, smoothstep, texture, uniform, uniformArray, vec2, vec4 } from "three/tsl";
4
7
 
5
8
  /** How many flash lights reach the particles themselves; the scene's own lights are the flash pool's. */
6
9
  export const PARTICLE_FLASH_COUNT = 4;
@@ -8,136 +11,157 @@ export const PARTICLE_FLASH_COUNT = 4;
8
11
  export const WRAP_LAYER_COUNT = 4;
9
12
  export const LANDING_LAYER_INDEX = 3;
10
13
 
11
- export function createSharedUniforms() {
14
+ /**
15
+ * How fast added light falls off toward a shape's soft edge. 1 is light as it adds up in the world, where one
16
+ * faint glow already lifts a dark scene; 2.2 is how the eye would read a single one, where many stacked (a fire)
17
+ * come out dull. Between the two, a halo stays a halo and a fire still burns white where its flames pile up.
18
+ */
19
+ const ADD_FALLOFF_NUMBER = 1.25;
20
+
21
+ const shared = (...given) => uniform(...given).setGroup(renderGroup);
22
+ const sharedList = (values) => uniformArray(values).setGroup(renderGroup);
23
+
24
+ /** A picture of one texel, to stand in until the real one is made. */
25
+ function blankPicture(typeNumber, values) {
26
+ const picture = new THREE.DataTexture(values, 1, 1, THREE.RGBAFormat, typeNumber);
27
+ picture.minFilter = THREE.NearestFilter;
28
+ picture.magFilter = THREE.NearestFilter;
29
+ picture.needsUpdate = true;
30
+ return picture;
31
+ }
32
+
33
+ /**
34
+ * The values. Each is a node with a `value` to write (a list's values are in its `array`). airAt: the lighting
35
+ * piece's air, when the game has it (lighting.airAt); without it, three's own fog on the scene is followed.
36
+ */
37
+ export function createSharedUniforms({ airAt = null } = {}) {
12
38
  const vectors = (vectorCount, make) => Array.from({ length: vectorCount }, make);
13
- return {
14
- uElements: { value: null },
15
- uPlays: { value: null },
16
- uAtlas: { value: null },
17
- uTime: { value: 0 },
39
+ const blanks = [blankPicture(THREE.FloatType, new Float32Array(4)), blankPicture(THREE.FloatType, new Float32Array(4)), blankPicture(THREE.UnsignedByteType, new Uint8Array([128, 255, 255, 255])), blankPicture(THREE.HalfFloatType, new Uint16Array(4))];
40
+ const uniforms = {
41
+ uElements: texture(blanks[0]),
42
+ uPlays: texture(blanks[1]),
43
+ uAtlas: texture(blanks[2]),
44
+ uTime: shared(0),
18
45
  // The weather's own clock, which never steps back as uTime does when the effects' clock starts over.
19
- uWeatherTime: { value: 0 },
20
- uWind: { value: new THREE.Vector3() },
21
- uSunDirection: { value: new THREE.Vector3(0.3, 0.8, 0.5).normalize() },
22
- uSunColor: { value: new THREE.Color(3, 3, 3) },
23
- uSkyColor: { value: new THREE.Color(1, 1, 1) },
24
- uGroundColor: { value: new THREE.Color(0.4, 0.4, 0.4) },
25
- // The sun's shadow map, as three drew it for the scene: what turns a place in the world into a place in it, how
26
- // much of the sun a shadow takes (0 when there's none to read), and how far apart its four readings are taken.
27
- uSunShadow: { value: null },
28
- uSunShadowMatrix: { value: new THREE.Matrix4() },
29
- uSunShadowShare: { value: 0 },
30
- uSunShadowSpread: { value: 0 },
31
- uFlashPlace: { value: vectors(PARTICLE_FLASH_COUNT, () => new THREE.Vector4(0, 0, 0, 1)) },
32
- uFlashColor: { value: vectors(PARTICLE_FLASH_COUNT, () => new THREE.Color(0, 0, 0)) },
33
- uWrapCenter: { value: vectors(WRAP_LAYER_COUNT, () => new THREE.Vector3()) },
34
- uWrapShift: { value: vectors(WRAP_LAYER_COUNT, () => new THREE.Vector3()) },
35
- uWrapBox: { value: vectors(WRAP_LAYER_COUNT, () => new THREE.Vector3(1, 1, 1)) },
36
- uWrapVelocity: { value: vectors(WRAP_LAYER_COUNT, () => new THREE.Vector3()) },
37
- uWrapShare: { value: new Array(WRAP_LAYER_COUNT).fill(0) },
38
- uShelter: { value: null },
46
+ uWeatherTime: shared(0),
47
+ uWind: shared(new THREE.Vector3()),
48
+ uSunDirection: shared(new THREE.Vector3(0.3, 0.8, 0.5).normalize()),
49
+ uSunColor: shared(new THREE.Color(3, 3, 3)),
50
+ uSkyColor: shared(new THREE.Color(1, 1, 1)),
51
+ uGroundColor: shared(new THREE.Color(0.4, 0.4, 0.4)),
52
+ uFlashPlace: sharedList(vectors(PARTICLE_FLASH_COUNT, () => new THREE.Vector4(0, 0, 0, 1))),
53
+ uFlashColor: sharedList(vectors(PARTICLE_FLASH_COUNT, () => new THREE.Color(0, 0, 0))),
54
+ uWrapCenter: sharedList(vectors(WRAP_LAYER_COUNT, () => new THREE.Vector3())),
55
+ uWrapShift: sharedList(vectors(WRAP_LAYER_COUNT, () => new THREE.Vector3())),
56
+ uWrapBox: sharedList(vectors(WRAP_LAYER_COUNT, () => new THREE.Vector3(1, 1, 1))),
57
+ uWrapVelocity: sharedList(vectors(WRAP_LAYER_COUNT, () => new THREE.Vector3())),
58
+ uWrapShare: sharedList(new Array(WRAP_LAYER_COUNT).fill(0)),
59
+ uShelter: texture(blanks[3]),
39
60
  // The shelter map's centre (x, z), how many metres across it is, and whether it's on (1 or 0).
40
- uShelterBox: { value: new THREE.Vector4(0, 0, 1, 0) },
61
+ uShelterBox: shared(new THREE.Vector4(0, 0, 1, 0)),
41
62
  // What the shelter map's heights are counted from, in metres: a height of 0 in it means nothing is there.
42
- uShelterBaseM: { value: 0 },
43
- uGroundHeightM: { value: 0 },
63
+ uShelterBaseM: shared(0),
64
+ uGroundHeightM: shared(0),
44
65
  // Pixels a metre covers at one metre away: what a particle too small to see is dropped by. 0 for a camera with no perspective.
45
- uPxPerM: { value: 0 },
66
+ uPxPerM: shared(0),
67
+ // three's own fog on the scene, for a game without the lighting piece: its colour, and where it starts, where
68
+ // it ends, how dense it is and its kind (0 none, 1 by distance, 2 by density).
69
+ uFogColor: shared(new THREE.Color(0, 0, 0)),
70
+ uFogRange: shared(new THREE.Vector4(0, 1, 0, 0)),
46
71
  };
47
- }
48
72
 
49
- /** The declarations of those values, for a vertex shader. */
50
- export const SHARED_VERTEX_GLSL = /* glsl */ `
51
- uniform highp sampler2D uElements;
52
- uniform highp sampler2D uPlays;
53
- uniform float uTime;
54
- uniform float uWeatherTime;
55
- uniform vec3 uWind;
56
- uniform vec3 uSunDirection;
57
- uniform vec3 uSunColor;
58
- uniform vec3 uSkyColor;
59
- uniform vec3 uGroundColor;
60
- uniform highp sampler2DShadow uSunShadow;
61
- uniform mat4 uSunShadowMatrix;
62
- uniform float uSunShadowShare;
63
- uniform float uSunShadowSpread;
64
- uniform vec4 uFlashPlace[${PARTICLE_FLASH_COUNT}];
65
- uniform vec3 uFlashColor[${PARTICLE_FLASH_COUNT}];
66
- uniform vec3 uWrapCenter[${WRAP_LAYER_COUNT}];
67
- uniform vec3 uWrapShift[${WRAP_LAYER_COUNT}];
68
- uniform vec3 uWrapBox[${WRAP_LAYER_COUNT}];
69
- uniform vec3 uWrapVelocity[${WRAP_LAYER_COUNT}];
70
- uniform float uWrapShare[${WRAP_LAYER_COUNT}];
71
- uniform highp sampler2D uShelter;
72
- uniform vec4 uShelterBox;
73
- uniform float uShelterBaseM;
74
- uniform float uGroundHeightM;
75
- uniform float uPxPerM;
76
-
77
- vec4 zaismaElement(int row, int texel) { return texelFetch(uElements, ivec2(texel, row), 0); }
78
- vec4 zaismaPlay(int row, int texel) { return texelFetch(uPlays, ivec2(texel, row), 0); }
79
-
80
- // How much of the sun reaches a place: 1 in the open, less inside a shadow the scene's own things cast. Four
81
- // readings a little apart, so smoke drifting into a shadow darkens over a step and not at a line.
82
- float zaismaSunShare(vec3 place) {
83
- if (uSunShadowShare <= 0.0) return 1.0;
84
- vec4 at = uSunShadowMatrix * vec4(place, 1.0);
85
- at.xyz /= at.w;
86
- if (at.x < 0.0 || at.x > 1.0 || at.y < 0.0 || at.y > 1.0 || at.z > 1.0) return 1.0;
87
- float depth = at.z - 0.0015;
88
- float lit = texture(uSunShadow, vec3(at.xy + vec2(uSunShadowSpread, uSunShadowSpread * 0.4), depth))
89
- + texture(uSunShadow, vec3(at.xy + vec2(-uSunShadowSpread * 0.4, uSunShadowSpread), depth))
90
- + texture(uSunShadow, vec3(at.xy - vec2(uSunShadowSpread, uSunShadowSpread * 0.4), depth))
91
- + texture(uSunShadow, vec3(at.xy + vec2(uSunShadowSpread * 0.4, -uSunShadowSpread), depth));
92
- return mix(1.0, lit * 0.25, uSunShadowShare);
93
- }
73
+ /** A texel of an element's row, and of a play's row. row: an int node; texel: a number or an int node. */
74
+ const element = (row, texel) => uniforms.uElements.load(ivec2(int(texel), row));
75
+ const play = (row, texel) => uniforms.uPlays.load(ivec2(int(texel), row));
76
+
77
+ /**
78
+ * The light that falls on something at a place, facing a way: the sky's and the ground's fill, the sun, and the
79
+ * flash lights near it. As three's own lights give it, so a lit particle sits in the scene's light.
80
+ */
81
+ const lightAt = Fn(([place, facing, wrapShare]) => {
82
+ const light = mix(uniforms.uGroundColor, uniforms.uSkyColor, facing.y.mul(0.5).add(0.5)).toVar();
83
+ const toSun = dot(facing, uniforms.uSunDirection);
84
+ light.addAssign(uniforms.uSunColor.mul(mix(toSun.max(0.0), toSun.mul(0.5).add(0.5), wrapShare)));
85
+ Loop(PARTICLE_FLASH_COUNT, ({ i }) => {
86
+ const flash = uniforms.uFlashPlace.element(i);
87
+ const toFlash = flash.xyz.sub(place).toVar();
88
+ const distanceSquared = dot(toFlash, toFlash).toVar();
89
+ const reach = distanceSquared.div(flash.w.mul(flash.w)).oneMinus().clamp();
90
+ const facingShare = mix(dot(facing, toFlash.mul(inverseSqrt(distanceSquared.add(1e-4)))).max(0.0), 1.0, wrapShare);
91
+ light.addAssign(uniforms.uFlashColor.element(i).mul(reach.mul(reach).mul(facingShare).div(distanceSquared.max(0.25))));
92
+ });
93
+ return light.mul(0.31831);
94
+ });
94
95
 
95
- // The light that falls on something at a place, facing a way: the sky's and the ground's fill, the sun, and the
96
- // flash lights near it. As three's own lights give it, so a lit particle sits in the scene's light.
97
- vec3 zaismaLightAt(vec3 place, vec3 facing, float wrapShare) {
98
- vec3 light = mix(uGroundColor, uSkyColor, 0.5 + 0.5 * facing.y);
99
- float toSun = dot(facing, uSunDirection);
100
- light += uSunColor * (mix(max(toSun, 0.0), 0.5 + 0.5 * toSun, wrapShare) * zaismaSunShare(place));
101
- for (int i = 0; i < ${PARTICLE_FLASH_COUNT}; i++) {
102
- vec3 toFlash = uFlashPlace[i].xyz - place;
103
- float distanceSquared = dot(toFlash, toFlash);
104
- float reach = clamp(1.0 - distanceSquared / (uFlashPlace[i].w * uFlashPlace[i].w), 0.0, 1.0);
105
- float facingShare = mix(max(dot(facing, toFlash * inversesqrt(distanceSquared + 1e-4)), 0.0), 1.0, wrapShare);
106
- light += uFlashColor[i] * (reach * reach * facingShare / max(distanceSquared, 0.25));
107
- }
108
- return light * 0.31831;
96
+ /** The roof over a place: the height nothing falls below, from the shelter map, or the ground's height without one. */
97
+ const roofHeightM = Fn(([placeXZ]) => {
98
+ const height = float(uniforms.uGroundHeightM).toVar();
99
+ If(uniforms.uShelterBox.w.greaterThan(0.5), () => {
100
+ // The map is drawn from above with -z up the picture, and a picture's own y runs down.
101
+ const mapPlace = placeXZ.sub(uniforms.uShelterBox.xy).div(uniforms.uShelterBox.z).add(0.5).toVar();
102
+ If(mapPlace.x.greaterThanEqual(0.0).and(mapPlace.x.lessThanEqual(1.0)).and(mapPlace.y.greaterThanEqual(0.0)).and(mapPlace.y.lessThanEqual(1.0)), () => {
103
+ const held = uniforms.uShelter.sample(mapPlace).level(0).r.toVar();
104
+ If(held.greaterThanEqual(0.5), () => {
105
+ height.assign(held.add(uniforms.uShelterBaseM));
106
+ });
107
+ });
108
+ });
109
+ return height;
110
+ });
111
+
112
+ /**
113
+ * The air between the camera and a place: rgb the light the air adds, a the share of the thing's own light that
114
+ * comes through. What's seen is color * a + rgb.
115
+ */
116
+ const ownAirAt = Fn(([place]) => {
117
+ const distanceM = length(place.sub(cameraPosition));
118
+ const kind = uniforms.uFogRange.w;
119
+ const byDistance = smoothstep(uniforms.uFogRange.x, uniforms.uFogRange.y, distanceM);
120
+ const byDensity = exp(distanceM.mul(distanceM).mul(uniforms.uFogRange.z).mul(uniforms.uFogRange.z).negate()).oneMinus();
121
+ const hidden = kind.lessThan(0.5).select(0.0, kind.lessThan(1.5).select(byDistance, byDensity));
122
+ return vec4(uniforms.uFogColor.mul(hidden), hidden.oneMinus());
123
+ });
124
+
125
+ /**
126
+ * The end of a fragment shader that blends as the sprites do. plain: the plain colour and how solid it is.
127
+ * addShare: how much of it is light added to what's behind it. air: what airAt answered for its place. The air
128
+ * dims what's added and fogs what covers, then the colour is made ready for one blend that serves both smoke and
129
+ * fire.
130
+ *
131
+ * The picture is blended as light (and fitted to the screen afterwards, by the renderer), where a faint glow
132
+ * adds far more than it does to the eye. So added light falls off toward a shape's soft edge as the eye sees it,
133
+ * and only where the shape is nearly solid does it keep light brighter than white: a fire's core blooms, and
134
+ * its halo stays a halo.
135
+ */
136
+ const blendEnd = (plain, addShare, air) => {
137
+ const add = float(addShare);
138
+ const held = vec4(plain).toVar();
139
+ const lit = held.rgb.mul(air.a).toVar();
140
+ const solid = held.a;
141
+ // Fitted to the screen's range one colour at a time, as a hot thing is seen: its strongest colour tops out
142
+ // first, so orange fire goes yellow, then white.
143
+ const fitted = exp(lit.negate()).oneMinus();
144
+ const added = mix(fitted, lit, solid.mul(solid)).mul(solid.pow(ADD_FALLOFF_NUMBER));
145
+ const covering = lit.add(air.rgb).mul(solid);
146
+ return vec4(mix(covering, added, add), solid.mul(add.oneMinus()));
147
+ };
148
+
149
+ return { ...uniforms, element, play, lightAt, roofHeightM, airAt: airAt ?? ownAirAt, blendEnd, blanks };
109
150
  }
110
151
 
111
- // The roof over a place: the height nothing falls below, from the shelter map, or the ground's height without one.
112
- float zaismaRoofHeightM(vec2 placeXZ) {
113
- if (uShelterBox.w < 0.5) return uGroundHeightM;
114
- // The map is drawn from above with -z up the picture.
115
- vec2 at = vec2(placeXZ.x - uShelterBox.x, uShelterBox.y - placeXZ.y) / uShelterBox.z + 0.5;
116
- if (at.x < 0.0 || at.x > 1.0 || at.y < 0.0 || at.y > 1.0) return uGroundHeightM;
117
- float held = texture2D(uShelter, at).r;
118
- return held < 0.5 ? uGroundHeightM : held + uShelterBaseM;
152
+ /** Follows three's own fog on a scene, for a game without the lighting piece. */
153
+ export function readSceneFog(sharedUniforms, scene) {
154
+ const fog = scene.fog;
155
+ if (fog?.isFog) {
156
+ sharedUniforms.uFogColor.value.copy(fog.color);
157
+ sharedUniforms.uFogRange.value.set(fog.near, fog.far, 0, 1);
158
+ } else if (fog?.isFogExp2) {
159
+ sharedUniforms.uFogColor.value.copy(fog.color);
160
+ sharedUniforms.uFogRange.value.set(0, 1, fog.density, 2);
161
+ } else sharedUniforms.uFogRange.value.w = 0;
119
162
  }
120
- `;
121
163
 
122
- /**
123
- * The end of a fragment shader that blends as the sprites do: gl_FragColor holds the plain colour and how solid it
124
- * is; addShare says how much of it is light added to what's behind it. Fog, tone mapping and the screen's colour
125
- * space are applied as three applies them to its own materials, then the colour is made ready for one blend that
126
- * serves both smoke and fire.
127
- */
128
- export const BLEND_END_GLSL = /* glsl */ `
129
- vec3 zaismaPlainColor = gl_FragColor.rgb;
130
- float zaismaSolid = gl_FragColor.a;
131
- #include <fog_fragment>
132
- #ifdef USE_FOG
133
- gl_FragColor.rgb = mix(gl_FragColor.rgb, zaismaPlainColor * (1.0 - fogFactor), zaismaAddShare);
134
- #endif
135
- #include <tonemapping_fragment>
136
- #include <colorspace_fragment>
137
- gl_FragColor = vec4(gl_FragColor.rgb * zaismaSolid, zaismaSolid * (1.0 - zaismaAddShare));
138
- `;
139
-
140
- /** A material's settings for that one blend: colour already multiplied by how solid it is. */
164
+ /** A material's settings for the one blend: colour already multiplied by how solid it is. */
141
165
  export const ONE_BLEND = {
142
166
  transparent: true,
143
167
  depthWrite: false,
@@ -149,7 +173,29 @@ export const ONE_BLEND = {
149
173
  blendDstAlpha: THREE.OneMinusSrcAlphaFactor,
150
174
  };
151
175
 
152
- /** three's fog values for a shader material, so the scene's fog (and the lighting piece's, when it's there) reaches it. */
153
- export function fogUniforms() {
154
- return THREE.UniformsUtils.clone(THREE.UniformsLib.fog);
176
+ const KEEP_BLEND = new THREE.BlendMode(THREE.CustomBlending);
177
+ KEEP_BLEND.blendSrc = THREE.ZeroFactor;
178
+ KEEP_BLEND.blendDst = THREE.OneFactor;
179
+ KEEP_BLEND.blendSrcAlpha = THREE.ZeroFactor;
180
+ KEEP_BLEND.blendDstAlpha = THREE.OneFactor;
181
+
182
+ /**
183
+ * For a see-through material drawn into a picture that also keeps each surface's normal (the lighting piece's,
184
+ * for outlines and corner shade): the normals behind it are left as they are, so smoke never gets an outline.
185
+ */
186
+ export function leaveNormals(material) {
187
+ material.mrtNode = mrt({ output, normal: vec4(0.0) }).setBlendMode("normal", KEEP_BLEND);
188
+ return material;
189
+ }
190
+
191
+ /** A material every batch starts from: drawn by its own nodes, with no light or fog from three. */
192
+ export function batchMaterial(name, settings = {}) {
193
+ const material = new THREE.NodeMaterial();
194
+ material.name = name;
195
+ material.lights = false;
196
+ material.fog = false;
197
+ // Both faces in one pass: three would otherwise draw a see-through two-sided material twice.
198
+ material.forceSinglePass = true;
199
+ Object.assign(material, settings);
200
+ return material;
155
201
  }