Add auto context restoration

This commit is contained in:
schmelczerandras 2020-09-27 16:10:52 +02:00
parent 40b9644171
commit 2e57f090e6
14 changed files with 352 additions and 136 deletions

View file

@ -0,0 +1,27 @@
let isEnabled = false;
export const enableContextLostSimulator = (canvas: HTMLCanvasElement) => {
if (isEnabled) {
return;
}
isEnabled = true;
const gl = canvas.getContext('webgl2')!;
const ext = gl.getExtension('WEBGL_lose_context');
const simulateContextLost = () => {
ext!.loseContext();
console.log('lost');
const restoreTimeout = Math.random() * 500;
setTimeout(() => {
ext!.restoreContext();
console.log('restored');
}, restoreTimeout);
setTimeout(() => simulateContextLost(), restoreTimeout + Math.random() * 500);
};
setTimeout(simulateContextLost, 1000);
};

View file

@ -1,32 +1,16 @@
import { Insights } from '../../rendering/insights';
import { UniversalRenderingContext } from '../universal-rendering-context';
const extensions: Map<string, any> = new Map();
const logExtensions = () => {
const values: any = {};
for (const [k, v] of extensions.entries()) {
values[k] = v !== null;
}
Insights.setValue('extensions', values);
};
export const tryEnableExtension = (
gl: UniversalRenderingContext,
name: string
): any | null => {
if (extensions.has(name)) {
return extensions.get(name);
}
let extension = null;
if (gl.getSupportedExtensions()!.indexOf(name) != -1) {
extension = gl.getExtension(name);
}
extensions.set(name, extension);
logExtensions();
Insights.setValue(['extensions', name], extension !== null);
return extension;
};

View file

@ -12,17 +12,17 @@ type CompilingProgram = {
type ShaderWithSource = WebGLShader & { source: string };
export abstract class ParallelCompiler {
private static extension?: any;
private static gl: UniversalRenderingContext;
private static programs: Array<CompilingProgram> = [];
export class ParallelCompiler {
private extension?: any;
private gl: UniversalRenderingContext;
private programs: Array<CompilingProgram> = [];
public static initialize(gl: UniversalRenderingContext) {
ParallelCompiler.gl = gl;
ParallelCompiler.extension = tryEnableExtension(gl, 'KHR_parallel_shader_compile');
public constructor(gl: UniversalRenderingContext) {
this.gl = gl;
this.extension = tryEnableExtension(gl, 'KHR_parallel_shader_compile');
}
public static createProgram(
public createProgram(
vertexShaderSource: string,
fragmentShaderSource: string,
substitutions: { [name: string]: string }
@ -31,23 +31,23 @@ export abstract class ParallelCompiler {
const promise = new Promise<WebGLProgram>((r) => (resolvePromise = r));
// can only return null on lost context
const program = ParallelCompiler.gl.createProgram()!;
const program = this.gl.createProgram()!;
const vertexShader = ParallelCompiler.compileShader(
const vertexShader = this.compileShader(
vertexShaderSource,
ParallelCompiler.gl.VERTEX_SHADER,
this.gl.VERTEX_SHADER,
program,
substitutions
);
const fragmentShader = ParallelCompiler.compileShader(
const fragmentShader = this.compileShader(
fragmentShaderSource,
ParallelCompiler.gl.FRAGMENT_SHADER,
this.gl.FRAGMENT_SHADER,
program,
substitutions
);
ParallelCompiler.programs.push({
this.programs.push({
program,
resolvePromise,
vertexShader,
@ -58,18 +58,18 @@ export abstract class ParallelCompiler {
}
@Insights.measure('compile programs')
public static async compilePrograms(): Promise<void> {
ParallelCompiler.programs.forEach((p) => ParallelCompiler.gl.linkProgram(p.program));
public async compilePrograms(): Promise<void> {
this.programs.forEach((p) => this.gl.linkProgram(p.program));
Insights.setValue('program count', ParallelCompiler.programs.length);
Insights.setValue('program count', this.programs.length);
while (ParallelCompiler.programs.length > 0) {
ParallelCompiler.resolveFinishedPrograms();
while (this.programs.length > 0) {
this.resolveFinishedPrograms();
await wait(0);
}
}
private static compileShader(
private compileShader(
source: string,
type: GLenum,
program: WebGLProgram,
@ -87,7 +87,7 @@ export abstract class ParallelCompiler {
} while (replaceHappened);
// can only return null on lost context
const shader = ParallelCompiler.gl.createShader(type)!;
const shader = this.gl.createShader(type)!;
this.gl.shaderSource(shader, processedSource);
this.gl.compileShader(shader);
@ -99,48 +99,40 @@ export abstract class ParallelCompiler {
return result;
}
private static resolveFinishedPrograms() {
private resolveFinishedPrograms() {
const done: Array<CompilingProgram> = [];
ParallelCompiler.programs.forEach((p) => {
this.programs.forEach((p) => {
if (
!ParallelCompiler.extension ||
ParallelCompiler.gl.getProgramParameter(
p.program,
ParallelCompiler.extension.COMPLETION_STATUS_KHR
)
!this.extension ||
this.gl.getProgramParameter(p.program, this.extension.COMPLETION_STATUS_KHR)
) {
ParallelCompiler.checkProgram(p);
this.checkProgram(p);
done.push(p);
p.resolvePromise!(p.program);
}
});
ParallelCompiler.programs = ParallelCompiler.programs.filter(
(p1) => done.findIndex((p2) => p2 === p1) == -1
);
this.programs = this.programs.filter((p1) => done.findIndex((p2) => p2 === p1) == -1);
}
private static checkProgram(program: CompilingProgram) {
const success = ParallelCompiler.gl.getProgramParameter(
program.program,
ParallelCompiler.gl.LINK_STATUS
);
private checkProgram(program: CompilingProgram) {
const success = this.gl.getProgramParameter(program.program, this.gl.LINK_STATUS);
if (!success && !ParallelCompiler.gl.isContextLost()) {
ParallelCompiler.prettyPrintErrorsIfThereAreAny(program.vertexShader);
ParallelCompiler.prettyPrintErrorsIfThereAreAny(program.fragmentShader);
if (!success) {
this.prettyPrintErrorsIfThereAreAny(program.vertexShader);
this.prettyPrintErrorsIfThereAreAny(program.fragmentShader);
throw new Error(ParallelCompiler.gl.getProgramInfoLog(program.program)!);
throw new Error(this.gl.getProgramInfoLog(program.program)!);
}
this.gl.deleteShader(program.vertexShader);
this.gl.deleteShader(program.fragmentShader);
}
private static prettyPrintErrorsIfThereAreAny(shader: ShaderWithSource) {
private prettyPrintErrorsIfThereAreAny(shader: ShaderWithSource) {
try {
ParallelCompiler.checkShader(shader);
this.checkShader(shader);
} catch (e) {
for (const match of e.toString().matchAll(/ERROR: 0:(\d+): (.*)$/gm)) {
const line = Number.parseInt(match[1]);
@ -155,14 +147,11 @@ export abstract class ParallelCompiler {
}
}
private static checkShader(shader: WebGLShader) {
const success = ParallelCompiler.gl.getShaderParameter(
shader,
ParallelCompiler.gl.COMPILE_STATUS
);
private checkShader(shader: WebGLShader) {
const success = this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS);
if (!success && !ParallelCompiler.gl.isContextLost()) {
throw new Error(ParallelCompiler.gl.getShaderInfoLog(shader)!);
if (!success) {
throw new Error(this.gl.getShaderInfoLog(shader)!);
}
}
}

View file

@ -1,4 +1,5 @@
import { enableExtension } from '../helper/enable-extension';
import { ParallelCompiler } from '../parallel-compiler';
import { UniversalRenderingContext } from '../universal-rendering-context';
import Program from './program';
@ -14,9 +15,10 @@ export class FragmentShaderOnlyProgram extends Program {
public async initialize(
sources: [string, string],
substitutions: { [name: string]: string }
substitutions: { [name: string]: string },
compiler: ParallelCompiler
): Promise<void> {
await super.initialize(sources, substitutions);
await super.initialize(sources, substitutions, compiler);
this.prepareScreenQuad('vertexPosition');
}

View file

@ -19,11 +19,12 @@ export default abstract class Program implements IProgram {
public async initialize(
[vertexShaderSource, fragmentShaderSource]: [string, string],
substitutions: { [name: string]: string }
substitutions: { [name: string]: string },
compiler: ParallelCompiler
): Promise<void> {
substitutions = { ...substitutions };
this.program = await ParallelCompiler.createProgram(
this.program = await compiler.createProgram(
vertexShaderSource,
fragmentShaderSource,
substitutions

View file

@ -2,6 +2,7 @@ import { mat2d, vec2 } from 'gl-matrix';
import { DrawableDescriptor } from '../../../drawables/drawable-descriptor';
import { getCombinations } from '../../../helper/get-combinations';
import { last } from '../../../helper/last';
import { ParallelCompiler } from '../parallel-compiler';
import { UniversalRenderingContext } from '../universal-rendering-context';
import { FragmentShaderOnlyProgram } from './fragment-shader-only-program';
import { IProgram } from './i-program';
@ -22,7 +23,8 @@ export class UniformArrayAutoScalingProgram implements IProgram {
public async initialize(
shaderSources: [string, string],
descriptors: Array<DrawableDescriptor>,
substitutions: { [name: string]: any }
substitutions: { [name: string]: any },
compiler: ParallelCompiler
): Promise<void> {
this.descriptors = descriptors;
@ -32,7 +34,13 @@ export class UniformArrayAutoScalingProgram implements IProgram {
descriptors.map((o) => o.shaderCombinationSteps)
)) {
promises.push(
this.createProgram(descriptors, substitutions, combination, shaderSources)
this.createProgram(
descriptors,
substitutions,
combination,
shaderSources,
compiler
)
);
}
@ -56,7 +64,7 @@ export class UniformArrayAutoScalingProgram implements IProgram {
const closest = this.programs.find((p) => p.values.every((v, i) => v >= values[i]));
this.current = closest ? closest.program : last(this.programs)?.program;
this.current = (closest ? closest : last(this.programs))?.program;
if (closest) {
this.descriptors!.map((d, i) => {
@ -67,12 +75,12 @@ export class UniformArrayAutoScalingProgram implements IProgram {
});
}
this.current!.setDrawingRectangleUV(
this.current?.setDrawingRectangleUV(
this.drawingRectangleBottomLeft,
this.drawingRectangleSize
);
this.current!.draw(uniforms);
this.current?.draw(uniforms);
}
public destroy(): void {
@ -83,7 +91,8 @@ export class UniformArrayAutoScalingProgram implements IProgram {
descriptors: Array<DrawableDescriptor>,
substitutions: { [name: string]: any },
combination: Array<number>,
shaderSources: [string, string]
shaderSources: [string, string],
compiler: ParallelCompiler
): Promise<void> {
const processedSubstitutions = {
macroDefinitions: this.getMacroDefinitions(combination, descriptors),
@ -93,7 +102,7 @@ export class UniformArrayAutoScalingProgram implements IProgram {
};
const program = new FragmentShaderOnlyProgram(this.gl);
await program.initialize(shaderSources, processedSubstitutions);
await program.initialize(shaderSources, processedSubstitutions, compiler);
this.programs.push({
program,
@ -150,7 +159,7 @@ export class UniformArrayAutoScalingProgram implements IProgram {
${
descriptors[i].sdf?.isInverted
? `step(-distanceNdcPixelSize, -objectMinDistance)`
: `step(distanceNdcPixelSize, objectMinDistance)`
: `step(1.0 * distanceNdcPixelSize, objectMinDistance)`
}
);

View file

@ -29,5 +29,32 @@ export const getUniversalRenderingContext = (
}
Insights.setValue('using WebGL2', result.isWebGL2);
return result;
let isDestroyed = false;
const handleContextLost = (e: Event) => {
e.preventDefault();
isDestroyed = true;
canvas.removeEventListener('webglcontextlost', handleContextLost, false);
};
canvas.addEventListener('webglcontextlost', handleContextLost, false);
const contextLostHandler = {
get: function (target: UniversalRenderingContext, prop: string) {
if (isDestroyed || target.isContextLost()) {
isDestroyed = true;
throw new Error('Context lost');
}
const value = (target as any)[prop];
if (typeof value === 'function') {
return value.bind(target);
}
return value;
},
};
return new Proxy(result, contextLostHandler);
};