RaytracingWorker.js 13 KB

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