Skip to content

Commit 9f06665

Browse files
committed
add dispose method
1 parent 68b8ae6 commit 9f06665

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

src/virtual-webgl.js

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,12 @@
138138
return value === undefined ? defaultValue : value;
139139
}
140140

141+
function errorDisposedContext(fnName) {
142+
return function() {
143+
throw new Error(`tried to call ${fnName} on disposed context`);
144+
};
145+
}
146+
141147
class DefaultCompositor {
142148
constructor(canvas) {
143149
this._ctx = canvas.getContext('2d');
@@ -172,15 +178,18 @@
172178
0, maxHeight - height, width, height, // src rect
173179
0, 0, width, height); // dest rect
174180
}
181+
dispose() {
182+
}
175183
}
176184

177185
class VirtualWebGLContext {
178-
constructor(canvas, contextAttributes = {}, compositor) {
186+
constructor(canvas, contextAttributes = {}, compositor, disposeHelper) {
179187
const gl = sharedWebGLContext;
180188
this.canvas = canvas;
181189
// Should use Symbols or someting to hide these variables from the outside.
182190

183191
this._compositor = compositor;
192+
this._disposeHelper = disposeHelper;
184193
this._extensions = {};
185194
// based on context attributes and canvas.width, canvas.height
186195
// create a texture and framebuffer
@@ -233,6 +242,28 @@
233242
this._defaultVertexArray = this._state.vertexArray;
234243
}
235244
}
245+
dispose() {
246+
this._disposeHelper();
247+
const gl = sharedWebGLContext;
248+
gl.deleteFramebuffer(this._drawingbufferFramebuffer);
249+
gl.deleteTexture(this._drawingbufferTexture);
250+
if (this._depthRenderbuffer) {
251+
gl.deleteRenderbuffer(this._depthRenderbuffer);
252+
}
253+
if (this._compositor.dispose) {
254+
this._compositor.dispose();
255+
}
256+
for (const [key, value] of Object.entries(this)) {
257+
if (typeof value === 'function') {
258+
this[key] = errorDisposedContext(key);
259+
}
260+
}
261+
for (const [key, value] of Object.entries(VirtualWebGLContext.prototype)) {
262+
if (typeof value === 'function') {
263+
this[key] = errorDisposedContext(key);
264+
}
265+
}
266+
}
236267
get drawingBufferWidth() {
237268
return this.canvas.width;
238269
}
@@ -691,7 +722,9 @@
691722
}
692723

693724
const compositor = settings.compositorCreator(canvas, type, contextAttributes) || new DefaultCompositor(canvas, type, contextAttributes);
694-
const newVirtualCtx = new VirtualWebGLContext(canvas, contextAttributes, compositor);
725+
const newVirtualCtx = new VirtualWebGLContext(canvas, contextAttributes, compositor, () => {
726+
canvasToVirtualContextMap.delete(canvas);
727+
});
695728
canvasToVirtualContextMap.set(canvas, newVirtualCtx);
696729

697730
return newVirtualCtx;

0 commit comments

Comments
 (0)