3DMLoader.js 31 KB

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