-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
WebGLProbe.ts
82 lines (70 loc) · 2.13 KB
/
WebGLProbe.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//@ts-nocheck
import { fabric } from '../../HEADER';
import { createCanvasElement } from '../util/misc/dom';
export const enum TWebGLPrecision {
low = 'lowp',
medium = 'mediump',
high = 'highp',
}
/**
* @todo remove once rollup supports transforming enums...
* https://github.com/rollup/plugins/issues/463
*/
const WebGLPrecision = [
TWebGLPrecision.low,
TWebGLPrecision.medium,
TWebGLPrecision.high,
];
/**
* Lazy initialize WebGL contants
*/
class WebGLProbe {
private initialized = false;
private _maxTextureSize?: number;
private _webGLPrecision?: TWebGLPrecision;
get maxTextureSize() {
this.queryWebGL();
return this._maxTextureSize;
}
get webGLPrecision() {
this.queryWebGL();
return this._webGLPrecision;
}
/**
* Tests if webgl supports certain precision
* @param {WebGL} Canvas WebGL context to test on
* @param {TWebGLPrecision} Precision to test can be any of following
* @returns {Boolean} Whether the user's browser WebGL supports given precision.
*/
private testPrecision(gl: WebGLRenderingContext, precision: TWebGLPrecision) {
const fragmentSource = `precision ${precision} float;\nvoid main(){}`;
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragmentSource);
gl.compileShader(fragmentShader);
return !!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS);
}
/**
* query browser for WebGL
* @returns config object if true
*/
private queryWebGL() {
if (this.initialized || fabric.isLikelyNode) {
return;
}
const canvas = createCanvasElement();
const gl =
canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
if (gl) {
this._maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
this._webGLPrecision = WebGLPrecision.find((key) =>
this.testPrecision(gl, key)
);
console.log(`fabric: max texture size ${this._maxTextureSize}`);
}
this.initialized = true;
}
isSupported(textureSize: number) {
return this.maxTextureSize && this.maxTextureSize >= textureSize;
}
}
export const webGLProbe = new WebGLProbe();