3DMLoader.js 29 KB

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