webgl_loader_obj2_meshspray.html 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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.callbackMeshBuilder = null;
  195. this.callbackProgress = null;
  196. this.serializedMaterials = null;
  197. this.logging = {
  198. enabled: true,
  199. debug: false
  200. };
  201. };
  202. MeshSpray.Parser.prototype = {
  203. constructor: MeshSpray.Parser,
  204. setLogging: function ( enabled, debug ) {
  205. this.logging.enabled = enabled === true;
  206. this.logging.debug = debug === true;
  207. },
  208. parse: function () {
  209. var baseTriangle = [ 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 0.0, -1.0, 1.0 ];
  210. var vertices = [];
  211. var colors = [];
  212. var normals = [];
  213. var uvs = [];
  214. var dimensionHalf = this.dimension / 2;
  215. var fixedOffsetX;
  216. var fixedOffsetY;
  217. var fixedOffsetZ;
  218. var s, t;
  219. // complete triangle
  220. var sizeVaring = this.sizeFactor * Math.random();
  221. // local coords offset
  222. var localOffsetFactor = this.localOffsetFactor;
  223. for ( var i = 0; i < this.quantity; i++ ) {
  224. sizeVaring = this.sizeFactor * Math.random();
  225. s = 2 * Math.PI * Math.random();
  226. t = Math.PI * Math.random();
  227. fixedOffsetX = dimensionHalf * Math.random() * Math.cos( s ) * Math.sin( t );
  228. fixedOffsetY = dimensionHalf * Math.random() * Math.sin( s ) * Math.sin( t );
  229. fixedOffsetZ = dimensionHalf * Math.random() * Math.cos( t );
  230. for ( var j = 0; j < baseTriangle.length; j += 3 ) {
  231. vertices.push( baseTriangle[ j ] * sizeVaring + localOffsetFactor * Math.random() + fixedOffsetX );
  232. vertices.push( baseTriangle[ j + 1 ] * sizeVaring + localOffsetFactor * Math.random() + fixedOffsetY );
  233. vertices.push( baseTriangle[ j + 2 ] * sizeVaring + localOffsetFactor * Math.random() + fixedOffsetZ );
  234. colors.push( Math.random() );
  235. colors.push( Math.random() );
  236. colors.push( Math.random() );
  237. }
  238. }
  239. var absoluteVertexCount = vertices.length;
  240. var absoluteColorCount = colors.length;
  241. var absoluteNormalCount = 0;
  242. var absoluteUvCount = 0;
  243. var vertexFA = new Float32Array( absoluteVertexCount );
  244. var colorFA = ( absoluteColorCount > 0 ) ? new Float32Array( absoluteColorCount ) : null;
  245. var normalFA = ( absoluteNormalCount > 0 ) ? new Float32Array( absoluteNormalCount ) : null;
  246. var uvFA = ( absoluteUvCount > 0 ) ? new Float32Array( absoluteUvCount ) : null;
  247. vertexFA.set( vertices, 0 );
  248. if ( colorFA ) {
  249. colorFA.set( colors, 0 );
  250. }
  251. if ( normalFA ) {
  252. normalFA.set( normals, 0 );
  253. }
  254. if ( uvFA ) {
  255. uvFA.set( uvs, 0 );
  256. }
  257. /*
  258. * This demonstrates the usage of embedded three.js in the worker blob and
  259. * the serialization of materials back to the Builder outside the worker.
  260. *
  261. * This is not the most effective way, but outlining possibilities
  262. */
  263. var materialName = 'defaultVertexColorMaterial_double';
  264. var defaultVertexColorMaterialJson = this.serializedMaterials[ 'defaultVertexColorMaterial' ];
  265. var loader = new THREE.MaterialLoader();
  266. var defaultVertexColorMaterialDouble = loader.parse( defaultVertexColorMaterialJson );
  267. defaultVertexColorMaterialDouble.name = materialName;
  268. defaultVertexColorMaterialDouble.side = THREE.DoubleSide;
  269. var newSerializedMaterials = {};
  270. newSerializedMaterials[ materialName ] = defaultVertexColorMaterialDouble.toJSON();
  271. var payload = {
  272. cmd: 'materialData',
  273. materials: {
  274. serializedMaterials: newSerializedMaterials
  275. }
  276. };
  277. this.callbackMeshBuilder( payload );
  278. this.globalObjectCount++;
  279. this.callbackMeshBuilder(
  280. {
  281. cmd: 'meshData',
  282. progress: {
  283. numericalValue: 1.0
  284. },
  285. params: {
  286. meshName: 'Gen' + this.globalObjectCount
  287. },
  288. materials: {
  289. multiMaterial: false,
  290. materialNames: [ materialName ],
  291. materialGroups: []
  292. },
  293. buffers: {
  294. vertices: vertexFA,
  295. colors: colorFA,
  296. normals: normalFA,
  297. uvs: uvFA
  298. }
  299. },
  300. [ vertexFA.buffer ],
  301. colorFA !== null ? [ colorFA.buffer ] : null,
  302. normalFA !== null ? [ normalFA.buffer ] : null,
  303. uvFA !== null ? [ uvFA.buffer ] : null
  304. );
  305. if ( this.logging.enabled ) console.info( 'Global output object count: ' + this.globalObjectCount );
  306. },
  307. setSerializedMaterials: function ( serializedMaterials ) {
  308. if ( THREE.LoaderSupport.Validator.isValid( serializedMaterials ) ) {
  309. this.serializedMaterials = serializedMaterials;
  310. }
  311. }
  312. };
  313. var MeshSprayApp = function ( elementToBindTo ) {
  314. this.renderer = null;
  315. this.canvas = elementToBindTo;
  316. this.aspectRatio = 1;
  317. this.recalcAspectRatio();
  318. this.scene = null;
  319. this.cameraDefaults = {
  320. posCamera: new THREE.Vector3( 500.0, 500.0, 1000.0 ),
  321. posCameraTarget: new THREE.Vector3( 0, 0, 0 ),
  322. near: 0.1,
  323. far: 10000,
  324. fov: 45
  325. };
  326. this.camera = null;
  327. this.cameraTarget = this.cameraDefaults.posCameraTarget;
  328. this.controls = null;
  329. this.cube = null;
  330. this.pivot = null;
  331. };
  332. MeshSprayApp.prototype = {
  333. constructor: MeshSprayApp,
  334. initGL: function () {
  335. this.renderer = new THREE.WebGLRenderer( {
  336. canvas: this.canvas,
  337. antialias: true,
  338. autoClear: true
  339. } );
  340. this.renderer.setClearColor( 0x050505 );
  341. this.scene = new THREE.Scene();
  342. this.camera = new THREE.PerspectiveCamera( this.cameraDefaults.fov, this.aspectRatio, this.cameraDefaults.near, this.cameraDefaults.far );
  343. this.resetCamera();
  344. this.controls = new THREE.TrackballControls( this.camera, this.renderer.domElement );
  345. var ambientLight = new THREE.AmbientLight( 0x404040 );
  346. var directionalLight1 = new THREE.DirectionalLight( 0xC0C090 );
  347. var directionalLight2 = new THREE.DirectionalLight( 0xC0C090 );
  348. directionalLight1.position.set( -100, -50, 100 );
  349. directionalLight2.position.set( 100, 50, -100 );
  350. this.scene.add( directionalLight1 );
  351. this.scene.add( directionalLight2 );
  352. this.scene.add( ambientLight );
  353. var helper = new THREE.GridHelper( 1200, 60, 0xFF4444, 0x404040 );
  354. this.scene.add( helper );
  355. var geometry = new THREE.BoxBufferGeometry( 10, 10, 10 );
  356. var material = new THREE.MeshNormalMaterial();
  357. this.cube = new THREE.Mesh( geometry, material );
  358. this.cube.position.set( 0, 0, 0 );
  359. this.scene.add( this.cube );
  360. this.pivot = new THREE.Object3D();
  361. this.pivot.name = 'Pivot';
  362. this.scene.add( this.pivot );
  363. },
  364. initContent: function () {
  365. var maxQueueSize = 1024;
  366. var maxWebWorkers = 4;
  367. var radius = 640;
  368. var workerDirector = new THREE.LoaderSupport.WorkerDirector( MeshSpray.Loader );
  369. workerDirector.setLogging( false, false );
  370. workerDirector.setCrossOrigin( 'anonymous' );
  371. var callbackOnLoad = function ( event ) {
  372. console.info( 'Worker #' + event.detail.instanceNo + ': Completed loading. (#' + workerDirector.objectsCompleted + ')' );
  373. };
  374. var reportProgress = function( event ) {
  375. document.getElementById( 'feedback' ).innerHTML = event.detail.text;
  376. console.info( event.detail.text );
  377. };
  378. var callbackMeshAlter = function ( event ) {
  379. var override = new THREE.LoaderSupport.LoadedMeshUserOverride( false, true );
  380. event.detail.side = THREE.DoubleSide;
  381. var mesh = new THREE.Mesh( event.detail.bufferGeometry, event.detail.material );
  382. mesh.name = event.detail.meshName;
  383. override.addMesh( mesh );
  384. return override;
  385. };
  386. var callbacks = new THREE.LoaderSupport.Callbacks();
  387. callbacks.setCallbackOnMeshAlter( callbackMeshAlter );
  388. callbacks.setCallbackOnLoad( callbackOnLoad );
  389. callbacks.setCallbackOnProgress( reportProgress );
  390. workerDirector.prepareWorkers( callbacks, maxQueueSize, maxWebWorkers );
  391. var prepData;
  392. var pivot;
  393. var s, t, r, x, y, z;
  394. var globalObjectCount = 0;
  395. for ( var i = 0; i < maxQueueSize; i++ ) {
  396. prepData = new THREE.LoaderSupport.PrepData( 'Triangles_' + i );
  397. pivot = new THREE.Object3D();
  398. s = 2 * Math.PI * Math.random();
  399. t = Math.PI * Math.random();
  400. r = radius * Math.random();
  401. x = r * Math.cos( s ) * Math.sin( t );
  402. y = r * Math.sin( s ) * Math.sin( t );
  403. z = r * Math.cos( t );
  404. pivot.position.set( x, y, z );
  405. this.scene.add( pivot );
  406. prepData.streamMeshesTo = pivot;
  407. prepData.setLogging( false, false );
  408. prepData.quantity = 8192;
  409. prepData.dimension = Math.max( Math.random() * 500, 100 );
  410. prepData.globalObjectCount = globalObjectCount++;
  411. workerDirector.enqueueForRun( prepData );
  412. }
  413. workerDirector.processQueue();
  414. },
  415. resizeDisplayGL: function () {
  416. this.controls.handleResize();
  417. this.recalcAspectRatio();
  418. this.renderer.setSize( this.canvas.offsetWidth, this.canvas.offsetHeight, false );
  419. this.updateCamera();
  420. },
  421. recalcAspectRatio: function () {
  422. this.aspectRatio = ( this.canvas.offsetHeight === 0 ) ? 1 : this.canvas.offsetWidth / this.canvas.offsetHeight;
  423. },
  424. resetCamera: function () {
  425. this.camera.position.copy( this.cameraDefaults.posCamera );
  426. this.cameraTarget.copy( this.cameraDefaults.posCameraTarget );
  427. this.updateCamera();
  428. },
  429. updateCamera: function () {
  430. this.camera.aspect = this.aspectRatio;
  431. this.camera.lookAt( this.cameraTarget );
  432. this.camera.updateProjectionMatrix();
  433. },
  434. render: function () {
  435. if ( ! this.renderer.autoClear ) this.renderer.clear();
  436. this.controls.update();
  437. this.cube.rotation.x += 0.05;
  438. this.cube.rotation.y += 0.05;
  439. this.renderer.render( this.scene, this.camera );
  440. }
  441. };
  442. var app = new MeshSprayApp( document.getElementById( 'example' ) );
  443. // init three.js example application
  444. var resizeWindow = function () {
  445. app.resizeDisplayGL();
  446. };
  447. var render = function () {
  448. requestAnimationFrame( render );
  449. app.render();
  450. };
  451. window.addEventListener( 'resize', resizeWindow, false );
  452. console.log( 'Starting initialisation phase...' );
  453. app.initGL();
  454. app.resizeDisplayGL();
  455. app.initContent();
  456. render();
  457. </script>
  458. </body>
  459. </html>