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