3DMLoader.js 27 KB

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