1 import { System
} from '@serpentity/serpentity';
2 import Drawable
from '../nodes/drawable';
3 import { initializeShaderProgram
, initializeBuffers
} from '../webgl_utils';
8 kTargetVerticalResolution: 32 + Math
.round(Math
.random() * 1024),
11 attribute vec3 aVertexPosition;
13 gl_Position = vec4(aVertexPosition.xy, 0.0, 1.0);
14 gl_PointSize = 10.0; // Set the point size
20 precision mediump float;
23 gl_FragColor = uColor;
28 export default class WebGLRenderer
extends System
{
30 constructor(canvasId
) {
33 this.canvasId
= canvasId
;
39 const canvas
= document
.getElementById(this.canvasId
);
40 window
.addEventListener('resize', () => this._resizeCanvas(canvas
));
43 const gl
= canvas
.getContext('webgl', {
44 preserveDrawingBuffer: true
48 const shaderProgram
= initializeShaderProgram(
50 internals
.kVertexShader
,
51 internals
.kFragmentShader
55 program: shaderProgram
,
57 vertexPosition: gl
.getAttribLocation(shaderProgram
, 'aVertexPosition')
60 color: gl
.getUniformLocation(shaderProgram
, 'uColor')
64 this.buffers
= initializeBuffers(gl
);
65 this._resizeCanvas(canvas
);
67 this.points
= engine
.getNodes(Drawable
);
72 this.points
= undefined;
77 const {gl
, programInfo
, buffers
} = this;
79 gl
.useProgram(programInfo
.program
);
82 const color
= [1, 1, 1, 1];
83 gl
.uniform4fv(programInfo
.uniformLocations
.color
, color
);
87 for (const point
of this.points
) {
88 positions
.push(point
.position
.x
, point
.position
.y
, point
.position
.z
);
90 point
.position
.prevX
|| point
.position
.x
,
91 point
.position
.prevY
|| point
.position
.y
,
92 point
.position
.prevZ
|| point
.position
.z
94 point
.position
.prevX
= point
.position
.x
;
95 point
.position
.prevY
= point
.position
.y
;
96 point
.position
.prevZ
= point
.position
.z
;
99 gl
.bindBuffer(gl
.ARRAY_BUFFER
, buffers
.position
);
100 gl
.bufferData(gl
.ARRAY_BUFFER
,
101 new Float32Array(positions
),
105 const numberOfComponents
= 3;
106 const type
= gl
.FLOAT
;
107 const normalize
= false;
111 gl
.bindBuffer(gl
.ARRAY_BUFFER
, buffers
.position
);
112 gl
.vertexAttribPointer(
113 programInfo
.attribLocations
.vertexPosition
,
120 gl
.enableVertexAttribArray(programInfo
.attribLocations
.vertexPosition
);
125 gl
.drawArrays(gl
.LINES
, 0, this.points
.nodes
.length
* 2);
129 _resizeCanvas(canvas
) {
131 console
.log('Resizing Canvas');
132 let width
= window
.innerWidth
;
133 let height
= Math
.round(width
* internals
.kHeightRatio
/ internals
.kWidthRatio
);
135 if (window
.innerHeight
< height
) {
136 height
= window
.innerHeight
;
137 width
= Math
.round(height
* internals
.kWidthRatio
/ internals
.kHeightRatio
);
138 console
.log(width
, height
);
141 canvas
.style
.width
= `${width}px`;
142 canvas
.style
.height
= `${height}px`;
144 canvas
.width
= internals
.kTargetVerticalResolution
* internals
.kWidthRatio
;
145 canvas
.height
= internals
.kTargetVerticalResolution
;
147 this.gl
.viewport(0, 0, canvas
.width
, canvas
.height
);