webgl_loader_obj2_meshspray.html 15 KB

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