3DMLoader.js 29 KB

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