3DMLoader.js 31 KB

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