3DMLoader.js 29 KB

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