3DMLoader.js 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453
  1. import {
  2. BufferGeometryLoader,
  3. FileLoader,
  4. Loader,
  5. Object3D,
  6. MeshStandardMaterial,
  7. Mesh,
  8. Color,
  9. Points,
  10. PointsMaterial,
  11. Line,
  12. LineBasicMaterial,
  13. Matrix4,
  14. DirectionalLight,
  15. PointLight,
  16. SpotLight,
  17. RectAreaLight,
  18. Vector3,
  19. Sprite,
  20. SpriteMaterial,
  21. CanvasTexture,
  22. LinearFilter,
  23. ClampToEdgeWrapping,
  24. TextureLoader
  25. } from '../../../build/three.module.js';
  26. var Rhino3dmLoader = function ( manager ) {
  27. Loader.call( this, manager );
  28. this.libraryPath = '';
  29. this.libraryPending = null;
  30. this.libraryBinary = null;
  31. this.libraryConfig = {};
  32. this.workerLimit = 4;
  33. this.workerPool = [];
  34. this.workerNextTaskID = 1;
  35. this.workerSourceURL = '';
  36. this.workerConfig = {};
  37. this.materials = [];
  38. };
  39. Rhino3dmLoader.taskCache = new WeakMap();
  40. Rhino3dmLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  41. constructor: Rhino3dmLoader,
  42. setLibraryPath: function ( path ) {
  43. this.libraryPath = path;
  44. return this;
  45. },
  46. setWorkerLimit: function ( workerLimit ) {
  47. this.workerLimit = workerLimit;
  48. return this;
  49. },
  50. load: function ( url, onLoad, onProgress, onError ) {
  51. var loader = new FileLoader( this.manager );
  52. loader.setPath( this.path );
  53. loader.setResponseType( 'arraybuffer' );
  54. loader.setRequestHeader( this.requestHeader );
  55. loader.load( url, ( buffer ) => {
  56. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  57. // again from this thread.
  58. if ( Rhino3dmLoader.taskCache.has( buffer ) ) {
  59. var cachedTask = Rhino3dmLoader.taskCache.get( buffer );
  60. return cachedTask.promise.then( onLoad ).catch( onError );
  61. }
  62. this.decodeObjects( buffer, url )
  63. .then( onLoad )
  64. .catch( onError );
  65. }, onProgress, onError );
  66. },
  67. debug: function () {
  68. console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
  69. },
  70. decodeObjects: function ( buffer, url ) {
  71. var worker;
  72. var taskID;
  73. var taskCost = buffer.byteLength;
  74. var objectPending = this._getWorker( taskCost )
  75. .then( ( _worker ) => {
  76. worker = _worker;
  77. taskID = this.workerNextTaskID ++; //hmmm
  78. return new Promise( ( resolve, reject ) => {
  79. worker._callbacks[ taskID ] = { resolve, reject };
  80. worker.postMessage( { type: 'decode', id: taskID, buffer }, [ buffer ] );
  81. //this.debug();
  82. } );
  83. } )
  84. .then( ( message ) => this._createGeometry( message.data ) );
  85. // Remove task from the task list.
  86. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  87. objectPending
  88. .catch( () => true )
  89. .then( () => {
  90. if ( worker && taskID ) {
  91. this._releaseTask( worker, taskID );
  92. //this.debug();
  93. }
  94. } );
  95. // Cache the task result.
  96. Rhino3dmLoader.taskCache.set( buffer, {
  97. url: url,
  98. promise: objectPending
  99. } );
  100. return objectPending;
  101. },
  102. parse: function ( data, onLoad, onError ) {
  103. if ( ! ( data instanceof ArrayBuffer ) ) {
  104. data = this._objToUint( data ).buffer;
  105. }
  106. this.decodeObjects( data, '' )
  107. .then( onLoad )
  108. .catch( onError );
  109. },
  110. // from https://stackoverflow.com/questions/35971566/store-a-json-object-in-arraybuffer/35971686#35971686
  111. _objToUint: function ( obj ) {
  112. var string = btoa( unescape( JSON.stringify( obj ) ) ),
  113. charList = string.split( '' ),
  114. uintArray = [];
  115. for ( var i = 0; i < charList.length; i ++ ) {
  116. uintArray.push( charList[ i ].charCodeAt( 0 ) );
  117. }
  118. return new Uint8Array( uintArray );
  119. },
  120. _compareMaterials: function ( material ) {
  121. var mat = {};
  122. mat.name = material.name;
  123. mat.color = {};
  124. mat.color.r = material.color.r;
  125. mat.color.g = material.color.g;
  126. mat.color.b = material.color.b;
  127. mat.type = material.type;
  128. for ( var i = 0; i < this.materials.length; i ++ ) {
  129. var m = this.materials[ i ];
  130. var _mat = {};
  131. _mat.name = m.name;
  132. _mat.color = {};
  133. _mat.color.r = m.color.r;
  134. _mat.color.g = m.color.g;
  135. _mat.color.b = m.color.b;
  136. _mat.type = m.type;
  137. if ( JSON.stringify( mat ) === JSON.stringify( _mat ) ) {
  138. return m;
  139. }
  140. }
  141. this.materials.push( material );
  142. return material;
  143. },
  144. _createMaterial: function ( material ) {
  145. if ( material === undefined ) {
  146. return new MeshStandardMaterial( {
  147. color: new Color( 1, 1, 1 ),
  148. metalness: 0.8,
  149. name: 'default',
  150. side: 2
  151. } );
  152. }
  153. var _diffuseColor = material.diffuseColor;
  154. var diffusecolor = new Color( _diffuseColor.r / 255.0, _diffuseColor.g / 255.0, _diffuseColor.b / 255.0 );
  155. if ( _diffuseColor.r === 0 && _diffuseColor.g === 0 && _diffuseColor.b === 0 ) {
  156. diffusecolor.r = 1;
  157. diffusecolor.g = 1;
  158. diffusecolor.b = 1;
  159. }
  160. // console.log( material );
  161. var mat = new MeshStandardMaterial( {
  162. color: diffusecolor,
  163. name: material.name,
  164. side: 2,
  165. transparent: material.transparency > 0 ? true : false,
  166. opacity: 1.0 - material.transparency
  167. } );
  168. var textureLoader = new TextureLoader();
  169. for ( var i = 0; i < material.textures.length; i ++ ) {
  170. var texture = material.textures[ i ];
  171. if ( texture.image !== null ) {
  172. var map = textureLoader.load( texture.image );
  173. switch ( texture.type ) {
  174. case 'Diffuse':
  175. mat.map = map;
  176. break;
  177. case 'Bump':
  178. mat.bumpMap = map;
  179. break;
  180. case 'Transparency':
  181. mat.alphaMap = map;
  182. mat.transparent = true;
  183. break;
  184. case 'Emap':
  185. mat.envMap = map;
  186. break;
  187. }
  188. }
  189. }
  190. return mat;
  191. },
  192. _createGeometry: function ( data ) {
  193. // console.log(data);
  194. var object = new Object3D();
  195. var instanceDefinitionObjects = [];
  196. var instanceDefinitions = [];
  197. var instanceReferences = [];
  198. object.userData[ 'layers' ] = data.layers;
  199. object.userData[ 'groups' ] = data.groups;
  200. object.userData[ 'settings' ] = data.settings;
  201. var objects = data.objects;
  202. var materials = data.materials;
  203. for ( var i = 0; i < objects.length; i ++ ) {
  204. var obj = objects[ i ];
  205. var attributes = obj.attributes;
  206. switch ( obj.objectType ) {
  207. case 'InstanceDefinition':
  208. instanceDefinitions.push( obj );
  209. break;
  210. case 'InstanceReference':
  211. instanceReferences.push( obj );
  212. break;
  213. default:
  214. if ( attributes.hasOwnProperty( 'materialUUID' ) ) {
  215. var rMaterial = materials.find( m => m.id === attributes.materialUUID );
  216. var material = this._createMaterial( rMaterial );
  217. material = this._compareMaterials( material );
  218. var _object = this._createObject( obj, material );
  219. } else {
  220. var material = this._createMaterial( );
  221. var _object = this._createObject( obj, material );
  222. }
  223. if ( _object === undefined ) {
  224. continue;
  225. }
  226. var layer = data.layers[ attributes.layerIndex ];
  227. _object.visible = layer ? data.layers[ attributes.layerIndex ].visible : true;
  228. if ( attributes.isInstanceDefinitionObject ) {
  229. instanceDefinitionObjects.push( _object );
  230. } else {
  231. object.add( _object );
  232. }
  233. break;
  234. }
  235. }
  236. for ( var i = 0; i < instanceDefinitions.length; i ++ ) {
  237. var iDef = instanceDefinitions[ i ];
  238. var objects = [];
  239. for ( var j = 0; j < iDef.attributes.objectIds.length; j ++ ) {
  240. var objId = iDef.attributes.objectIds[ j ];
  241. for ( var p = 0; p < instanceDefinitionObjects.length; p ++ ) {
  242. var idoId = instanceDefinitionObjects[ p ].userData.attributes.id;
  243. if ( objId === idoId ) {
  244. objects.push( instanceDefinitionObjects[ p ] );
  245. }
  246. }
  247. }
  248. // Currently clones geometry and does not take advantage of instancing
  249. for ( var j = 0; j < instanceReferences.length; j ++ ) {
  250. var iRef = instanceReferences[ j ];
  251. if ( iRef.geometry.parentIdefId === iDef.attributes.id ) {
  252. var iRefObject = new Object3D();
  253. var xf = iRef.geometry.xform.array;
  254. var matrix = new Matrix4();
  255. matrix.set( xf[ 0 ], xf[ 1 ], xf[ 2 ], xf[ 3 ], xf[ 4 ], xf[ 5 ], xf[ 6 ], xf[ 7 ], xf[ 8 ], xf[ 9 ], xf[ 10 ], xf[ 11 ], xf[ 12 ], xf[ 13 ], xf[ 14 ], xf[ 15 ] );
  256. iRefObject.applyMatrix4( matrix );
  257. for ( var p = 0; p < objects.length; p ++ ) {
  258. iRefObject.add( objects[ p ].clone( true ) );
  259. }
  260. object.add( iRefObject );
  261. }
  262. }
  263. }
  264. this.materials = [];
  265. return object;
  266. },
  267. _createObject: function ( obj, mat ) {
  268. var loader = new BufferGeometryLoader();
  269. var attributes = obj.attributes;
  270. switch ( obj.objectType ) {
  271. case 'Point':
  272. case 'PointSet':
  273. var geometry = loader.parse( obj.geometry );
  274. var _color = attributes.drawColor;
  275. var color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
  276. var material = new PointsMaterial( { color: color, sizeAttenuation: false, size: 2 } );
  277. if ( geometry.attributes.hasOwnProperty( 'color' ) ) {
  278. material.vertexColors = true;
  279. }
  280. material = this._compareMaterials( material );
  281. var points = new Points( geometry, material );
  282. points.userData[ 'attributes' ] = attributes;
  283. points.userData[ 'objectType' ] = obj.objectType;
  284. if ( attributes.name ) {
  285. points.name = attributes.name;
  286. }
  287. return points;
  288. case 'Mesh':
  289. case 'Extrusion':
  290. case 'SubD':
  291. var geometry = loader.parse( obj.geometry );
  292. if ( geometry.attributes.hasOwnProperty( 'color' ) ) {
  293. mat.vertexColors = true;
  294. }
  295. if ( mat === null ) {
  296. mat = this._createMaterial();
  297. mat = this._compareMaterials( mat );
  298. }
  299. var mesh = new Mesh( geometry, mat );
  300. mesh.castShadow = attributes.castsShadows;
  301. mesh.receiveShadow = attributes.receivesShadows;
  302. mesh.userData[ 'attributes' ] = attributes;
  303. mesh.userData[ 'objectType' ] = obj.objectType;
  304. if ( attributes.name ) {
  305. mesh.name = attributes.name;
  306. }
  307. return mesh;
  308. case 'Brep':
  309. var brepObject = new Object3D();
  310. for ( var j = 0; j < obj.geometry.length; j ++ ) {
  311. geometry = loader.parse( obj.geometry[ j ] );
  312. var mesh = new Mesh( geometry, mat );
  313. mesh.castShadow = attributes.castsShadows;
  314. mesh.receiveShadow = attributes.receivesShadows;
  315. brepObject.add( mesh );
  316. }
  317. brepObject.userData[ 'attributes' ] = attributes;
  318. brepObject.userData[ 'objectType' ] = obj.objectType;
  319. if ( attributes.name ) {
  320. brepObject.name = attributes.name;
  321. }
  322. return brepObject;
  323. case 'Curve':
  324. geometry = loader.parse( obj.geometry );
  325. var _color = attributes.drawColor;
  326. var color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
  327. var material = new LineBasicMaterial( { color: color } );
  328. material = this._compareMaterials( material );
  329. var lines = new Line( geometry, material );
  330. lines.userData[ 'attributes' ] = attributes;
  331. lines.userData[ 'objectType' ] = obj.objectType;
  332. if ( attributes.name ) {
  333. lines.name = attributes.name;
  334. }
  335. return lines;
  336. case 'TextDot':
  337. geometry = obj.geometry;
  338. var ctx = document.createElement( 'canvas' ).getContext( '2d' );
  339. var font = `${geometry.fontHeight}px ${geometry.fontFace}`;
  340. ctx.font = font;
  341. var width = ctx.measureText( geometry.text ).width + 10;
  342. var height = geometry.fontHeight + 10;
  343. var r = window.devicePixelRatio;
  344. ctx.canvas.width = width * r;
  345. ctx.canvas.height = height * r;
  346. ctx.canvas.style.width = width + 'px';
  347. ctx.canvas.style.height = height + 'px';
  348. ctx.setTransform( r, 0, 0, r, 0, 0 );
  349. ctx.font = font;
  350. ctx.textBaseline = 'middle';
  351. ctx.textAlign = 'center';
  352. var color = attributes.drawColor;
  353. ctx.fillStyle = `rgba(${color.r},${color.g},${color.b},${color.a})`;
  354. ctx.fillRect( 0, 0, width, height );
  355. ctx.fillStyle = 'white';
  356. ctx.fillText( geometry.text, width / 2, height / 2 );
  357. var texture = new CanvasTexture( ctx.canvas );
  358. texture.minFilter = LinearFilter;
  359. texture.wrapS = ClampToEdgeWrapping;
  360. texture.wrapT = ClampToEdgeWrapping;
  361. var material = new SpriteMaterial( { map: texture, depthTest: false } );
  362. var sprite = new Sprite( material );
  363. sprite.position.set( geometry.point[ 0 ], geometry.point[ 1 ], geometry.point[ 2 ] );
  364. sprite.scale.set( width / 10, height / 10, 1.0 );
  365. sprite.userData[ 'attributes' ] = attributes;
  366. sprite.userData[ 'objectType' ] = obj.objectType;
  367. if ( attributes.name ) {
  368. sprite.name = attributes.name;
  369. }
  370. return sprite;
  371. case 'Light':
  372. geometry = obj.geometry;
  373. var light;
  374. if ( geometry.isDirectionalLight ) {
  375. light = new DirectionalLight();
  376. light.castShadow = attributes.castsShadows;
  377. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  378. light.target.position.set( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] );
  379. light.shadow.normalBias = 0.1;
  380. } else if ( geometry.isPointLight ) {
  381. light = new PointLight();
  382. light.castShadow = attributes.castsShadows;
  383. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  384. light.shadow.normalBias = 0.1;
  385. } else if ( geometry.isRectangularLight ) {
  386. light = new RectAreaLight();
  387. var width = Math.abs( geometry.width[ 2 ] );
  388. var height = Math.abs( geometry.length[ 0 ] );
  389. light.position.set( geometry.location[ 0 ] - ( height / 2 ), geometry.location[ 1 ], geometry.location[ 2 ] - ( width / 2 ) );
  390. light.height = height;
  391. light.width = width;
  392. light.lookAt( new Vector3( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] ) );
  393. } else if ( geometry.isSpotLight ) {
  394. light = new SpotLight();
  395. light.castShadow = attributes.castsShadows;
  396. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  397. light.target.position.set( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] );
  398. light.angle = geometry.spotAngleRadians;
  399. light.shadow.normalBias = 0.1;
  400. } else if ( geometry.isLinearLight ) {
  401. console.warn( 'THREE.3DMLoader: No conversion exists for linear lights.' );
  402. return;
  403. }
  404. if ( light ) {
  405. light.intensity = geometry.intensity;
  406. var _color = geometry.diffuse;
  407. var color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
  408. light.color = color;
  409. light.userData[ 'attributes' ] = attributes;
  410. light.userData[ 'objectType' ] = obj.objectType;
  411. }
  412. return light;
  413. }
  414. },
  415. _initLibrary: function () {
  416. if ( ! this.libraryPending ) {
  417. // Load rhino3dm wrapper.
  418. var jsLoader = new FileLoader( this.manager );
  419. jsLoader.setPath( this.libraryPath );
  420. var jsContent = new Promise( ( resolve, reject ) => {
  421. jsLoader.load( 'rhino3dm.js', resolve, undefined, reject );
  422. } );
  423. // Load rhino3dm WASM binary.
  424. var binaryLoader = new FileLoader( this.manager );
  425. binaryLoader.setPath( this.libraryPath );
  426. binaryLoader.setResponseType( 'arraybuffer' );
  427. var binaryContent = new Promise( ( resolve, reject ) => {
  428. binaryLoader.load( 'rhino3dm.wasm', resolve, undefined, reject );
  429. } );
  430. this.libraryPending = Promise.all( [ jsContent, binaryContent ] )
  431. .then( ( [ jsContent, binaryContent ] ) => {
  432. //this.libraryBinary = binaryContent;
  433. this.libraryConfig.wasmBinary = binaryContent;
  434. var fn = Rhino3dmLoader.Rhino3dmWorker.toString();
  435. var body = [
  436. '/* rhino3dm.js */',
  437. jsContent,
  438. '/* worker */',
  439. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  440. ].join( '\n' );
  441. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  442. } );
  443. }
  444. return this.libraryPending;
  445. },
  446. _getWorker: function ( taskCost ) {
  447. return this._initLibrary().then( () => {
  448. if ( this.workerPool.length < this.workerLimit ) {
  449. var worker = new Worker( this.workerSourceURL );
  450. worker._callbacks = {};
  451. worker._taskCosts = {};
  452. worker._taskLoad = 0;
  453. worker.postMessage( {
  454. type: 'init',
  455. libraryConfig: this.libraryConfig
  456. } );
  457. worker.onmessage = function ( e ) {
  458. var message = e.data;
  459. switch ( message.type ) {
  460. case 'decode':
  461. worker._callbacks[ message.id ].resolve( message );
  462. break;
  463. case 'error':
  464. worker._callbacks[ message.id ].reject( message );
  465. break;
  466. default:
  467. console.error( 'THREE.Rhino3dmLoader: Unexpected message, "' + message.type + '"' );
  468. }
  469. };
  470. this.workerPool.push( worker );
  471. } else {
  472. this.workerPool.sort( function ( a, b ) {
  473. return a._taskLoad > b._taskLoad ? - 1 : 1;
  474. } );
  475. }
  476. var worker = this.workerPool[ this.workerPool.length - 1 ];
  477. worker._taskLoad += taskCost;
  478. return worker;
  479. } );
  480. },
  481. _releaseTask: function ( worker, taskID ) {
  482. worker._taskLoad -= worker._taskCosts[ taskID ];
  483. delete worker._callbacks[ taskID ];
  484. delete worker._taskCosts[ taskID ];
  485. },
  486. dispose: function () {
  487. for ( var i = 0; i < this.workerPool.length; ++ i ) {
  488. this.workerPool[ i ].terminate();
  489. }
  490. this.workerPool.length = 0;
  491. return this;
  492. }
  493. } );
  494. /* WEB WORKER */
  495. Rhino3dmLoader.Rhino3dmWorker = function () {
  496. var libraryPending;
  497. var libraryConfig;
  498. var rhino;
  499. onmessage = function ( e ) {
  500. var message = e.data;
  501. switch ( message.type ) {
  502. case 'init':
  503. libraryConfig = message.libraryConfig;
  504. var wasmBinary = libraryConfig.wasmBinary;
  505. var RhinoModule;
  506. libraryPending = new Promise( function ( resolve ) {
  507. /* Like Basis Loader */
  508. RhinoModule = { wasmBinary, onRuntimeInitialized: resolve };
  509. rhino3dm( RhinoModule ); // eslint-disable-line no-undef
  510. } ).then( () => {
  511. rhino = RhinoModule;
  512. } );
  513. break;
  514. case 'decode':
  515. var buffer = message.buffer;
  516. libraryPending.then( () => {
  517. var data = decodeObjects( rhino, buffer );
  518. self.postMessage( { type: 'decode', id: message.id, data } );
  519. } );
  520. break;
  521. }
  522. };
  523. // from https://stackoverflow.com/questions/35971566/store-a-json-object-in-arraybuffer/35971686#35971686
  524. function uintToObj( uintArray ) {
  525. var encodedString = String.fromCharCode.apply( null, uintArray ),
  526. decodedString = decodeURIComponent( escape( atob( encodedString ) ) );
  527. return JSON.parse( decodedString );
  528. }
  529. function decodeObjects( rhino, buffer ) {
  530. var arr = new Uint8Array( buffer );
  531. var doc = rhino.File3dm.fromByteArray( arr );
  532. var objects = [];
  533. var materials = [];
  534. var layers = [];
  535. var views = [];
  536. var namedViews = [];
  537. var groups = [];
  538. //Handle objects
  539. if ( doc === null ) {
  540. doc = new rhino.File3dm();
  541. var obj = uintToObj( arr );
  542. var rObj = rhino.CommonObject.decode( obj );
  543. doc.objects().add( rObj, null );
  544. }
  545. var objs = doc.objects();
  546. var cnt = objs.count;
  547. for ( var i = 0; i < cnt; i ++ ) {
  548. var _object = objs.get( i );
  549. var object = extractObjectData( _object, doc );
  550. _object.delete();
  551. if ( object !== undefined ) {
  552. if ( object.attributes.materialIndex >= 0 ) {
  553. var mId = doc.materials().findIndex( object.attributes.materialIndex ).id;
  554. object.attributes.materialUUID = mId;
  555. }
  556. objects.push( object );
  557. }
  558. }
  559. // Handle instance definitions
  560. // console.log( `Instance Definitions Count: ${doc.instanceDefinitions().count()}` );
  561. for ( var i = 0; i < doc.instanceDefinitions().count(); i ++ ) {
  562. var idef = doc.instanceDefinitions().get( i );
  563. var idefAttributes = extractProperties( idef );
  564. idefAttributes.objectIds = idef.getObjectIds();
  565. objects.push( { geometry: null, attributes: idefAttributes, objectType: 'InstanceDefinition' } );
  566. }
  567. // Handle materials
  568. var textureTypes = [
  569. // rhino.TextureType.Bitmap,
  570. rhino.TextureType.Diffuse,
  571. rhino.TextureType.Bump,
  572. rhino.TextureType.Transparency,
  573. rhino.TextureType.Opacity,
  574. rhino.TextureType.Emap
  575. ];
  576. var pbrTextureTypes = [
  577. rhino.TextureType.PBR_BaseColor,
  578. rhino.TextureType.PBR_Subsurface,
  579. rhino.TextureType.PBR_SubsurfaceScattering,
  580. rhino.TextureType.PBR_SubsurfaceScatteringRadius,
  581. rhino.TextureType.PBR_Metallic,
  582. rhino.TextureType.PBR_Specular,
  583. rhino.TextureType.PBR_SpecularTint,
  584. rhino.TextureType.PBR_Roughness,
  585. rhino.TextureType.PBR_Anisotropic,
  586. rhino.TextureType.PBR_Anisotropic_Rotation,
  587. rhino.TextureType.PBR_Sheen,
  588. rhino.TextureType.PBR_SheenTint,
  589. rhino.TextureType.PBR_Clearcoat,
  590. rhino.TextureType.PBR_ClearcoatBump,
  591. rhino.TextureType.PBR_ClearcoatRoughness,
  592. rhino.TextureType.PBR_OpacityIor,
  593. rhino.TextureType.PBR_OpacityRoughness,
  594. rhino.TextureType.PBR_Emission,
  595. rhino.TextureType.PBR_AmbientOcclusion,
  596. rhino.TextureType.PBR_Displacement
  597. ];
  598. for ( var i = 0; i < doc.materials().count(); i ++ ) {
  599. var _material = doc.materials().get( i );
  600. var _pbrMaterial = _material.physicallyBased();
  601. var material = extractProperties( _material );
  602. var textures = [];
  603. for ( var j = 0; j < textureTypes.length; j ++ ) {
  604. var _texture = _material.getTexture( textureTypes[ j ] );
  605. if ( _texture ) {
  606. var textureType = textureTypes[ j ].constructor.name;
  607. textureType = textureType.substring( 12, textureType.length );
  608. var texture = { type: textureType };
  609. var image = doc.getEmbeddedFileAsBase64( _texture.fileName );
  610. if ( image ) {
  611. texture.image = 'data:image/png;base64,' + image;
  612. } else {
  613. console.warn( `THREE.3DMLoader: Image for ${textureType} texture not embedded in file.` );
  614. texture.image = null;
  615. }
  616. textures.push( texture );
  617. _texture.delete();
  618. }
  619. }
  620. material.textures = textures;
  621. if ( _pbrMaterial.supported ) {
  622. console.log( 'pbr true' );
  623. for ( var j = 0; j < pbrTextureTypes.length; j ++ ) {
  624. var _texture = _material.getTexture( textureTypes[ j ] );
  625. if ( _texture ) {
  626. var image = doc.getEmbeddedFileAsBase64( _texture.fileName );
  627. var textureType = textureTypes[ j ].constructor.name;
  628. textureType = textureType.substring( 12, textureType.length );
  629. var texture = { type: textureType, image: 'data:image/png;base64,' + image };
  630. textures.push( texture );
  631. _texture.delete();
  632. }
  633. }
  634. var pbMaterialProperties = extractProperties( _material.physicallyBased() );
  635. material = Object.assign( pbMaterialProperties, material );
  636. }
  637. materials.push( material );
  638. _material.delete();
  639. _pbrMaterial.delete();
  640. }
  641. // Handle layers
  642. for ( var i = 0; i < doc.layers().count(); i ++ ) {
  643. var _layer = doc.layers().get( i );
  644. var layer = extractProperties( _layer );
  645. layers.push( layer );
  646. _layer.delete();
  647. }
  648. // Handle views
  649. for ( var i = 0; i < doc.views().count(); i ++ ) {
  650. var _view = doc.views().get( i );
  651. var view = extractProperties( _view );
  652. views.push( view );
  653. _view.delete();
  654. }
  655. // Handle named views
  656. for ( var i = 0; i < doc.namedViews().count(); i ++ ) {
  657. var _namedView = doc.namedViews().get( i );
  658. var namedView = extractProperties( _namedView );
  659. namedViews.push( namedView );
  660. _namedView.delete();
  661. }
  662. // Handle groups
  663. for ( var i = 0; i < doc.groups().count(); i ++ ) {
  664. var _group = doc.groups().get( i );
  665. var group = extractProperties( _group );
  666. groups.push( group );
  667. _group.delete();
  668. }
  669. // Handle settings
  670. var settings = extractProperties( doc.settings() );
  671. //TODO: Handle other document stuff like dimstyles, instance definitions, bitmaps etc.
  672. // Handle dimstyles
  673. // console.log( `Dimstyle Count: ${doc.dimstyles().count()}` );
  674. // Handle bitmaps
  675. // console.log( `Bitmap Count: ${doc.bitmaps().count()}` );
  676. // Handle strings -- this seems to be broken at the moment in rhino3dm
  677. // console.log( `Document Strings Count: ${doc.strings().count()}` );
  678. /*
  679. for( var i = 0; i < doc.strings().count(); i++ ){
  680. var _string= doc.strings().get( i );
  681. console.log(_string);
  682. var string = extractProperties( _group );
  683. strings.push( string );
  684. _string.delete();
  685. }
  686. */
  687. doc.delete();
  688. return { objects, materials, layers, views, namedViews, groups, settings };
  689. }
  690. function extractObjectData( object, doc ) {
  691. var _geometry = object.geometry();
  692. var _attributes = object.attributes();
  693. var objectType = _geometry.objectType;
  694. var geometry = null;
  695. var attributes = null;
  696. // skip instance definition objects
  697. //if( _attributes.isInstanceDefinitionObject ) { continue; }
  698. // TODO: handle other geometry types
  699. switch ( objectType ) {
  700. case rhino.ObjectType.Curve:
  701. var pts = curveToPoints( _geometry, 100 );
  702. var position = {};
  703. var attributes = {};
  704. var data = {};
  705. position.itemSize = 3;
  706. position.type = 'Float32Array';
  707. position.array = [];
  708. for ( var j = 0; j < pts.length; j ++ ) {
  709. position.array.push( pts[ j ][ 0 ] );
  710. position.array.push( pts[ j ][ 1 ] );
  711. position.array.push( pts[ j ][ 2 ] );
  712. }
  713. attributes.position = position;
  714. data.attributes = attributes;
  715. geometry = { data };
  716. break;
  717. case rhino.ObjectType.Point:
  718. var pt = _geometry.location;
  719. var position = {};
  720. var color = {};
  721. var attributes = {};
  722. var data = {};
  723. position.itemSize = 3;
  724. position.type = 'Float32Array';
  725. position.array = [ pt[ 0 ], pt[ 1 ], pt[ 2 ] ];
  726. var _color = _attributes.drawColor( doc );
  727. color.itemSize = 3;
  728. color.type = 'Float32Array';
  729. color.array = [ _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 ];
  730. attributes.position = position;
  731. attributes.color = color;
  732. data.attributes = attributes;
  733. geometry = { data };
  734. break;
  735. case rhino.ObjectType.PointSet:
  736. case rhino.ObjectType.Mesh:
  737. geometry = _geometry.toThreejsJSON();
  738. break;
  739. case rhino.ObjectType.Brep:
  740. var faces = _geometry.faces();
  741. geometry = [];
  742. for ( var faceIndex = 0; faceIndex < faces.count; faceIndex ++ ) {
  743. var face = faces.get( faceIndex );
  744. var mesh = face.getMesh( rhino.MeshType.Any );
  745. if ( mesh ) {
  746. geometry.push( mesh.toThreejsJSON() );
  747. mesh.delete();
  748. }
  749. face.delete();
  750. }
  751. faces.delete();
  752. break;
  753. case rhino.ObjectType.Extrusion:
  754. var mesh = _geometry.getMesh( rhino.MeshType.Any );
  755. if ( mesh ) {
  756. geometry = mesh.toThreejsJSON();
  757. mesh.delete();
  758. }
  759. break;
  760. case rhino.ObjectType.TextDot:
  761. geometry = extractProperties( _geometry );
  762. break;
  763. case rhino.ObjectType.Light:
  764. geometry = extractProperties( _geometry );
  765. break;
  766. case rhino.ObjectType.InstanceReference:
  767. geometry = extractProperties( _geometry );
  768. geometry.xform = extractProperties( _geometry.xform );
  769. geometry.xform.array = _geometry.xform.toFloatArray( true );
  770. break;
  771. case rhino.ObjectType.SubD:
  772. // TODO: precalculate resulting vertices and faces and warn on excessive results
  773. _geometry.subdivide( 3 );
  774. var mesh = rhino.Mesh.createFromSubDControlNet( _geometry );
  775. if ( mesh ) {
  776. geometry = mesh.toThreejsJSON();
  777. mesh.delete();
  778. }
  779. break;
  780. /*
  781. case rhino.ObjectType.Annotation:
  782. case rhino.ObjectType.Hatch:
  783. case rhino.ObjectType.ClipPlane:
  784. */
  785. default:
  786. console.warn( `THREE.3DMLoader: TODO: Implement ${objectType.constructor.name}` );
  787. break;
  788. }
  789. if ( Array.isArray( geometry ) === false || geometry.length > 0 ) {
  790. var attributes = extractProperties( _attributes );
  791. attributes.geometry = extractProperties( _geometry );
  792. if ( _attributes.groupCount > 0 ) {
  793. attributes.groupIds = _attributes.getGroupList();
  794. }
  795. if ( _attributes.userStringCount > 0 ) {
  796. attributes.userStrings = _attributes.getUserStrings();
  797. }
  798. attributes.drawColor = _attributes.drawColor( doc );
  799. objectType = objectType.constructor.name;
  800. objectType = objectType.substring( 11, objectType.length );
  801. attributes.geometry.objectType = objectType;
  802. return { geometry, attributes, objectType };
  803. } else {
  804. console.warn( 'THREE.3DMLoader: Object has no mesh geometry. Consider opening this in Rhino, using a shaded display mode, and exporting again.' );
  805. }
  806. }
  807. function extractProperties( object ) {
  808. var result = {};
  809. for ( var property in object ) {
  810. if ( typeof object[ property ] !== 'function' ) {
  811. result[ property ] = object[ property ];
  812. } else {
  813. // console.log( `${property}: ${object[ property ]}` );
  814. }
  815. }
  816. return result;
  817. }
  818. function curveToPoints( curve, pointLimit ) {
  819. var pointCount = pointLimit;
  820. var rc = [];
  821. var ts = [];
  822. if ( curve instanceof rhino.LineCurve ) {
  823. return [ curve.pointAtStart, curve.pointAtEnd ];
  824. }
  825. if ( curve instanceof rhino.PolylineCurve ) {
  826. pointCount = curve.pointCount;
  827. for ( var i = 0; i < pointCount; i ++ ) {
  828. rc.push( curve.point( i ) );
  829. }
  830. return rc;
  831. }
  832. if ( curve instanceof rhino.PolyCurve ) {
  833. var segmentCount = curve.segmentCount;
  834. for ( var i = 0; i < segmentCount; i ++ ) {
  835. var segment = curve.segmentCurve( i );
  836. var segmentArray = curveToPoints( segment, pointCount );
  837. rc = rc.concat( segmentArray );
  838. segment.delete();
  839. }
  840. return rc;
  841. }
  842. if ( curve instanceof rhino.ArcCurve ) {
  843. pointCount = Math.floor( curve.angleDegrees / 5 );
  844. pointCount = pointCount < 2 ? 2 : pointCount;
  845. // alternative to this hardcoded version: https://stackoverflow.com/a/18499923/2179399
  846. }
  847. if ( curve instanceof rhino.NurbsCurve && curve.degree === 1 ) {
  848. if ( curve.segmentCount === undefined || curve.segmentCount === 1 ) {
  849. return [ curve.pointAtStart, curve.pointAtEnd ];
  850. }
  851. }
  852. var domain = curve.domain;
  853. var divisions = pointCount - 1.0;
  854. for ( var j = 0; j < pointCount; j ++ ) {
  855. var t = domain[ 0 ] + ( j / divisions ) * ( domain[ 1 ] - domain[ 0 ] );
  856. if ( t === domain[ 0 ] || t === domain[ 1 ] ) {
  857. ts.push( t );
  858. continue;
  859. }
  860. var tan = curve.tangentAt( t );
  861. var prevTan = curve.tangentAt( ts.slice( - 1 )[ 0 ] );
  862. // Duplicaated from THREE.Vector3
  863. // How to pass imports to worker?
  864. var tS = tan[ 0 ] * tan[ 0 ] + tan[ 1 ] * tan[ 1 ] + tan[ 2 ] * tan[ 2 ];
  865. var ptS = prevTan[ 0 ] * prevTan[ 0 ] + prevTan[ 1 ] * prevTan[ 1 ] + prevTan[ 2 ] * prevTan[ 2 ];
  866. var denominator = Math.sqrt( tS * ptS );
  867. var angle;
  868. if ( denominator === 0 ) {
  869. angle = Math.PI / 2;
  870. } else {
  871. var theta = ( tan.x * prevTan.x + tan.y * prevTan.y + tan.z * prevTan.z ) / denominator;
  872. angle = Math.acos( Math.max( - 1, Math.min( 1, theta ) ) );
  873. }
  874. if ( angle < 0.1 ) continue;
  875. ts.push( t );
  876. }
  877. rc = ts.map( t => curve.pointAt( t ) );
  878. return rc;
  879. }
  880. };
  881. export { Rhino3dmLoader };