Merge branch 'engine-fixes' into 'master'
WebGL rendering, layers, bloom, and builtin effect shaders See merge request Timfa/frameworkv3!8
@@ -1,24 +1,4 @@
1
1
#!/usr/bin/env bash
2
BUILD_FILE="../js/framework.js"
3
SRC_DIR="../framework"
4
5
printf "Build started, output file: $BUILD_FILE\n"
6
unlink $BUILD_FILE
7
8
loop() {
9
shopt -s nullglob
10
shopt -s globstar
11
12
for file in "$@"/**
13
do
14
if [[ -f "$file" && "${file##*.}" = "js" ]]
15
then
16
printf "\n/*\n * Start File:\n * "$file"\n */ \n" >> "$BUILD_FILE";
17
printf "Building "$file"\n";
18
cat "$file" >> "$BUILD_FILE";
19
printf "\n/*\n * End File:\n * "$file"\n */ \n" >> "$BUILD_FILE";
20
fi
21
done
22
}
23
loop $SRC_DIR
24
printf "DONE"
2
# Keep in sync with ../glbuild.sh — VS Code tasks may call this path.
3
cd "$(dirname "$0")/.."
4
exec ./glbuild.sh
@@ -1,24 +1,4 @@1
#!/usr/bin/env bash1
#!/usr/bin/env bash2
BUILD_FILE="../js/framework.js"2
# Keep in sync with ../glbuild.sh — VS Code tasks may call this path.3
SRC_DIR="../framework"3
cd "$(dirname "$0")/.."4
4
exec ./glbuild.sh5
printf "Build started, output file: $BUILD_FILE\n"6
unlink $BUILD_FILE7
8
loop() {9
shopt -s nullglob10
shopt -s globstar11
12
for file in "$@"/**13
do14
if [[ -f "$file" && "${file##*.}" = "js" ]]15
then16
printf "\n/*\n * Start File:\n * "$file"\n */ \n" >> "$BUILD_FILE"; 17
printf "Building "$file"\n";18
cat "$file" >> "$BUILD_FILE"; 19
printf "\n/*\n * End File:\n * "$file"\n */ \n" >> "$BUILD_FILE"; 20
fi21
done22
}23
loop $SRC_DIR24
printf "DONE"@@ -8,6 +8,7 @@ class Game
8
8
rafId = null;
9
9
10
10
images = {};
11
shaders = {};
11
12
12
13
constructor ()
13
14
{
@@ -15,6 +16,7 @@ class Game
15
16
this.activeScenes = [];
16
17
this.isRunning = false;
17
18
this.rafId = null;
19
this.shaders = {};
18
20
this.update = this.update.bind(this);
19
21
}
20
22
@@ -117,6 +119,56 @@ class Game
117
119
return this.images;
118
120
}
119
121
122
async preloadShaders (shadersData)
123
{
124
const context = this;
125
const promises = [];
126
127
for (const shaderData of shadersData)
128
{
129
if (!shaderData || !shaderData.name)
130
{ throw new Error("preloadShaders: each entry needs a name"); }
131
132
if (!shaderData.frag)
133
{ throw new Error("preloadShaders: '" + shaderData.name + "' needs a frag path"); }
134
135
if (context.shaders[shaderData.name])
136
{ console.warn("Shader '" + shaderData.name + "' is already loaded! (overwriting anyway)"); }
137
138
promises.push((async () =>
139
{
140
let vertSource = shaderData.screen ? Shader.SCREEN_VERT : Shader.DEFAULT_VERT;
141
142
if (shaderData.vert)
143
{
144
const vertResponse = await fetch(shaderData.vert);
145
if (!vertResponse.ok)
146
{
147
throw new Error("Failed to load vertex shader '" + shaderData.name + "' from " + shaderData.vert);
148
}
149
150
vertSource = await vertResponse.text();
151
}
152
153
const fragResponse = await fetch(shaderData.frag);
154
if (!fragResponse.ok)
155
{
156
throw new Error("Failed to load fragment shader '" + shaderData.name + "' from " + shaderData.frag);
157
}
158
159
const fragSource = await fragResponse.text();
160
const shader = new Shader(vertSource, fragSource);
161
shader.name = shaderData.name;
162
shader.screen = !!shaderData.screen || vertSource === Shader.SCREEN_VERT;
163
context.shaders[shaderData.name] = shader;
164
})());
165
}
166
167
await Promise.all(promises);
168
console.log("all shaders loaded ", this.shaders);
169
return this.shaders;
170
}
171
120
172
loadScene (scene)
121
173
{
122
174
if (this.activeScenes.length == 0)
@@ -8,6 +8,7 @@ class Game8
rafId = null;8
rafId = null;9
9
10
images = {};10
images = {};11
shaders = {};11
12
12
constructor ()13
constructor ()13
{14
{@@ -15,6 +16,7 @@ class Game15
this.activeScenes = [];16
this.activeScenes = [];16
this.isRunning = false;17
this.isRunning = false;17
this.rafId = null;18
this.rafId = null;19
this.shaders = {};18
this.update = this.update.bind(this);20
this.update = this.update.bind(this);19
}21
}20
22
@@ -117,6 +119,56 @@ class Game117
return this.images;119
return this.images;118
}120
}119
121
122
async preloadShaders (shadersData)123
{124
const context = this;125
const promises = [];126
127
for (const shaderData of shadersData)128
{129
if (!shaderData || !shaderData.name)130
{ throw new Error("preloadShaders: each entry needs a name"); }131
132
if (!shaderData.frag)133
{ throw new Error("preloadShaders: '" + shaderData.name + "' needs a frag path"); }134
135
if (context.shaders[shaderData.name])136
{ console.warn("Shader '" + shaderData.name + "' is already loaded! (overwriting anyway)"); }137
138
promises.push((async () =>139
{140
let vertSource = shaderData.screen ? Shader.SCREEN_VERT : Shader.DEFAULT_VERT;141
142
if (shaderData.vert)143
{144
const vertResponse = await fetch(shaderData.vert);145
if (!vertResponse.ok)146
{147
throw new Error("Failed to load vertex shader '" + shaderData.name + "' from " + shaderData.vert);148
}149
150
vertSource = await vertResponse.text();151
}152
153
const fragResponse = await fetch(shaderData.frag);154
if (!fragResponse.ok)155
{156
throw new Error("Failed to load fragment shader '" + shaderData.name + "' from " + shaderData.frag);157
}158
159
const fragSource = await fragResponse.text();160
const shader = new Shader(vertSource, fragSource);161
shader.name = shaderData.name;162
shader.screen = !!shaderData.screen || vertSource === Shader.SCREEN_VERT;163
context.shaders[shaderData.name] = shader;164
})());165
}166
167
await Promise.all(promises);168
console.log("all shaders loaded ", this.shaders);169
return this.shaders;170
}171
120
loadScene (scene)172
loadScene (scene)121
{173
{122
if (this.activeScenes.length == 0)174
if (this.activeScenes.length == 0)@@ -0,0 +1,386 @@
1
// Built-in screen-space / effect shaders. Games can use these without fetching files.
2
// Expand this set over time into the default framework shader bundle.
3
4
Shader.Builtin = Shader.Builtin || {};
5
6
Shader.Builtin.BLOOM_BRIGHT_FRAG = [
7
"precision mediump float;",
8
"uniform sampler2D u_texture;",
9
"uniform float u_threshold;",
10
"uniform float u_softKnee;",
11
"varying vec2 v_texCoord;",
12
"void main() {",
13
" vec4 color = texture2D(u_texture, v_texCoord);",
14
" float lum = dot(color.rgb, vec3(0.299, 0.587, 0.114));",
15
" float knee = max(u_softKnee, 0.001);",
16
" float soft = smoothstep(u_threshold, u_threshold + knee, lum);",
17
" gl_FragColor = vec4(color.rgb * soft, 1.0);",
18
"}"
19
].join("\n");
20
21
// Max-filter dilate: fattens 1–4px hotspots so later blur has something to spread.
22
Shader.Builtin.BLOOM_DILATE_FRAG = [
23
"precision mediump float;",
24
"uniform sampler2D u_texture;",
25
"uniform vec2 u_resolution;",
26
"uniform float u_radius;",
27
"varying vec2 v_texCoord;",
28
"void main() {",
29
" vec2 px = u_radius / max(u_resolution, vec2(1.0));",
30
" vec4 c = texture2D(u_texture, v_texCoord);",
31
" c = max(c, texture2D(u_texture, v_texCoord + vec2(px.x, 0.0)));",
32
" c = max(c, texture2D(u_texture, v_texCoord - vec2(px.x, 0.0)));",
33
" c = max(c, texture2D(u_texture, v_texCoord + vec2(0.0, px.y)));",
34
" c = max(c, texture2D(u_texture, v_texCoord - vec2(0.0, px.y)));",
35
" c = max(c, texture2D(u_texture, v_texCoord + px));",
36
" c = max(c, texture2D(u_texture, v_texCoord - px));",
37
" c = max(c, texture2D(u_texture, v_texCoord + vec2(px.x, -px.y)));",
38
" c = max(c, texture2D(u_texture, v_texCoord + vec2(-px.x, px.y)));",
39
" vec2 px2 = px * 2.0;",
40
" c = max(c, texture2D(u_texture, v_texCoord + vec2(px2.x, 0.0)));",
41
" c = max(c, texture2D(u_texture, v_texCoord - vec2(px2.x, 0.0)));",
42
" c = max(c, texture2D(u_texture, v_texCoord + vec2(0.0, px2.y)));",
43
" c = max(c, texture2D(u_texture, v_texCoord - vec2(0.0, px2.y)));",
44
" gl_FragColor = c;",
45
"}"
46
].join("\n");
47
48
// Wider separable blur (13-tap). u_direction (1,0)/(0,1); u_blurSize in texels.
49
Shader.Builtin.BLOOM_BLUR_FRAG = [
50
"precision mediump float;",
51
"uniform sampler2D u_texture;",
52
"uniform vec2 u_resolution;",
53
"uniform vec2 u_direction;",
54
"uniform float u_blurSize;",
55
"varying vec2 v_texCoord;",
56
"void main() {",
57
" vec2 step = u_direction * u_blurSize / max(u_resolution, vec2(1.0));",
58
" vec4 c = vec4(0.0);",
59
" c += texture2D(u_texture, v_texCoord - step * 6.0) * 0.009;",
60
" c += texture2D(u_texture, v_texCoord - step * 5.0) * 0.019;",
61
" c += texture2D(u_texture, v_texCoord - step * 4.0) * 0.038;",
62
" c += texture2D(u_texture, v_texCoord - step * 3.0) * 0.071;",
63
" c += texture2D(u_texture, v_texCoord - step * 2.0) * 0.111;",
64
" c += texture2D(u_texture, v_texCoord - step) * 0.147;",
65
" c += texture2D(u_texture, v_texCoord) * 0.160;",
66
" c += texture2D(u_texture, v_texCoord + step) * 0.147;",
67
" c += texture2D(u_texture, v_texCoord + step * 2.0) * 0.111;",
68
" c += texture2D(u_texture, v_texCoord + step * 3.0) * 0.071;",
69
" c += texture2D(u_texture, v_texCoord + step * 4.0) * 0.038;",
70
" c += texture2D(u_texture, v_texCoord + step * 5.0) * 0.019;",
71
" c += texture2D(u_texture, v_texCoord + step * 6.0) * 0.009;",
72
" gl_FragColor = c;",
73
"}"
74
].join("\n");
75
76
// Combine: add bloom while keeping / boosting chroma (avoids gray wash at high intensity).
77
Shader.Builtin.BLOOM_COMBINE_FRAG = [
78
"precision mediump float;",
79
"uniform sampler2D u_texture;",
80
"uniform sampler2D u_scene;",
81
"uniform float u_intensity;",
82
"uniform float u_saturation;",
83
"uniform float u_colorPreserve;",
84
"varying vec2 v_texCoord;",
85
"void main() {",
86
" vec4 scene = texture2D(u_scene, v_texCoord);",
87
" vec4 bloom = texture2D(u_texture, v_texCoord);",
88
" vec3 bloomCol = bloom.rgb;",
89
" float bloomLum = dot(bloomCol, vec3(0.299, 0.587, 0.114));",
90
" bloomCol = mix(vec3(bloomLum), bloomCol, u_saturation);",
91
" float sceneLum = dot(scene.rgb, vec3(0.299, 0.587, 0.114));",
92
" vec3 sceneHue = scene.rgb / max(sceneLum, 0.04);",
93
" bloomCol *= mix(vec3(1.0), sceneHue, clamp(u_colorPreserve, 0.0, 1.0));",
94
" bloomCol *= u_intensity;",
95
// Soft add: keeps punchy color instead of clipping hard to white/gray.
96
" vec3 rgb = scene.rgb + bloomCol * (1.0 - scene.rgb * 0.35);",
97
" float bloomA = max(bloomCol.r, max(bloomCol.g, bloomCol.b));",
98
" float a = max(scene.a, min(bloomA, 1.0));",
99
" gl_FragColor = vec4(rgb, a);",
100
"}"
101
].join("\n");
102
103
/**
104
* Multi-pass bloom for a RenderLayer / scene.postShaders.
105
*
106
* options:
107
* - threshold, softKnee, intensity, blurSize
108
* - saturation: bloom chroma boost (1 = neutral, >1 = juicier)
109
* - colorPreserve: 0–1 tint bloom with the original sprite hue
110
* - smallSources: dilate tiny bright pixels before blur (good for 3–4px bullets)
111
* - dilate: explicit dilate radius in texels (overrides smallSources default)
112
* - scales: number of H/V blur scale pairs (default 3 with smallSources, else 2)
113
*/
114
Shader.getBloomPostChain = function (options)
115
{
116
options = options || {};
117
const threshold = options.threshold != null ? options.threshold : 0.4;
118
const softKnee = options.softKnee != null ? options.softKnee : 0.3;
119
const intensity = options.intensity != null ? options.intensity : 1.25;
120
const blurSize = options.blurSize != null ? options.blurSize : 3.0;
121
const saturation = options.saturation != null ? options.saturation : 1.0;
122
const colorPreserve = options.colorPreserve != null ? options.colorPreserve : 0.0;
123
const smallSources = !!options.smallSources;
124
125
let dilateRadius = 0;
126
if (options.dilate != null)
127
{ dilateRadius = options.dilate; }
128
else if (smallSources)
129
{ dilateRadius = 2.5; }
130
131
const scales = options.scales != null
132
? options.scales
133
: (smallSources ? 3 : 2);
134
135
if (!Shader._bloomBright)
136
{
137
Shader._bloomBright = Shader.screenFragment(Shader.Builtin.BLOOM_BRIGHT_FRAG);
138
Shader._bloomDilate = Shader.screenFragment(Shader.Builtin.BLOOM_DILATE_FRAG);
139
Shader._bloomBlur = Shader.screenFragment(Shader.Builtin.BLOOM_BLUR_FRAG);
140
Shader._bloomCombine = Shader.screenFragment(Shader.Builtin.BLOOM_COMBINE_FRAG);
141
}
142
143
const chain = [
144
{ shader: Shader._bloomBright, uniforms: { u_threshold: threshold, u_softKnee: softKnee } }
145
];
146
147
if (dilateRadius > 0)
148
{
149
chain.push({
150
shader: Shader._bloomDilate,
151
uniforms: { u_radius: dilateRadius }
152
});
153
}
154
155
const scaleFactors = [1, 2.2, 4.5, 8];
156
for (let i = 0; i < scales; i++)
157
{
158
const size = blurSize * scaleFactors[Math.min(i, scaleFactors.length - 1)];
159
chain.push({ shader: Shader._bloomBlur, uniforms: { u_direction: [1, 0], u_blurSize: size } });
160
chain.push({ shader: Shader._bloomBlur, uniforms: { u_direction: [0, 1], u_blurSize: size } });
161
}
162
163
chain.push({
164
shader: Shader._bloomCombine,
165
uniforms: {
166
u_intensity: intensity,
167
u_saturation: saturation,
168
u_colorPreserve: colorPreserve
169
}
170
});
171
return chain;
172
};
173
174
// --- Sprite effect builtins -------------------------------------------------
175
176
Shader.Builtin.BUMPMAP_FRAG = [
177
"precision mediump float;",
178
"uniform sampler2D u_texture;",
179
"uniform sampler2D u_bump;",
180
"uniform float u_alpha;",
181
"uniform vec2 u_worldCenter;",
182
"uniform vec2 u_worldSize;",
183
"uniform float u_rotationRad;",
184
"uniform int u_lightCount;",
185
"uniform vec2 u_lightPos[16];",
186
"uniform vec3 u_lightColor[16];",
187
"uniform float u_ambient;",
188
"uniform float u_specular;",
189
"varying vec2 v_texCoord;",
190
"void main() {",
191
" vec4 albedo = texture2D(u_texture, v_texCoord);",
192
" float hL = texture2D(u_bump, v_texCoord + vec2(-0.01, 0.0)).r;",
193
" float hR = texture2D(u_bump, v_texCoord + vec2(0.01, 0.0)).r;",
194
" float hU = texture2D(u_bump, v_texCoord + vec2(0.0, -0.01)).r;",
195
" float hD = texture2D(u_bump, v_texCoord + vec2(0.0, 0.01)).r;",
196
" vec3 normal = normalize(vec3(hL - hR, hU - hD, 0.35));",
197
" vec2 local = (v_texCoord - vec2(0.5)) * u_worldSize;",
198
" float c = cos(u_rotationRad);",
199
" float s = sin(u_rotationRad);",
200
" vec2 world = u_worldCenter + vec2(c * local.x - s * local.y, s * local.x + c * local.y);",
201
" vec3 lighting = vec3(u_ambient);",
202
" for (int i = 0; i < 16; i++) {",
203
" if (i >= u_lightCount) { break; }",
204
" vec2 toLight = u_lightPos[i] - world;",
205
" float dist = max(length(toLight), 0.001);",
206
" vec3 lightDir = normalize(vec3(toLight / dist, 0.65));",
207
" float diff = max(dot(normal, lightDir), 0.0);",
208
" float atten = 1.0 / (1.0 + dist * 0.008 + dist * dist * 0.00005);",
209
" float spec = pow(diff, 16.0) * u_specular;",
210
" lighting += u_lightColor[i] * (diff + spec) * atten;",
211
" }",
212
" gl_FragColor = vec4(albedo.rgb * lighting, albedo.a * u_alpha);",
213
"}"
214
].join("\n");
215
216
// Replace pure R/G/B paint channel with u_replaceColor.
217
Shader.Builtin.COLOUR_REPLACE_FRAG = [
218
"precision mediump float;",
219
"uniform sampler2D u_texture;",
220
"uniform float u_alpha;",
221
"uniform float u_channel;",
222
"uniform vec3 u_replaceColor;",
223
"varying vec2 v_texCoord;",
224
"void main() {",
225
" vec4 color = texture2D(u_texture, v_texCoord);",
226
" float ch = color.r;",
227
" float other = max(color.g, color.b);",
228
" if (u_channel > 0.5 && u_channel < 1.5) { ch = color.g; other = max(color.r, color.b); }",
229
" if (u_channel >= 1.5) { ch = color.b; other = max(color.r, color.g); }",
230
" float mask = clamp((ch - other) * 1.75, 0.0, 1.0);",
231
" vec3 rgb = mix(color.rgb, u_replaceColor, mask);",
232
" gl_FragColor = vec4(rgb, color.a * u_alpha);",
233
"}"
234
].join("\n");
235
236
// Clip sprite where secondary map luminance < u_amount (0 = full, 1 = gone).
237
Shader.Builtin.DISINTEGRATE_FRAG = [
238
"precision mediump float;",
239
"uniform sampler2D u_texture;",
240
"uniform sampler2D u_secondary;",
241
"uniform float u_alpha;",
242
"uniform float u_amount;",
243
"varying vec2 v_texCoord;",
244
"void main() {",
245
" vec4 color = texture2D(u_texture, v_texCoord);",
246
" float ref = texture2D(u_secondary, v_texCoord).r;",
247
" if (ref < u_amount) { discard; }",
248
" float edge = smoothstep(u_amount, u_amount + 0.08, ref);",
249
" gl_FragColor = vec4(color.rgb, color.a * u_alpha * edge);",
250
"}"
251
].join("\n");
252
253
Shader.getBumpmapShader = function ()
254
{
255
if (!Shader._bumpmap)
256
{ Shader._bumpmap = Shader.fragment(Shader.Builtin.BUMPMAP_FRAG); }
257
return Shader._bumpmap;
258
};
259
260
Shader.getColourReplaceShader = function ()
261
{
262
if (!Shader._colourReplace)
263
{ Shader._colourReplace = Shader.fragment(Shader.Builtin.COLOUR_REPLACE_FRAG); }
264
return Shader._colourReplace;
265
};
266
267
Shader.getDisintegrateShader = function ()
268
{
269
if (!Shader._disintegrate)
270
{ Shader._disintegrate = Shader.fragment(Shader.Builtin.DISINTEGRATE_FRAG); }
271
return Shader._disintegrate;
272
};
273
274
// --- Screen-space effect builtins ------------------------------------------
275
276
Shader.Builtin.DIRECTIONAL_BLUR_FRAG = [
277
"precision mediump float;",
278
"uniform sampler2D u_texture;",
279
"uniform vec2 u_resolution;",
280
"uniform vec2 u_direction;",
281
"uniform float u_length;",
282
"varying vec2 v_texCoord;",
283
"void main() {",
284
" vec2 dir = u_direction;",
285
" float len = length(dir);",
286
" if (len > 0.0001) { dir /= len; } else { dir = vec2(1.0, 0.0); }",
287
" vec2 step = dir * u_length / max(u_resolution, vec2(1.0));",
288
" vec4 c = vec4(0.0);",
289
" c += texture2D(u_texture, v_texCoord - step * 2.0) * 0.12;",
290
" c += texture2D(u_texture, v_texCoord - step) * 0.23;",
291
" c += texture2D(u_texture, v_texCoord) * 0.30;",
292
" c += texture2D(u_texture, v_texCoord + step) * 0.23;",
293
" c += texture2D(u_texture, v_texCoord + step * 2.0) * 0.12;",
294
" gl_FragColor = c;",
295
"}"
296
].join("\n");
297
298
Shader.Builtin.RADIAL_BLUR_FRAG = [
299
"precision mediump float;",
300
"uniform sampler2D u_texture;",
301
"uniform vec2 u_center;",
302
"uniform float u_amount;",
303
"varying vec2 v_texCoord;",
304
"void main() {",
305
" vec2 toCenter = u_center - v_texCoord;",
306
" vec4 c = vec4(0.0);",
307
" for (int i = 0; i < 8; i++) {",
308
" float t = float(i) / 7.0;",
309
" vec2 uv = v_texCoord + toCenter * t * u_amount;",
310
" c += texture2D(u_texture, uv);",
311
" }",
312
" gl_FragColor = c / 8.0;",
313
"}"
314
].join("\n");
315
316
Shader.Builtin.COLOR_ADJUST_FRAG = [
317
"precision mediump float;",
318
"uniform sampler2D u_texture;",
319
"uniform float u_saturation;",
320
"uniform float u_contrast;",
321
"uniform float u_brightness;",
322
"varying vec2 v_texCoord;",
323
"void main() {",
324
" vec4 color = texture2D(u_texture, v_texCoord);",
325
" float lum = dot(color.rgb, vec3(0.299, 0.587, 0.114));",
326
" vec3 rgb = mix(vec3(lum), color.rgb, u_saturation);",
327
" rgb = (rgb - 0.5) * u_contrast + 0.5 + u_brightness;",
328
" gl_FragColor = vec4(rgb, color.a);",
329
"}"
330
].join("\n");
331
332
Shader.getDirectionalBlurPostChain = function (options)
333
{
334
options = options || {};
335
const direction = options.direction || [1, 0];
336
const length = options.length != null ? options.length : 8;
337
338
if (!Shader._directionalBlur)
339
{ Shader._directionalBlur = Shader.screenFragment(Shader.Builtin.DIRECTIONAL_BLUR_FRAG); }
340
341
return [{
342
shader: Shader._directionalBlur,
343
uniforms: {
344
u_direction: [direction[0], direction[1]],
345
u_length: length
346
}
347
}];
348
};
349
350
Shader.getRadialBlurPostChain = function (options)
351
{
352
options = options || {};
353
const amount = options.amount != null ? options.amount : 0.15;
354
const center = options.center || [0.5, 0.5];
355
356
if (!Shader._radialBlur)
357
{ Shader._radialBlur = Shader.screenFragment(Shader.Builtin.RADIAL_BLUR_FRAG); }
358
359
return [{
360
shader: Shader._radialBlur,
361
uniforms: {
362
u_amount: amount,
363
u_center: [center[0], center[1]]
364
}
365
}];
366
};
367
368
Shader.getColorAdjustPostChain = function (options)
369
{
370
options = options || {};
371
const saturation = options.saturation != null ? options.saturation : 1.0;
372
const contrast = options.contrast != null ? options.contrast : 1.0;
373
const brightness = options.brightness != null ? options.brightness : 0.0;
374
375
if (!Shader._colorAdjust)
376
{ Shader._colorAdjust = Shader.screenFragment(Shader.Builtin.COLOR_ADJUST_FRAG); }
377
378
return [{
379
shader: Shader._colorAdjust,
380
uniforms: {
381
u_saturation: saturation,
382
u_contrast: contrast,
383
u_brightness: brightness
384
}
385
}];
386
};
@@ -0,0 +1,386 @@1
// Built-in screen-space / effect shaders. Games can use these without fetching files.2
// Expand this set over time into the default framework shader bundle.3
4
Shader.Builtin = Shader.Builtin || {};5
6
Shader.Builtin.BLOOM_BRIGHT_FRAG = [7
"precision mediump float;",8
"uniform sampler2D u_texture;",9
"uniform float u_threshold;",10
"uniform float u_softKnee;",11
"varying vec2 v_texCoord;",12
"void main() {",13
" vec4 color = texture2D(u_texture, v_texCoord);",14
" float lum = dot(color.rgb, vec3(0.299, 0.587, 0.114));",15
" float knee = max(u_softKnee, 0.001);",16
" float soft = smoothstep(u_threshold, u_threshold + knee, lum);",17
" gl_FragColor = vec4(color.rgb * soft, 1.0);",18
"}"19
].join("\n");20
21
// Max-filter dilate: fattens 1–4px hotspots so later blur has something to spread.22
Shader.Builtin.BLOOM_DILATE_FRAG = [23
"precision mediump float;",24
"uniform sampler2D u_texture;",25
"uniform vec2 u_resolution;",26
"uniform float u_radius;",27
"varying vec2 v_texCoord;",28
"void main() {",29
" vec2 px = u_radius / max(u_resolution, vec2(1.0));",30
" vec4 c = texture2D(u_texture, v_texCoord);",31
" c = max(c, texture2D(u_texture, v_texCoord + vec2(px.x, 0.0)));",32
" c = max(c, texture2D(u_texture, v_texCoord - vec2(px.x, 0.0)));",33
" c = max(c, texture2D(u_texture, v_texCoord + vec2(0.0, px.y)));",34
" c = max(c, texture2D(u_texture, v_texCoord - vec2(0.0, px.y)));",35
" c = max(c, texture2D(u_texture, v_texCoord + px));",36
" c = max(c, texture2D(u_texture, v_texCoord - px));",37
" c = max(c, texture2D(u_texture, v_texCoord + vec2(px.x, -px.y)));",38
" c = max(c, texture2D(u_texture, v_texCoord + vec2(-px.x, px.y)));",39
" vec2 px2 = px * 2.0;",40
" c = max(c, texture2D(u_texture, v_texCoord + vec2(px2.x, 0.0)));",41
" c = max(c, texture2D(u_texture, v_texCoord - vec2(px2.x, 0.0)));",42
" c = max(c, texture2D(u_texture, v_texCoord + vec2(0.0, px2.y)));",43
" c = max(c, texture2D(u_texture, v_texCoord - vec2(0.0, px2.y)));",44
" gl_FragColor = c;",45
"}"46
].join("\n");47
48
// Wider separable blur (13-tap). u_direction (1,0)/(0,1); u_blurSize in texels.49
Shader.Builtin.BLOOM_BLUR_FRAG = [50
"precision mediump float;",51
"uniform sampler2D u_texture;",52
"uniform vec2 u_resolution;",53
"uniform vec2 u_direction;",54
"uniform float u_blurSize;",55
"varying vec2 v_texCoord;",56
"void main() {",57
" vec2 step = u_direction * u_blurSize / max(u_resolution, vec2(1.0));",58
" vec4 c = vec4(0.0);",59
" c += texture2D(u_texture, v_texCoord - step * 6.0) * 0.009;",60
" c += texture2D(u_texture, v_texCoord - step * 5.0) * 0.019;",61
" c += texture2D(u_texture, v_texCoord - step * 4.0) * 0.038;",62
" c += texture2D(u_texture, v_texCoord - step * 3.0) * 0.071;",63
" c += texture2D(u_texture, v_texCoord - step * 2.0) * 0.111;",64
" c += texture2D(u_texture, v_texCoord - step) * 0.147;",65
" c += texture2D(u_texture, v_texCoord) * 0.160;",66
" c += texture2D(u_texture, v_texCoord + step) * 0.147;",67
" c += texture2D(u_texture, v_texCoord + step * 2.0) * 0.111;",68
" c += texture2D(u_texture, v_texCoord + step * 3.0) * 0.071;",69
" c += texture2D(u_texture, v_texCoord + step * 4.0) * 0.038;",70
" c += texture2D(u_texture, v_texCoord + step * 5.0) * 0.019;",71
" c += texture2D(u_texture, v_texCoord + step * 6.0) * 0.009;",72
" gl_FragColor = c;",73
"}"74
].join("\n");75
76
// Combine: add bloom while keeping / boosting chroma (avoids gray wash at high intensity).77
Shader.Builtin.BLOOM_COMBINE_FRAG = [78
"precision mediump float;",79
"uniform sampler2D u_texture;",80
"uniform sampler2D u_scene;",81
"uniform float u_intensity;",82
"uniform float u_saturation;",83
"uniform float u_colorPreserve;",84
"varying vec2 v_texCoord;",85
"void main() {",86
" vec4 scene = texture2D(u_scene, v_texCoord);",87
" vec4 bloom = texture2D(u_texture, v_texCoord);",88
" vec3 bloomCol = bloom.rgb;",89
" float bloomLum = dot(bloomCol, vec3(0.299, 0.587, 0.114));",90
" bloomCol = mix(vec3(bloomLum), bloomCol, u_saturation);",91
" float sceneLum = dot(scene.rgb, vec3(0.299, 0.587, 0.114));",92
" vec3 sceneHue = scene.rgb / max(sceneLum, 0.04);",93
" bloomCol *= mix(vec3(1.0), sceneHue, clamp(u_colorPreserve, 0.0, 1.0));",94
" bloomCol *= u_intensity;",95
// Soft add: keeps punchy color instead of clipping hard to white/gray.96
" vec3 rgb = scene.rgb + bloomCol * (1.0 - scene.rgb * 0.35);",97
" float bloomA = max(bloomCol.r, max(bloomCol.g, bloomCol.b));",98
" float a = max(scene.a, min(bloomA, 1.0));",99
" gl_FragColor = vec4(rgb, a);",100
"}"101
].join("\n");102
103
/**104
* Multi-pass bloom for a RenderLayer / scene.postShaders.105
*106
* options:107
* - threshold, softKnee, intensity, blurSize108
* - saturation: bloom chroma boost (1 = neutral, >1 = juicier)109
* - colorPreserve: 0–1 tint bloom with the original sprite hue110
* - smallSources: dilate tiny bright pixels before blur (good for 3–4px bullets)111
* - dilate: explicit dilate radius in texels (overrides smallSources default)112
* - scales: number of H/V blur scale pairs (default 3 with smallSources, else 2)113
*/114
Shader.getBloomPostChain = function (options)115
{116
options = options || {};117
const threshold = options.threshold != null ? options.threshold : 0.4;118
const softKnee = options.softKnee != null ? options.softKnee : 0.3;119
const intensity = options.intensity != null ? options.intensity : 1.25;120
const blurSize = options.blurSize != null ? options.blurSize : 3.0;121
const saturation = options.saturation != null ? options.saturation : 1.0;122
const colorPreserve = options.colorPreserve != null ? options.colorPreserve : 0.0;123
const smallSources = !!options.smallSources;124
125
let dilateRadius = 0;126
if (options.dilate != null)127
{ dilateRadius = options.dilate; }128
else if (smallSources)129
{ dilateRadius = 2.5; }130
131
const scales = options.scales != null132
? options.scales133
: (smallSources ? 3 : 2);134
135
if (!Shader._bloomBright)136
{137
Shader._bloomBright = Shader.screenFragment(Shader.Builtin.BLOOM_BRIGHT_FRAG);138
Shader._bloomDilate = Shader.screenFragment(Shader.Builtin.BLOOM_DILATE_FRAG);139
Shader._bloomBlur = Shader.screenFragment(Shader.Builtin.BLOOM_BLUR_FRAG);140
Shader._bloomCombine = Shader.screenFragment(Shader.Builtin.BLOOM_COMBINE_FRAG);141
}142
143
const chain = [144
{ shader: Shader._bloomBright, uniforms: { u_threshold: threshold, u_softKnee: softKnee } }145
];146
147
if (dilateRadius > 0)148
{149
chain.push({150
shader: Shader._bloomDilate,151
uniforms: { u_radius: dilateRadius }152
});153
}154
155
const scaleFactors = [1, 2.2, 4.5, 8];156
for (let i = 0; i < scales; i++)157
{158
const size = blurSize * scaleFactors[Math.min(i, scaleFactors.length - 1)];159
chain.push({ shader: Shader._bloomBlur, uniforms: { u_direction: [1, 0], u_blurSize: size } });160
chain.push({ shader: Shader._bloomBlur, uniforms: { u_direction: [0, 1], u_blurSize: size } });161
}162
163
chain.push({164
shader: Shader._bloomCombine,165
uniforms: {166
u_intensity: intensity,167
u_saturation: saturation,168
u_colorPreserve: colorPreserve169
}170
});171
return chain;172
};173
174
// --- Sprite effect builtins -------------------------------------------------175
176
Shader.Builtin.BUMPMAP_FRAG = [177
"precision mediump float;",178
"uniform sampler2D u_texture;",179
"uniform sampler2D u_bump;",180
"uniform float u_alpha;",181
"uniform vec2 u_worldCenter;",182
"uniform vec2 u_worldSize;",183
"uniform float u_rotationRad;",184
"uniform int u_lightCount;",185
"uniform vec2 u_lightPos[16];",186
"uniform vec3 u_lightColor[16];",187
"uniform float u_ambient;",188
"uniform float u_specular;",189
"varying vec2 v_texCoord;",190
"void main() {",191
" vec4 albedo = texture2D(u_texture, v_texCoord);",192
" float hL = texture2D(u_bump, v_texCoord + vec2(-0.01, 0.0)).r;",193
" float hR = texture2D(u_bump, v_texCoord + vec2(0.01, 0.0)).r;",194
" float hU = texture2D(u_bump, v_texCoord + vec2(0.0, -0.01)).r;",195
" float hD = texture2D(u_bump, v_texCoord + vec2(0.0, 0.01)).r;",196
" vec3 normal = normalize(vec3(hL - hR, hU - hD, 0.35));",197
" vec2 local = (v_texCoord - vec2(0.5)) * u_worldSize;",198
" float c = cos(u_rotationRad);",199
" float s = sin(u_rotationRad);",200
" vec2 world = u_worldCenter + vec2(c * local.x - s * local.y, s * local.x + c * local.y);",201
" vec3 lighting = vec3(u_ambient);",202
" for (int i = 0; i < 16; i++) {",203
" if (i >= u_lightCount) { break; }",204
" vec2 toLight = u_lightPos[i] - world;",205
" float dist = max(length(toLight), 0.001);",206
" vec3 lightDir = normalize(vec3(toLight / dist, 0.65));",207
" float diff = max(dot(normal, lightDir), 0.0);",208
" float atten = 1.0 / (1.0 + dist * 0.008 + dist * dist * 0.00005);",209
" float spec = pow(diff, 16.0) * u_specular;",210
" lighting += u_lightColor[i] * (diff + spec) * atten;",211
" }",212
" gl_FragColor = vec4(albedo.rgb * lighting, albedo.a * u_alpha);",213
"}"214
].join("\n");215
216
// Replace pure R/G/B paint channel with u_replaceColor.217
Shader.Builtin.COLOUR_REPLACE_FRAG = [218
"precision mediump float;",219
"uniform sampler2D u_texture;",220
"uniform float u_alpha;",221
"uniform float u_channel;",222
"uniform vec3 u_replaceColor;",223
"varying vec2 v_texCoord;",224
"void main() {",225
" vec4 color = texture2D(u_texture, v_texCoord);",226
" float ch = color.r;",227
" float other = max(color.g, color.b);",228
" if (u_channel > 0.5 && u_channel < 1.5) { ch = color.g; other = max(color.r, color.b); }",229
" if (u_channel >= 1.5) { ch = color.b; other = max(color.r, color.g); }",230
" float mask = clamp((ch - other) * 1.75, 0.0, 1.0);",231
" vec3 rgb = mix(color.rgb, u_replaceColor, mask);",232
" gl_FragColor = vec4(rgb, color.a * u_alpha);",233
"}"234
].join("\n");235
236
// Clip sprite where secondary map luminance < u_amount (0 = full, 1 = gone).237
Shader.Builtin.DISINTEGRATE_FRAG = [238
"precision mediump float;",239
"uniform sampler2D u_texture;",240
"uniform sampler2D u_secondary;",241
"uniform float u_alpha;",242
"uniform float u_amount;",243
"varying vec2 v_texCoord;",244
"void main() {",245
" vec4 color = texture2D(u_texture, v_texCoord);",246
" float ref = texture2D(u_secondary, v_texCoord).r;",247
" if (ref < u_amount) { discard; }",248
" float edge = smoothstep(u_amount, u_amount + 0.08, ref);",249
" gl_FragColor = vec4(color.rgb, color.a * u_alpha * edge);",250
"}"251
].join("\n");252
253
Shader.getBumpmapShader = function ()254
{255
if (!Shader._bumpmap)256
{ Shader._bumpmap = Shader.fragment(Shader.Builtin.BUMPMAP_FRAG); }257
return Shader._bumpmap;258
};259
260
Shader.getColourReplaceShader = function ()261
{262
if (!Shader._colourReplace)263
{ Shader._colourReplace = Shader.fragment(Shader.Builtin.COLOUR_REPLACE_FRAG); }264
return Shader._colourReplace;265
};266
267
Shader.getDisintegrateShader = function ()268
{269
if (!Shader._disintegrate)270
{ Shader._disintegrate = Shader.fragment(Shader.Builtin.DISINTEGRATE_FRAG); }271
return Shader._disintegrate;272
};273
274
// --- Screen-space effect builtins ------------------------------------------275
276
Shader.Builtin.DIRECTIONAL_BLUR_FRAG = [277
"precision mediump float;",278
"uniform sampler2D u_texture;",279
"uniform vec2 u_resolution;",280
"uniform vec2 u_direction;",281
"uniform float u_length;",282
"varying vec2 v_texCoord;",283
"void main() {",284
" vec2 dir = u_direction;",285
" float len = length(dir);",286
" if (len > 0.0001) { dir /= len; } else { dir = vec2(1.0, 0.0); }",287
" vec2 step = dir * u_length / max(u_resolution, vec2(1.0));",288
" vec4 c = vec4(0.0);",289
" c += texture2D(u_texture, v_texCoord - step * 2.0) * 0.12;",290
" c += texture2D(u_texture, v_texCoord - step) * 0.23;",291
" c += texture2D(u_texture, v_texCoord) * 0.30;",292
" c += texture2D(u_texture, v_texCoord + step) * 0.23;",293
" c += texture2D(u_texture, v_texCoord + step * 2.0) * 0.12;",294
" gl_FragColor = c;",295
"}"296
].join("\n");297
298
Shader.Builtin.RADIAL_BLUR_FRAG = [299
"precision mediump float;",300
"uniform sampler2D u_texture;",301
"uniform vec2 u_center;",302
"uniform float u_amount;",303
"varying vec2 v_texCoord;",304
"void main() {",305
" vec2 toCenter = u_center - v_texCoord;",306
" vec4 c = vec4(0.0);",307
" for (int i = 0; i < 8; i++) {",308
" float t = float(i) / 7.0;",309
" vec2 uv = v_texCoord + toCenter * t * u_amount;",310
" c += texture2D(u_texture, uv);",311
" }",312
" gl_FragColor = c / 8.0;",313
"}"314
].join("\n");315
316
Shader.Builtin.COLOR_ADJUST_FRAG = [317
"precision mediump float;",318
"uniform sampler2D u_texture;",319
"uniform float u_saturation;",320
"uniform float u_contrast;",321
"uniform float u_brightness;",322
"varying vec2 v_texCoord;",323
"void main() {",324
" vec4 color = texture2D(u_texture, v_texCoord);",325
" float lum = dot(color.rgb, vec3(0.299, 0.587, 0.114));",326
" vec3 rgb = mix(vec3(lum), color.rgb, u_saturation);",327
" rgb = (rgb - 0.5) * u_contrast + 0.5 + u_brightness;",328
" gl_FragColor = vec4(rgb, color.a);",329
"}"330
].join("\n");331
332
Shader.getDirectionalBlurPostChain = function (options)333
{334
options = options || {};335
const direction = options.direction || [1, 0];336
const length = options.length != null ? options.length : 8;337
338
if (!Shader._directionalBlur)339
{ Shader._directionalBlur = Shader.screenFragment(Shader.Builtin.DIRECTIONAL_BLUR_FRAG); }340
341
return [{342
shader: Shader._directionalBlur,343
uniforms: {344
u_direction: [direction[0], direction[1]],345
u_length: length346
}347
}];348
};349
350
Shader.getRadialBlurPostChain = function (options)351
{352
options = options || {};353
const amount = options.amount != null ? options.amount : 0.15;354
const center = options.center || [0.5, 0.5];355
356
if (!Shader._radialBlur)357
{ Shader._radialBlur = Shader.screenFragment(Shader.Builtin.RADIAL_BLUR_FRAG); }358
359
return [{360
shader: Shader._radialBlur,361
uniforms: {362
u_amount: amount,363
u_center: [center[0], center[1]]364
}365
}];366
};367
368
Shader.getColorAdjustPostChain = function (options)369
{370
options = options || {};371
const saturation = options.saturation != null ? options.saturation : 1.0;372
const contrast = options.contrast != null ? options.contrast : 1.0;373
const brightness = options.brightness != null ? options.brightness : 0.0;374
375
if (!Shader._colorAdjust)376
{ Shader._colorAdjust = Shader.screenFragment(Shader.Builtin.COLOR_ADJUST_FRAG); }377
378
return [{379
shader: Shader._colorAdjust,380
uniforms: {381
u_saturation: saturation,382
u_contrast: contrast,383
u_brightness: brightness384
}385
}];386
};@@ -0,0 +1,541 @@
1
class GLContext
2
{
3
static MAX_LIGHTS = 16;
4
5
constructor (canvas)
6
{
7
this.canvas = canvas;
8
9
const attrs = { alpha: true, premultipliedAlpha: false, antialias: true };
10
this.gl = canvas.getContext("webgl", attrs) || canvas.getContext("experimental-webgl", attrs);
11
12
if (!this.gl)
13
{ throw new Error("WebGL is not supported in this browser."); }
14
15
const gl = this.gl;
16
gl.enable(gl.BLEND);
17
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
18
gl.disable(gl.DEPTH_TEST);
19
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
20
21
this.defaultShader = new Shader(Shader.DEFAULT_VERT, Shader.DEFAULT_FRAG);
22
this.screenCopyShader = new Shader(Shader.SCREEN_VERT, Shader.SCREEN_COPY_FRAG);
23
this.textures = new WeakMap();
24
25
this.positionBuffer = gl.createBuffer();
26
gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
27
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
28
-0.5, -0.5,
29
0.5, -0.5,
30
-0.5, 0.5,
31
0.5, 0.5
32
]), gl.STATIC_DRAW);
33
34
this.texCoordBuffer = gl.createBuffer();
35
36
// Fullscreen NDC quad (triangle strip) + UVs (v=0 at bottom, matches FBO sampling).
37
this.screenPositionBuffer = gl.createBuffer();
38
gl.bindBuffer(gl.ARRAY_BUFFER, this.screenPositionBuffer);
39
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
40
-1, -1,
41
1, -1,
42
-1, 1,
43
1, 1
44
]), gl.STATIC_DRAW);
45
46
this.screenTexCoordBuffer = gl.createBuffer();
47
gl.bindBuffer(gl.ARRAY_BUFFER, this.screenTexCoordBuffer);
48
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
49
0, 0,
50
1, 0,
51
0, 1,
52
1, 1
53
]), gl.STATIC_DRAW);
54
55
// [0] = scene (stable during post), [1]/[2] = ping-pong for effect passes.
56
this.framebuffers = [null, null, null];
57
this.colorTextures = [null, null, null];
58
this._offscreenIndex = 0;
59
this._lastWidth = 0;
60
this._lastHeight = 0;
61
this.setSize(canvas.width, canvas.height);
62
}
63
64
setSize (width, height)
65
{
66
const gl = this.gl;
67
width = Math.max(1, width | 0);
68
height = Math.max(1, height | 0);
69
70
if (width !== this._lastWidth || height !== this._lastHeight)
71
{
72
this._lastWidth = width;
73
this._lastHeight = height;
74
gl.viewport(0, 0, width, height);
75
this._rebuildFramebuffers(width, height);
76
}
77
}
78
79
_destroyFramebuffers ()
80
{
81
const gl = this.gl;
82
for (let i = 0; i < this.framebuffers.length; i++)
83
{
84
if (this.framebuffers[i])
85
{
86
gl.deleteFramebuffer(this.framebuffers[i]);
87
this.framebuffers[i] = null;
88
}
89
90
if (this.colorTextures[i])
91
{
92
gl.deleteTexture(this.colorTextures[i]);
93
this.colorTextures[i] = null;
94
}
95
}
96
}
97
98
_rebuildFramebuffers (width, height)
99
{
100
const gl = this.gl;
101
this._destroyFramebuffers();
102
103
for (let i = 0; i < 3; i++)
104
{
105
const texture = gl.createTexture();
106
gl.bindTexture(gl.TEXTURE_2D, texture);
107
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
108
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
109
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
110
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
111
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
112
113
const fb = gl.createFramebuffer();
114
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
115
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
116
117
const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
118
if (status !== gl.FRAMEBUFFER_COMPLETE)
119
{
120
console.error("Framebuffer incomplete:", status);
121
}
122
123
this.framebuffers[i] = fb;
124
this.colorTextures[i] = texture;
125
}
126
127
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
128
gl.bindTexture(gl.TEXTURE_2D, null);
129
}
130
131
clear (r, g, b, a = 1)
132
{
133
const gl = this.gl;
134
gl.clearColor(r / 255, g / 255, b / 255, a);
135
gl.clear(gl.COLOR_BUFFER_BIT);
136
}
137
138
clearTransparent ()
139
{
140
const gl = this.gl;
141
gl.clearColor(0, 0, 0, 0);
142
gl.clear(gl.COLOR_BUFFER_BIT);
143
}
144
145
beginOffscreenPass ()
146
{
147
const gl = this.gl;
148
this._offscreenIndex = 0;
149
gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[0]);
150
gl.viewport(0, 0, this._lastWidth, this._lastHeight);
151
gl.enable(gl.BLEND);
152
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
153
}
154
155
endOffscreenPass ()
156
{
157
const gl = this.gl;
158
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
159
}
160
161
/**
162
* @param {Array} passes
163
* @param {Object} builtins
164
* @param {{ toCanvas?: boolean }} options - toCanvas true writes the last pass to the canvas.
165
* @returns {WebGLTexture|null} final color texture when not drawing to canvas
166
*/
167
applyPostShaders (passes, builtins = {}, options = {})
168
{
169
if (!passes || !passes.length)
170
{ return this.colorTextures[0]; }
171
172
const gl = this.gl;
173
const toCanvas = !!options.toCanvas;
174
const sceneTexture = this.colorTextures[0];
175
let read = 0;
176
177
gl.disable(gl.BLEND);
178
179
for (let i = 0; i < passes.length; i++)
180
{
181
const pass = passes[i];
182
const isLast = i === passes.length - 1;
183
184
// Never overwrite the scene buffer (index 0); ping-pong on 1/2.
185
let write = 1;
186
if (read === 1)
187
{ write = 2; }
188
else if (read === 2)
189
{ write = 1; }
190
191
if (isLast && toCanvas)
192
{
193
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
194
}
195
else
196
{
197
gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[write]);
198
}
199
200
gl.viewport(0, 0, this._lastWidth, this._lastHeight);
201
gl.clearColor(0, 0, 0, 0);
202
gl.clear(gl.COLOR_BUFFER_BIT);
203
204
const uniforms = Object.assign({}, builtins, pass.uniforms || {});
205
this.drawFullscreen(pass.shader, this.colorTextures[read], uniforms, sceneTexture);
206
207
if (!isLast || !toCanvas)
208
{ read = write; }
209
}
210
211
this._offscreenIndex = read;
212
gl.enable(gl.BLEND);
213
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
214
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
215
216
return toCanvas ? null : this.colorTextures[read];
217
}
218
219
blitToCanvas (texture, composite = "alpha")
220
{
221
if (!texture)
222
{ return; }
223
224
const gl = this.gl;
225
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
226
gl.viewport(0, 0, this._lastWidth, this._lastHeight);
227
gl.enable(gl.BLEND);
228
229
if (composite === "add")
230
{ gl.blendFunc(gl.ONE, gl.ONE); }
231
else
232
{ gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); }
233
234
this.drawFullscreen(this.screenCopyShader, texture, null, null);
235
236
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
237
}
238
239
drawFullscreen (shader, texture, uniforms, sceneTexture)
240
{
241
const gl = this.gl;
242
const info = shader.getProgramInfo(gl);
243
if (!info || !texture)
244
{ return; }
245
246
gl.useProgram(info.program);
247
248
gl.bindBuffer(gl.ARRAY_BUFFER, this.screenPositionBuffer);
249
if (info.attribs.position >= 0)
250
{
251
gl.enableVertexAttribArray(info.attribs.position);
252
gl.vertexAttribPointer(info.attribs.position, 2, gl.FLOAT, false, 0, 0);
253
}
254
255
gl.bindBuffer(gl.ARRAY_BUFFER, this.screenTexCoordBuffer);
256
if (info.attribs.texCoord >= 0)
257
{
258
gl.enableVertexAttribArray(info.attribs.texCoord);
259
gl.vertexAttribPointer(info.attribs.texCoord, 2, gl.FLOAT, false, 0, 0);
260
}
261
262
gl.activeTexture(gl.TEXTURE0);
263
gl.bindTexture(gl.TEXTURE_2D, texture);
264
this._setUniform(info, "u_texture", 0);
265
this._setUniform(info, "u_alpha", 1);
266
267
if (sceneTexture && info.uniforms.u_scene)
268
{
269
gl.activeTexture(gl.TEXTURE1);
270
gl.bindTexture(gl.TEXTURE_2D, sceneTexture);
271
this._setUniform(info, "u_scene", 1);
272
}
273
274
if (uniforms)
275
{
276
for (const name in uniforms)
277
{
278
if (!Object.prototype.hasOwnProperty.call(uniforms, name))
279
{ continue; }
280
281
this._setUniform(info, name, uniforms[name]);
282
}
283
}
284
285
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
286
}
287
288
getTexture (htmlImage)
289
{
290
if (!htmlImage)
291
{ return null; }
292
293
let texture = this.textures.get(htmlImage);
294
if (texture)
295
{ return texture; }
296
297
const gl = this.gl;
298
texture = gl.createTexture();
299
gl.bindTexture(gl.TEXTURE_2D, texture);
300
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
301
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
302
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
303
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
304
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, htmlImage);
305
306
this.textures.set(htmlImage, texture);
307
return texture;
308
}
309
310
drawSprite (options)
311
{
312
const gl = this.gl;
313
const width = this._lastWidth;
314
const height = this._lastHeight;
315
if (width <= 0 || height <= 0)
316
{ return; }
317
318
const shader = options.shader || this.defaultShader;
319
const info = shader.getProgramInfo(gl);
320
if (!info)
321
{ return; }
322
323
const texture = options.texture;
324
if (!texture)
325
{ return; }
326
327
gl.useProgram(info.program);
328
329
gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
330
if (info.attribs.position >= 0)
331
{
332
gl.enableVertexAttribArray(info.attribs.position);
333
gl.vertexAttribPointer(info.attribs.position, 2, gl.FLOAT, false, 0, 0);
334
}
335
336
const uv = options.uvRect || { u0: 0, v0: 0, u1: 1, v1: 1 };
337
gl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer);
338
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
339
uv.u0, uv.v0,
340
uv.u1, uv.v0,
341
uv.u0, uv.v1,
342
uv.u1, uv.v1
343
]), gl.DYNAMIC_DRAW);
344
345
if (info.attribs.texCoord >= 0)
346
{
347
gl.enableVertexAttribArray(info.attribs.texCoord);
348
gl.vertexAttribPointer(info.attribs.texCoord, 2, gl.FLOAT, false, 0, 0);
349
}
350
351
const matrix = GLContext._buildSpriteMatrix(
352
options.x, options.y,
353
options.w, options.h,
354
options.rotationDeg || 0,
355
options.mirrorX, options.mirrorY,
356
width, height
357
);
358
359
this._setUniform(info, "u_matrix", matrix);
360
this._setUniform(info, "u_alpha", options.alpha == null ? 1 : options.alpha);
361
this._setUniform(info, "u_worldCenter", [options.x, options.y]);
362
this._setUniform(info, "u_worldSize", [options.w, options.h]);
363
this._setUniform(info, "u_rotationRad", (options.rotationDeg || 0) * Math.PI / 180);
364
365
gl.activeTexture(gl.TEXTURE0);
366
gl.bindTexture(gl.TEXTURE_2D, texture);
367
this._setUniform(info, "u_texture", 0);
368
369
let nextUnit = 1;
370
if (options.textures)
371
{
372
for (const name in options.textures)
373
{
374
if (!Object.prototype.hasOwnProperty.call(options.textures, name))
375
{ continue; }
376
377
const extra = options.textures[name];
378
if (!extra)
379
{ continue; }
380
381
gl.activeTexture(gl.TEXTURE0 + nextUnit);
382
gl.bindTexture(gl.TEXTURE_2D, extra);
383
this._setUniform(info, name, nextUnit);
384
nextUnit++;
385
}
386
}
387
388
if (options.lights)
389
{ this._setLights(info, options.lights); }
390
else if (info.uniforms.u_lightCount)
391
{ this._setUniform(info, "u_lightCount", 0); }
392
393
// Sensible bump defaults when the shader asks for them.
394
if (info.uniforms.u_ambient && (!options.uniforms || options.uniforms.u_ambient == null))
395
{ this._setUniform(info, "u_ambient", 0.35); }
396
if (info.uniforms.u_specular && (!options.uniforms || options.uniforms.u_specular == null))
397
{ this._setUniform(info, "u_specular", 0.25); }
398
399
if (options.uniforms)
400
{
401
for (const name in options.uniforms)
402
{
403
if (!Object.prototype.hasOwnProperty.call(options.uniforms, name))
404
{ continue; }
405
406
this._setUniform(info, name, options.uniforms[name]);
407
}
408
}
409
410
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
411
}
412
413
_setLights (info, lights)
414
{
415
const gl = this.gl;
416
const max = GLContext.MAX_LIGHTS;
417
const count = Math.max(0, Math.min(lights.length, max));
418
this._setUniform(info, "u_lightCount", count);
419
420
const posEntry = info.uniforms["u_lightPos[0]"] || info.uniforms.u_lightPos;
421
const colEntry = info.uniforms["u_lightColor[0]"] || info.uniforms.u_lightColor;
422
if (!posEntry || !colEntry || count === 0)
423
{
424
if (count === 0)
425
{ this._setUniform(info, "u_lightCount", 0); }
426
return;
427
}
428
429
const pos = new Float32Array(max * 2);
430
const col = new Float32Array(max * 3);
431
432
for (let i = 0; i < count; i++)
433
{
434
const light = lights[i] || {};
435
pos[i * 2] = light.x != null ? light.x : (light.position ? light.position.x : 0);
436
pos[i * 2 + 1] = light.y != null ? light.y : (light.position ? light.position.y : 0);
437
438
const c = light.color != null ? light.color : [1, 1, 1];
439
if (Array.isArray(c))
440
{
441
col[i * 3] = c[0] != null ? c[0] : 0;
442
col[i * 3 + 1] = c[1] != null ? c[1] : 0;
443
col[i * 3 + 2] = c[2] != null ? c[2] : 0;
444
}
445
else
446
{
447
col[i * 3] = (c.r != null ? c.r : 1);
448
col[i * 3 + 1] = (c.g != null ? c.g : 1);
449
col[i * 3 + 2] = (c.b != null ? c.b : 1);
450
}
451
452
// Allow 0–255 style colors.
453
if (col[i * 3] > 1 || col[i * 3 + 1] > 1 || col[i * 3 + 2] > 1)
454
{
455
col[i * 3] /= 255;
456
col[i * 3 + 1] /= 255;
457
col[i * 3 + 2] /= 255;
458
}
459
}
460
461
gl.uniform2fv(posEntry.location, pos);
462
gl.uniform3fv(colEntry.location, col);
463
}
464
465
_setUniform (info, name, value)
466
{
467
const entry = info.uniforms[name];
468
if (!entry || entry.location == null)
469
{ return; }
470
471
const gl = this.gl;
472
const loc = entry.location;
473
474
if (typeof value === "number")
475
{
476
if (entry.type === gl.INT || entry.type === gl.SAMPLER_2D)
477
{ gl.uniform1i(loc, value); }
478
else
479
{ gl.uniform1f(loc, value); }
480
return;
481
}
482
483
if (value instanceof Float32Array)
484
{
485
if (value.length === 16)
486
{ gl.uniformMatrix4fv(loc, false, value); }
487
else if (value.length === 9)
488
{ gl.uniformMatrix3fv(loc, false, value); }
489
else if (value.length === 4)
490
{ gl.uniform4fv(loc, value); }
491
else if (value.length === 3)
492
{ gl.uniform3fv(loc, value); }
493
else if (value.length === 2)
494
{ gl.uniform2fv(loc, value); }
495
return;
496
}
497
498
if (Array.isArray(value))
499
{
500
if (value.length === 4)
501
{ gl.uniform4fv(loc, value); }
502
else if (value.length === 3)
503
{ gl.uniform3fv(loc, value); }
504
else if (value.length === 2)
505
{ gl.uniform2fv(loc, value); }
506
else if (value.length === 1)
507
{ gl.uniform1f(loc, value[0]); }
508
}
509
}
510
511
// Column-major mat4: projection (canvas Y-down) * T * R * S
512
static _buildSpriteMatrix (x, y, w, h, rotationDeg, mirrorX, mirrorY, canvasW, canvasH)
513
{
514
const sx = (mirrorX ? -1 : 1) * w;
515
const sy = (mirrorY ? -1 : 1) * h;
516
const rad = rotationDeg * Math.PI / 180;
517
const c = Math.cos(rad);
518
const s = Math.sin(rad);
519
520
// Model maps unit quad [-0.5,0.5] into pixel space.
521
const m00 = c * sx;
522
const m01 = -s * sy;
523
const m10 = s * sx;
524
const m11 = c * sy;
525
const m30 = x;
526
const m31 = y;
527
528
const pr0 = 2 / canvasW;
529
const pr5 = -2 / canvasH;
530
const pr12 = -1;
531
const pr13 = 1;
532
533
// P * M (only 2D affine terms matter)
534
return new Float32Array([
535
pr0 * m00, pr5 * m10, 0, 0,
536
pr0 * m01, pr5 * m11, 0, 0,
537
0, 0, -1, 0,
538
pr0 * m30 + pr12, pr5 * m31 + pr13, 0, 1
539
]);
540
}
541
}
@@ -0,0 +1,541 @@1
class GLContext2
{3
static MAX_LIGHTS = 16;4
5
constructor (canvas)6
{7
this.canvas = canvas;8
9
const attrs = { alpha: true, premultipliedAlpha: false, antialias: true };10
this.gl = canvas.getContext("webgl", attrs) || canvas.getContext("experimental-webgl", attrs);11
12
if (!this.gl)13
{ throw new Error("WebGL is not supported in this browser."); }14
15
const gl = this.gl;16
gl.enable(gl.BLEND);17
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);18
gl.disable(gl.DEPTH_TEST);19
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);20
21
this.defaultShader = new Shader(Shader.DEFAULT_VERT, Shader.DEFAULT_FRAG);22
this.screenCopyShader = new Shader(Shader.SCREEN_VERT, Shader.SCREEN_COPY_FRAG);23
this.textures = new WeakMap();24
25
this.positionBuffer = gl.createBuffer();26
gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);27
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([28
-0.5, -0.5,29
0.5, -0.5,30
-0.5, 0.5,31
0.5, 0.532
]), gl.STATIC_DRAW);33
34
this.texCoordBuffer = gl.createBuffer();35
36
// Fullscreen NDC quad (triangle strip) + UVs (v=0 at bottom, matches FBO sampling).37
this.screenPositionBuffer = gl.createBuffer();38
gl.bindBuffer(gl.ARRAY_BUFFER, this.screenPositionBuffer);39
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([40
-1, -1,41
1, -1,42
-1, 1,43
1, 144
]), gl.STATIC_DRAW);45
46
this.screenTexCoordBuffer = gl.createBuffer();47
gl.bindBuffer(gl.ARRAY_BUFFER, this.screenTexCoordBuffer);48
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([49
0, 0,50
1, 0,51
0, 1,52
1, 153
]), gl.STATIC_DRAW);54
55
// [0] = scene (stable during post), [1]/[2] = ping-pong for effect passes.56
this.framebuffers = [null, null, null];57
this.colorTextures = [null, null, null];58
this._offscreenIndex = 0;59
this._lastWidth = 0;60
this._lastHeight = 0;61
this.setSize(canvas.width, canvas.height);62
}63
64
setSize (width, height)65
{66
const gl = this.gl;67
width = Math.max(1, width | 0);68
height = Math.max(1, height | 0);69
70
if (width !== this._lastWidth || height !== this._lastHeight)71
{72
this._lastWidth = width;73
this._lastHeight = height;74
gl.viewport(0, 0, width, height);75
this._rebuildFramebuffers(width, height);76
}77
}78
79
_destroyFramebuffers ()80
{81
const gl = this.gl;82
for (let i = 0; i < this.framebuffers.length; i++)83
{84
if (this.framebuffers[i])85
{86
gl.deleteFramebuffer(this.framebuffers[i]);87
this.framebuffers[i] = null;88
}89
90
if (this.colorTextures[i])91
{92
gl.deleteTexture(this.colorTextures[i]);93
this.colorTextures[i] = null;94
}95
}96
}97
98
_rebuildFramebuffers (width, height)99
{100
const gl = this.gl;101
this._destroyFramebuffers();102
103
for (let i = 0; i < 3; i++)104
{105
const texture = gl.createTexture();106
gl.bindTexture(gl.TEXTURE_2D, texture);107
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);108
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);109
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);110
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);111
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);112
113
const fb = gl.createFramebuffer();114
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);115
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);116
117
const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);118
if (status !== gl.FRAMEBUFFER_COMPLETE)119
{120
console.error("Framebuffer incomplete:", status);121
}122
123
this.framebuffers[i] = fb;124
this.colorTextures[i] = texture;125
}126
127
gl.bindFramebuffer(gl.FRAMEBUFFER, null);128
gl.bindTexture(gl.TEXTURE_2D, null);129
}130
131
clear (r, g, b, a = 1)132
{133
const gl = this.gl;134
gl.clearColor(r / 255, g / 255, b / 255, a);135
gl.clear(gl.COLOR_BUFFER_BIT);136
}137
138
clearTransparent ()139
{140
const gl = this.gl;141
gl.clearColor(0, 0, 0, 0);142
gl.clear(gl.COLOR_BUFFER_BIT);143
}144
145
beginOffscreenPass ()146
{147
const gl = this.gl;148
this._offscreenIndex = 0;149
gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[0]);150
gl.viewport(0, 0, this._lastWidth, this._lastHeight);151
gl.enable(gl.BLEND);152
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);153
}154
155
endOffscreenPass ()156
{157
const gl = this.gl;158
gl.bindFramebuffer(gl.FRAMEBUFFER, null);159
}160
161
/**162
* @param {Array} passes163
* @param {Object} builtins164
* @param {{ toCanvas?: boolean }} options - toCanvas true writes the last pass to the canvas.165
* @returns {WebGLTexture|null} final color texture when not drawing to canvas166
*/167
applyPostShaders (passes, builtins = {}, options = {})168
{169
if (!passes || !passes.length)170
{ return this.colorTextures[0]; }171
172
const gl = this.gl;173
const toCanvas = !!options.toCanvas;174
const sceneTexture = this.colorTextures[0];175
let read = 0;176
177
gl.disable(gl.BLEND);178
179
for (let i = 0; i < passes.length; i++)180
{181
const pass = passes[i];182
const isLast = i === passes.length - 1;183
184
// Never overwrite the scene buffer (index 0); ping-pong on 1/2.185
let write = 1;186
if (read === 1)187
{ write = 2; }188
else if (read === 2)189
{ write = 1; }190
191
if (isLast && toCanvas)192
{193
gl.bindFramebuffer(gl.FRAMEBUFFER, null);194
}195
else196
{197
gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[write]);198
}199
200
gl.viewport(0, 0, this._lastWidth, this._lastHeight);201
gl.clearColor(0, 0, 0, 0);202
gl.clear(gl.COLOR_BUFFER_BIT);203
204
const uniforms = Object.assign({}, builtins, pass.uniforms || {});205
this.drawFullscreen(pass.shader, this.colorTextures[read], uniforms, sceneTexture);206
207
if (!isLast || !toCanvas)208
{ read = write; }209
}210
211
this._offscreenIndex = read;212
gl.enable(gl.BLEND);213
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);214
gl.bindFramebuffer(gl.FRAMEBUFFER, null);215
216
return toCanvas ? null : this.colorTextures[read];217
}218
219
blitToCanvas (texture, composite = "alpha")220
{221
if (!texture)222
{ return; }223
224
const gl = this.gl;225
gl.bindFramebuffer(gl.FRAMEBUFFER, null);226
gl.viewport(0, 0, this._lastWidth, this._lastHeight);227
gl.enable(gl.BLEND);228
229
if (composite === "add")230
{ gl.blendFunc(gl.ONE, gl.ONE); }231
else232
{ gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); }233
234
this.drawFullscreen(this.screenCopyShader, texture, null, null);235
236
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);237
}238
239
drawFullscreen (shader, texture, uniforms, sceneTexture)240
{241
const gl = this.gl;242
const info = shader.getProgramInfo(gl);243
if (!info || !texture)244
{ return; }245
246
gl.useProgram(info.program);247
248
gl.bindBuffer(gl.ARRAY_BUFFER, this.screenPositionBuffer);249
if (info.attribs.position >= 0)250
{251
gl.enableVertexAttribArray(info.attribs.position);252
gl.vertexAttribPointer(info.attribs.position, 2, gl.FLOAT, false, 0, 0);253
}254
255
gl.bindBuffer(gl.ARRAY_BUFFER, this.screenTexCoordBuffer);256
if (info.attribs.texCoord >= 0)257
{258
gl.enableVertexAttribArray(info.attribs.texCoord);259
gl.vertexAttribPointer(info.attribs.texCoord, 2, gl.FLOAT, false, 0, 0);260
}261
262
gl.activeTexture(gl.TEXTURE0);263
gl.bindTexture(gl.TEXTURE_2D, texture);264
this._setUniform(info, "u_texture", 0);265
this._setUniform(info, "u_alpha", 1);266
267
if (sceneTexture && info.uniforms.u_scene)268
{269
gl.activeTexture(gl.TEXTURE1);270
gl.bindTexture(gl.TEXTURE_2D, sceneTexture);271
this._setUniform(info, "u_scene", 1);272
}273
274
if (uniforms)275
{276
for (const name in uniforms)277
{278
if (!Object.prototype.hasOwnProperty.call(uniforms, name))279
{ continue; }280
281
this._setUniform(info, name, uniforms[name]);282
}283
}284
285
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);286
}287
288
getTexture (htmlImage)289
{290
if (!htmlImage)291
{ return null; }292
293
let texture = this.textures.get(htmlImage);294
if (texture)295
{ return texture; }296
297
const gl = this.gl;298
texture = gl.createTexture();299
gl.bindTexture(gl.TEXTURE_2D, texture);300
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);301
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);302
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);303
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);304
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, htmlImage);305
306
this.textures.set(htmlImage, texture);307
return texture;308
}309
310
drawSprite (options)311
{312
const gl = this.gl;313
const width = this._lastWidth;314
const height = this._lastHeight;315
if (width <= 0 || height <= 0)316
{ return; }317
318
const shader = options.shader || this.defaultShader;319
const info = shader.getProgramInfo(gl);320
if (!info)321
{ return; }322
323
const texture = options.texture;324
if (!texture)325
{ return; }326
327
gl.useProgram(info.program);328
329
gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);330
if (info.attribs.position >= 0)331
{332
gl.enableVertexAttribArray(info.attribs.position);333
gl.vertexAttribPointer(info.attribs.position, 2, gl.FLOAT, false, 0, 0);334
}335
336
const uv = options.uvRect || { u0: 0, v0: 0, u1: 1, v1: 1 };337
gl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer);338
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([339
uv.u0, uv.v0,340
uv.u1, uv.v0,341
uv.u0, uv.v1,342
uv.u1, uv.v1343
]), gl.DYNAMIC_DRAW);344
345
if (info.attribs.texCoord >= 0)346
{347
gl.enableVertexAttribArray(info.attribs.texCoord);348
gl.vertexAttribPointer(info.attribs.texCoord, 2, gl.FLOAT, false, 0, 0);349
}350
351
const matrix = GLContext._buildSpriteMatrix(352
options.x, options.y,353
options.w, options.h,354
options.rotationDeg || 0,355
options.mirrorX, options.mirrorY,356
width, height357
);358
359
this._setUniform(info, "u_matrix", matrix);360
this._setUniform(info, "u_alpha", options.alpha == null ? 1 : options.alpha);361
this._setUniform(info, "u_worldCenter", [options.x, options.y]);362
this._setUniform(info, "u_worldSize", [options.w, options.h]);363
this._setUniform(info, "u_rotationRad", (options.rotationDeg || 0) * Math.PI / 180);364
365
gl.activeTexture(gl.TEXTURE0);366
gl.bindTexture(gl.TEXTURE_2D, texture);367
this._setUniform(info, "u_texture", 0);368
369
let nextUnit = 1;370
if (options.textures)371
{372
for (const name in options.textures)373
{374
if (!Object.prototype.hasOwnProperty.call(options.textures, name))375
{ continue; }376
377
const extra = options.textures[name];378
if (!extra)379
{ continue; }380
381
gl.activeTexture(gl.TEXTURE0 + nextUnit);382
gl.bindTexture(gl.TEXTURE_2D, extra);383
this._setUniform(info, name, nextUnit);384
nextUnit++;385
}386
}387
388
if (options.lights)389
{ this._setLights(info, options.lights); }390
else if (info.uniforms.u_lightCount)391
{ this._setUniform(info, "u_lightCount", 0); }392
393
// Sensible bump defaults when the shader asks for them.394
if (info.uniforms.u_ambient && (!options.uniforms || options.uniforms.u_ambient == null))395
{ this._setUniform(info, "u_ambient", 0.35); }396
if (info.uniforms.u_specular && (!options.uniforms || options.uniforms.u_specular == null))397
{ this._setUniform(info, "u_specular", 0.25); }398
399
if (options.uniforms)400
{401
for (const name in options.uniforms)402
{403
if (!Object.prototype.hasOwnProperty.call(options.uniforms, name))404
{ continue; }405
406
this._setUniform(info, name, options.uniforms[name]);407
}408
}409
410
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);411
}412
413
_setLights (info, lights)414
{415
const gl = this.gl;416
const max = GLContext.MAX_LIGHTS;417
const count = Math.max(0, Math.min(lights.length, max));418
this._setUniform(info, "u_lightCount", count);419
420
const posEntry = info.uniforms["u_lightPos[0]"] || info.uniforms.u_lightPos;421
const colEntry = info.uniforms["u_lightColor[0]"] || info.uniforms.u_lightColor;422
if (!posEntry || !colEntry || count === 0)423
{424
if (count === 0)425
{ this._setUniform(info, "u_lightCount", 0); }426
return;427
}428
429
const pos = new Float32Array(max * 2);430
const col = new Float32Array(max * 3);431
432
for (let i = 0; i < count; i++)433
{434
const light = lights[i] || {};435
pos[i * 2] = light.x != null ? light.x : (light.position ? light.position.x : 0);436
pos[i * 2 + 1] = light.y != null ? light.y : (light.position ? light.position.y : 0);437
438
const c = light.color != null ? light.color : [1, 1, 1];439
if (Array.isArray(c))440
{441
col[i * 3] = c[0] != null ? c[0] : 0;442
col[i * 3 + 1] = c[1] != null ? c[1] : 0;443
col[i * 3 + 2] = c[2] != null ? c[2] : 0;444
}445
else446
{447
col[i * 3] = (c.r != null ? c.r : 1);448
col[i * 3 + 1] = (c.g != null ? c.g : 1);449
col[i * 3 + 2] = (c.b != null ? c.b : 1);450
}451
452
// Allow 0–255 style colors.453
if (col[i * 3] > 1 || col[i * 3 + 1] > 1 || col[i * 3 + 2] > 1)454
{455
col[i * 3] /= 255;456
col[i * 3 + 1] /= 255;457
col[i * 3 + 2] /= 255;458
}459
}460
461
gl.uniform2fv(posEntry.location, pos);462
gl.uniform3fv(colEntry.location, col);463
}464
465
_setUniform (info, name, value)466
{467
const entry = info.uniforms[name];468
if (!entry || entry.location == null)469
{ return; }470
471
const gl = this.gl;472
const loc = entry.location;473
474
if (typeof value === "number")475
{476
if (entry.type === gl.INT || entry.type === gl.SAMPLER_2D)477
{ gl.uniform1i(loc, value); }478
else479
{ gl.uniform1f(loc, value); }480
return;481
}482
483
if (value instanceof Float32Array)484
{485
if (value.length === 16)486
{ gl.uniformMatrix4fv(loc, false, value); }487
else if (value.length === 9)488
{ gl.uniformMatrix3fv(loc, false, value); }489
else if (value.length === 4)490
{ gl.uniform4fv(loc, value); }491
else if (value.length === 3)492
{ gl.uniform3fv(loc, value); }493
else if (value.length === 2)494
{ gl.uniform2fv(loc, value); }495
return;496
}497
498
if (Array.isArray(value))499
{500
if (value.length === 4)501
{ gl.uniform4fv(loc, value); }502
else if (value.length === 3)503
{ gl.uniform3fv(loc, value); }504
else if (value.length === 2)505
{ gl.uniform2fv(loc, value); }506
else if (value.length === 1)507
{ gl.uniform1f(loc, value[0]); }508
}509
}510
511
// Column-major mat4: projection (canvas Y-down) * T * R * S512
static _buildSpriteMatrix (x, y, w, h, rotationDeg, mirrorX, mirrorY, canvasW, canvasH)513
{514
const sx = (mirrorX ? -1 : 1) * w;515
const sy = (mirrorY ? -1 : 1) * h;516
const rad = rotationDeg * Math.PI / 180;517
const c = Math.cos(rad);518
const s = Math.sin(rad);519
520
// Model maps unit quad [-0.5,0.5] into pixel space.521
const m00 = c * sx;522
const m01 = -s * sy;523
const m10 = s * sx;524
const m11 = c * sy;525
const m30 = x;526
const m31 = y;527
528
const pr0 = 2 / canvasW;529
const pr5 = -2 / canvasH;530
const pr12 = -1;531
const pr13 = 1;532
533
// P * M (only 2D affine terms matter)534
return new Float32Array([535
pr0 * m00, pr5 * m10, 0, 0,536
pr0 * m01, pr5 * m11, 0, 0,537
0, 0, -1, 0,538
pr0 * m30 + pr12, pr5 * m31 + pr13, 0, 1539
]);540
}541
}@@ -0,0 +1,140 @@
1
class Shader
2
{
3
static DEFAULT_VERT = [
4
"attribute vec2 a_position;",
5
"attribute vec2 a_texCoord;",
6
"uniform mat4 u_matrix;",
7
"varying vec2 v_texCoord;",
8
"void main() {",
9
" gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);",
10
" v_texCoord = a_texCoord;",
11
"}"
12
].join("\n");
13
14
static DEFAULT_FRAG = [
15
"precision mediump float;",
16
"uniform sampler2D u_texture;",
17
"uniform float u_alpha;",
18
"varying vec2 v_texCoord;",
19
"void main() {",
20
" vec4 color = texture2D(u_texture, v_texCoord);",
21
" gl_FragColor = vec4(color.rgb, color.a * u_alpha);",
22
"}"
23
].join("\n");
24
25
// Fullscreen NDC quad for screen-space / post-process passes.
26
static SCREEN_VERT = [
27
"attribute vec2 a_position;",
28
"attribute vec2 a_texCoord;",
29
"varying vec2 v_texCoord;",
30
"void main() {",
31
" gl_Position = vec4(a_position, 0.0, 1.0);",
32
" v_texCoord = a_texCoord;",
33
"}"
34
].join("\n");
35
36
static SCREEN_COPY_FRAG = [
37
"precision mediump float;",
38
"uniform sampler2D u_texture;",
39
"varying vec2 v_texCoord;",
40
"void main() {",
41
" gl_FragColor = texture2D(u_texture, v_texCoord);",
42
"}"
43
].join("\n");
44
45
constructor (vertSource, fragSource)
46
{
47
this.vertSource = vertSource || Shader.DEFAULT_VERT;
48
this.fragSource = fragSource || Shader.DEFAULT_FRAG;
49
this._programs = new WeakMap();
50
}
51
52
static fragment (fragSource)
53
{
54
return new Shader(Shader.DEFAULT_VERT, fragSource);
55
}
56
57
static screenFragment (fragSource)
58
{
59
return new Shader(Shader.SCREEN_VERT, fragSource);
60
}
61
62
getProgramInfo (gl)
63
{
64
let info = this._programs.get(gl);
65
if (info)
66
{ return info; }
67
68
const program = Shader._createProgram(gl, this.vertSource, this.fragSource);
69
if (!program)
70
{ return null; }
71
72
info = {
73
program: program,
74
attribs: {
75
position: gl.getAttribLocation(program, "a_position"),
76
texCoord: gl.getAttribLocation(program, "a_texCoord")
77
},
78
uniforms: {}
79
};
80
81
const numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
82
for (let i = 0; i < numUniforms; i++)
83
{
84
const uniformInfo = gl.getActiveUniform(program, i);
85
if (!uniformInfo)
86
{ continue; }
87
88
info.uniforms[uniformInfo.name] = {
89
location: gl.getUniformLocation(program, uniformInfo.name),
90
type: uniformInfo.type,
91
size: uniformInfo.size
92
};
93
}
94
95
this._programs.set(gl, info);
96
return info;
97
}
98
99
static _createShader (gl, type, source)
100
{
101
const shader = gl.createShader(type);
102
gl.shaderSource(shader, source);
103
gl.compileShader(shader);
104
105
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS))
106
{
107
console.error("Shader compile error:", gl.getShaderInfoLog(shader));
108
console.error(source);
109
gl.deleteShader(shader);
110
return null;
111
}
112
113
return shader;
114
}
115
116
static _createProgram (gl, vertSource, fragSource)
117
{
118
const vertexShader = Shader._createShader(gl, gl.VERTEX_SHADER, vertSource);
119
const fragmentShader = Shader._createShader(gl, gl.FRAGMENT_SHADER, fragSource);
120
if (!vertexShader || !fragmentShader)
121
{ return null; }
122
123
const program = gl.createProgram();
124
gl.attachShader(program, vertexShader);
125
gl.attachShader(program, fragmentShader);
126
gl.linkProgram(program);
127
128
gl.deleteShader(vertexShader);
129
gl.deleteShader(fragmentShader);
130
131
if (!gl.getProgramParameter(program, gl.LINK_STATUS))
132
{
133
console.error("Shader link error:", gl.getProgramInfoLog(program));
134
gl.deleteProgram(program);
135
return null;
136
}
137
138
return program;
139
}
140
}
@@ -0,0 +1,140 @@1
class Shader2
{3
static DEFAULT_VERT = [4
"attribute vec2 a_position;",5
"attribute vec2 a_texCoord;",6
"uniform mat4 u_matrix;",7
"varying vec2 v_texCoord;",8
"void main() {",9
" gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);",10
" v_texCoord = a_texCoord;",11
"}"12
].join("\n");13
14
static DEFAULT_FRAG = [15
"precision mediump float;",16
"uniform sampler2D u_texture;",17
"uniform float u_alpha;",18
"varying vec2 v_texCoord;",19
"void main() {",20
" vec4 color = texture2D(u_texture, v_texCoord);",21
" gl_FragColor = vec4(color.rgb, color.a * u_alpha);",22
"}"23
].join("\n");24
25
// Fullscreen NDC quad for screen-space / post-process passes.26
static SCREEN_VERT = [27
"attribute vec2 a_position;",28
"attribute vec2 a_texCoord;",29
"varying vec2 v_texCoord;",30
"void main() {",31
" gl_Position = vec4(a_position, 0.0, 1.0);",32
" v_texCoord = a_texCoord;",33
"}"34
].join("\n");35
36
static SCREEN_COPY_FRAG = [37
"precision mediump float;",38
"uniform sampler2D u_texture;",39
"varying vec2 v_texCoord;",40
"void main() {",41
" gl_FragColor = texture2D(u_texture, v_texCoord);",42
"}"43
].join("\n");44
45
constructor (vertSource, fragSource)46
{47
this.vertSource = vertSource || Shader.DEFAULT_VERT;48
this.fragSource = fragSource || Shader.DEFAULT_FRAG;49
this._programs = new WeakMap();50
}51
52
static fragment (fragSource)53
{54
return new Shader(Shader.DEFAULT_VERT, fragSource);55
}56
57
static screenFragment (fragSource)58
{59
return new Shader(Shader.SCREEN_VERT, fragSource);60
}61
62
getProgramInfo (gl)63
{64
let info = this._programs.get(gl);65
if (info)66
{ return info; }67
68
const program = Shader._createProgram(gl, this.vertSource, this.fragSource);69
if (!program)70
{ return null; }71
72
info = {73
program: program,74
attribs: {75
position: gl.getAttribLocation(program, "a_position"),76
texCoord: gl.getAttribLocation(program, "a_texCoord")77
},78
uniforms: {}79
};80
81
const numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);82
for (let i = 0; i < numUniforms; i++)83
{84
const uniformInfo = gl.getActiveUniform(program, i);85
if (!uniformInfo)86
{ continue; }87
88
info.uniforms[uniformInfo.name] = {89
location: gl.getUniformLocation(program, uniformInfo.name),90
type: uniformInfo.type,91
size: uniformInfo.size92
};93
}94
95
this._programs.set(gl, info);96
return info;97
}98
99
static _createShader (gl, type, source)100
{101
const shader = gl.createShader(type);102
gl.shaderSource(shader, source);103
gl.compileShader(shader);104
105
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS))106
{107
console.error("Shader compile error:", gl.getShaderInfoLog(shader));108
console.error(source);109
gl.deleteShader(shader);110
return null;111
}112
113
return shader;114
}115
116
static _createProgram (gl, vertSource, fragSource)117
{118
const vertexShader = Shader._createShader(gl, gl.VERTEX_SHADER, vertSource);119
const fragmentShader = Shader._createShader(gl, gl.FRAGMENT_SHADER, fragSource);120
if (!vertexShader || !fragmentShader)121
{ return null; }122
123
const program = gl.createProgram();124
gl.attachShader(program, vertexShader);125
gl.attachShader(program, fragmentShader);126
gl.linkProgram(program);127
128
gl.deleteShader(vertexShader);129
gl.deleteShader(fragmentShader);130
131
if (!gl.getProgramParameter(program, gl.LINK_STATUS))132
{133
console.error("Shader link error:", gl.getProgramInfoLog(program));134
gl.deleteProgram(program);135
return null;136
}137
138
return program;139
}140
}@@ -30,41 +30,67 @@ class image
30
30
console.log("Image loaded: " + (image && image.src ? image.src : ""));
31
31
}
32
32
33
draw (scene, dx, dy, dw, dh, rotation, mirrorX, mirrorY, alpha, subImage)
33
draw (scene, dx, dy, dw, dh, rotation, mirrorX, mirrorY, alpha, subImage, shader, uniforms, textures, lights)
34
34
{
35
35
var shouldDraw = true;
36
36
37
37
if (dx < -Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
38
{shouldDraw = false;}
38
{ shouldDraw = false; }
39
39
40
40
if (dy < -Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
41
{shouldDraw = false;}
41
{ shouldDraw = false; }
42
42
43
43
if (dx > scene.real_size.x + Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
44
{shouldDraw = false;}
44
{ shouldDraw = false; }
45
45
46
46
if (dy > scene.real_size.y + Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
47
{shouldDraw = false;}
47
{ shouldDraw = false; }
48
48
49
if (shouldDraw)
50
{
51
var context = scene.context;
52
context.save();
53
var oldAlpha = context.globalAlpha;
54
context.globalAlpha = alpha;
55
56
context.translate(dx, dy);
57
context.rotate(rotation * (Math.PI / 180));
58
59
(mirrorX || mirrorY) && context.scale(mirrorX ? -1 : 1, mirrorY ? -1 : 1);
49
if (!shouldDraw || !scene.glContext || !this.g_image)
50
{ return; }
60
51
61
var subImageData = this.getSubImage(subImage);
52
const subImageData = this.getSubImage(subImage);
53
const imgW = this.g_image.width;
54
const imgH = this.g_image.height;
55
const glTextures = {};
62
56
63
context.drawImage(this.g_image, subImageData.sx, subImageData.sy, subImageData.sw, subImageData.sh, -dw / 2, -dh / 2, dw, dh);
64
65
context.restore();
66
context.globalAlpha = oldAlpha;
57
if (textures)
58
{
59
for (const name in textures)
60
{
61
if (!Object.prototype.hasOwnProperty.call(textures, name))
62
{ continue; }
63
64
const src = textures[name];
65
if (!src)
66
{ continue; }
67
68
const htmlImage = src.g_image || src;
69
glTextures[name] = scene.glContext.getTexture(htmlImage);
70
}
67
71
}
72
73
scene.glContext.drawSprite({
74
texture: scene.glContext.getTexture(this.g_image),
75
x: dx,
76
y: dy,
77
w: dw,
78
h: dh,
79
rotationDeg: rotation,
80
mirrorX: mirrorX,
81
mirrorY: mirrorY,
82
alpha: alpha,
83
uvRect: {
84
u0: subImageData.sx / imgW,
85
v0: subImageData.sy / imgH,
86
u1: (subImageData.sx + subImageData.sw) / imgW,
87
v1: (subImageData.sy + subImageData.sh) / imgH
88
},
89
shader: shader || scene.glContext.defaultShader,
90
uniforms: uniforms,
91
textures: glTextures,
92
lights: lights
93
});
68
94
}
69
95
70
96
hasAnimationCycle (label)
@@ -87,7 +113,7 @@ class image
87
113
get width ()
88
114
{
89
115
if (this.cacheWidth < 0)
90
{this.cacheWidth = this.g_image.width / this.subImagesPerRow;}
116
{ this.cacheWidth = this.g_image.width / this.subImagesPerRow; }
91
117
92
118
return this.cacheWidth;
93
119
}
@@ -95,7 +121,7 @@ class image
95
121
get height ()
96
122
{
97
123
if (this.cacheHeight < 0)
98
{this.cacheHeight = this.g_image.height / (Math.ceil(this.subImages / this.subImagesPerRow) + 0);}
124
{ this.cacheHeight = this.g_image.height / (Math.ceil(this.subImages / this.subImagesPerRow) + 0); }
99
125
100
126
return this.cacheHeight;
101
127
}
@@ -117,4 +143,4 @@ class image
117
143
118
144
return { sw: sw, sh: sh, sx: sx, sy: sy };
119
145
}
120
}
146
}
@@ -30,41 +30,67 @@ class image30
console.log("Image loaded: " + (image && image.src ? image.src : ""));
30
console.log("Image loaded: " + (image && image.src ? image.src : ""));
31
}
31
}
32
32
33
draw (scene, dx, dy, dw, dh, rotation, mirrorX, mirrorY, alpha, subImage)
33
draw (scene, dx, dy, dw, dh, rotation, mirrorX, mirrorY, alpha, subImage, shader, uniforms, textures, lights)
34
{
34
{
35
var shouldDraw = true;
35
var shouldDraw = true;
36
36
37
if (dx < -Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
37
if (dx < -Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
38
{shouldDraw = false;}
38
{ shouldDraw = false; }
39
39
40
if (dy < -Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
40
if (dy < -Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
41
{shouldDraw = false;}
41
{ shouldDraw = false; }
42
42
43
if (dx > scene.real_size.x + Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
43
if (dx > scene.real_size.x + Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
44
{shouldDraw = false;}
44
{ shouldDraw = false; }
45
45
46
if (dy > scene.real_size.y + Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
46
if (dy > scene.real_size.y + Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
47
{shouldDraw = false;}
47
{ shouldDraw = false; }
48
48
49
if (shouldDraw)
49
if (!shouldDraw || !scene.glContext || !this.g_image)
50
{
50
{ return; }
51
var context = scene.context;
52
context.save();
53
var oldAlpha = context.globalAlpha;
54
context.globalAlpha = alpha;
55
56
context.translate(dx, dy);
57
context.rotate(rotation * (Math.PI / 180));
58
59
(mirrorX || mirrorY) && context.scale(mirrorX ? -1 : 1, mirrorY ? -1 : 1);
60
51
61
var subImageData = this.getSubImage(subImage);
52
const subImageData = this.getSubImage(subImage);
53
const imgW = this.g_image.width;
54
const imgH = this.g_image.height;
55
const glTextures = {};
62
56
63
context.drawImage(this.g_image, subImageData.sx, subImageData.sy, subImageData.sw, subImageData.sh, -dw / 2, -dh / 2, dw, dh);
57
if (textures)
64
58
{
65
context.restore();
59
for (const name in textures)
66
context.globalAlpha = oldAlpha;
60
{
61
if (!Object.prototype.hasOwnProperty.call(textures, name))
62
{ continue; }
63
64
const src = textures[name];
65
if (!src)
66
{ continue; }
67
68
const htmlImage = src.g_image || src;
69
glTextures[name] = scene.glContext.getTexture(htmlImage);
70
}
67
}
71
}
72
73
scene.glContext.drawSprite({
74
texture: scene.glContext.getTexture(this.g_image),
75
x: dx,
76
y: dy,
77
w: dw,
78
h: dh,
79
rotationDeg: rotation,
80
mirrorX: mirrorX,
81
mirrorY: mirrorY,
82
alpha: alpha,
83
uvRect: {
84
u0: subImageData.sx / imgW,
85
v0: subImageData.sy / imgH,
86
u1: (subImageData.sx + subImageData.sw) / imgW,
87
v1: (subImageData.sy + subImageData.sh) / imgH
88
},
89
shader: shader || scene.glContext.defaultShader,
90
uniforms: uniforms,
91
textures: glTextures,
92
lights: lights
93
});
68
}
94
}
69
95
70
hasAnimationCycle (label)
96
hasAnimationCycle (label)
@@ -87,7 +113,7 @@ class image87
get width ()
113
get width ()
88
{
114
{
89
if (this.cacheWidth < 0)
115
if (this.cacheWidth < 0)
90
{this.cacheWidth = this.g_image.width / this.subImagesPerRow;}
116
{ this.cacheWidth = this.g_image.width / this.subImagesPerRow; }
91
117
92
return this.cacheWidth;
118
return this.cacheWidth;
93
}
119
}
@@ -95,7 +121,7 @@ class image95
get height ()
121
get height ()
96
{
122
{
97
if (this.cacheHeight < 0)
123
if (this.cacheHeight < 0)
98
{this.cacheHeight = this.g_image.height / (Math.ceil(this.subImages / this.subImagesPerRow) + 0);}
124
{ this.cacheHeight = this.g_image.height / (Math.ceil(this.subImages / this.subImagesPerRow) + 0); }
99
125
100
return this.cacheHeight;
126
return this.cacheHeight;
101
}
127
}
@@ -117,4 +143,4 @@ class image117
143
118
return { sw: sw, sh: sh, sx: sx, sy: sy };
144
return { sw: sw, sh: sh, sx: sx, sy: sy };
119
}
145
}
120
}146
}
@@ -13,10 +13,34 @@ class Renderer
13
13
14
14
visible = true;
15
15
16
shader = null;
17
shaderUniforms = null;
18
19
// Optional maps for builtin sprite effects (framework `image` instances).
20
bumpMap = null;
21
secondaryMap = null;
22
23
// Dynamic lights for bumpmap: [{ x, y, color: [r,g,b]|{r,g,b} }, ...]
24
lights = null;
25
26
// RenderLayer name; null uses RenderLayer.DEFAULT_NAME ("default").
27
layer = null;
28
16
29
constructor (parentObject, sprite)
17
30
{
18
31
this.gameObject = parentObject;
19
32
this.sprite = sprite;
33
this.shader = null;
34
this.shaderUniforms = null;
35
this.bumpMap = null;
36
this.secondaryMap = null;
37
this.lights = null;
38
this.layer = null;
39
}
40
41
get layerName ()
42
{
43
return this.layer || RenderLayer.DEFAULT_NAME;
20
44
}
21
45
22
46
update (deltaTime)
@@ -96,6 +120,12 @@ class Renderer
96
120
this.g_subImgOld = this.subImage;
97
121
}
98
122
123
const textures = {};
124
if (this.bumpMap)
125
{ textures.u_bump = this.bumpMap; }
126
if (this.secondaryMap)
127
{ textures.u_secondary = this.secondaryMap; }
128
99
129
this.sprite.draw(
100
130
this.gameObject.scene,
101
131
Math.round(dx),
@@ -106,7 +136,11 @@ class Renderer
106
136
this.mirrorX,
107
137
this.mirrorY,
108
138
this.alpha,
109
this.subImage
139
this.subImage,
140
this.shader,
141
this.shaderUniforms,
142
textures,
143
this.lights
110
144
);
111
145
}
112
146
@@ -13,10 +13,34 @@ class Renderer13
13
14
visible = true;14
visible = true;15
15
16
shader = null;17
shaderUniforms = null;18
19
// Optional maps for builtin sprite effects (framework `image` instances).20
bumpMap = null;21
secondaryMap = null;22
23
// Dynamic lights for bumpmap: [{ x, y, color: [r,g,b]|{r,g,b} }, ...]24
lights = null;25
26
// RenderLayer name; null uses RenderLayer.DEFAULT_NAME ("default").27
layer = null;28
16
constructor (parentObject, sprite)29
constructor (parentObject, sprite)17
{30
{18
this.gameObject = parentObject;31
this.gameObject = parentObject;19
this.sprite = sprite;32
this.sprite = sprite;33
this.shader = null;34
this.shaderUniforms = null;35
this.bumpMap = null;36
this.secondaryMap = null;37
this.lights = null;38
this.layer = null;39
}40
41
get layerName ()42
{43
return this.layer || RenderLayer.DEFAULT_NAME;20
}44
}21
45
22
update (deltaTime) 46
update (deltaTime) @@ -96,6 +120,12 @@ class Renderer96
this.g_subImgOld = this.subImage;120
this.g_subImgOld = this.subImage;97
}121
}98
122
123
const textures = {};124
if (this.bumpMap)125
{ textures.u_bump = this.bumpMap; }126
if (this.secondaryMap)127
{ textures.u_secondary = this.secondaryMap; }128
99
this.sprite.draw(129
this.sprite.draw(100
this.gameObject.scene,130
this.gameObject.scene,101
Math.round(dx),131
Math.round(dx),@@ -106,7 +136,11 @@ class Renderer106
this.mirrorX,136
this.mirrorX,107
this.mirrorY,137
this.mirrorY,108
this.alpha,138
this.alpha,109
this.subImage139
this.subImage,140
this.shader,141
this.shaderUniforms,142
textures,143
this.lights110
);144
);111
}145
}112
146
@@ -0,0 +1,13 @@
1
class RenderLayer
2
{
3
static DEFAULT_NAME = "default";
4
5
constructor (name, options)
6
{
7
options = options || {};
8
this.name = name || RenderLayer.DEFAULT_NAME;
9
this.postShaders = options.postShaders || [];
10
// "alpha" (source-over) or "add" (additive)
11
this.composite = options.composite || "alpha";
12
}
13
}
@@ -0,0 +1,13 @@1
class RenderLayer2
{3
static DEFAULT_NAME = "default";4
5
constructor (name, options)6
{7
options = options || {};8
this.name = name || RenderLayer.DEFAULT_NAME;9
this.postShaders = options.postShaders || [];10
// "alpha" (source-over) or "add" (additive)11
this.composite = options.composite || "alpha";12
}13
}@@ -22,9 +22,16 @@ class Scene
22
22
displayMode = Scene.DisplayModes.absolute;
23
23
24
24
cv_canvas = null;
25
cv_context = null;
25
glContext = null;
26
26
destroyed = false;
27
27
28
// Legacy: posts applied to the "default" layer when that layer has none of its own.
29
postShaders = [];
30
postTime = 0;
31
32
// Ordered list of RenderLayer. Index 0 is drawn first (back).
33
renderLayers = null;
34
28
35
game = null;
29
36
30
37
get primary ()
@@ -50,12 +57,59 @@ class Scene
50
57
body.insertAdjacentHTML('beforeend', '<canvas id="' + this.id + '" style="position: absolute; left: ' + x + 'px; top: ' + y + 'px;" width="' + width + '" height="' + height + '"></canvas>');
51
58
52
59
this.cv_canvas = document.getElementById(this.id);
53
this.cv_context = this.cv_canvas.getContext('2d');
60
this.glContext = new GLContext(this.cv_canvas);
61
this.postShaders = [];
62
this.postTime = 0;
63
this.renderLayers = [new RenderLayer(RenderLayer.DEFAULT_NAME)];
54
64
55
65
this.g_fixSize();
56
66
this.quadTree = new QuadTree(this.real_size.x, this.real_size.y);
57
67
}
58
68
69
/**
70
* Replace the layer stack. Order in the array is draw order (first = back).
71
* Each entry: RenderLayer, or { name, postShaders?, composite? }.
72
*/
73
setLayers (layerConfigs)
74
{
75
if (!layerConfigs || !layerConfigs.length)
76
{
77
this.renderLayers = [new RenderLayer(RenderLayer.DEFAULT_NAME)];
78
return this.renderLayers;
79
}
80
81
const layers = [];
82
for (let i = 0; i < layerConfigs.length; i++)
83
{
84
const cfg = layerConfigs[i];
85
if (!cfg)
86
{ continue; }
87
88
if (cfg instanceof RenderLayer)
89
{ layers.push(cfg); }
90
else
91
{ layers.push(new RenderLayer(cfg.name, cfg)); }
92
}
93
94
if (!layers.length)
95
{ layers.push(new RenderLayer(RenderLayer.DEFAULT_NAME)); }
96
97
this.renderLayers = layers;
98
return this.renderLayers;
99
}
100
101
getLayer (name)
102
{
103
const layers = this.renderLayers || [];
104
for (let i = 0; i < layers.length; i++)
105
{
106
if (layers[i].name === name)
107
{ return layers[i]; }
108
}
109
110
return null;
111
}
112
59
113
setPrimary ()
60
114
{
61
115
this.game.setPrimaryScene(this);
@@ -129,7 +183,7 @@ class Scene
129
183
}
130
184
131
185
this.cv_canvas = null;
132
this.cv_context = null;
186
this.glContext = null;
133
187
}
134
188
135
189
backgroundColor =
@@ -146,7 +200,7 @@ class Scene
146
200
147
201
get context ()
148
202
{
149
return this.cv_context;
203
return this.glContext ? this.glContext.gl : null;
150
204
}
151
205
152
206
addObject (obj)
@@ -181,6 +235,8 @@ class Scene
181
235
if (this.destroyed)
182
236
{ return; }
183
237
238
this.postTime += deltaTime;
239
184
240
for (let i = 0; i < this.activeObjects.length; i++)
185
241
{
186
242
this.activeObjects[i].update(deltaTime);
@@ -232,11 +288,27 @@ class Scene
232
288
this.real_size.y = this.size.y;
233
289
}
234
290
235
if (this.canvas.width != this.real_size.x)
236
{ this.canvas.width = this.real_size.x; }
291
const canvasW = Math.max(1, Math.round(this.real_size.x));
292
const canvasH = Math.max(1, Math.round(this.real_size.y));
293
let resized = false;
294
295
if (this.canvas.width != canvasW)
296
{
297
this.canvas.width = canvasW;
298
resized = true;
299
}
300
301
if (this.canvas.height != canvasH)
302
{
303
this.canvas.height = canvasH;
304
resized = true;
305
}
237
306
238
if (this.canvas.height != this.real_size.y)
239
{ this.canvas.height = this.real_size.y; }
307
// Changing canvas dimensions resets WebGL — rebuild helper/buffers/programs.
308
if (resized || !this.glContext)
309
{ this.glContext = new GLContext(this.cv_canvas); }
310
else
311
{ this.glContext.setSize(this.canvas.width, this.canvas.height); }
240
312
241
313
if (this.px != this.real_position.x)
242
314
{
@@ -251,29 +323,116 @@ class Scene
251
323
}
252
324
}
253
325
326
normalizePostShaderList (list)
327
{
328
if (!list || !list.length)
329
{ return []; }
330
331
const passes = [];
332
for (let i = 0; i < list.length; i++)
333
{
334
const entry = list[i];
335
if (!entry)
336
{ continue; }
337
338
if (entry instanceof Shader || (entry.vertSource && entry.fragSource && entry.getProgramInfo))
339
{
340
passes.push({ shader: entry, uniforms: null });
341
}
342
else if (entry.shader)
343
{
344
passes.push({ shader: entry.shader, uniforms: entry.uniforms || null });
345
}
346
}
347
348
return passes;
349
}
350
351
normalizePostShaders ()
352
{
353
return this.normalizePostShaderList(this.postShaders);
354
}
355
356
getPostPassesForLayer (layer)
357
{
358
const fromLayer = this.normalizePostShaderList(layer.postShaders);
359
if (fromLayer.length)
360
{ return fromLayer; }
361
362
// Back-compat: scene.postShaders apply to the default layer only.
363
if (layer.name === RenderLayer.DEFAULT_NAME)
364
{ return this.normalizePostShaders(); }
365
366
return [];
367
}
368
254
369
draw ()
255
370
{
256
if (this.destroyed)
371
if (this.destroyed || !this.glContext)
257
372
{ return; }
258
373
259
374
this.g_fixSize();
260
375
376
const gl = this.glContext;
377
const layers = this.renderLayers && this.renderLayers.length
378
? this.renderLayers
379
: [new RenderLayer(RenderLayer.DEFAULT_NAME)];
380
381
// Canvas clear (background behind all layers).
382
gl.endOffscreenPass();
261
383
if (this.renderBackground)
262
384
{
263
this.context.fillStyle = "rgb(" + this.backgroundColor.r + "," + this.backgroundColor.g + "," + this.backgroundColor.b + ")"; // sets the color to fill in the rectangle with
264
this.context.fillRect(0, 0, this.real_size.x, this.real_size.y);
385
gl.clear(
386
this.backgroundColor.r,
387
this.backgroundColor.g,
388
this.backgroundColor.b,
389
1
390
);
265
391
}
266
else
392
else
267
393
{
268
this.context.clearRect(0, 0, this.real_size.x, this.real_size.y);
394
gl.clearTransparent();
269
395
}
270
396
271
397
const sortedActiveObjects = this.activeObjects.slice().sort((a, b) => a.layer - b.layer);
398
const builtins = {
399
u_resolution: [gl._lastWidth, gl._lastHeight],
400
u_time: this.postTime
401
};
272
402
273
for (var i = 0; i < sortedActiveObjects.length; i++)
403
for (let li = 0; li < layers.length; li++)
274
404
{
275
if (!sortedActiveObjects[i].destroyed && sortedActiveObjects[i].renderer.visible)
276
{ sortedActiveObjects[i].draw(this.context); }
405
const renderLayer = layers[li];
406
const layerName = renderLayer.name;
407
408
gl.beginOffscreenPass();
409
gl.clearTransparent();
410
411
for (let i = 0; i < sortedActiveObjects.length; i++)
412
{
413
const obj = sortedActiveObjects[i];
414
if (obj.destroyed || !obj.renderer || !obj.renderer.visible)
415
{ continue; }
416
417
if (obj.renderer.layerName !== layerName)
418
{ continue; }
419
420
obj.draw(this.context);
421
}
422
423
const postPasses = this.getPostPassesForLayer(renderLayer);
424
let texture = gl.colorTextures[0];
425
426
if (postPasses.length)
427
{
428
texture = gl.applyPostShaders(postPasses, builtins, { toCanvas: false });
429
}
430
else
431
{
432
gl.endOffscreenPass();
433
}
434
435
gl.blitToCanvas(texture, renderLayer.composite || "alpha");
277
436
}
278
437
}
279
438
}
@@ -22,9 +22,16 @@ class Scene22
displayMode = Scene.DisplayModes.absolute;22
displayMode = Scene.DisplayModes.absolute;23
23
24
cv_canvas = null;24
cv_canvas = null;25
cv_context = null;25
glContext = null;26
destroyed = false;26
destroyed = false;27
27
28
// Legacy: posts applied to the "default" layer when that layer has none of its own.29
postShaders = [];30
postTime = 0;31
32
// Ordered list of RenderLayer. Index 0 is drawn first (back).33
renderLayers = null;34
28
game = null;35
game = null;29
36
30
get primary ()37
get primary ()@@ -50,12 +57,59 @@ class Scene50
body.insertAdjacentHTML('beforeend', '<canvas id="' + this.id + '" style="position: absolute; left: ' + x + 'px; top: ' + y + 'px;" width="' + width + '" height="' + height + '"></canvas>');57
body.insertAdjacentHTML('beforeend', '<canvas id="' + this.id + '" style="position: absolute; left: ' + x + 'px; top: ' + y + 'px;" width="' + width + '" height="' + height + '"></canvas>');51
58
52
this.cv_canvas = document.getElementById(this.id);59
this.cv_canvas = document.getElementById(this.id);53
this.cv_context = this.cv_canvas.getContext('2d');60
this.glContext = new GLContext(this.cv_canvas);61
this.postShaders = [];62
this.postTime = 0;63
this.renderLayers = [new RenderLayer(RenderLayer.DEFAULT_NAME)];54
64
55
this.g_fixSize();65
this.g_fixSize();56
this.quadTree = new QuadTree(this.real_size.x, this.real_size.y);66
this.quadTree = new QuadTree(this.real_size.x, this.real_size.y);57
}67
}58
68
69
/**70
* Replace the layer stack. Order in the array is draw order (first = back).71
* Each entry: RenderLayer, or { name, postShaders?, composite? }.72
*/73
setLayers (layerConfigs)74
{75
if (!layerConfigs || !layerConfigs.length)76
{77
this.renderLayers = [new RenderLayer(RenderLayer.DEFAULT_NAME)];78
return this.renderLayers;79
}80
81
const layers = [];82
for (let i = 0; i < layerConfigs.length; i++)83
{84
const cfg = layerConfigs[i];85
if (!cfg)86
{ continue; }87
88
if (cfg instanceof RenderLayer)89
{ layers.push(cfg); }90
else91
{ layers.push(new RenderLayer(cfg.name, cfg)); }92
}93
94
if (!layers.length)95
{ layers.push(new RenderLayer(RenderLayer.DEFAULT_NAME)); }96
97
this.renderLayers = layers;98
return this.renderLayers;99
}100
101
getLayer (name)102
{103
const layers = this.renderLayers || [];104
for (let i = 0; i < layers.length; i++)105
{106
if (layers[i].name === name)107
{ return layers[i]; }108
}109
110
return null;111
}112
59
setPrimary ()113
setPrimary ()60
{114
{61
this.game.setPrimaryScene(this);115
this.game.setPrimaryScene(this);@@ -129,7 +183,7 @@ class Scene129
}183
}130
184
131
this.cv_canvas = null;185
this.cv_canvas = null;132
this.cv_context = null;186
this.glContext = null;133
}187
}134
188
135
backgroundColor =189
backgroundColor =@@ -146,7 +200,7 @@ class Scene146
200
147
get context ()201
get context ()148
{202
{149
return this.cv_context;203
return this.glContext ? this.glContext.gl : null;150
}204
}151
205
152
addObject (obj)206
addObject (obj)@@ -181,6 +235,8 @@ class Scene181
if (this.destroyed)235
if (this.destroyed)182
{ return; }236
{ return; }183
237
238
this.postTime += deltaTime;239
184
for (let i = 0; i < this.activeObjects.length; i++)240
for (let i = 0; i < this.activeObjects.length; i++)185
{241
{186
this.activeObjects[i].update(deltaTime);242
this.activeObjects[i].update(deltaTime);@@ -232,11 +288,27 @@ class Scene232
this.real_size.y = this.size.y;288
this.real_size.y = this.size.y;233
}289
}234
290
235
if (this.canvas.width != this.real_size.x)291
const canvasW = Math.max(1, Math.round(this.real_size.x));236
{ this.canvas.width = this.real_size.x; }292
const canvasH = Math.max(1, Math.round(this.real_size.y));293
let resized = false;294
295
if (this.canvas.width != canvasW)296
{297
this.canvas.width = canvasW;298
resized = true;299
}300
301
if (this.canvas.height != canvasH)302
{303
this.canvas.height = canvasH;304
resized = true;305
}237
306
238
if (this.canvas.height != this.real_size.y)307
// Changing canvas dimensions resets WebGL — rebuild helper/buffers/programs.239
{ this.canvas.height = this.real_size.y; }308
if (resized || !this.glContext)309
{ this.glContext = new GLContext(this.cv_canvas); }310
else311
{ this.glContext.setSize(this.canvas.width, this.canvas.height); }240
312
241
if (this.px != this.real_position.x)313
if (this.px != this.real_position.x)242
{314
{@@ -251,29 +323,116 @@ class Scene251
}323
}252
}324
}253
325
326
normalizePostShaderList (list)327
{328
if (!list || !list.length)329
{ return []; }330
331
const passes = [];332
for (let i = 0; i < list.length; i++)333
{334
const entry = list[i];335
if (!entry)336
{ continue; }337
338
if (entry instanceof Shader || (entry.vertSource && entry.fragSource && entry.getProgramInfo))339
{340
passes.push({ shader: entry, uniforms: null });341
}342
else if (entry.shader)343
{344
passes.push({ shader: entry.shader, uniforms: entry.uniforms || null });345
}346
}347
348
return passes;349
}350
351
normalizePostShaders ()352
{353
return this.normalizePostShaderList(this.postShaders);354
}355
356
getPostPassesForLayer (layer)357
{358
const fromLayer = this.normalizePostShaderList(layer.postShaders);359
if (fromLayer.length)360
{ return fromLayer; }361
362
// Back-compat: scene.postShaders apply to the default layer only.363
if (layer.name === RenderLayer.DEFAULT_NAME)364
{ return this.normalizePostShaders(); }365
366
return [];367
}368
254
draw ()369
draw ()255
{370
{256
if (this.destroyed)371
if (this.destroyed || !this.glContext)257
{ return; }372
{ return; }258
373
259
this.g_fixSize();374
this.g_fixSize();260
375
376
const gl = this.glContext;377
const layers = this.renderLayers && this.renderLayers.length378
? this.renderLayers379
: [new RenderLayer(RenderLayer.DEFAULT_NAME)];380
381
// Canvas clear (background behind all layers).382
gl.endOffscreenPass();261
if (this.renderBackground)383
if (this.renderBackground)262
{384
{263
this.context.fillStyle = "rgb(" + this.backgroundColor.r + "," + this.backgroundColor.g + "," + this.backgroundColor.b + ")"; // sets the color to fill in the rectangle with385
gl.clear(264
this.context.fillRect(0, 0, this.real_size.x, this.real_size.y);386
this.backgroundColor.r,387
this.backgroundColor.g,388
this.backgroundColor.b,389
1390
);265
}391
}266
else 392
else267
{393
{268
this.context.clearRect(0, 0, this.real_size.x, this.real_size.y);394
gl.clearTransparent();269
}395
}270
396
271
const sortedActiveObjects = this.activeObjects.slice().sort((a, b) => a.layer - b.layer);397
const sortedActiveObjects = this.activeObjects.slice().sort((a, b) => a.layer - b.layer);398
const builtins = {399
u_resolution: [gl._lastWidth, gl._lastHeight],400
u_time: this.postTime401
};272
402
273
for (var i = 0; i < sortedActiveObjects.length; i++)403
for (let li = 0; li < layers.length; li++)274
{404
{275
if (!sortedActiveObjects[i].destroyed && sortedActiveObjects[i].renderer.visible)405
const renderLayer = layers[li];276
{ sortedActiveObjects[i].draw(this.context); }406
const layerName = renderLayer.name;407
408
gl.beginOffscreenPass();409
gl.clearTransparent();410
411
for (let i = 0; i < sortedActiveObjects.length; i++)412
{413
const obj = sortedActiveObjects[i];414
if (obj.destroyed || !obj.renderer || !obj.renderer.visible)415
{ continue; }416
417
if (obj.renderer.layerName !== layerName)418
{ continue; }419
420
obj.draw(this.context);421
}422
423
const postPasses = this.getPostPassesForLayer(renderLayer);424
let texture = gl.colorTextures[0];425
426
if (postPasses.length)427
{428
texture = gl.applyPostShaders(postPasses, builtins, { toCanvas: false });429
}430
else431
{432
gl.endOffscreenPass();433
}434
435
gl.blitToCanvas(texture, renderLayer.composite || "alpha");277
}436
}278
}437
}279
}438
}@@ -1,24 +1,53 @@
1
1
#!/usr/bin/env bash
2
set -euo pipefail
3
2
4
BUILD_FILE="./js/framework.js"
3
SRC_DIR="./framework"
4
5
5
printf "Build started, output file: $BUILD_FILE\n"
6
unlink $BUILD_FILE
6
# Explicit order: GL helpers before scene/image consumers; extensions last.
7
FILES=(
8
"framework/extensions/polyfills.js"
9
"framework/extensions/extentions.js"
10
"framework/extensions/thirdparty.js"
11
"framework/util/vector.js"
12
"framework/util/ease.js"
13
"framework/util/timingUtil.js"
14
"framework/util/signal.js"
15
"framework/util/cookie.js"
16
"framework/util/urlParams.js"
17
"framework/util/input.js"
18
"framework/util/audio.js"
19
"framework/util/ray.js"
20
"framework/util/quadTree.js"
21
"framework/util/particleEmitter.js"
22
"framework/engine/gl/shader.js"
23
"framework/engine/gl/builtinShaders.js"
24
"framework/engine/gl/glContext.js"
25
"framework/engine/renderLayer.js"
26
"framework/engine/objectComponents/transform.js"
27
"framework/engine/objectComponents/collider.js"
28
"framework/engine/objectComponents/renderer.js"
29
"framework/engine/image.js"
30
"framework/engine/gameobject.js"
31
"framework/engine/scene.js"
32
"framework/engine/game.js"
33
)
34
35
printf "Build started, output file: %s\n" "$BUILD_FILE"
36
rm -f "$BUILD_FILE"
37
mkdir -p "$(dirname "$BUILD_FILE")"
38
39
for file in "${FILES[@]}"
40
do
41
if [[ ! -f "$file" ]]
42
then
43
printf "Missing source file: %s\n" "$file" >&2
44
exit 1
45
fi
7
46
8
loop() {
9
shopt -s nullglob
10
shopt -s globstar
47
printf "\n/*\n * Start File:\n * %s\n */ \n" "$file" >> "$BUILD_FILE"
48
printf "Building %s\n" "$file"
49
cat "$file" >> "$BUILD_FILE"
50
printf "\n/*\n * End File:\n * %s\n */ \n" "$file" >> "$BUILD_FILE"
51
done
11
52
12
for file in "$@"/**
13
do
14
if [[ -f "$file" && "${file##*.}" = "js" ]]
15
then
16
printf "\n/*\n * Start File:\n * "$file"\n */ \n" >> "$BUILD_FILE";
17
printf "Building "$file"\n";
18
cat "$file" >> "$BUILD_FILE";
19
printf "\n/*\n * End File:\n * "$file"\n */ \n" >> "$BUILD_FILE";
20
fi
21
done
22
}
23
loop $SRC_DIR
24
printf "DONE"
53
printf "DONE\n"
@@ -1,24 +1,53 @@1
#!/usr/bin/env bash1
#!/usr/bin/env bash2
set -euo pipefail3
2
BUILD_FILE="./js/framework.js"4
BUILD_FILE="./js/framework.js"3
SRC_DIR="./framework"4
5
5
printf "Build started, output file: $BUILD_FILE\n"6
# Explicit order: GL helpers before scene/image consumers; extensions last.6
unlink $BUILD_FILE7
FILES=(8
"framework/extensions/polyfills.js"9
"framework/extensions/extentions.js"10
"framework/extensions/thirdparty.js"11
"framework/util/vector.js"12
"framework/util/ease.js"13
"framework/util/timingUtil.js"14
"framework/util/signal.js"15
"framework/util/cookie.js"16
"framework/util/urlParams.js"17
"framework/util/input.js"18
"framework/util/audio.js"19
"framework/util/ray.js"20
"framework/util/quadTree.js"21
"framework/util/particleEmitter.js"22
"framework/engine/gl/shader.js"23
"framework/engine/gl/builtinShaders.js"24
"framework/engine/gl/glContext.js"25
"framework/engine/renderLayer.js"26
"framework/engine/objectComponents/transform.js"27
"framework/engine/objectComponents/collider.js"28
"framework/engine/objectComponents/renderer.js"29
"framework/engine/image.js"30
"framework/engine/gameobject.js"31
"framework/engine/scene.js"32
"framework/engine/game.js"33
)34
35
printf "Build started, output file: %s\n" "$BUILD_FILE"36
rm -f "$BUILD_FILE"37
mkdir -p "$(dirname "$BUILD_FILE")"38
39
for file in "${FILES[@]}"40
do41
if [[ ! -f "$file" ]]42
then43
printf "Missing source file: %s\n" "$file" >&244
exit 145
fi7
46
8
loop() {47
printf "\n/*\n * Start File:\n * %s\n */ \n" "$file" >> "$BUILD_FILE"9
shopt -s nullglob48
printf "Building %s\n" "$file"10
shopt -s globstar49
cat "$file" >> "$BUILD_FILE"50
printf "\n/*\n * End File:\n * %s\n */ \n" "$file" >> "$BUILD_FILE"51
done11
52
12
for file in "$@"/**53
printf "DONE\n"13
do14
if [[ -f "$file" && "${file##*.}" = "js" ]]15
then16
printf "\n/*\n * Start File:\n * "$file"\n */ \n" >> "$BUILD_FILE"; 17
printf "Building "$file"\n";18
cat "$file" >> "$BUILD_FILE"; 19
printf "\n/*\n * End File:\n * "$file"\n */ \n" >> "$BUILD_FILE"; 20
fi21
done22
}23
loop $SRC_DIR24
printf "DONE"