-
Notifications
You must be signed in to change notification settings - Fork 2
/
Context.ts
198 lines (173 loc) · 6.01 KB
/
Context.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import type { CompressedTextureStorageFormat } from './texture/textureEnums';
import { devLog, prodLog } from './utils/log';
/**
* The rendering context, tied to a canvas element.
*
* @example Most of the time, you won't need to manually create a context.
*
* The {@linkcode defaultContext} is, as the name suggests, the context that is used,
* unless another one is manually specified. It still needs to be initialized:
* ```typescript
* import { defaultContext, Sampler } from '@gdgt/webgl';
*
*
* const canvas = document.createElement( 'canvas' );
* document.body.appendChild( canvas );
*
* defaultContext.initialize( canvas );
*
* // All objects created without a specified context are tied to defaultContext:
* const sampler = new Sampler();
* // is equivalent to
* const sampler = new Sampler({ context: defaultContext });
*
* // You can also access the underlying WebGL2RenderingContext.
* // This will resolve once defaultContext has been initialized.
* const gl = await defaultContext.getGlContext();
* ```
*
* If you'd rather manage your own context, you can do so by providing each
* object with your context upon instantiation:
* ```typescript
* import { Context, Sampler } from '@gdgt/webgl';
*
*
* const canvas = document.createElement( 'canvas' );
* document.body.appendChild( canvas );
*
* const myContext = new Context();
* myContext.initialize( canvas );
*
* const sampler = new Sampler({ context: myContext });
* ```
* Remember to do so on __every__ object you create – using objects across
* multiple contexts is currently __not__ supported.
*/
export default class Context {
private glContextReady: Promise<WebGL2RenderingContext>;
private resolveContext: ( ctx: WebGL2RenderingContext ) => void;
private compressedFormats: CompressedTextureStorageFormat[];
private astcProfiles: string[];
public constructor() {
this.glContextReady = new Promise( ( resolve ) => {
this.resolveContext = resolve;
} );
}
/**
* Ties the context to a given canvas element.
* This can only be called once and needs to be called,
* before any rendering can take place.
*
* @param canvas - The canvas element to render to
* @param options - Additional settings for context creation, passed to the canvas element.
* See {@linkcode https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext#contextattributes | WebGLContextAttributes}.
* `{ alpha: true }` is used unless explicitly overwritten.
* Note that `{ alpha: false }` can lead to major performance issues on some platforms.
*/
public initialize( canvas: HTMLCanvasElement, options: WebGLContextAttributes = {} ): void {
if ( this.resolveContext ) {
const ctx = canvas.getContext( 'webgl2', {
alpha: true,
...options,
} );
const hasFloatLinear = ctx.getExtension( 'OES_texture_float_linear' );
const hasHalfColorBuffer = ctx.getExtension( 'EXT_color_buffer_half_float' );
const hasFloatColorBuffer = ctx.getExtension( 'EXT_color_buffer_float' );
const availableFormats: CompressedTextureStorageFormat[] = [];
const availableFormatNames: string[] = [];
[
'WEBGL_compressed_texture_etc',
'WEBGL_compressed_texture_etc1',
'WEBGL_compressed_texture_s3tc',
'WEBGL_compressed_texture_s3tc_srgb',
'WEBGL_compressed_texture_pvrtc',
'WEBKIT_WEBGL_compressed_texture_pvrtc',
'EXT_texture_compression_bptc',
'EXT_texture_compression_rgtc',
'WEBGL_compressed_texture_astc',
].forEach( ( name ) => {
const ext = ctx.getExtension( name );
if ( ext === null ) return;
// eslint-disable-next-line no-restricted-syntax, guard-for-in
for ( const prop in ext ) {
const value = ext[prop];
if ( typeof value === 'number' ) {
availableFormats.push( value );
if ( __DEV_BUILD__ ) {
availableFormatNames.push(
prop,
);
}
}
}
} );
this.compressedFormats = availableFormats;
this.astcProfiles = ctx.getExtension( 'WEBGL_compressed_texture_astc' )?.getSupportedProfiles() || [];
if ( __DEV_BUILD__ ) {
devLog( {
level: 'info',
msg: 'Renderer info:',
groups: {
'Float textures': {
expanded: false,
content: `${
hasHalfColorBuffer ? '✅' : '❌'
} f16 color buffer\n${
hasFloatColorBuffer ? '✅' : '❌'
} f32 color buffer\n${
hasFloatLinear ? '✅' : '❌'
} f32 linear interpolation`,
},
'Supported compressed texture formats': {
expanded: false,
content: availableFormatNames.length > 0 ? availableFormatNames.join( '\n' ) : '❌ none',
},
'Supported ASTC profiles': {
expanded: false,
content: this.astcProfiles.length > 0 ? this.astcProfiles.join( '\n' ) : '❌ none',
},
},
} );
}
this.resolveContext( ctx );
this.resolveContext = null;
} else if ( __DEV_BUILD__ ) {
devLog( {
level: 'error',
msg: 'Trying to initialize context that has already been initialized.',
} );
} else {
prodLog( 'Context' );
}
}
/**
* Returns the `WebGL2RenderingContext` of the canvas element it's tied to once available.
*
* @returns The underlying `WebGL2RenderingContext`.
*/
public async getGlContext(): Promise<WebGL2RenderingContext> {
return this.glContextReady;
}
/**
* Returns an array of supported compressed texture formats once available.
*
* @returns An array of supported compressed texture formats.
*/
public async getCompressedFormats(): Promise<CompressedTextureStorageFormat[]> {
await this.glContextReady;
return this.compressedFormats;
}
/**
* Returns an array of supported {@link https://developer.mozilla.org/en-US/docs/Web/API/WEBGL_compressed_texture_astc/getSupportedProfiles | ASTC profiles} once available.
*
* @returns An array of supported ASTC profiles.
*/
public async getAstcProfiles(): Promise<string[]> {
await this.glContextReady;
return this.astcProfiles;
}
}
/**
* Default instance of {@linkcode Context} used if no other context is specified.
*/
export const defaultContext = new Context();