Object3D.js 16 KB

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