Object3D.js 16 KB

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