Add render layers and multi-pass screen-space bloom.
Support ordered layer stacks with per-layer post shaders, keep scene color for combines, and ship a tunable builtin bloom chain (including small-source dilate). Co-authored-by: Cursor <cursoragent@cursor.com>
@@ -137,7 +137,7 @@ class Game
137
137
138
138
promises.push((async () =>
139
139
{
140
let vertSource = Shader.DEFAULT_VERT;
140
let vertSource = shaderData.screen ? Shader.SCREEN_VERT : Shader.DEFAULT_VERT;
141
141
142
142
if (shaderData.vert)
143
143
{
@@ -159,6 +159,7 @@ class Game
159
159
const fragSource = await fragResponse.text();
160
160
const shader = new Shader(vertSource, fragSource);
161
161
shader.name = shaderData.name;
162
shader.screen = !!shaderData.screen || vertSource === Shader.SCREEN_VERT;
162
163
context.shaders[shaderData.name] = shader;
163
164
})());
164
165
}
@@ -137,7 +137,7 @@ class Game137
137
138
promises.push((async () =>138
promises.push((async () =>139
{139
{140
let vertSource = Shader.DEFAULT_VERT;140
let vertSource = shaderData.screen ? Shader.SCREEN_VERT : Shader.DEFAULT_VERT;141
141
142
if (shaderData.vert)142
if (shaderData.vert)143
{143
{@@ -159,6 +159,7 @@ class Game159
const fragSource = await fragResponse.text();159
const fragSource = await fragResponse.text();160
const shader = new Shader(vertSource, fragSource);160
const shader = new Shader(vertSource, fragSource);161
shader.name = shaderData.name;161
shader.name = shaderData.name;162
shader.screen = !!shaderData.screen || vertSource === Shader.SCREEN_VERT;162
context.shaders[shaderData.name] = shader;163
context.shaders[shaderData.name] = shader;163
})());164
})());164
}165
}@@ -0,0 +1,172 @@
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
};
@@ -0,0 +1,172 @@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
};@@ -17,6 +17,7 @@ class GLContext
17
17
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
18
18
19
19
this.defaultShader = new Shader(Shader.DEFAULT_VERT, Shader.DEFAULT_FRAG);
20
this.screenCopyShader = new Shader(Shader.SCREEN_VERT, Shader.SCREEN_COPY_FRAG);
20
21
this.textures = new WeakMap();
21
22
22
23
this.positionBuffer = gl.createBuffer();
@@ -29,6 +30,30 @@ class GLContext
29
30
]), gl.STATIC_DRAW);
30
31
31
32
this.texCoordBuffer = gl.createBuffer();
33
34
// Fullscreen NDC quad (triangle strip) + UVs (v=0 at bottom, matches FBO sampling).
35
this.screenPositionBuffer = gl.createBuffer();
36
gl.bindBuffer(gl.ARRAY_BUFFER, this.screenPositionBuffer);
37
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
38
-1, -1,
39
1, -1,
40
-1, 1,
41
1, 1
42
]), gl.STATIC_DRAW);
43
44
this.screenTexCoordBuffer = gl.createBuffer();
45
gl.bindBuffer(gl.ARRAY_BUFFER, this.screenTexCoordBuffer);
46
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
47
0, 0,
48
1, 0,
49
0, 1,
50
1, 1
51
]), gl.STATIC_DRAW);
52
53
// [0] = scene (stable during post), [1]/[2] = ping-pong for effect passes.
54
this.framebuffers = [null, null, null];
55
this.colorTextures = [null, null, null];
56
this._offscreenIndex = 0;
32
57
this._lastWidth = 0;
33
58
this._lastHeight = 0;
34
59
this.setSize(canvas.width, canvas.height);
@@ -37,12 +62,68 @@ class GLContext
37
62
setSize (width, height)
38
63
{
39
64
const gl = this.gl;
65
width = Math.max(1, width | 0);
66
height = Math.max(1, height | 0);
67
40
68
if (width !== this._lastWidth || height !== this._lastHeight)
41
69
{
42
70
this._lastWidth = width;
43
71
this._lastHeight = height;
44
72
gl.viewport(0, 0, width, height);
73
this._rebuildFramebuffers(width, height);
74
}
75
}
76
77
_destroyFramebuffers ()
78
{
79
const gl = this.gl;
80
for (let i = 0; i < this.framebuffers.length; i++)
81
{
82
if (this.framebuffers[i])
83
{
84
gl.deleteFramebuffer(this.framebuffers[i]);
85
this.framebuffers[i] = null;
86
}
87
88
if (this.colorTextures[i])
89
{
90
gl.deleteTexture(this.colorTextures[i]);
91
this.colorTextures[i] = null;
92
}
93
}
94
}
95
96
_rebuildFramebuffers (width, height)
97
{
98
const gl = this.gl;
99
this._destroyFramebuffers();
100
101
for (let i = 0; i < 3; i++)
102
{
103
const texture = gl.createTexture();
104
gl.bindTexture(gl.TEXTURE_2D, texture);
105
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
106
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
107
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
108
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
109
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
110
111
const fb = gl.createFramebuffer();
112
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
113
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
114
115
const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
116
if (status !== gl.FRAMEBUFFER_COMPLETE)
117
{
118
console.error("Framebuffer incomplete:", status);
119
}
120
121
this.framebuffers[i] = fb;
122
this.colorTextures[i] = texture;
45
123
}
124
125
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
126
gl.bindTexture(gl.TEXTURE_2D, null);
46
127
}
47
128
48
129
clear (r, g, b, a = 1)
@@ -59,6 +140,149 @@ class GLContext
59
140
gl.clear(gl.COLOR_BUFFER_BIT);
60
141
}
61
142
143
beginOffscreenPass ()
144
{
145
const gl = this.gl;
146
this._offscreenIndex = 0;
147
gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[0]);
148
gl.viewport(0, 0, this._lastWidth, this._lastHeight);
149
gl.enable(gl.BLEND);
150
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
151
}
152
153
endOffscreenPass ()
154
{
155
const gl = this.gl;
156
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
157
}
158
159
/**
160
* @param {Array} passes
161
* @param {Object} builtins
162
* @param {{ toCanvas?: boolean }} options - toCanvas true writes the last pass to the canvas.
163
* @returns {WebGLTexture|null} final color texture when not drawing to canvas
164
*/
165
applyPostShaders (passes, builtins = {}, options = {})
166
{
167
if (!passes || !passes.length)
168
{ return this.colorTextures[0]; }
169
170
const gl = this.gl;
171
const toCanvas = !!options.toCanvas;
172
const sceneTexture = this.colorTextures[0];
173
let read = 0;
174
175
gl.disable(gl.BLEND);
176
177
for (let i = 0; i < passes.length; i++)
178
{
179
const pass = passes[i];
180
const isLast = i === passes.length - 1;
181
182
// Never overwrite the scene buffer (index 0); ping-pong on 1/2.
183
let write = 1;
184
if (read === 1)
185
{ write = 2; }
186
else if (read === 2)
187
{ write = 1; }
188
189
if (isLast && toCanvas)
190
{
191
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
192
}
193
else
194
{
195
gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[write]);
196
}
197
198
gl.viewport(0, 0, this._lastWidth, this._lastHeight);
199
gl.clearColor(0, 0, 0, 0);
200
gl.clear(gl.COLOR_BUFFER_BIT);
201
202
const uniforms = Object.assign({}, builtins, pass.uniforms || {});
203
this.drawFullscreen(pass.shader, this.colorTextures[read], uniforms, sceneTexture);
204
205
if (!isLast || !toCanvas)
206
{ read = write; }
207
}
208
209
this._offscreenIndex = read;
210
gl.enable(gl.BLEND);
211
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
212
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
213
214
return toCanvas ? null : this.colorTextures[read];
215
}
216
217
blitToCanvas (texture, composite = "alpha")
218
{
219
if (!texture)
220
{ return; }
221
222
const gl = this.gl;
223
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
224
gl.viewport(0, 0, this._lastWidth, this._lastHeight);
225
gl.enable(gl.BLEND);
226
227
if (composite === "add")
228
{ gl.blendFunc(gl.ONE, gl.ONE); }
229
else
230
{ gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); }
231
232
this.drawFullscreen(this.screenCopyShader, texture, null, null);
233
234
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
235
}
236
237
drawFullscreen (shader, texture, uniforms, sceneTexture)
238
{
239
const gl = this.gl;
240
const info = shader.getProgramInfo(gl);
241
if (!info || !texture)
242
{ return; }
243
244
gl.useProgram(info.program);
245
246
gl.bindBuffer(gl.ARRAY_BUFFER, this.screenPositionBuffer);
247
if (info.attribs.position >= 0)
248
{
249
gl.enableVertexAttribArray(info.attribs.position);
250
gl.vertexAttribPointer(info.attribs.position, 2, gl.FLOAT, false, 0, 0);
251
}
252
253
gl.bindBuffer(gl.ARRAY_BUFFER, this.screenTexCoordBuffer);
254
if (info.attribs.texCoord >= 0)
255
{
256
gl.enableVertexAttribArray(info.attribs.texCoord);
257
gl.vertexAttribPointer(info.attribs.texCoord, 2, gl.FLOAT, false, 0, 0);
258
}
259
260
gl.activeTexture(gl.TEXTURE0);
261
gl.bindTexture(gl.TEXTURE_2D, texture);
262
this._setUniform(info, "u_texture", 0);
263
this._setUniform(info, "u_alpha", 1);
264
265
if (sceneTexture && info.uniforms.u_scene)
266
{
267
gl.activeTexture(gl.TEXTURE1);
268
gl.bindTexture(gl.TEXTURE_2D, sceneTexture);
269
this._setUniform(info, "u_scene", 1);
270
}
271
272
if (uniforms)
273
{
274
for (const name in uniforms)
275
{
276
if (!Object.prototype.hasOwnProperty.call(uniforms, name))
277
{ continue; }
278
279
this._setUniform(info, name, uniforms[name]);
280
}
281
}
282
283
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
284
}
285
62
286
getTexture (htmlImage)
63
287
{
64
288
if (!htmlImage)
@@ -17,6 +17,7 @@ class GLContext17
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);17
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);18
18
19
this.defaultShader = new Shader(Shader.DEFAULT_VERT, Shader.DEFAULT_FRAG);19
this.defaultShader = new Shader(Shader.DEFAULT_VERT, Shader.DEFAULT_FRAG);20
this.screenCopyShader = new Shader(Shader.SCREEN_VERT, Shader.SCREEN_COPY_FRAG);20
this.textures = new WeakMap();21
this.textures = new WeakMap();21
22
22
this.positionBuffer = gl.createBuffer();23
this.positionBuffer = gl.createBuffer();@@ -29,6 +30,30 @@ class GLContext29
]), gl.STATIC_DRAW);30
]), gl.STATIC_DRAW);30
31
31
this.texCoordBuffer = gl.createBuffer();32
this.texCoordBuffer = gl.createBuffer();33
34
// Fullscreen NDC quad (triangle strip) + UVs (v=0 at bottom, matches FBO sampling).35
this.screenPositionBuffer = gl.createBuffer();36
gl.bindBuffer(gl.ARRAY_BUFFER, this.screenPositionBuffer);37
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([38
-1, -1,39
1, -1,40
-1, 1,41
1, 142
]), gl.STATIC_DRAW);43
44
this.screenTexCoordBuffer = gl.createBuffer();45
gl.bindBuffer(gl.ARRAY_BUFFER, this.screenTexCoordBuffer);46
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([47
0, 0,48
1, 0,49
0, 1,50
1, 151
]), gl.STATIC_DRAW);52
53
// [0] = scene (stable during post), [1]/[2] = ping-pong for effect passes.54
this.framebuffers = [null, null, null];55
this.colorTextures = [null, null, null];56
this._offscreenIndex = 0;32
this._lastWidth = 0;57
this._lastWidth = 0;33
this._lastHeight = 0;58
this._lastHeight = 0;34
this.setSize(canvas.width, canvas.height);59
this.setSize(canvas.width, canvas.height);@@ -37,12 +62,68 @@ class GLContext37
setSize (width, height)62
setSize (width, height)38
{63
{39
const gl = this.gl;64
const gl = this.gl;65
width = Math.max(1, width | 0);66
height = Math.max(1, height | 0);67
40
if (width !== this._lastWidth || height !== this._lastHeight)68
if (width !== this._lastWidth || height !== this._lastHeight)41
{69
{42
this._lastWidth = width;70
this._lastWidth = width;43
this._lastHeight = height;71
this._lastHeight = height;44
gl.viewport(0, 0, width, height);72
gl.viewport(0, 0, width, height);73
this._rebuildFramebuffers(width, height);74
}75
}76
77
_destroyFramebuffers ()78
{79
const gl = this.gl;80
for (let i = 0; i < this.framebuffers.length; i++)81
{82
if (this.framebuffers[i])83
{84
gl.deleteFramebuffer(this.framebuffers[i]);85
this.framebuffers[i] = null;86
}87
88
if (this.colorTextures[i])89
{90
gl.deleteTexture(this.colorTextures[i]);91
this.colorTextures[i] = null;92
}93
}94
}95
96
_rebuildFramebuffers (width, height)97
{98
const gl = this.gl;99
this._destroyFramebuffers();100
101
for (let i = 0; i < 3; i++)102
{103
const texture = gl.createTexture();104
gl.bindTexture(gl.TEXTURE_2D, texture);105
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);106
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);107
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);108
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);109
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);110
111
const fb = gl.createFramebuffer();112
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);113
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);114
115
const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);116
if (status !== gl.FRAMEBUFFER_COMPLETE)117
{118
console.error("Framebuffer incomplete:", status);119
}120
121
this.framebuffers[i] = fb;122
this.colorTextures[i] = texture;45
}123
}124
125
gl.bindFramebuffer(gl.FRAMEBUFFER, null);126
gl.bindTexture(gl.TEXTURE_2D, null);46
}127
}47
128
48
clear (r, g, b, a = 1)129
clear (r, g, b, a = 1)@@ -59,6 +140,149 @@ class GLContext59
gl.clear(gl.COLOR_BUFFER_BIT);140
gl.clear(gl.COLOR_BUFFER_BIT);60
}141
}61
142
143
beginOffscreenPass ()144
{145
const gl = this.gl;146
this._offscreenIndex = 0;147
gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[0]);148
gl.viewport(0, 0, this._lastWidth, this._lastHeight);149
gl.enable(gl.BLEND);150
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);151
}152
153
endOffscreenPass ()154
{155
const gl = this.gl;156
gl.bindFramebuffer(gl.FRAMEBUFFER, null);157
}158
159
/**160
* @param {Array} passes161
* @param {Object} builtins162
* @param {{ toCanvas?: boolean }} options - toCanvas true writes the last pass to the canvas.163
* @returns {WebGLTexture|null} final color texture when not drawing to canvas164
*/165
applyPostShaders (passes, builtins = {}, options = {})166
{167
if (!passes || !passes.length)168
{ return this.colorTextures[0]; }169
170
const gl = this.gl;171
const toCanvas = !!options.toCanvas;172
const sceneTexture = this.colorTextures[0];173
let read = 0;174
175
gl.disable(gl.BLEND);176
177
for (let i = 0; i < passes.length; i++)178
{179
const pass = passes[i];180
const isLast = i === passes.length - 1;181
182
// Never overwrite the scene buffer (index 0); ping-pong on 1/2.183
let write = 1;184
if (read === 1)185
{ write = 2; }186
else if (read === 2)187
{ write = 1; }188
189
if (isLast && toCanvas)190
{191
gl.bindFramebuffer(gl.FRAMEBUFFER, null);192
}193
else194
{195
gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[write]);196
}197
198
gl.viewport(0, 0, this._lastWidth, this._lastHeight);199
gl.clearColor(0, 0, 0, 0);200
gl.clear(gl.COLOR_BUFFER_BIT);201
202
const uniforms = Object.assign({}, builtins, pass.uniforms || {});203
this.drawFullscreen(pass.shader, this.colorTextures[read], uniforms, sceneTexture);204
205
if (!isLast || !toCanvas)206
{ read = write; }207
}208
209
this._offscreenIndex = read;210
gl.enable(gl.BLEND);211
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);212
gl.bindFramebuffer(gl.FRAMEBUFFER, null);213
214
return toCanvas ? null : this.colorTextures[read];215
}216
217
blitToCanvas (texture, composite = "alpha")218
{219
if (!texture)220
{ return; }221
222
const gl = this.gl;223
gl.bindFramebuffer(gl.FRAMEBUFFER, null);224
gl.viewport(0, 0, this._lastWidth, this._lastHeight);225
gl.enable(gl.BLEND);226
227
if (composite === "add")228
{ gl.blendFunc(gl.ONE, gl.ONE); }229
else230
{ gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); }231
232
this.drawFullscreen(this.screenCopyShader, texture, null, null);233
234
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);235
}236
237
drawFullscreen (shader, texture, uniforms, sceneTexture)238
{239
const gl = this.gl;240
const info = shader.getProgramInfo(gl);241
if (!info || !texture)242
{ return; }243
244
gl.useProgram(info.program);245
246
gl.bindBuffer(gl.ARRAY_BUFFER, this.screenPositionBuffer);247
if (info.attribs.position >= 0)248
{249
gl.enableVertexAttribArray(info.attribs.position);250
gl.vertexAttribPointer(info.attribs.position, 2, gl.FLOAT, false, 0, 0);251
}252
253
gl.bindBuffer(gl.ARRAY_BUFFER, this.screenTexCoordBuffer);254
if (info.attribs.texCoord >= 0)255
{256
gl.enableVertexAttribArray(info.attribs.texCoord);257
gl.vertexAttribPointer(info.attribs.texCoord, 2, gl.FLOAT, false, 0, 0);258
}259
260
gl.activeTexture(gl.TEXTURE0);261
gl.bindTexture(gl.TEXTURE_2D, texture);262
this._setUniform(info, "u_texture", 0);263
this._setUniform(info, "u_alpha", 1);264
265
if (sceneTexture && info.uniforms.u_scene)266
{267
gl.activeTexture(gl.TEXTURE1);268
gl.bindTexture(gl.TEXTURE_2D, sceneTexture);269
this._setUniform(info, "u_scene", 1);270
}271
272
if (uniforms)273
{274
for (const name in uniforms)275
{276
if (!Object.prototype.hasOwnProperty.call(uniforms, name))277
{ continue; }278
279
this._setUniform(info, name, uniforms[name]);280
}281
}282
283
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);284
}285
62
getTexture (htmlImage)286
getTexture (htmlImage)63
{287
{64
if (!htmlImage)288
if (!htmlImage)@@ -22,6 +22,26 @@ class Shader
22
22
"}"
23
23
].join("\n");
24
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
25
45
constructor (vertSource, fragSource)
26
46
{
27
47
this.vertSource = vertSource || Shader.DEFAULT_VERT;
@@ -34,6 +54,11 @@ class Shader
34
54
return new Shader(Shader.DEFAULT_VERT, fragSource);
35
55
}
36
56
57
static screenFragment (fragSource)
58
{
59
return new Shader(Shader.SCREEN_VERT, fragSource);
60
}
61
37
62
getProgramInfo (gl)
38
63
{
39
64
let info = this._programs.get(gl);
@@ -22,6 +22,26 @@ class Shader22
"}"22
"}"23
].join("\n");23
].join("\n");24
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
25
constructor (vertSource, fragSource)45
constructor (vertSource, fragSource)26
{46
{27
this.vertSource = vertSource || Shader.DEFAULT_VERT;47
this.vertSource = vertSource || Shader.DEFAULT_VERT;@@ -34,6 +54,11 @@ class Shader34
return new Shader(Shader.DEFAULT_VERT, fragSource);54
return new Shader(Shader.DEFAULT_VERT, fragSource);35
}55
}36
56
57
static screenFragment (fragSource)58
{59
return new Shader(Shader.SCREEN_VERT, fragSource);60
}61
37
getProgramInfo (gl)62
getProgramInfo (gl)38
{63
{39
let info = this._programs.get(gl);64
let info = this._programs.get(gl);@@ -16,12 +16,21 @@ class Renderer
16
16
shader = null;
17
17
shaderUniforms = null;
18
18
19
// RenderLayer name; null uses RenderLayer.DEFAULT_NAME ("default").
20
layer = null;
21
19
22
constructor (parentObject, sprite)
20
23
{
21
24
this.gameObject = parentObject;
22
25
this.sprite = sprite;
23
26
this.shader = null;
24
27
this.shaderUniforms = null;
28
this.layer = null;
29
}
30
31
get layerName ()
32
{
33
return this.layer || RenderLayer.DEFAULT_NAME;
25
34
}
26
35
27
36
update (deltaTime)
@@ -16,12 +16,21 @@ class Renderer16
shader = null;16
shader = null;17
shaderUniforms = null;17
shaderUniforms = null;18
18
19
// RenderLayer name; null uses RenderLayer.DEFAULT_NAME ("default").20
layer = null;21
19
constructor (parentObject, sprite)22
constructor (parentObject, sprite)20
{23
{21
this.gameObject = parentObject;24
this.gameObject = parentObject;22
this.sprite = sprite;25
this.sprite = sprite;23
this.shader = null;26
this.shader = null;24
this.shaderUniforms = null;27
this.shaderUniforms = null;28
this.layer = null;29
}30
31
get layerName ()32
{33
return this.layer || RenderLayer.DEFAULT_NAME;25
}34
}26
35
27
update (deltaTime) 36
update (deltaTime) @@ -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
}@@ -25,6 +25,13 @@ class Scene
25
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 ()
@@ -51,11 +58,58 @@ class Scene
51
58
52
59
this.cv_canvas = document.getElementById(this.id);
53
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);
@@ -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);
@@ -267,6 +323,49 @@ class Scene
267
323
}
268
324
}
269
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
270
369
draw ()
271
370
{
272
371
if (this.destroyed || !this.glContext)
@@ -274,9 +373,16 @@ class Scene
274
373
275
374
this.g_fixSize();
276
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();
277
383
if (this.renderBackground)
278
384
{
279
this.glContext.clear(
385
gl.clear(
280
386
this.backgroundColor.r,
281
387
this.backgroundColor.g,
282
388
this.backgroundColor.b,
@@ -285,15 +391,48 @@ class Scene
285
391
}
286
392
else
287
393
{
288
this.glContext.clearTransparent();
394
gl.clearTransparent();
289
395
}
290
396
291
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
};
292
402
293
for (var i = 0; i < sortedActiveObjects.length; i++)
403
for (let li = 0; li < layers.length; li++)
294
404
{
295
if (!sortedActiveObjects[i].destroyed && sortedActiveObjects[i].renderer.visible)
296
{ 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");
297
436
}
298
437
}
299
438
}
@@ -25,6 +25,13 @@ class Scene25
glContext = 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 ()@@ -51,11 +58,58 @@ class Scene51
58
52
this.cv_canvas = document.getElementById(this.id);59
this.cv_canvas = document.getElementById(this.id);53
this.glContext = new GLContext(this.cv_canvas);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);@@ -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);@@ -267,6 +323,49 @@ class Scene267
}323
}268
}324
}269
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
270
draw ()369
draw ()271
{370
{272
if (this.destroyed || !this.glContext)371
if (this.destroyed || !this.glContext)@@ -274,9 +373,16 @@ class Scene274
373
275
this.g_fixSize();374
this.g_fixSize();276
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();277
if (this.renderBackground)383
if (this.renderBackground)278
{384
{279
this.glContext.clear(385
gl.clear(280
this.backgroundColor.r,386
this.backgroundColor.r,281
this.backgroundColor.g,387
this.backgroundColor.g,282
this.backgroundColor.b,388
this.backgroundColor.b,@@ -285,15 +391,48 @@ class Scene285
}391
}286
else392
else287
{393
{288
this.glContext.clearTransparent();394
gl.clearTransparent();289
}395
}290
396
291
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
};292
402
293
for (var i = 0; i < sortedActiveObjects.length; i++)403
for (let li = 0; li < layers.length; li++)294
{404
{295
if (!sortedActiveObjects[i].destroyed && sortedActiveObjects[i].renderer.visible)405
const renderLayer = layers[li];296
{ 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");297
}436
}298
}437
}299
}438
}@@ -20,7 +20,9 @@ FILES=(
20
20
"framework/util/quadTree.js"
21
21
"framework/util/particleEmitter.js"
22
22
"framework/engine/gl/shader.js"
23
"framework/engine/gl/builtinShaders.js"
23
24
"framework/engine/gl/glContext.js"
25
"framework/engine/renderLayer.js"
24
26
"framework/engine/objectComponents/transform.js"
25
27
"framework/engine/objectComponents/collider.js"
26
28
"framework/engine/objectComponents/renderer.js"
@@ -20,7 +20,9 @@ FILES=(20
"framework/util/quadTree.js"20
"framework/util/quadTree.js"21
"framework/util/particleEmitter.js"21
"framework/util/particleEmitter.js"22
"framework/engine/gl/shader.js"22
"framework/engine/gl/shader.js"23
"framework/engine/gl/builtinShaders.js"23
"framework/engine/gl/glContext.js"24
"framework/engine/gl/glContext.js"25
"framework/engine/renderLayer.js"24
"framework/engine/objectComponents/transform.js"26
"framework/engine/objectComponents/transform.js"25
"framework/engine/objectComponents/collider.js"27
"framework/engine/objectComponents/collider.js"26
"framework/engine/objectComponents/renderer.js"28
"framework/engine/objectComponents/renderer.js"