webgl_loader_obj2_meshspray.html 17 KB

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