3DMLoader.js 30 KB

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