3DMLoader.js 29 KB

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