Object3D.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  1. import { Quaternion } from '../math/Quaternion.js';
  2. import { Vector3 } from '../math/Vector3.js';
  3. import { Matrix4 } from '../math/Matrix4.js';
  4. import { EventDispatcher } from './EventDispatcher.js';
  5. import { Euler } from '../math/Euler.js';
  6. import { Layers } from './Layers.js';
  7. import { Matrix3 } from '../math/Matrix3.js';
  8. import * as MathUtils from '../math/MathUtils.js';
  9. let _object3DId = 0;
  10. const _v1 = /*@__PURE__*/ new Vector3();
  11. const _q1 = /*@__PURE__*/ new Quaternion();
  12. const _m1 = /*@__PURE__*/ new Matrix4();
  13. const _target = /*@__PURE__*/ new Vector3();
  14. const _position = /*@__PURE__*/ new Vector3();
  15. const _scale = /*@__PURE__*/ new Vector3();
  16. const _quaternion = /*@__PURE__*/ new Quaternion();
  17. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  18. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  19. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  20. const _addedEvent = { type: 'added' };
  21. const _removedEvent = { type: 'removed' };
  22. class Object3D extends EventDispatcher {
  23. constructor() {
  24. super();
  25. this.isObject3D = true;
  26. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  27. this.uuid = MathUtils.generateUUID();
  28. this.name = '';
  29. this.type = 'Object3D';
  30. this.parent = null;
  31. this.children = [];
  32. this.up = Object3D.DEFAULT_UP.clone();
  33. const position = new Vector3();
  34. const rotation = new Euler();
  35. const quaternion = new Quaternion();
  36. const scale = new Vector3( 1, 1, 1 );
  37. function onRotationChange() {
  38. quaternion.setFromEuler( rotation, false );
  39. }
  40. function onQuaternionChange() {
  41. rotation.setFromQuaternion( quaternion, undefined, false );
  42. }
  43. rotation._onChange( onRotationChange );
  44. quaternion._onChange( onQuaternionChange );
  45. Object.defineProperties( this, {
  46. position: {
  47. configurable: true,
  48. enumerable: true,
  49. value: position
  50. },
  51. rotation: {
  52. configurable: true,
  53. enumerable: true,
  54. value: rotation
  55. },
  56. quaternion: {
  57. configurable: true,
  58. enumerable: true,
  59. value: quaternion
  60. },
  61. scale: {
  62. configurable: true,
  63. enumerable: true,
  64. value: scale
  65. },
  66. modelViewMatrix: {
  67. value: new Matrix4()
  68. },
  69. normalMatrix: {
  70. value: new Matrix3()
  71. }
  72. } );
  73. this.matrix = new Matrix4();
  74. this.matrixWorld = new Matrix4();
  75. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  76. this.matrixWorldNeedsUpdate = false;
  77. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  78. this.layers = new Layers();
  79. this.visible = true;
  80. this.castShadow = false;
  81. this.receiveShadow = false;
  82. this.frustumCulled = true;
  83. this.renderOrder = 0;
  84. this.animations = [];
  85. this.userData = {};
  86. }
  87. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  88. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  89. applyMatrix4( matrix ) {
  90. if ( this.matrixAutoUpdate ) this.updateMatrix();
  91. this.matrix.premultiply( matrix );
  92. this.matrix.decompose( this.position, this.quaternion, this.scale );
  93. }
  94. applyQuaternion( q ) {
  95. this.quaternion.premultiply( q );
  96. return this;
  97. }
  98. setRotationFromAxisAngle( axis, angle ) {
  99. // assumes axis is normalized
  100. this.quaternion.setFromAxisAngle( axis, angle );
  101. }
  102. setRotationFromEuler( euler ) {
  103. this.quaternion.setFromEuler( euler, true );
  104. }
  105. setRotationFromMatrix( m ) {
  106. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  107. this.quaternion.setFromRotationMatrix( m );
  108. }
  109. setRotationFromQuaternion( q ) {
  110. // assumes q is normalized
  111. this.quaternion.copy( q );
  112. }
  113. rotateOnAxis( axis, angle ) {
  114. // rotate object on axis in object space
  115. // axis is assumed to be normalized
  116. _q1.setFromAxisAngle( axis, angle );
  117. this.quaternion.multiply( _q1 );
  118. return this;
  119. }
  120. rotateOnWorldAxis( axis, angle ) {
  121. // rotate object on axis in world space
  122. // axis is assumed to be normalized
  123. // method assumes no rotated parent
  124. _q1.setFromAxisAngle( axis, angle );
  125. this.quaternion.premultiply( _q1 );
  126. return this;
  127. }
  128. rotateX( angle ) {
  129. return this.rotateOnAxis( _xAxis, angle );
  130. }
  131. rotateY( angle ) {
  132. return this.rotateOnAxis( _yAxis, angle );
  133. }
  134. rotateZ( angle ) {
  135. return this.rotateOnAxis( _zAxis, angle );
  136. }
  137. translateOnAxis( axis, distance ) {
  138. // translate object by distance along axis in object space
  139. // axis is assumed to be normalized
  140. _v1.copy( axis ).applyQuaternion( this.quaternion );
  141. this.position.add( _v1.multiplyScalar( distance ) );
  142. return this;
  143. }
  144. translateX( distance ) {
  145. return this.translateOnAxis( _xAxis, distance );
  146. }
  147. translateY( distance ) {
  148. return this.translateOnAxis( _yAxis, distance );
  149. }
  150. translateZ( distance ) {
  151. return this.translateOnAxis( _zAxis, distance );
  152. }
  153. localToWorld( vector ) {
  154. this.updateWorldMatrix( true, false );
  155. return vector.applyMatrix4( this.matrixWorld );
  156. }
  157. worldToLocal( vector ) {
  158. this.updateWorldMatrix( true, false );
  159. return vector.applyMatrix4( _m1.copy( this.matrixWorld ).invert() );
  160. }
  161. lookAt( x, y, z ) {
  162. // This method does not support objects having non-uniformly-scaled parent(s)
  163. if ( x.isVector3 ) {
  164. _target.copy( x );
  165. } else {
  166. _target.set( x, y, z );
  167. }
  168. const parent = this.parent;
  169. this.updateWorldMatrix( true, false );
  170. _position.setFromMatrixPosition( this.matrixWorld );
  171. if ( this.isCamera || this.isLight ) {
  172. _m1.lookAt( _position, _target, this.up );
  173. } else {
  174. _m1.lookAt( _target, _position, this.up );
  175. }
  176. this.quaternion.setFromRotationMatrix( _m1 );
  177. if ( parent ) {
  178. _m1.extractRotation( parent.matrixWorld );
  179. _q1.setFromRotationMatrix( _m1 );
  180. this.quaternion.premultiply( _q1.invert() );
  181. }
  182. }
  183. add( object ) {
  184. if ( arguments.length > 1 ) {
  185. for ( let i = 0; i < arguments.length; i ++ ) {
  186. this.add( arguments[ i ] );
  187. }
  188. return this;
  189. }
  190. if ( object === this ) {
  191. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  192. return this;
  193. }
  194. if ( object && object.isObject3D ) {
  195. if ( object.parent !== null ) {
  196. object.parent.remove( object );
  197. }
  198. object.parent = this;
  199. this.children.push( object );
  200. object.dispatchEvent( _addedEvent );
  201. } else {
  202. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  203. }
  204. return this;
  205. }
  206. remove( object ) {
  207. if ( arguments.length > 1 ) {
  208. for ( let i = 0; i < arguments.length; i ++ ) {
  209. this.remove( arguments[ i ] );
  210. }
  211. return this;
  212. }
  213. const index = this.children.indexOf( object );
  214. if ( index !== - 1 ) {
  215. object.parent = null;
  216. this.children.splice( index, 1 );
  217. object.dispatchEvent( _removedEvent );
  218. }
  219. return this;
  220. }
  221. removeFromParent() {
  222. const parent = this.parent;
  223. if ( parent !== null ) {
  224. parent.remove( this );
  225. }
  226. return this;
  227. }
  228. clear() {
  229. for ( let i = 0; i < this.children.length; i ++ ) {
  230. const object = this.children[ i ];
  231. object.parent = null;
  232. object.dispatchEvent( _removedEvent );
  233. }
  234. this.children.length = 0;
  235. return this;
  236. }
  237. attach( object ) {
  238. // adds object as a child of this, while maintaining the object's world transform
  239. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  240. this.updateWorldMatrix( true, false );
  241. _m1.copy( this.matrixWorld ).invert();
  242. if ( object.parent !== null ) {
  243. object.parent.updateWorldMatrix( true, false );
  244. _m1.multiply( object.parent.matrixWorld );
  245. }
  246. object.applyMatrix4( _m1 );
  247. this.add( object );
  248. object.updateWorldMatrix( false, true );
  249. return this;
  250. }
  251. getObjectById( id ) {
  252. return this.getObjectByProperty( 'id', id );
  253. }
  254. getObjectByName( name ) {
  255. return this.getObjectByProperty( 'name', name );
  256. }
  257. getObjectByProperty( name, value ) {
  258. if ( this[ name ] === value ) return this;
  259. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  260. const child = this.children[ i ];
  261. const object = child.getObjectByProperty( name, value );
  262. if ( object !== undefined ) {
  263. return object;
  264. }
  265. }
  266. return undefined;
  267. }
  268. getObjectsByProperty( name, value ) {
  269. let result = [];
  270. if ( this[ name ] === value ) result.push( this );
  271. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  272. const childResult = this.children[ i ].getObjectsByProperty( name, value );
  273. if ( childResult.length > 0 ) {
  274. result = result.concat( childResult );
  275. }
  276. }
  277. return result;
  278. }
  279. getWorldPosition( target ) {
  280. this.updateWorldMatrix( true, false );
  281. return target.setFromMatrixPosition( this.matrixWorld );
  282. }
  283. getWorldQuaternion( target ) {
  284. this.updateWorldMatrix( true, false );
  285. this.matrixWorld.decompose( _position, target, _scale );
  286. return target;
  287. }
  288. getWorldScale( target ) {
  289. this.updateWorldMatrix( true, false );
  290. this.matrixWorld.decompose( _position, _quaternion, target );
  291. return target;
  292. }
  293. getWorldDirection( target ) {
  294. this.updateWorldMatrix( true, false );
  295. const e = this.matrixWorld.elements;
  296. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  297. }
  298. raycast( /* raycaster, intersects */ ) {}
  299. traverse( callback ) {
  300. callback( this );
  301. const children = this.children;
  302. for ( let i = 0, l = children.length; i < l; i ++ ) {
  303. children[ i ].traverse( callback );
  304. }
  305. }
  306. traverseVisible( callback ) {
  307. if ( this.visible === false ) return;
  308. callback( this );
  309. const children = this.children;
  310. for ( let i = 0, l = children.length; i < l; i ++ ) {
  311. children[ i ].traverseVisible( callback );
  312. }
  313. }
  314. traverseAncestors( callback ) {
  315. const parent = this.parent;
  316. if ( parent !== null ) {
  317. callback( parent );
  318. parent.traverseAncestors( callback );
  319. }
  320. }
  321. updateMatrix() {
  322. this.matrix.compose( this.position, this.quaternion, this.scale );
  323. this.matrixWorldNeedsUpdate = true;
  324. }
  325. updateMatrixWorld( force ) {
  326. if ( this.matrixAutoUpdate ) this.updateMatrix();
  327. if ( this.matrixWorldNeedsUpdate || force ) {
  328. if ( this.parent === null ) {
  329. this.matrixWorld.copy( this.matrix );
  330. } else {
  331. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  332. }
  333. this.matrixWorldNeedsUpdate = false;
  334. force = true;
  335. }
  336. // update children
  337. const children = this.children;
  338. for ( let i = 0, l = children.length; i < l; i ++ ) {
  339. const child = children[ i ];
  340. if ( child.matrixWorldAutoUpdate === true || force === true ) {
  341. child.updateMatrixWorld( force );
  342. }
  343. }
  344. }
  345. updateWorldMatrix( updateParents, updateChildren ) {
  346. const parent = this.parent;
  347. if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {
  348. parent.updateWorldMatrix( true, false );
  349. }
  350. if ( this.matrixAutoUpdate ) this.updateMatrix();
  351. if ( this.parent === null ) {
  352. this.matrixWorld.copy( this.matrix );
  353. } else {
  354. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  355. }
  356. // update children
  357. if ( updateChildren === true ) {
  358. const children = this.children;
  359. for ( let i = 0, l = children.length; i < l; i ++ ) {
  360. const child = children[ i ];
  361. if ( child.matrixWorldAutoUpdate === true ) {
  362. child.updateWorldMatrix( false, true );
  363. }
  364. }
  365. }
  366. }
  367. toJSON( meta ) {
  368. // meta is a string when called from JSON.stringify
  369. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  370. const output = {};
  371. // meta is a hash used to collect geometries, materials.
  372. // not providing it implies that this is the root object
  373. // being serialized.
  374. if ( isRootObject ) {
  375. // initialize meta obj
  376. meta = {
  377. geometries: {},
  378. materials: {},
  379. textures: {},
  380. images: {},
  381. shapes: {},
  382. skeletons: {},
  383. animations: {},
  384. nodes: {}
  385. };
  386. output.metadata = {
  387. version: 4.5,
  388. type: 'Object',
  389. generator: 'Object3D.toJSON'
  390. };
  391. }
  392. // standard Object3D serialization
  393. const object = {};
  394. object.uuid = this.uuid;
  395. object.type = this.type;
  396. if ( this.name !== '' ) object.name = this.name;
  397. if ( this.castShadow === true ) object.castShadow = true;
  398. if ( this.receiveShadow === true ) object.receiveShadow = true;
  399. if ( this.visible === false ) object.visible = false;
  400. if ( this.frustumCulled === false ) object.frustumCulled = false;
  401. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  402. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  403. object.layers = this.layers.mask;
  404. object.matrix = this.matrix.toArray();
  405. object.up = this.up.toArray();
  406. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  407. // object specific properties
  408. if ( this.isInstancedMesh ) {
  409. object.type = 'InstancedMesh';
  410. object.count = this.count;
  411. object.instanceMatrix = this.instanceMatrix.toJSON();
  412. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  413. }
  414. //
  415. function serialize( library, element ) {
  416. if ( library[ element.uuid ] === undefined ) {
  417. library[ element.uuid ] = element.toJSON( meta );
  418. }
  419. return element.uuid;
  420. }
  421. if ( this.isScene ) {
  422. if ( this.background ) {
  423. if ( this.background.isColor ) {
  424. object.background = this.background.toJSON();
  425. } else if ( this.background.isTexture ) {
  426. object.background = this.background.toJSON( meta ).uuid;
  427. }
  428. }
  429. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  430. object.environment = this.environment.toJSON( meta ).uuid;
  431. }
  432. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  433. object.geometry = serialize( meta.geometries, this.geometry );
  434. const parameters = this.geometry.parameters;
  435. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  436. const shapes = parameters.shapes;
  437. if ( Array.isArray( shapes ) ) {
  438. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  439. const shape = shapes[ i ];
  440. serialize( meta.shapes, shape );
  441. }
  442. } else {
  443. serialize( meta.shapes, shapes );
  444. }
  445. }
  446. }
  447. if ( this.isSkinnedMesh ) {
  448. object.bindMode = this.bindMode;
  449. object.bindMatrix = this.bindMatrix.toArray();
  450. if ( this.skeleton !== undefined ) {
  451. serialize( meta.skeletons, this.skeleton );
  452. object.skeleton = this.skeleton.uuid;
  453. }
  454. }
  455. if ( this.material !== undefined ) {
  456. if ( Array.isArray( this.material ) ) {
  457. const uuids = [];
  458. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  459. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  460. }
  461. object.material = uuids;
  462. } else {
  463. object.material = serialize( meta.materials, this.material );
  464. }
  465. }
  466. //
  467. if ( this.children.length > 0 ) {
  468. object.children = [];
  469. for ( let i = 0; i < this.children.length; i ++ ) {
  470. object.children.push( this.children[ i ].toJSON( meta ).object );
  471. }
  472. }
  473. //
  474. if ( this.animations.length > 0 ) {
  475. object.animations = [];
  476. for ( let i = 0; i < this.animations.length; i ++ ) {
  477. const animation = this.animations[ i ];
  478. object.animations.push( serialize( meta.animations, animation ) );
  479. }
  480. }
  481. if ( isRootObject ) {
  482. const geometries = extractFromCache( meta.geometries );
  483. const materials = extractFromCache( meta.materials );
  484. const textures = extractFromCache( meta.textures );
  485. const images = extractFromCache( meta.images );
  486. const shapes = extractFromCache( meta.shapes );
  487. const skeletons = extractFromCache( meta.skeletons );
  488. const animations = extractFromCache( meta.animations );
  489. const nodes = extractFromCache( meta.nodes );
  490. if ( geometries.length > 0 ) output.geometries = geometries;
  491. if ( materials.length > 0 ) output.materials = materials;
  492. if ( textures.length > 0 ) output.textures = textures;
  493. if ( images.length > 0 ) output.images = images;
  494. if ( shapes.length > 0 ) output.shapes = shapes;
  495. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  496. if ( animations.length > 0 ) output.animations = animations;
  497. if ( nodes.length > 0 ) output.nodes = nodes;
  498. }
  499. output.object = object;
  500. return output;
  501. // extract data from the cache hash
  502. // remove metadata on each item
  503. // and return as array
  504. function extractFromCache( cache ) {
  505. const values = [];
  506. for ( const key in cache ) {
  507. const data = cache[ key ];
  508. delete data.metadata;
  509. values.push( data );
  510. }
  511. return values;
  512. }
  513. }
  514. clone( recursive ) {
  515. return new this.constructor().copy( this, recursive );
  516. }
  517. copy( source, recursive = true ) {
  518. this.name = source.name;
  519. this.up.copy( source.up );
  520. this.position.copy( source.position );
  521. this.rotation.order = source.rotation.order;
  522. this.quaternion.copy( source.quaternion );
  523. this.scale.copy( source.scale );
  524. this.matrix.copy( source.matrix );
  525. this.matrixWorld.copy( source.matrixWorld );
  526. this.matrixAutoUpdate = source.matrixAutoUpdate;
  527. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  528. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  529. this.layers.mask = source.layers.mask;
  530. this.visible = source.visible;
  531. this.castShadow = source.castShadow;
  532. this.receiveShadow = source.receiveShadow;
  533. this.frustumCulled = source.frustumCulled;
  534. this.renderOrder = source.renderOrder;
  535. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  536. if ( recursive === true ) {
  537. for ( let i = 0; i < source.children.length; i ++ ) {
  538. const child = source.children[ i ];
  539. this.add( child.clone() );
  540. }
  541. }
  542. return this;
  543. }
  544. }
  545. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  546. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  547. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  548. export { Object3D };