-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
program.ts
393 lines (328 loc) · 13.1 KB
/
program.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
/**
* Sigma.js WebGL Renderer Program
* ================================
*
* Class representing a single WebGL program used by sigma's WebGL renderer.
* @module
*/
import { Attributes } from "graphology-types";
import type Sigma from "../sigma";
import type { RenderParams } from "../types";
import { loadFragmentShader, loadProgram, loadVertexShader } from "./utils";
const PICKING_PREFIX = `#define PICKING_MODE\n`;
const SIZE_FACTOR_PER_ATTRIBUTE_TYPE: Record<number, number> = {
[WebGL2RenderingContext.BOOL]: 1,
[WebGL2RenderingContext.BYTE]: 1,
[WebGL2RenderingContext.UNSIGNED_BYTE]: 1,
[WebGL2RenderingContext.SHORT]: 2,
[WebGL2RenderingContext.UNSIGNED_SHORT]: 2,
[WebGL2RenderingContext.INT]: 4,
[WebGL2RenderingContext.UNSIGNED_INT]: 4,
[WebGL2RenderingContext.FLOAT]: 4,
};
function getAttributeItemsCount(attr: ProgramAttributeSpecification): number {
return attr.normalized ? 1 : attr.size;
}
function getAttributesItemsCount(attrs: ProgramAttributeSpecification[]): number {
let res = 0;
attrs.forEach((attr) => (res += getAttributeItemsCount(attr)));
return res;
}
export interface ProgramInfo<Uniform extends string = string> {
name: string;
isPicking: boolean;
program: WebGLProgram;
gl: WebGLRenderingContext | WebGL2RenderingContext;
frameBuffer: WebGLFramebuffer | null;
buffer: WebGLBuffer;
constantBuffer: WebGLBuffer;
uniformLocations: Record<Uniform, WebGLUniformLocation>;
attributeLocations: Record<string, GLint>;
}
export interface ProgramAttributeSpecification {
name: string;
size: number;
type: number;
normalized?: boolean;
}
export interface ProgramDefinition<Uniform extends string = string> {
VERTICES: number;
VERTEX_SHADER_SOURCE: string;
FRAGMENT_SHADER_SOURCE: string;
UNIFORMS: ReadonlyArray<Uniform>;
ATTRIBUTES: Array<ProgramAttributeSpecification>;
METHOD: GLenum;
}
export interface InstancedProgramDefinition<Uniform extends string = string> extends ProgramDefinition<Uniform> {
CONSTANT_ATTRIBUTES: Array<ProgramAttributeSpecification>;
CONSTANT_DATA: number[][];
}
export abstract class AbstractProgram<
N extends Attributes = Attributes,
E extends Attributes = Attributes,
G extends Attributes = Attributes,
> {
// eslint-disable-next-line @typescript-eslint/no-empty-function
constructor(_gl: WebGLRenderingContext, _pickGl: WebGLRenderingContext, _renderer: Sigma<N, E, G>) {}
abstract reallocate(capacity: number): void;
abstract render(params: RenderParams): void;
abstract kill(): void;
}
export abstract class Program<
Uniform extends string = string,
N extends Attributes = Attributes,
E extends Attributes = Attributes,
G extends Attributes = Attributes,
>
implements AbstractProgram<N, E, G>, InstancedProgramDefinition
{
VERTICES: number;
VERTEX_SHADER_SOURCE: string;
FRAGMENT_SHADER_SOURCE: string;
UNIFORMS: ReadonlyArray<Uniform>;
ATTRIBUTES: Array<ProgramAttributeSpecification>;
METHOD: GLenum;
CONSTANT_ATTRIBUTES: Array<ProgramAttributeSpecification>;
CONSTANT_DATA: number[][];
ATTRIBUTES_ITEMS_COUNT: number;
STRIDE: number;
renderer: Sigma<N, E, G>;
array: Float32Array = new Float32Array();
constantArray: Float32Array = new Float32Array();
capacity = 0;
verticesCount = 0;
normalProgram: ProgramInfo;
pickProgram: ProgramInfo | null;
isInstanced: boolean;
abstract getDefinition(): ProgramDefinition<Uniform> | InstancedProgramDefinition<Uniform>;
constructor(
gl: WebGLRenderingContext | WebGL2RenderingContext,
pickingBuffer: WebGLFramebuffer | null,
renderer: Sigma<N, E, G>,
) {
// Reading and caching program definition
const def = this.getDefinition();
this.VERTICES = def.VERTICES;
this.VERTEX_SHADER_SOURCE = def.VERTEX_SHADER_SOURCE;
this.FRAGMENT_SHADER_SOURCE = def.FRAGMENT_SHADER_SOURCE;
this.UNIFORMS = def.UNIFORMS;
this.ATTRIBUTES = def.ATTRIBUTES;
this.METHOD = def.METHOD;
this.CONSTANT_ATTRIBUTES = "CONSTANT_ATTRIBUTES" in def ? def.CONSTANT_ATTRIBUTES : [];
this.CONSTANT_DATA = "CONSTANT_DATA" in def ? def.CONSTANT_DATA : [];
this.isInstanced = "CONSTANT_ATTRIBUTES" in def;
// Computing stride
this.ATTRIBUTES_ITEMS_COUNT = getAttributesItemsCount(this.ATTRIBUTES);
this.STRIDE = this.VERTICES * this.ATTRIBUTES_ITEMS_COUNT;
// Members
this.renderer = renderer;
this.normalProgram = this.getProgramInfo("normal", gl, def.VERTEX_SHADER_SOURCE, def.FRAGMENT_SHADER_SOURCE, null);
this.pickProgram = pickingBuffer
? this.getProgramInfo(
"pick",
gl,
PICKING_PREFIX + def.VERTEX_SHADER_SOURCE,
PICKING_PREFIX + def.FRAGMENT_SHADER_SOURCE,
pickingBuffer,
)
: null;
// For instanced programs:
if (this.isInstanced) {
const constantAttributesItemsCount = getAttributesItemsCount(this.CONSTANT_ATTRIBUTES);
if (this.CONSTANT_DATA.length !== this.VERTICES)
throw new Error(
`Program: error while getting constant data (expected ${this.VERTICES} items, received ${this.CONSTANT_DATA.length} instead)`,
);
this.constantArray = new Float32Array(this.CONSTANT_DATA.length * constantAttributesItemsCount);
for (let i = 0; i < this.CONSTANT_DATA.length; i++) {
const vector = this.CONSTANT_DATA[i];
if (vector.length !== constantAttributesItemsCount)
throw new Error(
`Program: error while getting constant data (one vector has ${vector.length} items instead of ${constantAttributesItemsCount})`,
);
for (let j = 0; j < vector.length; j++) this.constantArray[i * constantAttributesItemsCount + j] = vector[j];
}
this.STRIDE = this.ATTRIBUTES_ITEMS_COUNT;
}
}
abstract kill(): void;
protected getProgramInfo(
name: "normal" | "pick",
gl: WebGLRenderingContext | WebGL2RenderingContext,
vertexShaderSource: string,
fragmentShaderSource: string,
frameBuffer: WebGLFramebuffer | null,
): ProgramInfo {
const def = this.getDefinition();
// WebGL buffers
const buffer = gl.createBuffer();
if (buffer === null) throw new Error("Program: error while creating the WebGL buffer.");
// Shaders and program
const vertexShader = loadVertexShader(gl, vertexShaderSource);
const fragmentShader = loadFragmentShader(gl, fragmentShaderSource);
const program = loadProgram(gl, [vertexShader, fragmentShader]);
// Initializing locations
const uniformLocations = {} as ProgramInfo["uniformLocations"];
def.UNIFORMS.forEach((uniformName) => {
const location = gl.getUniformLocation(program, uniformName);
if (location) uniformLocations[uniformName] = location;
});
const attributeLocations = {} as ProgramInfo["attributeLocations"];
def.ATTRIBUTES.forEach((attr) => {
attributeLocations[attr.name] = gl.getAttribLocation(program, attr.name);
});
// For instanced programs:
let constantBuffer;
if ("CONSTANT_ATTRIBUTES" in def) {
def.CONSTANT_ATTRIBUTES.forEach((attr) => {
attributeLocations[attr.name] = gl.getAttribLocation(program, attr.name);
});
constantBuffer = gl.createBuffer();
if (constantBuffer === null) throw new Error("Program: error while creating the WebGL constant buffer.");
}
return {
name,
program,
gl,
frameBuffer,
buffer,
constantBuffer: constantBuffer || ({} as WebGLBuffer),
uniformLocations,
attributeLocations,
isPicking: name === "pick",
};
}
protected bindProgram(program: ProgramInfo): void {
let offset = 0;
const { gl, buffer } = program;
if (!this.isInstanced) {
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
offset = 0;
this.ATTRIBUTES.forEach((attr) => (offset += this.bindAttribute(attr, program, offset)));
gl.bufferData(gl.ARRAY_BUFFER, this.array, gl.DYNAMIC_DRAW);
} else {
// Handle constant data (things that remain unchanged for all items):
gl.bindBuffer(gl.ARRAY_BUFFER, program.constantBuffer);
offset = 0;
this.CONSTANT_ATTRIBUTES.forEach((attr) => (offset += this.bindAttribute(attr, program, offset, false)));
gl.bufferData(gl.ARRAY_BUFFER, this.constantArray, gl.STATIC_DRAW);
// Handle "instance specific" data (things that vary for each item):
gl.bindBuffer(gl.ARRAY_BUFFER, program.buffer);
offset = 0;
this.ATTRIBUTES.forEach((attr) => (offset += this.bindAttribute(attr, program, offset, true)));
gl.bufferData(gl.ARRAY_BUFFER, this.array, gl.DYNAMIC_DRAW);
}
gl.bindBuffer(gl.ARRAY_BUFFER, null);
}
protected unbindProgram(program: ProgramInfo): void {
if (!this.isInstanced) {
this.ATTRIBUTES.forEach((attr) => this.unbindAttribute(attr, program));
} else {
this.CONSTANT_ATTRIBUTES.forEach((attr) => this.unbindAttribute(attr, program, false));
this.ATTRIBUTES.forEach((attr) => this.unbindAttribute(attr, program, true));
}
}
protected bindAttribute(
attr: ProgramAttributeSpecification,
program: ProgramInfo,
offset: number,
setDivisor?: boolean,
): number {
const sizeFactor = SIZE_FACTOR_PER_ATTRIBUTE_TYPE[attr.type];
if (typeof sizeFactor !== "number") throw new Error(`Program.bind: yet unsupported attribute type "${attr.type}"`);
const location = program.attributeLocations[attr.name];
const gl = program.gl;
if (location !== -1) {
gl.enableVertexAttribArray(location);
const stride = !this.isInstanced
? this.ATTRIBUTES_ITEMS_COUNT * Float32Array.BYTES_PER_ELEMENT
: (setDivisor ? this.ATTRIBUTES_ITEMS_COUNT : getAttributesItemsCount(this.CONSTANT_ATTRIBUTES)) *
Float32Array.BYTES_PER_ELEMENT;
gl.vertexAttribPointer(location, attr.size, attr.type, attr.normalized || false, stride, offset);
if (this.isInstanced && setDivisor) {
if (gl instanceof WebGL2RenderingContext) {
gl.vertexAttribDivisor(location, 1);
} else {
const ext = gl.getExtension("ANGLE_instanced_arrays");
if (ext) ext.vertexAttribDivisorANGLE(location, 1);
}
}
}
return attr.size * sizeFactor;
}
protected unbindAttribute(attr: ProgramAttributeSpecification, program: ProgramInfo, unsetDivisor?: boolean) {
const location = program.attributeLocations[attr.name];
const gl = program.gl;
if (location !== -1) {
gl.disableVertexAttribArray(location);
if (this.isInstanced && unsetDivisor) {
if (gl instanceof WebGL2RenderingContext) {
gl.vertexAttribDivisor(location, 0);
} else {
const ext = gl.getExtension("ANGLE_instanced_arrays");
if (ext) ext.vertexAttribDivisorANGLE(location, 0);
}
}
}
}
reallocate(capacity: number): void {
// If desired capacity has not changed we do nothing
// NOTE: it's possible here to implement more subtle reallocation schemes
// when the number of rendered items increase or decrease
if (capacity === this.capacity) return;
this.capacity = capacity;
this.verticesCount = this.VERTICES * capacity;
this.array = new Float32Array(
!this.isInstanced
? this.verticesCount * this.ATTRIBUTES_ITEMS_COUNT
: this.capacity * this.ATTRIBUTES_ITEMS_COUNT,
);
}
hasNothingToRender(): boolean {
return this.verticesCount === 0;
}
abstract setUniforms(params: RenderParams, programInfo: ProgramInfo): void;
protected renderProgram(params: RenderParams, programInfo: ProgramInfo): void {
const { gl, program } = programInfo;
// With the current fix for #1397, the alpha blending is enabled for the
// picking layer:
gl.enable(gl.BLEND);
// Original code:
// if (!isPicking) gl.enable(gl.BLEND);
// else gl.disable(gl.BLEND);
gl.useProgram(program);
this.setUniforms(params, programInfo);
this.drawWebGL(this.METHOD, programInfo);
}
render(params: RenderParams): void {
if (this.hasNothingToRender()) return;
if (this.pickProgram) {
this.pickProgram.gl.viewport(
0,
0,
(params.width * params.pixelRatio) / params.downSizingRatio,
(params.height * params.pixelRatio) / params.downSizingRatio,
);
this.bindProgram(this.pickProgram);
this.renderProgram({ ...params, pixelRatio: params.pixelRatio / params.downSizingRatio }, this.pickProgram);
this.unbindProgram(this.pickProgram);
}
this.normalProgram.gl.viewport(0, 0, params.width * params.pixelRatio, params.height * params.pixelRatio);
this.bindProgram(this.normalProgram);
this.renderProgram(params, this.normalProgram);
this.unbindProgram(this.normalProgram);
}
drawWebGL(method: GLenum, { gl, frameBuffer }: ProgramInfo): void {
gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
if (!this.isInstanced) {
gl.drawArrays(method, 0, this.verticesCount);
} else {
if (gl instanceof WebGL2RenderingContext) {
gl.drawArraysInstanced(method, 0, this.VERTICES, this.capacity);
} else {
const ext = gl.getExtension("ANGLE_instanced_arrays");
if (ext) ext.drawArraysInstancedANGLE(method, 0, this.VERTICES, this.capacity);
}
}
}
}