3DMLoader.js 30 KB

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