3DMLoader.js 31 KB

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