RaytracingWorker.js 13 KB

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