RaytracingRenderer.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author alteredq / http://alteredqualia.com/
  4. */
  5. THREE.RaytracingRenderer = function ( parameters ) {
  6. console.log( 'THREE.RaytracingRenderer', THREE.REVISION );
  7. parameters = parameters || {};
  8. var scope = this;
  9. var canvas = document.createElement( 'canvas' );
  10. var context = canvas.getContext( '2d', {
  11. alpha: parameters.alpha === true
  12. } );
  13. var maxRecursionDepth = 3;
  14. var canvasWidth, canvasHeight;
  15. var canvasWidthHalf, canvasHeightHalf;
  16. var clearColor = new THREE.Color( 0x000000 );
  17. var origin = new THREE.Vector3();
  18. var direction = new THREE.Vector3();
  19. var cameraPosition = new THREE.Vector3();
  20. var raycaster = new THREE.Raycaster( origin, direction );
  21. var raycasterLight = new THREE.Raycaster();
  22. var perspective;
  23. var modelViewMatrix = new THREE.Matrix4();
  24. var cameraNormalMatrix = new THREE.Matrix3();
  25. var objects;
  26. var lights = [];
  27. var cache = {};
  28. var timeRendering = 0;
  29. var animationFrameId = null;
  30. this.domElement = canvas;
  31. this.autoClear = true;
  32. this.setClearColor = function ( color, alpha ) {
  33. clearColor.set( color );
  34. };
  35. this.setPixelRatio = function () {};
  36. this.setSize = function ( width, height ) {
  37. canvas.width = width;
  38. canvas.height = height;
  39. canvasWidth = canvas.width;
  40. canvasHeight = canvas.height;
  41. canvasWidthHalf = Math.floor( canvasWidth / 2 );
  42. canvasHeightHalf = Math.floor( canvasHeight / 2 );
  43. context.fillStyle = 'white';
  44. };
  45. this.setSize( canvas.width, canvas.height );
  46. this.clear = function () {
  47. };
  48. //
  49. var spawnRay = ( function () {
  50. var diffuseColor = new THREE.Color();
  51. var specularColor = new THREE.Color();
  52. var lightColor = new THREE.Color();
  53. var schlick = new THREE.Color();
  54. var lightContribution = new THREE.Color();
  55. var eyeVector = new THREE.Vector3();
  56. var lightVector = new THREE.Vector3();
  57. var normalVector = new THREE.Vector3();
  58. var halfVector = new THREE.Vector3();
  59. var localPoint = new THREE.Vector3();
  60. var reflectionVector = new THREE.Vector3();
  61. var tmpVec = new THREE.Vector3();
  62. var tmpColor = [];
  63. for ( var i = 0; i < maxRecursionDepth; i ++ ) {
  64. tmpColor[ i ] = new THREE.Color();
  65. }
  66. return function spawnRay( rayOrigin, rayDirection, outputColor, recursionDepth ) {
  67. var ray = raycaster.ray;
  68. ray.origin = rayOrigin;
  69. ray.direction = rayDirection;
  70. //
  71. var rayLight = raycasterLight.ray;
  72. //
  73. outputColor.setRGB( 0, 0, 0 );
  74. //
  75. var intersections = raycaster.intersectObjects( objects, true );
  76. // ray didn't find anything
  77. // (here should come setting of background color?)
  78. if ( intersections.length === 0 ) {
  79. return;
  80. }
  81. // ray hit
  82. var intersection = intersections[ 0 ];
  83. var point = intersection.point;
  84. var object = intersection.object;
  85. var material = object.material;
  86. var face = intersection.face;
  87. var vertices = object.geometry.vertices;
  88. //
  89. var _object = cache[ object.id ];
  90. localPoint.copy( point ).applyMatrix4( _object.inverseMatrix );
  91. eyeVector.subVectors( raycaster.ray.origin, point ).normalize();
  92. // resolve pixel diffuse color
  93. if ( material instanceof THREE.MeshLambertMaterial ||
  94. material instanceof THREE.MeshPhongMaterial ||
  95. material instanceof THREE.MeshBasicMaterial ) {
  96. diffuseColor.copyGammaToLinear( material.color );
  97. } else {
  98. diffuseColor.setRGB( 1, 1, 1 );
  99. }
  100. if ( material.vertexColors === THREE.FaceColors ) {
  101. diffuseColor.multiply( face.color );
  102. }
  103. // compute light shading
  104. rayLight.origin.copy( point );
  105. if ( material instanceof THREE.MeshBasicMaterial ) {
  106. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  107. var light = lights[ i ];
  108. lightVector.setFromMatrixPosition( light.matrixWorld );
  109. lightVector.sub( point );
  110. rayLight.direction.copy( lightVector ).normalize();
  111. var intersections = raycasterLight.intersectObjects( objects, true );
  112. // point in shadow
  113. if ( intersections.length > 0 ) continue;
  114. // point visible
  115. outputColor.add( diffuseColor );
  116. }
  117. } else if ( material instanceof THREE.MeshLambertMaterial ||
  118. material instanceof THREE.MeshPhongMaterial ) {
  119. var normalComputed = false;
  120. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  121. var light = lights[ i ];
  122. lightColor.copyGammaToLinear( light.color );
  123. lightVector.setFromMatrixPosition( light.matrixWorld );
  124. lightVector.sub( point );
  125. rayLight.direction.copy( lightVector ).normalize();
  126. var intersections = raycasterLight.intersectObjects( objects, true );
  127. // point in shadow
  128. if ( intersections.length > 0 ) continue;
  129. // point lit
  130. if ( normalComputed === false ) {
  131. // the same normal can be reused for all lights
  132. // (should be possible to cache even more)
  133. computePixelNormal( normalVector, localPoint, material.shading, face, vertices );
  134. normalVector.applyMatrix3( _object.normalMatrix ).normalize();
  135. normalComputed = true;
  136. }
  137. // compute attenuation
  138. var attenuation = 1.0;
  139. if ( light.physicalAttenuation === true ) {
  140. attenuation = lightVector.length();
  141. attenuation = 1.0 / ( attenuation * attenuation );
  142. }
  143. lightVector.normalize();
  144. // compute diffuse
  145. var dot = Math.max( normalVector.dot( lightVector ), 0 );
  146. var diffuseIntensity = dot * light.intensity;
  147. lightContribution.copy( diffuseColor );
  148. lightContribution.multiply( lightColor );
  149. lightContribution.multiplyScalar( diffuseIntensity * attenuation );
  150. outputColor.add( lightContribution );
  151. // compute specular
  152. if ( material instanceof THREE.MeshPhongMaterial ) {
  153. halfVector.addVectors( lightVector, eyeVector ).normalize();
  154. var dotNormalHalf = Math.max( normalVector.dot( halfVector ), 0.0 );
  155. var specularIntensity = Math.max( Math.pow( dotNormalHalf, material.shininess ), 0.0 ) * diffuseIntensity;
  156. var specularNormalization = ( material.shininess + 2.0 ) / 8.0;
  157. specularColor.copyGammaToLinear( material.specular );
  158. var alpha = Math.pow( Math.max( 1.0 - lightVector.dot( halfVector ), 0.0 ), 5.0 );
  159. schlick.r = specularColor.r + ( 1.0 - specularColor.r ) * alpha;
  160. schlick.g = specularColor.g + ( 1.0 - specularColor.g ) * alpha;
  161. schlick.b = specularColor.b + ( 1.0 - specularColor.b ) * alpha;
  162. lightContribution.copy( schlick );
  163. lightContribution.multiply( lightColor );
  164. lightContribution.multiplyScalar( specularNormalization * specularIntensity * attenuation );
  165. outputColor.add( lightContribution );
  166. }
  167. }
  168. }
  169. // reflection / refraction
  170. var reflectivity = material.reflectivity;
  171. if ( ( material.mirror || material.glass ) && reflectivity > 0 && recursionDepth < maxRecursionDepth ) {
  172. if ( material.mirror ) {
  173. reflectionVector.copy( rayDirection );
  174. reflectionVector.reflect( normalVector );
  175. } else if ( material.glass ) {
  176. var eta = material.refractionRatio;
  177. var dotNI = rayDirection.dot( normalVector );
  178. var k = 1.0 - eta * eta * ( 1.0 - dotNI * dotNI );
  179. if ( k < 0.0 ) {
  180. reflectionVector.set( 0, 0, 0 );
  181. } else {
  182. reflectionVector.copy( rayDirection );
  183. reflectionVector.multiplyScalar( eta );
  184. var alpha = eta * dotNI + Math.sqrt( k );
  185. tmpVec.copy( normalVector );
  186. tmpVec.multiplyScalar( alpha );
  187. reflectionVector.sub( tmpVec );
  188. }
  189. }
  190. var theta = Math.max( eyeVector.dot( normalVector ), 0.0 );
  191. var rf0 = reflectivity;
  192. var fresnel = rf0 + ( 1.0 - rf0 ) * Math.pow( ( 1.0 - theta ), 5.0 );
  193. var weight = fresnel;
  194. var zColor = tmpColor[ recursionDepth ];
  195. spawnRay( point, reflectionVector, zColor, recursionDepth + 1 );
  196. if ( material.specular !== undefined ) {
  197. zColor.multiply( material.specular );
  198. }
  199. zColor.multiplyScalar( weight );
  200. outputColor.multiplyScalar( 1 - weight );
  201. outputColor.add( zColor );
  202. }
  203. };
  204. }() );
  205. var computePixelNormal = ( function () {
  206. var tmpVec1 = new THREE.Vector3();
  207. var tmpVec2 = new THREE.Vector3();
  208. var tmpVec3 = new THREE.Vector3();
  209. return function computePixelNormal( outputVector, point, shading, face, vertices ) {
  210. var faceNormal = face.normal;
  211. var vertexNormals = face.vertexNormals;
  212. if ( shading === THREE.FlatShading ) {
  213. outputVector.copy( faceNormal );
  214. } else if ( shading === THREE.SmoothShading ) {
  215. // compute barycentric coordinates
  216. var vA = vertices[ face.a ];
  217. var vB = vertices[ face.b ];
  218. var vC = vertices[ face.c ];
  219. tmpVec3.crossVectors( tmpVec1.subVectors( vB, vA ), tmpVec2.subVectors( vC, vA ) );
  220. var areaABC = faceNormal.dot( tmpVec3 );
  221. tmpVec3.crossVectors( tmpVec1.subVectors( vB, point ), tmpVec2.subVectors( vC, point ) );
  222. var areaPBC = faceNormal.dot( tmpVec3 );
  223. var a = areaPBC / areaABC;
  224. tmpVec3.crossVectors( tmpVec1.subVectors( vC, point ), tmpVec2.subVectors( vA, point ) );
  225. var areaPCA = faceNormal.dot( tmpVec3 );
  226. var b = areaPCA / areaABC;
  227. var c = 1.0 - a - b;
  228. // compute interpolated vertex normal
  229. tmpVec1.copy( vertexNormals[ 0 ] );
  230. tmpVec1.multiplyScalar( a );
  231. tmpVec2.copy( vertexNormals[ 1 ] );
  232. tmpVec2.multiplyScalar( b );
  233. tmpVec3.copy( vertexNormals[ 2 ] );
  234. tmpVec3.multiplyScalar( c );
  235. outputVector.addVectors( tmpVec1, tmpVec2 );
  236. outputVector.add( tmpVec3 );
  237. }
  238. };
  239. }() );
  240. var renderBlock = ( function () {
  241. var blockSize = 64;
  242. var canvasBlock = document.createElement( 'canvas' );
  243. canvasBlock.width = blockSize;
  244. canvasBlock.height = blockSize;
  245. var contextBlock = canvasBlock.getContext( '2d', {
  246. alpha: parameters.alpha === true
  247. } );
  248. var imagedata = contextBlock.getImageData( 0, 0, blockSize, blockSize );
  249. var data = imagedata.data;
  250. var pixelColor = new THREE.Color();
  251. return function renderBlock( blockX, blockY ) {
  252. var index = 0;
  253. for ( var y = 0; y < blockSize; y ++ ) {
  254. for ( var x = 0; x < blockSize; x ++, index += 4 ) {
  255. // spawn primary ray at pixel position
  256. origin.copy( cameraPosition );
  257. direction.set( x + blockX - canvasWidthHalf, - ( y + blockY - canvasHeightHalf ), - perspective );
  258. direction.applyMatrix3( cameraNormalMatrix ).normalize();
  259. spawnRay( origin, direction, pixelColor, 0 );
  260. // convert from linear to gamma
  261. data[ index ] = Math.sqrt( pixelColor.r ) * 255;
  262. data[ index + 1 ] = Math.sqrt( pixelColor.g ) * 255;
  263. data[ index + 2 ] = Math.sqrt( pixelColor.b ) * 255;
  264. }
  265. }
  266. context.putImageData( imagedata, blockX, blockY );
  267. blockX += blockSize;
  268. if ( blockX >= canvasWidth ) {
  269. blockX = 0;
  270. blockY += blockSize;
  271. if ( blockY >= canvasHeight ) {
  272. console.log('Total Renderering time', timeRendering / 1000, 's');
  273. console.log('Absolute time', (Date.now() - reallyThen) / 1000, 's');
  274. scope.dispatchEvent( { type: "complete" } );
  275. return;
  276. }
  277. }
  278. context.fillRect( blockX, blockY, blockSize, blockSize );
  279. animationFrameId = requestAnimationFrame( function () {
  280. console.time('render')
  281. var then = Date.now();
  282. renderBlock( blockX, blockY );
  283. timeRendering += Date.now() - then;
  284. console.timeEnd('render')
  285. } );
  286. };
  287. }() );
  288. this.render = function ( scene, camera ) {
  289. reallyThen = Date.now()
  290. if ( this.autoClear === true ) this.clear();
  291. cancelAnimationFrame( animationFrameId );
  292. // update scene graph
  293. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  294. // update camera matrices
  295. if ( camera.parent === null ) camera.updateMatrixWorld();
  296. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  297. cameraPosition.setFromMatrixPosition( camera.matrixWorld );
  298. //
  299. cameraNormalMatrix.getNormalMatrix( camera.matrixWorld );
  300. origin.copy( cameraPosition );
  301. perspective = 0.5 / Math.tan( THREE.Math.degToRad( camera.fov * 0.5 ) ) * canvasHeight;
  302. objects = scene.children;
  303. // collect lights and set up object matrices
  304. lights.length = 0;
  305. scene.traverse( function ( object ) {
  306. if ( object instanceof THREE.Light ) {
  307. lights.push( object );
  308. }
  309. if ( cache[ object.id ] === undefined ) {
  310. cache[ object.id ] = {
  311. normalMatrix: new THREE.Matrix3(),
  312. inverseMatrix: new THREE.Matrix4()
  313. };
  314. }
  315. modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  316. var _object = cache[ object.id ];
  317. _object.normalMatrix.getNormalMatrix( modelViewMatrix );
  318. _object.inverseMatrix.getInverse( object.matrixWorld );
  319. } );
  320. renderBlock( 0, 0 );
  321. };
  322. };
  323. THREE.EventDispatcher.prototype.apply( THREE.RaytracingRenderer.prototype );