webgl_loader_obj2_meshspray.html 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - Mesh Spray</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <style>
  8. body {
  9. font-family: Monospace;
  10. background-color: #000;
  11. color: #fff;
  12. margin: 0 0 0 0;
  13. padding: 0 0 0 0;
  14. border: none;
  15. cursor: default;
  16. }
  17. #info {
  18. color: #fff;
  19. position: absolute;
  20. top: 10px;
  21. width: 100%;
  22. text-align: center;
  23. z-index: 100;
  24. display:block;
  25. }
  26. #info a {
  27. color: #f00;
  28. font-weight: bold;
  29. text-decoration: underline;
  30. cursor: pointer
  31. }
  32. #glFullscreen {
  33. width: 100%;
  34. height: 100vh;
  35. min-width: 640px;
  36. min-height: 360px;
  37. position: relative;
  38. overflow: hidden;
  39. z-index: 0;
  40. }
  41. #example {
  42. width: 100%;
  43. height: 100%;
  44. top: 0;
  45. left: 0;
  46. background-color: #000000;
  47. }
  48. #feedback {
  49. color: darkorange;
  50. }
  51. #dat {
  52. user-select: none;
  53. position: absolute;
  54. left: 0;
  55. top: 0;
  56. z-Index: 200;
  57. }
  58. </style>
  59. </head>
  60. <body>
  61. <div id="glFullscreen">
  62. <canvas id="example"></canvas>
  63. </div>
  64. <div id="dat">
  65. </div>
  66. <div id="info">
  67. <a href="http://threejs.org" target="_blank">three.js</a> - Mesh Spray
  68. <div id="feedback"></div>
  69. </div>
  70. <script src="../build/three.js"></script>
  71. <script src="js/controls/TrackballControls.js"></script>
  72. <script src="js/libs/dat.gui.min.js"></script>
  73. <script src="js/loaders/LoaderSupport.js"></script>
  74. <script>
  75. 'use strict';
  76. var MeshSpray = (function () {
  77. var Validator = THREE.LoaderSupport.Validator;
  78. function MeshSpray( manager ) {
  79. this.manager = Validator.verifyInput( manager, THREE.DefaultLoadingManager );
  80. this.logging = {
  81. enabled: true,
  82. debug: false
  83. };
  84. this.instanceNo = 0;
  85. this.loaderRootNode = new THREE.Group();
  86. this.meshBuilder = new THREE.LoaderSupport.MeshBuilder();
  87. this.callbacks = new THREE.LoaderSupport.Callbacks();
  88. this.workerSupport = null;
  89. }
  90. MeshSpray.prototype.setLogging = function ( enabled, debug ) {
  91. this.logging.enabled = enabled === true;
  92. this.logging.debug = debug === true;
  93. this.meshBuilder.setLogging( this.logging.enabled, this.logging.debug );
  94. };
  95. MeshSpray.prototype.setStreamMeshesTo = function ( streamMeshesTo ) {
  96. this.loaderRootNode = Validator.verifyInput( streamMeshesTo, this.loaderRootNode );
  97. };
  98. MeshSpray.prototype.setForceWorkerDataCopy = function ( forceWorkerDataCopy ) {
  99. // nothing to do here
  100. };
  101. MeshSpray.prototype.run = function ( prepData, workerSupportExternal ) {
  102. if ( THREE.LoaderSupport.Validator.isValid( workerSupportExternal ) ) {
  103. this.workerSupport = workerSupportExternal;
  104. this.logging.enabled = this.workerSupport.logging.enabled;
  105. this.logging.debug = this.workerSupport.logging.debug;
  106. } else {
  107. this.workerSupport = THREE.LoaderSupport.Validator.verifyInput( this.workerSupport, new THREE.LoaderSupport.WorkerSupport() );
  108. }
  109. if ( this.logging.enabled ) console.time( 'MeshSpray' + this.instanceNo );
  110. this._applyPrepData( prepData );
  111. this.meshBuilder.init();
  112. var scope = this;
  113. var scopeBuilderFunc = function ( payload ) {
  114. var meshes = scope.meshBuilder.processPayload( payload );
  115. var mesh;
  116. for ( var i in meshes ) {
  117. mesh = meshes[ i ];
  118. scope.loaderRootNode.add( mesh );
  119. }
  120. };
  121. var scopeFuncComplete = function ( message ) {
  122. var callback = scope.callbacks.onLoad;
  123. if ( THREE.LoaderSupport.Validator.isValid( callback ) ) callback(
  124. {
  125. detail: {
  126. loaderRootNode: scope.loaderRootNode,
  127. modelName: scope.modelName,
  128. instanceNo: scope.instanceNo
  129. }
  130. }
  131. );
  132. if ( scope.logging.enabled ) console.timeEnd( 'MeshSpray' + scope.instanceNo );
  133. };
  134. var buildCode = function ( funcBuildObject, funcBuildSingleton ) {
  135. var workerCode = '';
  136. workerCode += '/**\n';
  137. workerCode += ' * This code was constructed by MeshSpray buildCode.\n';
  138. workerCode += ' */\n\n';
  139. workerCode += 'THREE.LoaderSupport = {};\n\n';
  140. workerCode += funcBuildObject( 'THREE.LoaderSupport.Validator', THREE.LoaderSupport.Validator );
  141. workerCode += funcBuildSingleton( 'Parser', Parser );
  142. return workerCode;
  143. };
  144. var libs2Load = [ 'build/three.min.js' ];
  145. this.workerSupport.validate( buildCode, 'Parser', libs2Load, '../' );
  146. this.workerSupport.setCallbacks( scopeBuilderFunc, scopeFuncComplete );
  147. this.workerSupport.run(
  148. {
  149. params: {
  150. dimension: prepData.dimension,
  151. quantity: prepData.quantity,
  152. globalObjectCount: prepData.globalObjectCount
  153. },
  154. materials: {
  155. serializedMaterials: this.meshBuilder.getMaterialsJSON()
  156. },
  157. logging: {
  158. enabled: this.logging.enabled,
  159. debug: this.logging.debug
  160. },
  161. data: {
  162. input: null,
  163. options: null
  164. }
  165. }
  166. );
  167. };
  168. MeshSpray.prototype._applyPrepData = function ( prepData ) {
  169. if ( Validator.isValid( prepData ) ) {
  170. this.setLogging( prepData.logging.enabled, prepData.logging.debug );
  171. this.setStreamMeshesTo( prepData.streamMeshesTo );
  172. this.meshBuilder.setMaterials( prepData.materials );
  173. this._setCallbacks( prepData.getCallbacks() );
  174. }
  175. };
  176. MeshSpray.prototype._setCallbacks = function ( callbacks ) {
  177. if ( Validator.isValid( callbacks.onProgress ) ) this.callbacks.setCallbackOnProgress( callbacks.onProgress );
  178. if ( Validator.isValid( callbacks.onMeshAlter ) ) this.callbacks.setCallbackOnMeshAlter( callbacks.onMeshAlter );
  179. if ( Validator.isValid( callbacks.onLoad ) ) this.callbacks.setCallbackOnLoad( callbacks.onLoad );
  180. if ( Validator.isValid( callbacks.onLoadMaterials ) ) this.callbacks.setCallbackOnLoadMaterials( callbacks.onLoadMaterials );
  181. this.meshBuilder._setCallbacks( this.callbacks );
  182. };
  183. var Parser = ( function () {
  184. function Parser() {
  185. this.sizeFactor = 0.5;
  186. this.localOffsetFactor = 1.0;
  187. this.globalObjectCount = 0;
  188. this.debug = false;
  189. this.dimension = 200;
  190. this.quantity = 1;
  191. this.callbackMeshBuilder = null;
  192. this.callbackProgress = null;
  193. this.serializedMaterials = null;
  194. this.logging = {
  195. enabled: true,
  196. debug: false
  197. };
  198. };
  199. Parser.prototype.setLogging = function ( enabled, debug ) {
  200. this.logging.enabled = enabled === true;
  201. this.logging.debug = debug === true;
  202. };
  203. Parser.prototype.parse = function () {
  204. var baseTriangle = [ 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 0.0, -1.0, 1.0 ];
  205. var vertices = [];
  206. var colors = [];
  207. var normals = [];
  208. var uvs = [];
  209. var dimensionHalf = this.dimension / 2;
  210. var fixedOffsetX;
  211. var fixedOffsetY;
  212. var fixedOffsetZ;
  213. var s, t;
  214. // complete triangle
  215. // local coords offset
  216. var localOffsetFactor = this.localOffsetFactor;
  217. for ( var i = 0; i < this.quantity; i++ ) {
  218. var sizeVaring = this.sizeFactor * Math.random();
  219. s = 2 * Math.PI * Math.random();
  220. t = Math.PI * Math.random();
  221. fixedOffsetX = dimensionHalf * Math.random() * Math.cos( s ) * Math.sin( t );
  222. fixedOffsetY = dimensionHalf * Math.random() * Math.sin( s ) * Math.sin( t );
  223. fixedOffsetZ = dimensionHalf * Math.random() * Math.cos( t );
  224. for ( var j = 0; j < baseTriangle.length; j += 3 ) {
  225. vertices.push( baseTriangle[ j ] * sizeVaring + localOffsetFactor * Math.random() + fixedOffsetX );
  226. vertices.push( baseTriangle[ j + 1 ] * sizeVaring + localOffsetFactor * Math.random() + fixedOffsetY );
  227. vertices.push( baseTriangle[ j + 2 ] * sizeVaring + localOffsetFactor * Math.random() + fixedOffsetZ );
  228. colors.push( Math.random() );
  229. colors.push( Math.random() );
  230. colors.push( Math.random() );
  231. }
  232. }
  233. var absoluteVertexCount = vertices.length;
  234. var absoluteColorCount = colors.length;
  235. var absoluteNormalCount = 0;
  236. var absoluteUvCount = 0;
  237. var vertexFA = new Float32Array( absoluteVertexCount );
  238. var colorFA = ( absoluteColorCount > 0 ) ? new Float32Array( absoluteColorCount ) : null;
  239. var normalFA = ( absoluteNormalCount > 0 ) ? new Float32Array( absoluteNormalCount ) : null;
  240. var uvFA = ( absoluteUvCount > 0 ) ? new Float32Array( absoluteUvCount ) : null;
  241. vertexFA.set( vertices, 0 );
  242. if ( colorFA ) {
  243. colorFA.set( colors, 0 );
  244. }
  245. if ( normalFA ) {
  246. normalFA.set( normals, 0 );
  247. }
  248. if ( uvFA ) {
  249. uvFA.set( uvs, 0 );
  250. }
  251. /*
  252. * This demonstrates the usage of embedded three.js in the worker blob and
  253. * the serialization of materials back to the Builder outside the worker.
  254. *
  255. * This is not the most effective way, but outlining possibilities
  256. */
  257. var materialName = 'defaultVertexColorMaterial_double';
  258. var defaultVertexColorMaterialJson = this.serializedMaterials[ 'defaultVertexColorMaterial' ];
  259. var loader = new THREE.MaterialLoader();
  260. var defaultVertexColorMaterialDouble = loader.parse( defaultVertexColorMaterialJson );
  261. defaultVertexColorMaterialDouble.name = materialName;
  262. defaultVertexColorMaterialDouble.side = THREE.DoubleSide;
  263. var newSerializedMaterials = {};
  264. newSerializedMaterials[ materialName ] = defaultVertexColorMaterialDouble.toJSON();
  265. var payload = {
  266. cmd: 'materialData',
  267. materials: {
  268. serializedMaterials: newSerializedMaterials
  269. }
  270. };
  271. this.callbackMeshBuilder( payload );
  272. this.globalObjectCount++;
  273. this.callbackMeshBuilder(
  274. {
  275. cmd: 'meshData',
  276. progress: {
  277. numericalValue: 1.0
  278. },
  279. params: {
  280. meshName: 'Gen' + this.globalObjectCount
  281. },
  282. materials: {
  283. multiMaterial: false,
  284. materialNames: [ materialName ],
  285. materialGroups: []
  286. },
  287. buffers: {
  288. vertices: vertexFA,
  289. colors: colorFA,
  290. normals: normalFA,
  291. uvs: uvFA
  292. }
  293. },
  294. [ vertexFA.buffer ],
  295. colorFA !== null ? [ colorFA.buffer ] : null,
  296. normalFA !== null ? [ normalFA.buffer ] : null,
  297. uvFA !== null ? [ uvFA.buffer ] : null
  298. );
  299. if ( this.logging.enabled ) console.info( 'Global output object count: ' + this.globalObjectCount );
  300. };
  301. return Parser;
  302. })();
  303. Parser.prototype.setSerializedMaterials = function ( serializedMaterials ) {
  304. if ( THREE.LoaderSupport.Validator.isValid( serializedMaterials ) ) {
  305. this.serializedMaterials = serializedMaterials;
  306. }
  307. };
  308. return MeshSpray;
  309. })();
  310. var MeshSprayApp = (function () {
  311. function MeshSprayApp( elementToBindTo ) {
  312. this.renderer = null;
  313. this.canvas = elementToBindTo;
  314. this.aspectRatio = 1;
  315. this.recalcAspectRatio();
  316. this.scene = null;
  317. this.cameraDefaults = {
  318. posCamera: new THREE.Vector3( 500.0, 500.0, 1000.0 ),
  319. posCameraTarget: new THREE.Vector3( 0, 0, 0 ),
  320. near: 0.1,
  321. far: 10000,
  322. fov: 45
  323. };
  324. this.camera = null;
  325. this.cameraTarget = this.cameraDefaults.posCameraTarget;
  326. this.controls = null;
  327. this.cube = null;
  328. this.pivot = null;
  329. }
  330. MeshSprayApp.prototype.initGL = function () {
  331. this.renderer = new THREE.WebGLRenderer( {
  332. canvas: this.canvas,
  333. antialias: true,
  334. autoClear: true
  335. } );
  336. this.renderer.setClearColor( 0x050505 );
  337. this.scene = new THREE.Scene();
  338. this.camera = new THREE.PerspectiveCamera( this.cameraDefaults.fov, this.aspectRatio, this.cameraDefaults.near, this.cameraDefaults.far );
  339. this.resetCamera();
  340. this.controls = new THREE.TrackballControls( this.camera, this.renderer.domElement );
  341. var ambientLight = new THREE.AmbientLight( 0x404040 );
  342. var directionalLight1 = new THREE.DirectionalLight( 0xC0C090 );
  343. var directionalLight2 = new THREE.DirectionalLight( 0xC0C090 );
  344. directionalLight1.position.set( -100, -50, 100 );
  345. directionalLight2.position.set( 100, 50, -100 );
  346. this.scene.add( directionalLight1 );
  347. this.scene.add( directionalLight2 );
  348. this.scene.add( ambientLight );
  349. var helper = new THREE.GridHelper( 1200, 60, 0xFF4444, 0x404040 );
  350. this.scene.add( helper );
  351. var geometry = new THREE.BoxBufferGeometry( 10, 10, 10 );
  352. var material = new THREE.MeshNormalMaterial();
  353. this.cube = new THREE.Mesh( geometry, material );
  354. this.cube.position.set( 0, 0, 0 );
  355. this.scene.add( this.cube );
  356. this.pivot = new THREE.Object3D();
  357. this.pivot.name = 'Pivot';
  358. this.scene.add( this.pivot );
  359. };
  360. MeshSprayApp.prototype.initContent = function () {
  361. var maxQueueSize = 1024;
  362. var maxWebWorkers = 4;
  363. var radius = 640;
  364. var workerDirector = new THREE.LoaderSupport.WorkerDirector( MeshSpray );
  365. workerDirector.setLogging( false, false );
  366. workerDirector.setCrossOrigin( 'anonymous' );
  367. var callbackOnLoad = function ( event ) {
  368. console.info( 'Worker #' + event.detail.instanceNo + ': Completed loading. (#' + workerDirector.objectsCompleted + ')' );
  369. };
  370. var reportProgress = function( event ) {
  371. document.getElementById( 'feedback' ).innerHTML = event.detail.text;
  372. console.info( event.detail.text );
  373. };
  374. var callbackMeshAlter = function ( event ) {
  375. var override = new THREE.LoaderSupport.LoadedMeshUserOverride( false, true );
  376. event.detail.side = THREE.DoubleSide;
  377. var mesh = new THREE.Mesh( event.detail.bufferGeometry, event.detail.material );
  378. mesh.name = event.detail.meshName;
  379. override.addMesh( mesh );
  380. return override;
  381. };
  382. var callbacks = new THREE.LoaderSupport.Callbacks();
  383. callbacks.setCallbackOnMeshAlter( callbackMeshAlter );
  384. callbacks.setCallbackOnLoad( callbackOnLoad );
  385. callbacks.setCallbackOnProgress( reportProgress );
  386. workerDirector.prepareWorkers( callbacks, maxQueueSize, maxWebWorkers );
  387. var prepData;
  388. var pivot;
  389. var s, t, r, x, y, z;
  390. var globalObjectCount = 0;
  391. for ( var i = 0; i < maxQueueSize; i++ ) {
  392. prepData = new THREE.LoaderSupport.PrepData( 'Triangles_' + i );
  393. pivot = new THREE.Object3D();
  394. s = 2 * Math.PI * Math.random();
  395. t = Math.PI * Math.random();
  396. r = radius * Math.random();
  397. x = r * Math.cos( s ) * Math.sin( t );
  398. y = r * Math.sin( s ) * Math.sin( t );
  399. z = r * Math.cos( t );
  400. pivot.position.set( x, y, z );
  401. this.scene.add( pivot );
  402. prepData.streamMeshesTo = pivot;
  403. prepData.setLogging( false, false );
  404. prepData.quantity = 8192;
  405. prepData.dimension = Math.max( Math.random() * 500, 100 );
  406. prepData.globalObjectCount = globalObjectCount++;
  407. workerDirector.enqueueForRun( prepData );
  408. }
  409. workerDirector.processQueue();
  410. };
  411. MeshSprayApp.prototype.resizeDisplayGL = function () {
  412. this.controls.handleResize();
  413. this.recalcAspectRatio();
  414. this.renderer.setSize( this.canvas.offsetWidth, this.canvas.offsetHeight, false );
  415. this.updateCamera();
  416. };
  417. MeshSprayApp.prototype.recalcAspectRatio = function () {
  418. this.aspectRatio = ( this.canvas.offsetHeight === 0 ) ? 1 : this.canvas.offsetWidth / this.canvas.offsetHeight;
  419. };
  420. MeshSprayApp.prototype.resetCamera = function () {
  421. this.camera.position.copy( this.cameraDefaults.posCamera );
  422. this.cameraTarget.copy( this.cameraDefaults.posCameraTarget );
  423. this.updateCamera();
  424. };
  425. MeshSprayApp.prototype.updateCamera = function () {
  426. this.camera.aspect = this.aspectRatio;
  427. this.camera.lookAt( this.cameraTarget );
  428. this.camera.updateProjectionMatrix();
  429. };
  430. MeshSprayApp.prototype.render = function () {
  431. if ( ! this.renderer.autoClear ) this.renderer.clear();
  432. this.controls.update();
  433. this.cube.rotation.x += 0.05;
  434. this.cube.rotation.y += 0.05;
  435. this.renderer.render( this.scene, this.camera );
  436. };
  437. return MeshSprayApp;
  438. })();
  439. var app = new MeshSprayApp( document.getElementById( 'example' ) );
  440. // init three.js example application
  441. var resizeWindow = function () {
  442. app.resizeDisplayGL();
  443. };
  444. var render = function () {
  445. requestAnimationFrame( render );
  446. app.render();
  447. };
  448. window.addEventListener( 'resize', resizeWindow, false );
  449. console.log( 'Starting initialisation phase...' );
  450. app.initGL();
  451. app.resizeDisplayGL();
  452. app.initContent();
  453. render();
  454. </script>
  455. </body>
  456. </html>