AMFLoader.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. import {
  2. BufferGeometry,
  3. Color,
  4. FileLoader,
  5. Float32BufferAttribute,
  6. Group,
  7. Loader,
  8. Mesh,
  9. MeshPhongMaterial
  10. } from 'three';
  11. import * as fflate from '../libs/fflate.module.js';
  12. /**
  13. * A loader for the AMF format.
  14. *
  15. * The loader supports materials, color and ZIP compressed files.
  16. * No constellation support (yet).
  17. *
  18. * ```js
  19. * const loader = new AMFLoader();
  20. *
  21. * const object = await loader.loadAsync( './models/amf/rook.amf' );
  22. * scene.add( object );
  23. * ```
  24. *
  25. * @augments Loader
  26. * @three_import import { AMFLoader } from 'three/addons/loaders/AMFLoader.js';
  27. */
  28. class AMFLoader extends Loader {
  29. /**
  30. * Constructs a new AMF loader.
  31. *
  32. * @param {LoadingManager} [manager] - The loading manager.
  33. */
  34. constructor( manager ) {
  35. super( manager );
  36. }
  37. /**
  38. * Starts loading from the given URL and passes the loaded AMF asset
  39. * to the `onLoad()` callback.
  40. *
  41. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  42. * @param {function(Group)} onLoad - Executed when the loading process has been finished.
  43. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  44. * @param {onErrorCallback} onError - Executed when errors occur.
  45. */
  46. load( url, onLoad, onProgress, onError ) {
  47. const scope = this;
  48. const loader = new FileLoader( scope.manager );
  49. loader.setPath( scope.path );
  50. loader.setResponseType( 'arraybuffer' );
  51. loader.setRequestHeader( scope.requestHeader );
  52. loader.setWithCredentials( scope.withCredentials );
  53. loader.load( url, function ( text ) {
  54. try {
  55. onLoad( scope.parse( text ) );
  56. } catch ( e ) {
  57. if ( onError ) {
  58. onError( e );
  59. } else {
  60. console.error( e );
  61. }
  62. scope.manager.itemError( url );
  63. }
  64. }, onProgress, onError );
  65. }
  66. /**
  67. * Parses the given AMF data and returns the resulting group.
  68. *
  69. * @param {ArrayBuffer} data - The raw AMF asset data as an array buffer.
  70. * @return {Group} A group representing the parsed asset.
  71. */
  72. parse( data ) {
  73. function loadDocument( data ) {
  74. let view = new DataView( data );
  75. const magic = String.fromCharCode( view.getUint8( 0 ), view.getUint8( 1 ) );
  76. if ( magic === 'PK' ) {
  77. let zip = null;
  78. let file = null;
  79. console.log( 'THREE.AMFLoader: Loading Zip' );
  80. try {
  81. zip = fflate.unzipSync( new Uint8Array( data ) );
  82. } catch ( e ) {
  83. if ( e instanceof ReferenceError ) {
  84. console.log( 'THREE.AMFLoader: fflate missing and file is compressed.' );
  85. return null;
  86. }
  87. }
  88. for ( file in zip ) {
  89. if ( file.toLowerCase().slice( - 4 ) === '.amf' ) {
  90. break;
  91. }
  92. }
  93. console.log( 'THREE.AMFLoader: Trying to load file asset: ' + file );
  94. view = new DataView( zip[ file ].buffer );
  95. }
  96. const fileText = new TextDecoder().decode( view );
  97. const xmlData = new DOMParser().parseFromString( fileText, 'application/xml' );
  98. if ( xmlData.documentElement.nodeName.toLowerCase() !== 'amf' ) {
  99. console.log( 'THREE.AMFLoader: Error loading AMF - no AMF document found.' );
  100. return null;
  101. }
  102. return xmlData;
  103. }
  104. function loadDocumentScale( node ) {
  105. let scale = 1.0;
  106. let unit = 'millimeter';
  107. if ( node.documentElement.attributes.unit !== undefined ) {
  108. unit = node.documentElement.attributes.unit.value.toLowerCase();
  109. }
  110. const scaleUnits = {
  111. millimeter: 1.0,
  112. inch: 25.4,
  113. feet: 304.8,
  114. meter: 1000.0,
  115. micron: 0.001
  116. };
  117. if ( scaleUnits[ unit ] !== undefined ) {
  118. scale = scaleUnits[ unit ];
  119. }
  120. console.log( 'THREE.AMFLoader: Unit scale: ' + scale );
  121. return scale;
  122. }
  123. function loadMaterials( node ) {
  124. let matName = 'AMF Material';
  125. const matId = node.attributes.id.textContent;
  126. let color = { r: 1.0, g: 1.0, b: 1.0, a: 1.0 };
  127. let loadedMaterial = null;
  128. for ( let i = 0; i < node.childNodes.length; i ++ ) {
  129. const matChildEl = node.childNodes[ i ];
  130. if ( matChildEl.nodeName === 'metadata' && matChildEl.attributes.type !== undefined ) {
  131. if ( matChildEl.attributes.type.value === 'name' ) {
  132. matName = matChildEl.textContent;
  133. }
  134. } else if ( matChildEl.nodeName === 'color' ) {
  135. color = loadColor( matChildEl );
  136. }
  137. }
  138. loadedMaterial = new MeshPhongMaterial( {
  139. flatShading: true,
  140. color: new Color( color.r, color.g, color.b ),
  141. name: matName
  142. } );
  143. if ( color.a !== 1.0 ) {
  144. loadedMaterial.transparent = true;
  145. loadedMaterial.opacity = color.a;
  146. }
  147. return { id: matId, material: loadedMaterial };
  148. }
  149. function loadColor( node ) {
  150. const color = { r: 1.0, g: 1.0, b: 1.0, a: 1.0 };
  151. for ( let i = 0; i < node.childNodes.length; i ++ ) {
  152. const matColor = node.childNodes[ i ];
  153. if ( matColor.nodeName === 'r' ) {
  154. color.r = matColor.textContent;
  155. } else if ( matColor.nodeName === 'g' ) {
  156. color.g = matColor.textContent;
  157. } else if ( matColor.nodeName === 'b' ) {
  158. color.b = matColor.textContent;
  159. } else if ( matColor.nodeName === 'a' ) {
  160. color.a = matColor.textContent;
  161. }
  162. }
  163. return color;
  164. }
  165. function loadMeshVolume( node ) {
  166. const volume = { name: '', triangles: [], materialId: null };
  167. let currVolumeNode = node.firstElementChild;
  168. if ( node.attributes.materialid !== undefined ) {
  169. volume.materialId = node.attributes.materialid.nodeValue;
  170. }
  171. while ( currVolumeNode ) {
  172. if ( currVolumeNode.nodeName === 'metadata' ) {
  173. if ( currVolumeNode.attributes.type !== undefined ) {
  174. if ( currVolumeNode.attributes.type.value === 'name' ) {
  175. volume.name = currVolumeNode.textContent;
  176. }
  177. }
  178. } else if ( currVolumeNode.nodeName === 'triangle' ) {
  179. const v1 = currVolumeNode.getElementsByTagName( 'v1' )[ 0 ].textContent;
  180. const v2 = currVolumeNode.getElementsByTagName( 'v2' )[ 0 ].textContent;
  181. const v3 = currVolumeNode.getElementsByTagName( 'v3' )[ 0 ].textContent;
  182. volume.triangles.push( v1, v2, v3 );
  183. }
  184. currVolumeNode = currVolumeNode.nextElementSibling;
  185. }
  186. return volume;
  187. }
  188. function loadMeshVertices( node ) {
  189. const vertArray = [];
  190. const normalArray = [];
  191. let currVerticesNode = node.firstElementChild;
  192. while ( currVerticesNode ) {
  193. if ( currVerticesNode.nodeName === 'vertex' ) {
  194. let vNode = currVerticesNode.firstElementChild;
  195. while ( vNode ) {
  196. if ( vNode.nodeName === 'coordinates' ) {
  197. const x = vNode.getElementsByTagName( 'x' )[ 0 ].textContent;
  198. const y = vNode.getElementsByTagName( 'y' )[ 0 ].textContent;
  199. const z = vNode.getElementsByTagName( 'z' )[ 0 ].textContent;
  200. vertArray.push( x, y, z );
  201. } else if ( vNode.nodeName === 'normal' ) {
  202. const nx = vNode.getElementsByTagName( 'nx' )[ 0 ].textContent;
  203. const ny = vNode.getElementsByTagName( 'ny' )[ 0 ].textContent;
  204. const nz = vNode.getElementsByTagName( 'nz' )[ 0 ].textContent;
  205. normalArray.push( nx, ny, nz );
  206. }
  207. vNode = vNode.nextElementSibling;
  208. }
  209. }
  210. currVerticesNode = currVerticesNode.nextElementSibling;
  211. }
  212. return { 'vertices': vertArray, 'normals': normalArray };
  213. }
  214. function loadObject( node ) {
  215. const objId = node.attributes.id.textContent;
  216. const loadedObject = { name: 'amfobject', meshes: [] };
  217. let currColor = null;
  218. let currObjNode = node.firstElementChild;
  219. while ( currObjNode ) {
  220. if ( currObjNode.nodeName === 'metadata' ) {
  221. if ( currObjNode.attributes.type !== undefined ) {
  222. if ( currObjNode.attributes.type.value === 'name' ) {
  223. loadedObject.name = currObjNode.textContent;
  224. }
  225. }
  226. } else if ( currObjNode.nodeName === 'color' ) {
  227. currColor = loadColor( currObjNode );
  228. } else if ( currObjNode.nodeName === 'mesh' ) {
  229. let currMeshNode = currObjNode.firstElementChild;
  230. const mesh = { vertices: [], normals: [], volumes: [], color: currColor };
  231. while ( currMeshNode ) {
  232. if ( currMeshNode.nodeName === 'vertices' ) {
  233. const loadedVertices = loadMeshVertices( currMeshNode );
  234. mesh.normals = mesh.normals.concat( loadedVertices.normals );
  235. mesh.vertices = mesh.vertices.concat( loadedVertices.vertices );
  236. } else if ( currMeshNode.nodeName === 'volume' ) {
  237. mesh.volumes.push( loadMeshVolume( currMeshNode ) );
  238. }
  239. currMeshNode = currMeshNode.nextElementSibling;
  240. }
  241. loadedObject.meshes.push( mesh );
  242. }
  243. currObjNode = currObjNode.nextElementSibling;
  244. }
  245. return { 'id': objId, 'obj': loadedObject };
  246. }
  247. const xmlData = loadDocument( data );
  248. let amfName = '';
  249. let amfAuthor = '';
  250. const amfScale = loadDocumentScale( xmlData );
  251. const amfMaterials = {};
  252. const amfObjects = {};
  253. const childNodes = xmlData.documentElement.childNodes;
  254. let i, j;
  255. for ( i = 0; i < childNodes.length; i ++ ) {
  256. const child = childNodes[ i ];
  257. if ( child.nodeName === 'metadata' ) {
  258. if ( child.attributes.type !== undefined ) {
  259. if ( child.attributes.type.value === 'name' ) {
  260. amfName = child.textContent;
  261. } else if ( child.attributes.type.value === 'author' ) {
  262. amfAuthor = child.textContent;
  263. }
  264. }
  265. } else if ( child.nodeName === 'material' ) {
  266. const loadedMaterial = loadMaterials( child );
  267. amfMaterials[ loadedMaterial.id ] = loadedMaterial.material;
  268. } else if ( child.nodeName === 'object' ) {
  269. const loadedObject = loadObject( child );
  270. amfObjects[ loadedObject.id ] = loadedObject.obj;
  271. }
  272. }
  273. const sceneObject = new Group();
  274. const defaultMaterial = new MeshPhongMaterial( {
  275. name: Loader.DEFAULT_MATERIAL_NAME,
  276. color: 0xaaaaff,
  277. flatShading: true
  278. } );
  279. sceneObject.name = amfName;
  280. sceneObject.userData.author = amfAuthor;
  281. sceneObject.userData.loader = 'AMF';
  282. for ( const id in amfObjects ) {
  283. const part = amfObjects[ id ];
  284. const meshes = part.meshes;
  285. const newObject = new Group();
  286. newObject.name = part.name || '';
  287. for ( i = 0; i < meshes.length; i ++ ) {
  288. let objDefaultMaterial = defaultMaterial;
  289. const mesh = meshes[ i ];
  290. const vertices = new Float32BufferAttribute( mesh.vertices, 3 );
  291. let normals = null;
  292. if ( mesh.normals.length ) {
  293. normals = new Float32BufferAttribute( mesh.normals, 3 );
  294. }
  295. if ( mesh.color ) {
  296. const color = mesh.color;
  297. objDefaultMaterial = defaultMaterial.clone();
  298. objDefaultMaterial.color = new Color( color.r, color.g, color.b );
  299. if ( color.a !== 1.0 ) {
  300. objDefaultMaterial.transparent = true;
  301. objDefaultMaterial.opacity = color.a;
  302. }
  303. }
  304. const volumes = mesh.volumes;
  305. for ( j = 0; j < volumes.length; j ++ ) {
  306. const volume = volumes[ j ];
  307. const newGeometry = new BufferGeometry();
  308. let material = objDefaultMaterial;
  309. newGeometry.setIndex( volume.triangles );
  310. newGeometry.setAttribute( 'position', vertices.clone() );
  311. if ( normals ) {
  312. newGeometry.setAttribute( 'normal', normals.clone() );
  313. }
  314. if ( amfMaterials[ volume.materialId ] !== undefined ) {
  315. material = amfMaterials[ volume.materialId ];
  316. }
  317. newGeometry.scale( amfScale, amfScale, amfScale );
  318. newObject.add( new Mesh( newGeometry, material.clone() ) );
  319. }
  320. }
  321. sceneObject.add( newObject );
  322. }
  323. return sceneObject;
  324. }
  325. }
  326. export { AMFLoader };