forked from ninjadev/webgl-kurs-ntnu
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
742 lines (460 loc) · 14.4 KB
/
index.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Kurs i WebGL med THREE.js</title>
<script src=remark-0.5.7.min.js></script>
<script src=res/libs/three.min.js></script>
<link rel=stylesheet type=text/css href=res/css/style.css />
<link href='http://fonts.googleapis.com/css?family=Lato&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<style>
canvas {
border: 1px solid #000;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<textarea id="source">
class: center, middle
# The THREE.js Musketeers
<span class=subtle>by Poëtene</span>
---
# This course
Short tasks that demonstrate basic THREE.js concepts.
Then: combine what you have learned to make your own cool effect!
Have some fun :)
???
Hver del skal de gjøre litt selv.
De må gjerne finne på og tweake selv.
---
<img src="res/img/DSC_0303.JPG" style="width:100%">
---
<img src="res/img/DSC_0304.JPG" style="width:100%">
---
# WebGL
Javascript API for GPU rendering
OpenGL in the browser
Works in modern browser (mobile and desktop)
???
WebGL er et JavaScript-API for 3D-grafikk i nettleseren.
Det er basert på OpenGL
Grafikken tegnes på et canvas-element (HTML5)
Støttes av Firefox, Chrome, Safari, Opera, IE11
Støttes også i iOS 8 og i nye Android-versjoner
---
### Coordinate system in WebGL
.float-left[x goes rightwards
y goes upwards
z goes outwards (from the screen)
]
.float-right[
![Coordinate system in WebGL](res/img/3d_coordinate_system.png)
]
???
Forklar at når man ser et 2-dimensjonalt koordinatsystem på skjermen er det veldig naturlig å ha Y-aksen oppover og X-aksen bortover.
WebGL er en utvidelse av dette, og har dermed Z-aksen som dybde.
---
# THREE.js
### Makes 3D easier
- Camera
- Scene
- 3D-objects (mesh)
- Lighting
???
THREE.js er et javascript-rammeverk som gjør det enkelt å jobbe med 3D i nettleseren.
---
class: tiny-font
```html
...
<canvas></canvas>
<div id="info"></div>
<script id="vs" type="x-shader/vertex">
attribute vec3 position;
void main() {
gl_Position = vec4( position, 1.0 );
}
</script>
<script id="fs" type="x-shader/fragment">
uniform float time;
uniform vec2 resolution;
void main( void ) {
vec2 position = - 1.0 + 2.0 * gl_FragCoord.xy / resolution.xy;
float red = abs( sin( position.x * position.y + time / 5.0 ) );
float green = abs( sin( position.x * position.y + time / 4.0 ) );
float blue = abs( sin( position.x * position.y + time / 3.0 ) );
gl_FragColor = vec4( red, green, blue, 1.0 );
}
</script>
<script>
/**
* Provides requestAnimationFrame in a cross browser way.
* paulirish.com/2011/requestanimationframe-for-smart-animating/
*/
window.requestAnimationFrame = window.requestAnimationFrame || ( function() {
return window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback, element ) {
window.setTimeout( callback, 1000 / 60 );
};
})();
var canvas,
gl,
buffer,
vertex_shader, fragment_shader,
currentProgram,
vertex_position,
parameters = { start_time : new Date().getTime(),
time : 0,
screenWidth : 0,
screenHeight: 0 };
init();
animate();
function init() {
vertex_shader = document.getElementById('vs').textContent;
fragment_shader = document.getElementById('fs').textContent;
canvas = document.querySelector( 'canvas' );
// Initialise WebGL
try {
gl = canvas.getContext( 'experimental-webgl' );
} catch( error ) { }
if ( !gl ) {
throw "cannot create webgl context";
}
// Create Vertex buffer (2 triangles)
buffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
gl.bufferData( gl.ARRAY_BUFFER, new Float32Array( [ - 1.0, - 1.0, 1.0, - 1.0, - 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, - 1.0, 1.0 ] ), gl.STATIC_DRAW );
// Create Program
currentProgram = createProgram( vertex_shader, fragment_shader );
onWindowResize();
window.addEventListener( 'resize', onWindowResize, false );
}
function createProgram( vertex, fragment ) {
var program = gl.createProgram();
var vs = createShader( vertex, gl.VERTEX_SHADER );
var fs = createShader( '#ifdef GL_ES\nprecision highp float;\n#endif\n\n' + fragment, gl.FRAGMENT_SHADER );
if ( vs == null || fs == null ) return null;
gl.attachShader( program, vs );
gl.attachShader( program, fs );
gl.deleteShader( vs );
gl.deleteShader( fs );
gl.linkProgram( program );
if ( !gl.getProgramParameter( program, gl.LINK_STATUS ) ) {
alert( "ERROR:\n" +
"VALIDATE_STATUS: " + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + "\n" +
"ERROR: " + gl.getError() + "\n\n" +
"- Vertex Shader -\n" + vertex + "\n\n" +
"- Fragment Shader -\n" + fragment );
return null;
}
return program;
}
function createShader( src, type ) {
var shader = gl.createShader( type );
gl.shaderSource( shader, src );
gl.compileShader( shader );
if ( !gl.getShaderParameter( shader, gl.COMPILE_STATUS ) ) {
alert( ( type == gl.VERTEX_SHADER ? "VERTEX" : "FRAGMENT" ) + " SHADER:\n" + gl.getShaderInfoLog( shader ) );
return null;
}
return shader;
}
function onWindowResize( event ) {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
parameters.screenWidth = canvas.width;
parameters.screenHeight = canvas.height;
gl.viewport( 0, 0, canvas.width, canvas.height );
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
if ( !currentProgram ) return;
parameters.time = new Date().getTime() - parameters.start_time;
gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
// Load program into GPU
gl.useProgram( currentProgram );
// Set values to program variables
gl.uniform1f( gl.getUniformLocation( currentProgram, 'time' ), parameters.time / 1000 );
gl.uniform2f( gl.getUniformLocation( currentProgram, 'resolution' ), parameters.screenWidth, parameters.screenHeight );
// Render geometry
gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
gl.vertexAttribPointer( vertex_position, 2, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vertex_position );
gl.drawArrays( gl.TRIANGLES, 0, 6 );
gl.disableVertexAttribArray( vertex_position );
}
...
```
???
Eksempel på WebGL uten THREE.js
---
class: middle
```javascript
var renderer = new THREE.WebGLRenderer();
var scene = new THREE.Scene();
var view_angle = 45;
var aspect = width / height;
var near = 0.1;
var far = 10000;
var camera = new THREE.PerspectiveCamera(
view_angle,
aspect,
near,
far
);
renderer.setSize(width, height);
document.body.appendChild(renderer.domElement);
renderer.render(scene, camera);
```
???
Minimalt eksempel.
Dette er den minste versjonen av boilerplaten du trenger.
Forklar de viktigste konseptene godt, alle talla er ikke så interessante.
---
demo: show-sphere
<div id=show-sphere class=small-demo></div>
# Add an object
## Geometry
```javascript
var geometry = new THREE.SphereGeometry(
50, // radius
16, // segments
16 // rings
);
```
---
<div style="width:200px; height: 200px; background: red; float: right;"></div>
# Add an object
## Material
```javascript
var material = new THREE.MeshBasicMaterial(
{color: 0xff0000}
);
```
---
demo: show-sphere-mesh
<div id=show-sphere-mesh class=small-demo></div>
# add an object
## Mesh
```javascript
var sphere = new THREE.Mesh(
geometry,
material
);
scene.add(sphere);
```
---
# Animation
The canvas must be redrawn many times per second
```javascript
function animate() {
requestAnimationFrame(animate);
// do animation here
renderer.render(scene, camera);
}
animate();
```
???
Nettleseren bestemmer hvor ofte funksjonen kalles.
Vi kaller animate én gang for å starte den, resten går automatisk.
---
class: center, middle
# Time
## Date.now()
Millisekunder siden 1. januar 1970
---
class: middle
```javascript
var initial_t = Date.now() / 1000;
function animate() {
requestAnimationFrame(animate);
var t = Date.now() / 1000 - initial_t;
// do animation here
renderer.render(scene, camera);
}
animate();
```
???
Nå har vi en variabel som øker for hver frame i animasjonen.
Uansett hvor ofte skjermen oppdateres øker den med én hvert sekund.
Initial_t gjør at den starter på 0.
---
class: center middle
# Tasks
???
Nå kommer noen oppgaver som viser ulike ting som er kjekt å kunne.
Til slutt skal dere kunne sette sammen ting dere har lært til en demo.
Og så har vi konkurranse.
---
demo: rotate-cube
# Task 1
## Make a rotating cube
<div id=rotate-cube class=demo></div>
???
De fyller ut der det står kommentarer i koden på linken
---
# Task 1
```javascript
cube = new THREE.Mesh(geometry, material);
```
cube.rotation has three properties: x, y og z
```javascript
cube.rotation.x = 1;
```
---
# Task 1
## Make a rotating cube
### http://poetene.net/threejs/effect/4
---
# Solution Task 1
```javascript
function animate() {
requestAnimationFrame(animate);
var t = Date.now() / 1000 - initial_t;
cube.rotation.x = t * 5;
cube.rotation.z = t * 5;
renderer.render(scene, camera);
}
```
---
# Task 2
Animate the camera in a circle around the z-axis
---
# Task 2
Set camera.position.x og .y
<div style=background:white;text-align:center;height:45%>
<img style=height:70% src=res/img/unit_circle.svg>
</div>
---
# Task 2
Animate the camera in a circle around the z-axis
http://poetene.net/threejs/effect/13-camera/
---
# Solution Task 2
Move the camera
```javascript
camera.position.x = DISTANCE_FROM_Z_PLANE * Math.sin(t);
camera.position.y = DISTANCE_FROM_Z_PLANE * Math.cos(t);
```
---
# Task 3
## Animate multiple cubes in fun trajectories
You could go for instance a circular movement, a ∞ trajectory, or in a ☃ trajectory.
---
# Task 3
An array of cubes is available in ```cubes```.
Can e.g. by animated by:
```javascript
for (var i = 0; i < cubes.length; i++) {
var cube = cubes[i];
//manipulate every cube here
cube.position.x = 200 * Math.sin(t + 0.5 * i);
}
```
---
# Task 3
## Animate many cubes
### http://poetene.net/threejs/effect/12
---
# Task 4
## Skybox
<img src=res/img/Skybox_example.png>
---
class: skybox-code-slide middle
```javascript
var urlPrefix = "/static/res/skyboxes/TropicalSunnyDay_";
var directions = ["left", "right", "up", "down", "front", "back"];
var skyGeometry = new THREE.BoxGeometry(15000, 15000, 15000);
var materialArray = [];
for (var i = 0; i < 6; i++) {
var url = urlPrefix + directions[i] + ".jpg";
materialArray.push(new THREE.MeshBasicMaterial({
map: THREE.ImageUtils.loadTexture(url),
side: THREE.BackSide
}));
}
var skyMaterial = new THREE.MeshFaceMaterial(materialArray);
var skyBoxMesh = new THREE.Mesh(skyGeometry, skyMaterial);
scene.add(skyBoxMesh);
```
---
# Task 4
Example: http://poetene.net/threejs/effect/51
Skyboxes available at http://poetene.net/threejs/skyboxes/
Add a skybox in your demo
---
# Task 5
## Music ♫ ♪
```html
<audio id="music" loop>
<source src="my_music.mp3" type="audio/mpeg">
</audio>
```
```javascript
music.play();
function animate() {
console.log(music.currentTime); // antall sekunder
}
```
---
# Task 5
## Add music
http://poetene.net/threejs/effect/44-musikk-eksempel/
---
# Task 6
## Shaders
<img src=res/img/shader_example.png alt="Shader example" style="width: 100%;" >
---
# What are shaders?
Programs written in GLSL that are designed to operate on arrays (vertex) and render textures (fragment).
THREE.js supplies their own shaders that contain the actual drawing, coloring, lighting, ++ logic
Can also chained for post-processing fx
???
glsl er et språk som ligner litt på c
Vi skal ikke lære glsl i dag, men bruke en del ferdig skrevne shaders vi har lagd fra før
---
# Using post-processing shaders
http://poetene.net/threejs/shaders/
```javascript
var shaderPass = new THREE.ShaderPass(SHADERS.multiply);
// Skriv kun dette for den siste shaderen
shaderPass.renderToScreen = true;
composer.addPass(shaderPass);
```
???
Laster inn en av de ferdige shaderne våre
---
# Uniforms
Parameters that are sent to a shader
```javascript
shaderPass.uniforms.amount.value = 1;
```
???
Et objekt med ulike verdier som kan styres fra javascript.
Shaderen bruker disse verdiene i beregningene sine
---
# Shaders
## Play with shaders
http://poetene.net/threejs/effect/54-oppgave-6-shaders/
---
# Demo compo
Lag noe kult, og vinn premie!
Make some cool effects \p/
???
Sjekk eksemplene på nettsiden, og sett sammen noe eget
Etterpå viser vi frem det dere har laget.
Spør oss om hjelp
</textarea>
<script type="text/javascript">
var slideshow = remark.create();
</script>
<script src=script.js></script>
</body>
</html>