RaytracingRenderer.js 12 KB

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