RaytracingWorker.js 12 KB

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