webgl_loader_obj2_meshspray.html 17 KB

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