-
Notifications
You must be signed in to change notification settings - Fork 682
/
Copy pathwebgl-scene-graph-block-guy.html
412 lines (353 loc) · 11.7 KB
/
webgl-scene-graph-block-guy.html
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
<!-- Licensed under a BSD license. See license.html for license -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<title>WebGL - Scene Graph - Block Guy</title>
<link type="text/css" href="resources/webgl-tutorials.css" rel="stylesheet" />
</head>
<body>
<div class="description">
A human hierarchy using a scene graph
</div>
<canvas id="canvas"></canvas>
</body>
<!-- vertex shader -->
<script id="vertex-shader-3d" type="x-shader/x-vertex">
attribute vec4 a_position;
attribute vec4 a_color;
uniform mat4 u_matrix;
varying vec4 v_color;
void main() {
// Multiply the position by the matrix.
gl_Position = u_matrix * a_position;
// Pass the color to the fragment shader.
v_color = a_color;
}
</script>
<!-- fragment shader -->
<script id="fragment-shader-3d" type="x-shader/x-fragment">
precision mediump float;
// Passed in from the vertex shader.
varying vec4 v_color;
uniform vec4 u_colorMult;
uniform vec4 u_colorOffset;
void main() {
gl_FragColor = v_color * u_colorMult + u_colorOffset;
}
</script>
<!--
for most samples webgl-utils only provides shader compiling/linking and
canvas resizing because why clutter the examples with code that's the same in every sample.
See https://webglfundamentals.org/webgl/lessons/webgl-boilerplate.html
and https://webglfundamentals.org/webgl/lessons/webgl-resizing-the-canvas.html
for webgl-utils, m3, m4, and webgl-lessons-ui.
-->
<script src="resources/webgl-utils.js"></script>
<script src="resources/m4.js"></script>
<script src="resources/primitives.js"></script>
<script>
"use strict";
var TRS = function() {
this.translation = [0, 0, 0];
this.rotation = [0, 0, 0];
this.scale = [1, 1, 1];
};
TRS.prototype.getMatrix = function(dst) {
dst = dst || new Float32Array(16);
var t = this.translation;
var r = this.rotation;
var s = this.scale;
m4.translation(t[0], t[1], t[2], dst);
m4.xRotate(dst, r[0], dst);
m4.yRotate(dst, r[1], dst);
m4.zRotate(dst, r[2], dst);
m4.scale(dst, s[0], s[1], s[2], dst);
return dst;
};
var Node = function(source) {
this.children = [];
this.localMatrix = m4.identity();
this.worldMatrix = m4.identity();
this.source = source;
};
Node.prototype.setParent = function(parent) {
// remove us from our parent
if (this.parent) {
var ndx = this.parent.children.indexOf(this);
if (ndx >= 0) {
this.parent.children.splice(ndx, 1);
}
}
// Add us to our new parent
if (parent) {
parent.children.push(this);
}
this.parent = parent;
};
Node.prototype.updateWorldMatrix = function(parentWorldMatrix) {
var source = this.source;
if (source) {
source.getMatrix(this.localMatrix);
}
if (parentWorldMatrix) {
// a matrix was passed in so do the math
m4.multiply(parentWorldMatrix, this.localMatrix, this.worldMatrix);
} else {
// no matrix was passed in so just copy local to world
m4.copy(this.localMatrix, this.worldMatrix);
}
// now process all the children
var worldMatrix = this.worldMatrix;
this.children.forEach(function(child) {
child.updateWorldMatrix(worldMatrix);
});
};
function main() {
// Get A WebGL context
/** @type {HTMLCanvasElement} */
var canvas = document.querySelector("#canvas");
var gl = canvas.getContext("webgl");
if (!gl) {
return;
}
// creates buffers with position, normal, texcoord, and vertex color
// data for primitives by calling gl.createBuffer, gl.bindBuffer,
// and gl.bufferData
const cubeBufferInfo = primitives.createCubeWithVertexColorsBufferInfo(gl, 1);
// setup GLSL program
var programInfo = webglUtils.createProgramInfo(gl, ["vertex-shader-3d", "fragment-shader-3d"]);
function degToRad(d) {
return d * Math.PI / 180;
}
function rand(min, max) {
return Math.random() * (max - min) + min;
}
function emod(x, n) {
return x >= 0 ? (x % n) : ((n - (-x % n)) % n);
}
var cameraAngleRadians = degToRad(0);
var fieldOfViewRadians = degToRad(60);
var cameraHeight = 50;
var objectsToDraw = [];
var objects = [];
var nodeInfosByName = {};
// Let's make all the nodes
var blockGuyNodeDescriptions =
{
name: "point between feet",
draw: false,
children: [
{
name: "waist",
translation: [0, 3, 0],
children: [
{
name: "torso",
translation: [0, 2, 0],
children: [
{
name: "neck",
translation: [0, 1, 0],
children: [
{
name: "head",
translation: [0, 1, 0],
},
],
},
{
name: "left-arm",
translation: [-1, 0, 0],
children: [
{
name: "left-forearm",
translation: [-1, 0, 0],
children: [
{
name: "left-hand",
translation: [-1, 0, 0],
},
],
},
],
},
{
name: "right-arm",
translation: [1, 0, 0],
children: [
{
name: "right-forearm",
translation: [1, 0, 0],
children: [
{
name: "right-hand",
translation: [1, 0, 0],
},
],
},
],
},
],
},
{
name: "left-leg",
translation: [-1, -1, 0],
children: [
{
name: "left-calf",
translation: [0, -1, 0],
children: [
{
name: "left-foot",
translation: [0, -1, 0],
},
],
}
],
},
{
name: "right-leg",
translation: [1, -1, 0],
children: [
{
name: "right-calf",
translation: [0, -1, 0],
children: [
{
name: "right-foot",
translation: [0, -1, 0],
},
],
}
],
},
],
},
],
};
function makeNode(nodeDescription) {
var trs = new TRS();
var node = new Node(trs);
nodeInfosByName[nodeDescription.name] = {
trs: trs,
node: node,
};
trs.translation = nodeDescription.translation || trs.translation;
if (nodeDescription.draw !== false) {
node.drawInfo = {
uniforms: {
u_colorOffset: [0, 0, 0.6, 0],
u_colorMult: [0.4, 0.4, 0.4, 1],
},
programInfo: programInfo,
bufferInfo: cubeBufferInfo,
};
objectsToDraw.push(node.drawInfo);
objects.push(node);
}
makeNodes(nodeDescription.children).forEach(function(child) {
child.setParent(node);
});
return node;
}
function makeNodes(nodeDescriptions) {
return nodeDescriptions ? nodeDescriptions.map(makeNode) : [];
}
var scene = makeNode(blockGuyNodeDescriptions);
requestAnimationFrame(drawScene);
// Draw the scene.
function drawScene(time) {
time *= 0.001;
webglUtils.resizeCanvasToDisplaySize(gl.canvas);
// Tell WebGL how to convert from clip space to pixels
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
gl.enable(gl.CULL_FACE);
gl.enable(gl.DEPTH_TEST);
// Clear the canvas AND the depth buffer.
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// Compute the projection matrix
var aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
var projectionMatrix =
m4.perspective(fieldOfViewRadians, aspect, 1, 2000);
// Compute the camera's matrix using look at.
var cameraPosition = [4, 3.5, 10];
var target = [0, 3.5, 0];
var up = [0, 1, 0];
var cameraMatrix = m4.lookAt(cameraPosition, target, up);
// Make a view matrix from the camera matrix.
var viewMatrix = m4.inverse(cameraMatrix);
var viewProjectionMatrix = m4.multiply(projectionMatrix, viewMatrix);
// Draw objects
// Update all world matrices in the scene graph
scene.updateWorldMatrix();
var adjust;
var speed = 3;
var c = time * speed;
adjust = Math.abs(Math.sin(c));
nodeInfosByName["point between feet"].trs.translation[1] = adjust;
adjust = Math.sin(c);
nodeInfosByName["left-leg" ].trs.rotation[0] = adjust;
nodeInfosByName["right-leg"].trs.rotation[0] = -adjust;
adjust = Math.sin(c + 0.1) * 0.4;
nodeInfosByName["left-calf" ].trs.rotation[0] = -adjust;
nodeInfosByName["right-calf"].trs.rotation[0] = adjust;
adjust = Math.sin(c + 0.1) * 0.4;
nodeInfosByName["left-foot" ].trs.rotation[0] = -adjust;
nodeInfosByName["right-foot"].trs.rotation[0] = adjust;
adjust = Math.sin(c) * 0.4;
nodeInfosByName["left-arm" ].trs.rotation[2] = adjust;
nodeInfosByName["right-arm"].trs.rotation[2] = adjust;
adjust = Math.sin(c + 0.1) * 0.4;
nodeInfosByName["left-forearm" ].trs.rotation[2] = adjust;
nodeInfosByName["right-forearm"].trs.rotation[2] = adjust;
adjust = Math.sin(c - 0.1) * 0.4;
nodeInfosByName["left-hand" ].trs.rotation[2] = adjust;
nodeInfosByName["right-hand"].trs.rotation[2] = adjust;
adjust = Math.sin(c) * 0.4;
nodeInfosByName["waist"].trs.rotation[1] = adjust;
adjust = Math.sin(c) * 0.4;
nodeInfosByName["torso"].trs.rotation[1] = adjust;
adjust = Math.sin(c + 0.25) * 0.4;
nodeInfosByName["neck"].trs.rotation[1] = adjust;
adjust = Math.sin(c + 0.5) * 0.4;
nodeInfosByName["head"].trs.rotation[1] = adjust;
adjust = Math.cos(c * 2) * 0.4;
nodeInfosByName["head"].trs.rotation[0] = adjust;
// Compute all the matrices for rendering
objects.forEach(function(object) {
object.drawInfo.uniforms.u_matrix = m4.multiply(viewProjectionMatrix, object.worldMatrix);
});
// ------ Draw the objects --------
var lastUsedProgramInfo = null;
var lastUsedBufferInfo = null;
objectsToDraw.forEach(function(object) {
var programInfo = object.programInfo;
var bufferInfo = object.bufferInfo;
var bindBuffers = false;
if (programInfo !== lastUsedProgramInfo) {
lastUsedProgramInfo = programInfo;
gl.useProgram(programInfo.program);
// We have to rebind buffers when changing programs because we
// only bind buffers the program uses. So if 2 programs use the same
// bufferInfo but the 1st one uses only positions the when the
// we switch to the 2nd one some of the attributes will not be on.
bindBuffers = true;
}
// Setup all the needed attributes.
if (bindBuffers || bufferInfo !== lastUsedBufferInfo) {
lastUsedBufferInfo = bufferInfo;
webglUtils.setBuffersAndAttributes(gl, programInfo, bufferInfo);
}
// Set the uniforms.
webglUtils.setUniforms(programInfo, object.uniforms);
// Draw
gl.drawArrays(gl.TRIANGLES, 0, bufferInfo.numElements);
});
requestAnimationFrame(drawScene);
}
}
main();
</script>
</html>