-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathraytracing_gem.html
More file actions
685 lines (493 loc) · 17.9 KB
/
raytracing_gem.html
File metadata and controls
685 lines (493 loc) · 17.9 KB
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
<!DOCTYPE html>
<!--
Copyright (c) 2016 gam0022
Released under the MIT license
http://opensource.org/licenses/mit-license.php
-->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<title>three.js webgl - raytracing - ruby</title>
<style type="text/css">
body {
background-color: black;
margin: 0;
padding: 0;
}
a { color: skyblue }
canvas {
display: block;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
#info {
color: white;
font-size: 13px;
position: absolute;
bottom: 10px;
width: 100%;
text-align: center;
z-index: 100;
}
</style>
</head>
<body>
<div id="info">
<a href="http://threejs.org" target="_blank">three.js</a> - webgl raytracing example -
gem by <a href="https://github.com/gam0022" target="_blank">gam0022</a> (<a href="http://qiita.com/gam0022/items/9875480d33e03fe2113c" target="_blank">article in Japanese</a>)
</div>
<script id="fragment_shader" type="x-shader/x-fragment">
precision highp float;
//uniform vec3 diamondVertexes[ diamondFaceCount * 3 ];
uniform int diamondFaceCount;
uniform sampler2D diamondVertexTexture;
uniform vec3 cameraPos;
uniform vec3 cameraDir;
uniform bool gammaCorrection;
uniform float refractiveIndex;
float invRefractiveIndex;
uniform vec2 resolution;
const float EPS = 0.001;
uniform vec3 diamondDiffuseColor;
uniform vec3 diamondSpecularColor;
// 上方向からの光源
const vec3 lightDir1 = vec3( 0.48666426339228763, 0.3244428422615251, 0.8111071056538127 );
// 下方向からの光源
const vec3 lightDir2 = vec3( -0.48666426339228763, -0.3244428422615251, -0.8111071056538127 );
float det( vec3 a, vec3 b, vec3 c ) {
return (a.x * b.y * c.z)
+ (a.y * b.z * c.x)
+ (a.z * b.x * c.y)
- (a.x * b.z * c.y)
- (a.y * b.x * c.z)
- (a.z * b.y * c.x);
}
struct Intersect {
bool isHit;
bool isFront;
vec3 position;
float distance;
vec3 normal;
int material;
vec3 color;
};
struct Plane {
vec3 position;
vec3 normal;
//vec3 color;
};
const int DIAMOND_MATERIAL = 0;
const int FLOOR_MATERIAL = 1;
float frag;
float texShift;
void rayIntersectsTriangle( vec3 origin, vec3 ray, vec3 v0, vec3 v1, vec3 v2, inout Intersect nearest ) {
vec3 invRay = -ray;
vec3 edge1 = v1 - v0;
vec3 edge2 = v2 - v0;
float denominator = det( edge1, edge2, invRay );
if ( denominator == 0.0 ) return;
float invDenominator = 1.0 / denominator;
vec3 d = origin - v0;
float u = det( d, edge2, invRay ) * invDenominator;
if ( u < 0.0 || u > 1.0 ) return;
float v = det( edge1, d, invRay ) * invDenominator;
if ( v < 0.0 || u + v > 1.0 ) return;
float t = det( edge1, edge2, d ) * invDenominator;
if ( t < 0.0 || t > nearest.distance ) return;
nearest.isHit = true;
nearest.position = origin + ray * t;
nearest.distance = t;
nearest.normal = normalize( cross( edge1, edge2 ) ) * sign( invDenominator );
nearest.material = DIAMOND_MATERIAL;
//nearest.color = diamondDiffuseColor;
nearest.isFront = invDenominator > 0.0;
}
void rayIntersectPlane( vec3 origin, vec3 ray, Plane plane, inout Intersect nearest ) {
float d = -dot( plane.position, plane.normal );
float v = dot( ray, plane.normal );
float t = -( dot( origin, plane.normal ) + d ) / v;
if( t > 0.0 && t < nearest.distance ) {
nearest.isHit = true;
nearest.position = origin + ray * t;
nearest.normal = plane.normal;
nearest.distance = t;
//nearest.color = plane.color;
nearest.material = FLOOR_MATERIAL;
}
}
void getRayColor( vec3 origin, vec3 ray, inout Intersect nearest ) {
nearest.isHit = false;
nearest.distance = 1.0e+30;
// Plane
Plane plane;
plane.position = vec3( 0.0, 0.0, 0.0 );
plane.normal = vec3( 0.0, 1.0, 0.0 );
//plane.color = vec3(1.0);
rayIntersectPlane( origin, ray, plane, nearest );
float pu = texShift;
float pv = 0.5;
// diamond
for( int i = 0; i < VERTEX_TEXTURE_WIDTH; i++ ) {
if ( i >= diamondFaceCount ) break;
vec3 v0 = texture2D( diamondVertexTexture, vec2( pu, pv ) ).xyz;
pu += frag;
vec3 v1 = texture2D( diamondVertexTexture, vec2( pu, pv ) ).xyz;
pu += frag;
vec3 v2 = texture2D( diamondVertexTexture, vec2( pu, pv ) ).xyz;
pu += frag;
rayIntersectsTriangle( origin, ray, v0, v1, v2, nearest );
}
if ( nearest.isHit ) {
if ( nearest.material == DIAMOND_MATERIAL ) {
float diffuse1 = clamp( dot( lightDir1, nearest.normal ), 0.1, 1.0 );
float diffuse2 = clamp( dot( lightDir2, nearest.normal ), 0.1, 1.0 );
nearest.color = diamondDiffuseColor * clamp( diffuse1 + diffuse2, 0.0, 1.0 );
float specular1 = pow( clamp( dot( reflect( lightDir1, nearest.normal ), ray ), 0.0, 1.0 ), 100.0 );
float specular2 = pow( clamp( dot( reflect( lightDir2, nearest.normal ), ray ), 0.0, 1.0 ), 100.0 );
nearest.color += diamondSpecularColor * clamp( specular1 + specular2, 0.0, 1.0 );
}
if ( nearest.material == FLOOR_MATERIAL ) {
float diffuse1 = clamp( dot( nearest.normal, lightDir1 ), 0.1, 1.0 );
float diffuse2 = clamp( dot( nearest.normal, lightDir2 ), 0.1, 1.0 );
float d = diffuse1 + diffuse2;
float m = mod( nearest.position.x, 2.0 );
float n = mod( nearest.position.z, 2.0 );
if ( ( m > 1.0 && n > 1.0 ) || ( m < 1.0 && n < 1.0 ) ) d *= 0.1;
nearest.color = vec3( d );
}
nearest.color -= clamp( 0.05 * nearest.distance, 0.0, 0.6 );
} else {
nearest.color = vec3( 0.0 );
}
}
void main(void) {
// calc consts
invRefractiveIndex = 1.0 / refractiveIndex;
frag = 1.0 / float( VERTEX_TEXTURE_WIDTH );
texShift = 0.5 * frag;
// fragment position
vec2 p = ( gl_FragCoord.xy * 2.0 - resolution ) / min( resolution.x, resolution.y );
// camera and ray
vec3 cPos = cameraPos;
vec3 cDir = cameraDir;
vec3 cSide = normalize( cross( cDir, vec3( 0.0, 1.0 ,0.0 ) ) );
vec3 cUp = normalize( cross( cSide, cDir ) );
float targetDepth = 1.3;
vec3 ray = normalize( cSide * p.x + cUp * p.y + cDir * targetDepth );
vec3 color = vec3( 0.0 );
Intersect nearest;
float alpha = 1.0;
for ( int i = 0; i < 5; i++ ) {
getRayColor( cPos, ray, nearest );
color += clamp( nearest.color, 0.0, 1.0 ) * alpha;
alpha *= 0.99;
if ( nearest.material == DIAMOND_MATERIAL ) {
ray = refract( ray, nearest.normal, nearest.isFront ? invRefractiveIndex : refractiveIndex );
cPos = nearest.position - nearest.normal * EPS;
if ( ray == vec3( 0.0 ) ) {
ray = reflect( ray, nearest.normal );
cPos = nearest.position + nearest.normal * EPS;
}
}
if ( nearest.material == FLOOR_MATERIAL ) {
ray = reflect( ray, nearest.normal );
cPos = nearest.position + nearest.normal * EPS;
}
ray = normalize( ray );
if ( !nearest.isHit ) break;
}
color = clamp( color, 0.0, 1.0 );
if ( gammaCorrection ) {
gl_FragColor = vec4( pow( color, vec3( 1.0 / 2.2 ) ), 1.0 );
} else {
gl_FragColor = vec4( color, 1.0 );
}
}
</script>
<script id="vertex_shader" type="x-shader/x-vertex">
attribute vec3 position;
void main(void) {
gl_Position = vec4(position, 1.0);
}
</script>
<script src="js/three.min.js"></script>
<script src="js/controls/OrbitControls.js"></script>
<script src="js/loaders/OBJLoader.js"></script>
<script src="js/libs/stats.min.js"></script>
<script src="js/libs/dat.gui.min.js"></script>
<script>
var camera, dummyCamera, scene, controls, renderer;
var geometry, material, mesh;
var mouse = new THREE.Vector2( 0.5, 0.5 );
var canvas;
var stats;
var config = {
saveImage: function() {
renderer.render( scene, dummyCamera );
canvas.toBlob(function(blob) {
var url = URL.createObjectURL(blob);
var link = document.createElement('a');
link.href = url;
link.download = 'raytracing_' + Date.now() + '.png';
link.click();
URL.revokeObjectURL(url);
}, 'image/png');
},
camera: 'Auto Rotate',
gammaCorrection: false,
refractiveIndex: 1.42,
diamond: 'round_brilliant',
diamondDiffuseColor: "#590606",
diamondSpecularColor: "#ff6666",
resolution: '256',
};
var diamondDiffuseColorVector = new THREE.Vector3();
var diamondSpecularColorVector = new THREE.Vector3();
var diamond = {
faceCount: 0,
vertexTexture: new THREE.DataTexture (
new Float32Array(1),
1, 1,
THREE.RGBAFormat,
THREE.FloatType
),
};
var VERTEX_TEXTURE_WIDTH = 512;
init();
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(35, 800/600);//new THREE.Camera();
camera.position.set( 0.5952697396278381, 2.9264581203460693, 0.45332589745521545 );
camera.lookAt( new THREE.Vector3( 0.34052577821311814, 1.9785592579218645, 0.26203224399464353 ) );
dummyCamera = new THREE.Camera();
updateVertexTexture( "models/" + config.diamond + ".obj", diamond );
setColorVectorFromHex( config.diamondDiffuseColor, diamondDiffuseColorVector );
setColorVectorFromHex( config.diamondSpecularColor, diamondSpecularColorVector );
geometry = new THREE.PlaneBufferGeometry( 2.0, 2.0 );
material = new THREE.RawShaderMaterial( {
uniforms: {
cameraPos: { type: 'v3', value: camera.getWorldPosition() },
cameraDir: { type: 'v3', value: camera.getWorldDirection() },
gammaCorrection: { type: 'i', value: config.gammaCorrection },
resolution: { type: 'v2', value: new THREE.Vector2( config.resolution, config.resolution ) },
diamondFaceCount: { type: 'i', value: diamond.faceCount },
diamondVertexTexture: { type: 't', value: diamond.vertexTexture },
refractiveIndex: { type: 'f', value: config.refractiveIndex },
diamondDiffuseColor: { type: 'v3', value: diamondDiffuseColorVector },
diamondSpecularColor: { type: 'v3', value: diamondSpecularColorVector },
},
vertexShader: document.getElementById( 'vertex_shader' ).textContent,
fragmentShader: document.getElementById( 'fragment_shader' ).textContent.replace( /VERTEX_TEXTURE_WIDTH/g, VERTEX_TEXTURE_WIDTH ),
} );
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
renderer = new THREE.WebGLRenderer();
//renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( config.resolution, config.resolution );
canvas = renderer.domElement;
canvas.addEventListener( 'mousemove', onMouseMove );
window.addEventListener( 'resize', onWindowResize );
document.body.appendChild( canvas );
var gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
var ext = gl.getExtension('OES_texture_float');
if( ext == null ) {
alert('float texture not supported');
return;
}
controls = new THREE.OrbitControls( camera, canvas );
controls.enableDamping = true;
controls.dampingFactor = 0.15;
controls.enableZoom = true;
controls.rotateSpeed = 0.2;
controls.autoRotate = ( config.camera === 'Auto Rotate' );
controls.autoRotateSpeed = 0.8;
controls.target = new THREE.Vector3( 0, 0.7, 0 );
var gui = new dat.GUI({
load: {
"preset": "Ruby",
"closed": false,
"remembered": {
"Ruby": {
"0": {
"camera": config.camera,
"gammaCorrection": config.gammaCorrection,
"diamond": config.diamond,
"diamondDiffuseColor": config.diamondDiffuseColor,
"diamondSpecularColor": config.diamondSpecularColor,
"refractiveIndex": config.refractiveIndex,
"resolution": config.resolution,
}
},
"Emerald": {
"0": {
"camera": "Auto",
"gammaCorrection": false,
"diamond": "barion",
"diamondDiffuseColor": "#065914",
"diamondSpecularColor": "#93ff93",
"refractiveIndex": 1.3656227239621275,
"resolution": "256"
}
},
"Topaz": {
"0": {
"camera": "Auto Rotate",
"gammaCorrection": false,
"diamond": "oval_brilliant",
"diamondDiffuseColor": "#554b05",
"diamondSpecularColor": "#ff7800",
"refractiveIndex": 1.4,
"resolution": "256"
}
},
"Ramiel": {
"0": {
"camera": "Auto Rotate",
"gammaCorrection": false,
"diamond": "octahedron",
"diamondDiffuseColor": "#0c0255",
"diamondSpecularColor": "#a2b8ff",
"refractiveIndex": 1.1,
"resolution": "256"
}
}
},
"folders": {}
}
});
gui.remember( config );
gui.add( config, 'saveImage' ).name( 'Save Image' );
gui.add( config, 'camera', [ 'Manual', 'Auto Rotate', 'Auto' ] ).name( 'Camera' ).onChange( function( value ) {
controls.autoRotate = ( value === 'Auto Rotate' );
} );
gui.add( config, 'gammaCorrection' ).name( 'Gamma Correction' );
gui.add( config, 'diamond', [
'round_brilliant',
'round_brilliant2',
'octahedron',
'barion',
'oval_brilliant',
'asscher',
'trillion_brilliant',
//'princess',
] ).name( 'Model' ).onChange( function( value ) {
updateVertexTexture( "models/" + value + ".obj", diamond );
} );
gui.addColor( config, 'diamondDiffuseColor' ).name( 'Diffuse Color' ).onChange( function( value ) {
setColorVectorFromHex( value, diamondDiffuseColorVector );
} );
gui.addColor( config, 'diamondSpecularColor' ).name( 'Specular Color' ).onChange( function( value ) {
setColorVectorFromHex( value, diamondSpecularColorVector );
} );
gui.add( config, 'refractiveIndex', 0.0, 3.0 ).name( 'Refractive Index' );
gui.add( config, 'resolution', [ '128', '256', '512', '800', 'full' ] ).name( 'Resolution' ).onChange( function( value ) {
if ( value !== 'full' ) {
canvas.width = value;
canvas.height = value;
}
onWindowResize();
} );
stats = new Stats();
document.body.appendChild( stats.domElement );
render();
}
function updateVertexTexture( obj_url, target ) {
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
console.log( item, loaded, total );
};
var onProgress = function ( xhr ) {
if ( xhr.lengthComputable ) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log( Math.round(percentComplete, 2) + '% downloaded' );
}
};
var onError = function ( xhr ) {
};
var loader = new THREE.OBJLoader( manager );
loader.load( obj_url, function ( object ) {
var bufferGeometry = object.children[0].geometry;
var diamondGeometry = new THREE.Geometry().fromBufferGeometry( bufferGeometry );
var faces = diamondGeometry.faces;
var vertices = diamondGeometry.vertices;
var faceCount = faces.length;
console.log( "faceCount: " + faceCount );
var width = VERTEX_TEXTURE_WIDTH;
var height = 1;
var diamondVertexes = new Float32Array( width * height * 4 );
for ( var i = 0; i < faceCount; i++ ) {
var face = faces[ i ];
var a = vertices[ face.a ];
var b = vertices[ face.b ];
var c = vertices[ face.c ];
diamondVertexes[ i * 12 ] = a.x;
diamondVertexes[ i * 12 + 1 ] = a.y;
diamondVertexes[ i * 12 + 2 ] = a.z;
diamondVertexes[ i * 12 + 3 ] = 1.0;
diamondVertexes[ i * 12 + 4 ] = b.x;
diamondVertexes[ i * 12 + 5 ] = b.y;
diamondVertexes[ i * 12 + 6 ] = b.z;
diamondVertexes[ i * 12 + 7 ] = 1.0;
diamondVertexes[ i * 12 + 8 ] = c.x;
diamondVertexes[ i * 12 + 9 ] = c.y;
diamondVertexes[ i * 12 + 10 ] = c.z;
diamondVertexes[ i * 12 + 11 ] = 1.0;
}
var vertexTexture = new THREE.DataTexture (
diamondVertexes,
width,
height,
THREE.RGBAFormat,
THREE.FloatType
);
vertexTexture.needsUpdate = true;
target.faceCount = faceCount;
target.vertexTexture = vertexTexture;
}, onProgress, onError );
}
function render( timestamp ) {
stats.begin();
if ( config.camera === 'Auto' ) {
var rad = 0.0004 * timestamp;
var h = Math.cos( rad * 1.5 );
camera.position.set( ( 1.3 - h ) * Math.cos( rad ), 2.0 + h, ( 2.0 - h ) * Math.sin( rad ) );
camera.lookAt( new THREE.Vector3( 0, 1, 0 ) );
} else {
controls.update();
}
material.uniforms.cameraPos.value = camera.getWorldPosition();
material.uniforms.cameraDir.value = camera.getWorldDirection();
material.uniforms.gammaCorrection.value = config.gammaCorrection;
material.uniforms.resolution.value = new THREE.Vector2( canvas.width, canvas.height );
material.uniforms.diamondFaceCount.value = diamond.faceCount;
material.uniforms.diamondVertexTexture.value = diamond.vertexTexture;
material.uniforms.diamondDiffuseColor.value = diamondDiffuseColorVector;
material.uniforms.diamondSpecularColor.value = diamondSpecularColorVector;
material.uniforms.refractiveIndex.value = config.refractiveIndex;
renderer.render( scene, dummyCamera );
stats.end();
requestAnimationFrame( render );
}
function onMouseMove( e ) {
mouse.x = e.offsetX / canvas.width;
mouse.y = e.offsetY / canvas.height;
}
function onWindowResize( e ) {
if ( config.resolution === 'full' ) {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
renderer.setSize( canvas.width, canvas.height );
}
function setColorVectorFromHex( hex, vector ) {
var color = new THREE.Color( hex );
vector.set( color.r, color.g, color.b );
}
</script>
</body>
</html>