ObjectLoader.js 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  1. import {
  2. UVMapping,
  3. CubeReflectionMapping,
  4. CubeRefractionMapping,
  5. EquirectangularReflectionMapping,
  6. EquirectangularRefractionMapping,
  7. CubeUVReflectionMapping,
  8. RepeatWrapping,
  9. ClampToEdgeWrapping,
  10. MirroredRepeatWrapping,
  11. NearestFilter,
  12. NearestMipmapNearestFilter,
  13. NearestMipmapLinearFilter,
  14. LinearFilter,
  15. LinearMipmapNearestFilter,
  16. LinearMipmapLinearFilter
  17. } from '../constants.js';
  18. import { InstancedBufferAttribute } from '../core/InstancedBufferAttribute.js';
  19. import { Color } from '../math/Color.js';
  20. import { Object3D } from '../core/Object3D.js';
  21. import { Group } from '../objects/Group.js';
  22. import { InstancedMesh } from '../objects/InstancedMesh.js';
  23. import { BatchedMesh } from '../objects/BatchedMesh.js';
  24. import { Sprite } from '../objects/Sprite.js';
  25. import { Points } from '../objects/Points.js';
  26. import { Line } from '../objects/Line.js';
  27. import { LineLoop } from '../objects/LineLoop.js';
  28. import { LineSegments } from '../objects/LineSegments.js';
  29. import { LOD } from '../objects/LOD.js';
  30. import { Mesh } from '../objects/Mesh.js';
  31. import { SkinnedMesh } from '../objects/SkinnedMesh.js';
  32. import { Bone } from '../objects/Bone.js';
  33. import { Skeleton } from '../objects/Skeleton.js';
  34. import { Shape } from '../extras/core/Shape.js';
  35. import { Fog } from '../scenes/Fog.js';
  36. import { FogExp2 } from '../scenes/FogExp2.js';
  37. import { HemisphereLight } from '../lights/HemisphereLight.js';
  38. import { SpotLight } from '../lights/SpotLight.js';
  39. import { PointLight } from '../lights/PointLight.js';
  40. import { DirectionalLight } from '../lights/DirectionalLight.js';
  41. import { AmbientLight } from '../lights/AmbientLight.js';
  42. import { RectAreaLight } from '../lights/RectAreaLight.js';
  43. import { LightProbe } from '../lights/LightProbe.js';
  44. import { OrthographicCamera } from '../cameras/OrthographicCamera.js';
  45. import { PerspectiveCamera } from '../cameras/PerspectiveCamera.js';
  46. import { Scene } from '../scenes/Scene.js';
  47. import { CubeTexture } from '../textures/CubeTexture.js';
  48. import { Texture } from '../textures/Texture.js';
  49. import { Source } from '../textures/Source.js';
  50. import { DataTexture } from '../textures/DataTexture.js';
  51. import { ImageLoader } from './ImageLoader.js';
  52. import { LoadingManager } from './LoadingManager.js';
  53. import { AnimationClip } from '../animation/AnimationClip.js';
  54. import { MaterialLoader } from './MaterialLoader.js';
  55. import { LoaderUtils } from './LoaderUtils.js';
  56. import { BufferGeometryLoader } from './BufferGeometryLoader.js';
  57. import { Loader } from './Loader.js';
  58. import { FileLoader } from './FileLoader.js';
  59. import * as Geometries from '../geometries/Geometries.js';
  60. import { getTypedArray, error, warn } from '../utils.js';
  61. import { Box3 } from '../math/Box3.js';
  62. import { Sphere } from '../math/Sphere.js';
  63. /**
  64. * A loader for loading a JSON resource in the [JSON Object/Scene format](https://github.com/mrdoob/three.js/wiki/JSON-Object-Scene-format-4).
  65. * The files are internally loaded via {@link FileLoader}.
  66. *
  67. * ```js
  68. * const loader = new THREE.ObjectLoader();
  69. * const obj = await loader.loadAsync( 'models/json/example.json' );
  70. * scene.add( obj );
  71. *
  72. * // Alternatively, to parse a previously loaded JSON structure
  73. * const object = await loader.parseAsync( a_json_object );
  74. * scene.add( object );
  75. * ```
  76. *
  77. * @augments Loader
  78. */
  79. class ObjectLoader extends Loader {
  80. /**
  81. * Constructs a new object loader.
  82. *
  83. * @param {LoadingManager} [manager] - The loading manager.
  84. */
  85. constructor( manager ) {
  86. super( manager );
  87. }
  88. /**
  89. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  90. *
  91. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  92. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  93. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  94. * @param {onErrorCallback} onError - Executed when errors occur.
  95. */
  96. load( url, onLoad, onProgress, onError ) {
  97. const scope = this;
  98. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  99. this.resourcePath = this.resourcePath || path;
  100. const loader = new FileLoader( this.manager );
  101. loader.setPath( this.path );
  102. loader.setRequestHeader( this.requestHeader );
  103. loader.setWithCredentials( this.withCredentials );
  104. loader.load( url, function ( text ) {
  105. let json = null;
  106. try {
  107. json = JSON.parse( text );
  108. } catch ( error ) {
  109. if ( onError !== undefined ) onError( error );
  110. error( 'ObjectLoader: Can\'t parse ' + url + '.', error.message );
  111. return;
  112. }
  113. const metadata = json.metadata;
  114. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  115. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  116. error( 'ObjectLoader: Can\'t load ' + url );
  117. return;
  118. }
  119. scope.parse( json, onLoad );
  120. }, onProgress, onError );
  121. }
  122. /**
  123. * Async version of {@link ObjectLoader#load}.
  124. *
  125. * @async
  126. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  127. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  128. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  129. */
  130. async loadAsync( url, onProgress ) {
  131. const scope = this;
  132. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  133. this.resourcePath = this.resourcePath || path;
  134. const loader = new FileLoader( this.manager );
  135. loader.setPath( this.path );
  136. loader.setRequestHeader( this.requestHeader );
  137. loader.setWithCredentials( this.withCredentials );
  138. const text = await loader.loadAsync( url, onProgress );
  139. const json = JSON.parse( text );
  140. const metadata = json.metadata;
  141. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  142. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  143. }
  144. return await scope.parseAsync( json );
  145. }
  146. /**
  147. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  148. * but can also be used directly to parse a previously loaded JSON structure.
  149. *
  150. * @param {Object} json - The serialized 3D object.
  151. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  152. * @return {Object3D} The parsed 3D object.
  153. */
  154. parse( json, onLoad ) {
  155. const animations = this.parseAnimations( json.animations );
  156. const shapes = this.parseShapes( json.shapes );
  157. const geometries = this.parseGeometries( json.geometries, shapes );
  158. const images = this.parseImages( json.images, function () {
  159. if ( onLoad !== undefined ) onLoad( object );
  160. } );
  161. const textures = this.parseTextures( json.textures, images );
  162. const materials = this.parseMaterials( json.materials, textures );
  163. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  164. const skeletons = this.parseSkeletons( json.skeletons, object );
  165. this.bindSkeletons( object, skeletons );
  166. this.bindLightTargets( object );
  167. //
  168. if ( onLoad !== undefined ) {
  169. let hasImages = false;
  170. for ( const uuid in images ) {
  171. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  172. hasImages = true;
  173. break;
  174. }
  175. }
  176. if ( hasImages === false ) onLoad( object );
  177. }
  178. return object;
  179. }
  180. /**
  181. * Async version of {@link ObjectLoader#parse}.
  182. *
  183. * @param {Object} json - The serialized 3D object.
  184. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  185. */
  186. async parseAsync( json ) {
  187. const animations = this.parseAnimations( json.animations );
  188. const shapes = this.parseShapes( json.shapes );
  189. const geometries = this.parseGeometries( json.geometries, shapes );
  190. const images = await this.parseImagesAsync( json.images );
  191. const textures = this.parseTextures( json.textures, images );
  192. const materials = this.parseMaterials( json.materials, textures );
  193. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  194. const skeletons = this.parseSkeletons( json.skeletons, object );
  195. this.bindSkeletons( object, skeletons );
  196. this.bindLightTargets( object );
  197. return object;
  198. }
  199. // internals
  200. parseShapes( json ) {
  201. const shapes = {};
  202. if ( json !== undefined ) {
  203. for ( let i = 0, l = json.length; i < l; i ++ ) {
  204. const shape = new Shape().fromJSON( json[ i ] );
  205. shapes[ shape.uuid ] = shape;
  206. }
  207. }
  208. return shapes;
  209. }
  210. parseSkeletons( json, object ) {
  211. const skeletons = {};
  212. const bones = {};
  213. // generate bone lookup table
  214. object.traverse( function ( child ) {
  215. if ( child.isBone ) bones[ child.uuid ] = child;
  216. } );
  217. // create skeletons
  218. if ( json !== undefined ) {
  219. for ( let i = 0, l = json.length; i < l; i ++ ) {
  220. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  221. skeletons[ skeleton.uuid ] = skeleton;
  222. }
  223. }
  224. return skeletons;
  225. }
  226. parseGeometries( json, shapes ) {
  227. const geometries = {};
  228. if ( json !== undefined ) {
  229. const bufferGeometryLoader = new BufferGeometryLoader();
  230. for ( let i = 0, l = json.length; i < l; i ++ ) {
  231. let geometry;
  232. const data = json[ i ];
  233. switch ( data.type ) {
  234. case 'BufferGeometry':
  235. case 'InstancedBufferGeometry':
  236. geometry = bufferGeometryLoader.parse( data );
  237. break;
  238. default:
  239. if ( data.type in Geometries ) {
  240. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  241. } else {
  242. warn( `ObjectLoader: Unsupported geometry type "${ data.type }"` );
  243. }
  244. }
  245. geometry.uuid = data.uuid;
  246. if ( data.name !== undefined ) geometry.name = data.name;
  247. if ( data.userData !== undefined ) geometry.userData = data.userData;
  248. geometries[ data.uuid ] = geometry;
  249. }
  250. }
  251. return geometries;
  252. }
  253. parseMaterials( json, textures ) {
  254. const cache = {}; // MultiMaterial
  255. const materials = {};
  256. if ( json !== undefined ) {
  257. const loader = new MaterialLoader();
  258. loader.setTextures( textures );
  259. for ( let i = 0, l = json.length; i < l; i ++ ) {
  260. const data = json[ i ];
  261. if ( cache[ data.uuid ] === undefined ) {
  262. cache[ data.uuid ] = loader.parse( data );
  263. }
  264. materials[ data.uuid ] = cache[ data.uuid ];
  265. }
  266. }
  267. return materials;
  268. }
  269. parseAnimations( json ) {
  270. const animations = {};
  271. if ( json !== undefined ) {
  272. for ( let i = 0; i < json.length; i ++ ) {
  273. const data = json[ i ];
  274. const clip = AnimationClip.parse( data );
  275. animations[ clip.uuid ] = clip;
  276. }
  277. }
  278. return animations;
  279. }
  280. parseImages( json, onLoad ) {
  281. const scope = this;
  282. const images = {};
  283. let loader;
  284. function loadImage( url ) {
  285. scope.manager.itemStart( url );
  286. return loader.load( url, function () {
  287. scope.manager.itemEnd( url );
  288. }, undefined, function () {
  289. scope.manager.itemError( url );
  290. scope.manager.itemEnd( url );
  291. } );
  292. }
  293. function deserializeImage( image ) {
  294. if ( typeof image === 'string' ) {
  295. const url = image;
  296. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  297. return loadImage( path );
  298. } else {
  299. if ( image.data ) {
  300. return {
  301. data: getTypedArray( image.type, image.data ),
  302. width: image.width,
  303. height: image.height
  304. };
  305. } else {
  306. return null;
  307. }
  308. }
  309. }
  310. if ( json !== undefined && json.length > 0 ) {
  311. const manager = new LoadingManager( onLoad );
  312. loader = new ImageLoader( manager );
  313. loader.setCrossOrigin( this.crossOrigin );
  314. for ( let i = 0, il = json.length; i < il; i ++ ) {
  315. const image = json[ i ];
  316. const url = image.url;
  317. if ( Array.isArray( url ) ) {
  318. // load array of images e.g CubeTexture
  319. const imageArray = [];
  320. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  321. const currentUrl = url[ j ];
  322. const deserializedImage = deserializeImage( currentUrl );
  323. if ( deserializedImage !== null ) {
  324. if ( deserializedImage instanceof HTMLImageElement ) {
  325. imageArray.push( deserializedImage );
  326. } else {
  327. // special case: handle array of data textures for cube textures
  328. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  329. }
  330. }
  331. }
  332. images[ image.uuid ] = new Source( imageArray );
  333. } else {
  334. // load single image
  335. const deserializedImage = deserializeImage( image.url );
  336. images[ image.uuid ] = new Source( deserializedImage );
  337. }
  338. }
  339. }
  340. return images;
  341. }
  342. async parseImagesAsync( json ) {
  343. const scope = this;
  344. const images = {};
  345. let loader;
  346. async function deserializeImage( image ) {
  347. if ( typeof image === 'string' ) {
  348. const url = image;
  349. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  350. return await loader.loadAsync( path );
  351. } else {
  352. if ( image.data ) {
  353. return {
  354. data: getTypedArray( image.type, image.data ),
  355. width: image.width,
  356. height: image.height
  357. };
  358. } else {
  359. return null;
  360. }
  361. }
  362. }
  363. if ( json !== undefined && json.length > 0 ) {
  364. loader = new ImageLoader( this.manager );
  365. loader.setCrossOrigin( this.crossOrigin );
  366. for ( let i = 0, il = json.length; i < il; i ++ ) {
  367. const image = json[ i ];
  368. const url = image.url;
  369. if ( Array.isArray( url ) ) {
  370. // load array of images e.g CubeTexture
  371. const imageArray = [];
  372. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  373. const currentUrl = url[ j ];
  374. const deserializedImage = await deserializeImage( currentUrl );
  375. if ( deserializedImage !== null ) {
  376. if ( deserializedImage instanceof HTMLImageElement ) {
  377. imageArray.push( deserializedImage );
  378. } else {
  379. // special case: handle array of data textures for cube textures
  380. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  381. }
  382. }
  383. }
  384. images[ image.uuid ] = new Source( imageArray );
  385. } else {
  386. // load single image
  387. const deserializedImage = await deserializeImage( image.url );
  388. images[ image.uuid ] = new Source( deserializedImage );
  389. }
  390. }
  391. }
  392. return images;
  393. }
  394. parseTextures( json, images ) {
  395. function parseConstant( value, type ) {
  396. if ( typeof value === 'number' ) return value;
  397. warn( 'ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  398. return type[ value ];
  399. }
  400. const textures = {};
  401. if ( json !== undefined ) {
  402. for ( let i = 0, l = json.length; i < l; i ++ ) {
  403. const data = json[ i ];
  404. if ( data.image === undefined ) {
  405. warn( 'ObjectLoader: No "image" specified for', data.uuid );
  406. }
  407. if ( images[ data.image ] === undefined ) {
  408. warn( 'ObjectLoader: Undefined image', data.image );
  409. }
  410. const source = images[ data.image ];
  411. const image = source.data;
  412. let texture;
  413. if ( Array.isArray( image ) ) {
  414. texture = new CubeTexture();
  415. if ( image.length === 6 ) texture.needsUpdate = true;
  416. } else {
  417. if ( image && image.data ) {
  418. texture = new DataTexture();
  419. } else {
  420. texture = new Texture();
  421. }
  422. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  423. }
  424. texture.source = source;
  425. texture.uuid = data.uuid;
  426. if ( data.name !== undefined ) texture.name = data.name;
  427. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  428. if ( data.channel !== undefined ) texture.channel = data.channel;
  429. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  430. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  431. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  432. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  433. if ( data.wrap !== undefined ) {
  434. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  435. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  436. }
  437. if ( data.format !== undefined ) texture.format = data.format;
  438. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  439. if ( data.type !== undefined ) texture.type = data.type;
  440. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  441. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  442. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  443. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  444. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  445. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  446. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  447. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  448. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  449. if ( data.userData !== undefined ) texture.userData = data.userData;
  450. textures[ data.uuid ] = texture;
  451. }
  452. }
  453. return textures;
  454. }
  455. parseObject( data, geometries, materials, textures, animations ) {
  456. let object;
  457. function getGeometry( name ) {
  458. if ( geometries[ name ] === undefined ) {
  459. warn( 'ObjectLoader: Undefined geometry', name );
  460. }
  461. return geometries[ name ];
  462. }
  463. function getMaterial( name ) {
  464. if ( name === undefined ) return undefined;
  465. if ( Array.isArray( name ) ) {
  466. const array = [];
  467. for ( let i = 0, l = name.length; i < l; i ++ ) {
  468. const uuid = name[ i ];
  469. if ( materials[ uuid ] === undefined ) {
  470. warn( 'ObjectLoader: Undefined material', uuid );
  471. }
  472. array.push( materials[ uuid ] );
  473. }
  474. return array;
  475. }
  476. if ( materials[ name ] === undefined ) {
  477. warn( 'ObjectLoader: Undefined material', name );
  478. }
  479. return materials[ name ];
  480. }
  481. function getTexture( uuid ) {
  482. if ( textures[ uuid ] === undefined ) {
  483. warn( 'ObjectLoader: Undefined texture', uuid );
  484. }
  485. return textures[ uuid ];
  486. }
  487. let geometry, material;
  488. switch ( data.type ) {
  489. case 'Scene':
  490. object = new Scene();
  491. if ( data.background !== undefined ) {
  492. if ( Number.isInteger( data.background ) ) {
  493. object.background = new Color( data.background );
  494. } else {
  495. object.background = getTexture( data.background );
  496. }
  497. }
  498. if ( data.environment !== undefined ) {
  499. object.environment = getTexture( data.environment );
  500. }
  501. if ( data.fog !== undefined ) {
  502. if ( data.fog.type === 'Fog' ) {
  503. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  504. } else if ( data.fog.type === 'FogExp2' ) {
  505. object.fog = new FogExp2( data.fog.color, data.fog.density );
  506. }
  507. if ( data.fog.name !== '' ) {
  508. object.fog.name = data.fog.name;
  509. }
  510. }
  511. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  512. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  513. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  514. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  515. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  516. break;
  517. case 'PerspectiveCamera':
  518. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  519. if ( data.focus !== undefined ) object.focus = data.focus;
  520. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  521. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  522. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  523. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  524. break;
  525. case 'OrthographicCamera':
  526. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  527. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  528. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  529. break;
  530. case 'AmbientLight':
  531. object = new AmbientLight( data.color, data.intensity );
  532. break;
  533. case 'DirectionalLight':
  534. object = new DirectionalLight( data.color, data.intensity );
  535. object.target = data.target || '';
  536. break;
  537. case 'PointLight':
  538. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  539. break;
  540. case 'RectAreaLight':
  541. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  542. break;
  543. case 'SpotLight':
  544. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  545. object.target = data.target || '';
  546. break;
  547. case 'HemisphereLight':
  548. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  549. break;
  550. case 'LightProbe':
  551. object = new LightProbe().fromJSON( data );
  552. break;
  553. case 'SkinnedMesh':
  554. geometry = getGeometry( data.geometry );
  555. material = getMaterial( data.material );
  556. object = new SkinnedMesh( geometry, material );
  557. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  558. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  559. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  560. break;
  561. case 'Mesh':
  562. geometry = getGeometry( data.geometry );
  563. material = getMaterial( data.material );
  564. object = new Mesh( geometry, material );
  565. break;
  566. case 'InstancedMesh':
  567. geometry = getGeometry( data.geometry );
  568. material = getMaterial( data.material );
  569. const count = data.count;
  570. const instanceMatrix = data.instanceMatrix;
  571. const instanceColor = data.instanceColor;
  572. object = new InstancedMesh( geometry, material, count );
  573. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  574. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  575. break;
  576. case 'BatchedMesh':
  577. geometry = getGeometry( data.geometry );
  578. material = getMaterial( data.material );
  579. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  580. object.geometry = geometry;
  581. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  582. object.sortObjects = data.sortObjects;
  583. object._drawRanges = data.drawRanges;
  584. object._reservedRanges = data.reservedRanges;
  585. object._geometryInfo = data.geometryInfo.map( info => {
  586. let box = null;
  587. let sphere = null;
  588. if ( info.boundingBox !== undefined ) {
  589. box = new Box3().fromJSON( info.boundingBox );
  590. }
  591. if ( info.boundingSphere !== undefined ) {
  592. sphere = new Sphere().fromJSON( info.boundingSphere );
  593. }
  594. return {
  595. ...info,
  596. boundingBox: box,
  597. boundingSphere: sphere
  598. };
  599. } );
  600. object._instanceInfo = data.instanceInfo;
  601. object._availableInstanceIds = data._availableInstanceIds;
  602. object._availableGeometryIds = data._availableGeometryIds;
  603. object._nextIndexStart = data.nextIndexStart;
  604. object._nextVertexStart = data.nextVertexStart;
  605. object._geometryCount = data.geometryCount;
  606. object._maxInstanceCount = data.maxInstanceCount;
  607. object._maxVertexCount = data.maxVertexCount;
  608. object._maxIndexCount = data.maxIndexCount;
  609. object._geometryInitialized = data.geometryInitialized;
  610. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  611. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  612. if ( data.colorsTexture !== undefined ) {
  613. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  614. }
  615. if ( data.boundingSphere !== undefined ) {
  616. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  617. }
  618. if ( data.boundingBox !== undefined ) {
  619. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  620. }
  621. break;
  622. case 'LOD':
  623. object = new LOD();
  624. break;
  625. case 'Line':
  626. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  627. break;
  628. case 'LineLoop':
  629. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  630. break;
  631. case 'LineSegments':
  632. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  633. break;
  634. case 'PointCloud':
  635. case 'Points':
  636. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  637. break;
  638. case 'Sprite':
  639. object = new Sprite( getMaterial( data.material ) );
  640. break;
  641. case 'Group':
  642. object = new Group();
  643. break;
  644. case 'Bone':
  645. object = new Bone();
  646. break;
  647. default:
  648. object = new Object3D();
  649. }
  650. object.uuid = data.uuid;
  651. if ( data.name !== undefined ) object.name = data.name;
  652. if ( data.matrix !== undefined ) {
  653. object.matrix.fromArray( data.matrix );
  654. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  655. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  656. } else {
  657. if ( data.position !== undefined ) object.position.fromArray( data.position );
  658. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  659. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  660. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  661. }
  662. if ( data.up !== undefined ) object.up.fromArray( data.up );
  663. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  664. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  665. if ( data.shadow ) {
  666. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  667. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  668. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  669. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  670. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  671. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  672. }
  673. if ( data.visible !== undefined ) object.visible = data.visible;
  674. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  675. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  676. if ( data.userData !== undefined ) object.userData = data.userData;
  677. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  678. if ( data.children !== undefined ) {
  679. const children = data.children;
  680. for ( let i = 0; i < children.length; i ++ ) {
  681. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  682. }
  683. }
  684. if ( data.animations !== undefined ) {
  685. const objectAnimations = data.animations;
  686. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  687. const uuid = objectAnimations[ i ];
  688. object.animations.push( animations[ uuid ] );
  689. }
  690. }
  691. if ( data.type === 'LOD' ) {
  692. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  693. const levels = data.levels;
  694. for ( let l = 0; l < levels.length; l ++ ) {
  695. const level = levels[ l ];
  696. const child = object.getObjectByProperty( 'uuid', level.object );
  697. if ( child !== undefined ) {
  698. object.addLevel( child, level.distance, level.hysteresis );
  699. }
  700. }
  701. }
  702. return object;
  703. }
  704. bindSkeletons( object, skeletons ) {
  705. if ( Object.keys( skeletons ).length === 0 ) return;
  706. object.traverse( function ( child ) {
  707. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  708. const skeleton = skeletons[ child.skeleton ];
  709. if ( skeleton === undefined ) {
  710. warn( 'ObjectLoader: No skeleton found with UUID:', child.skeleton );
  711. } else {
  712. child.bind( skeleton, child.bindMatrix );
  713. }
  714. }
  715. } );
  716. }
  717. bindLightTargets( object ) {
  718. object.traverse( function ( child ) {
  719. if ( child.isDirectionalLight || child.isSpotLight ) {
  720. const uuid = child.target;
  721. const target = object.getObjectByProperty( 'uuid', uuid );
  722. if ( target !== undefined ) {
  723. child.target = target;
  724. } else {
  725. child.target = new Object3D();
  726. }
  727. }
  728. } );
  729. }
  730. }
  731. const TEXTURE_MAPPING = {
  732. UVMapping: UVMapping,
  733. CubeReflectionMapping: CubeReflectionMapping,
  734. CubeRefractionMapping: CubeRefractionMapping,
  735. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  736. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  737. CubeUVReflectionMapping: CubeUVReflectionMapping
  738. };
  739. const TEXTURE_WRAPPING = {
  740. RepeatWrapping: RepeatWrapping,
  741. ClampToEdgeWrapping: ClampToEdgeWrapping,
  742. MirroredRepeatWrapping: MirroredRepeatWrapping
  743. };
  744. const TEXTURE_FILTER = {
  745. NearestFilter: NearestFilter,
  746. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  747. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  748. LinearFilter: LinearFilter,
  749. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  750. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  751. };
  752. export { ObjectLoader };
粤ICP备19079148号