MD2CharacterComplex.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. import {
  2. Box3,
  3. MathUtils,
  4. MeshLambertMaterial,
  5. Object3D,
  6. TextureLoader,
  7. UVMapping,
  8. SRGBColorSpace
  9. } from 'three';
  10. import { MD2Loader } from '../loaders/MD2Loader.js';
  11. import { MorphBlendMesh } from '../misc/MorphBlendMesh.js';
  12. /**
  13. * This class represents a management component for animated MD2
  14. * character assets. It provides a larger API compared to {@link MD2Character}.
  15. *
  16. * @three_import import { MD2CharacterComplex } from 'three/addons/misc/MD2CharacterComplex.js';
  17. */
  18. class MD2CharacterComplex {
  19. /**
  20. * Constructs a new MD2 character.
  21. */
  22. constructor() {
  23. /**
  24. * The mesh scale.
  25. *
  26. * @type {number}
  27. * @default 1
  28. */
  29. this.scale = 1;
  30. /**
  31. * The FPS
  32. *
  33. * @type {number}
  34. * @default 6
  35. */
  36. this.animationFPS = 6;
  37. /**
  38. * The transition frames.
  39. *
  40. * @type {number}
  41. * @default 15
  42. */
  43. this.transitionFrames = 15;
  44. /**
  45. * The character's maximum speed.
  46. *
  47. * @type {number}
  48. * @default 275
  49. */
  50. this.maxSpeed = 275;
  51. /**
  52. * The character's maximum reverse speed.
  53. *
  54. * @type {number}
  55. * @default - 275
  56. */
  57. this.maxReverseSpeed = - 275;
  58. /**
  59. * The character's front acceleration.
  60. *
  61. * @type {number}
  62. * @default 600
  63. */
  64. this.frontAcceleration = 600;
  65. /**
  66. * The character's back acceleration.
  67. *
  68. * @type {number}
  69. * @default 600
  70. */
  71. this.backAcceleration = 600;
  72. /**
  73. * The character's front deceleration.
  74. *
  75. * @type {number}
  76. * @default 600
  77. */
  78. this.frontDeceleration = 600;
  79. /**
  80. * The character's angular speed.
  81. *
  82. * @type {number}
  83. * @default 2.5
  84. */
  85. this.angularSpeed = 2.5;
  86. /**
  87. * The root 3D object
  88. *
  89. * @type {Object3D}
  90. */
  91. this.root = new Object3D();
  92. /**
  93. * The body mesh.
  94. *
  95. * @type {?Mesh}
  96. * @default null
  97. */
  98. this.meshBody = null;
  99. /**
  100. * The weapon mesh.
  101. *
  102. * @type {?Mesh}
  103. * @default null
  104. */
  105. this.meshWeapon = null;
  106. /**
  107. * The movement controls.
  108. *
  109. * @type {Object}
  110. * @default null
  111. */
  112. this.controls = null;
  113. /**
  114. * The body skins.
  115. *
  116. * @type {Array<Texture>}
  117. */
  118. this.skinsBody = [];
  119. /**
  120. * The weapon skins.
  121. *
  122. * @type {Array<Texture>}
  123. */
  124. this.skinsWeapon = [];
  125. /**
  126. * The weapon meshes.
  127. *
  128. * @type {Array<Mesh>}
  129. */
  130. this.weapons = [];
  131. /**
  132. * The current skin.
  133. *
  134. * @type {Texture}
  135. * @default undefined
  136. */
  137. this.currentSkin = undefined;
  138. //
  139. this.onLoadComplete = function () {};
  140. // internals
  141. this.meshes = [];
  142. this.animations = {};
  143. this.loadCounter = 0;
  144. // internal movement control variables
  145. this.speed = 0;
  146. this.bodyOrientation = 0;
  147. this.walkSpeed = this.maxSpeed;
  148. this.crouchSpeed = this.maxSpeed * 0.5;
  149. // internal animation parameters
  150. this.activeAnimation = null;
  151. this.oldAnimation = null;
  152. // API
  153. }
  154. /**
  155. * Toggles shadow casting and receiving on the character's meshes.
  156. *
  157. * @param {boolean} enable - Whether to enable shadows or not.
  158. */
  159. enableShadows( enable ) {
  160. for ( let i = 0; i < this.meshes.length; i ++ ) {
  161. this.meshes[ i ].castShadow = enable;
  162. this.meshes[ i ].receiveShadow = enable;
  163. }
  164. }
  165. /**
  166. * Toggles visibility on the character's meshes.
  167. *
  168. * @param {boolean} enable - Whether the character is visible or not.
  169. */
  170. setVisible( enable ) {
  171. for ( let i = 0; i < this.meshes.length; i ++ ) {
  172. this.meshes[ i ].visible = enable;
  173. this.meshes[ i ].visible = enable;
  174. }
  175. }
  176. /**
  177. * Shares certain resources from a different character model.
  178. *
  179. * @param {MD2CharacterComplex} original - The original MD2 character.
  180. */
  181. shareParts( original ) {
  182. this.animations = original.animations;
  183. this.walkSpeed = original.walkSpeed;
  184. this.crouchSpeed = original.crouchSpeed;
  185. this.skinsBody = original.skinsBody;
  186. this.skinsWeapon = original.skinsWeapon;
  187. // BODY
  188. const mesh = this._createPart( original.meshBody.geometry, this.skinsBody[ 0 ] );
  189. mesh.scale.set( this.scale, this.scale, this.scale );
  190. this.root.position.y = original.root.position.y;
  191. this.root.add( mesh );
  192. this.meshBody = mesh;
  193. this.meshes.push( mesh );
  194. // WEAPONS
  195. for ( let i = 0; i < original.weapons.length; i ++ ) {
  196. const meshWeapon = this._createPart( original.weapons[ i ].geometry, this.skinsWeapon[ i ] );
  197. meshWeapon.scale.set( this.scale, this.scale, this.scale );
  198. meshWeapon.visible = false;
  199. meshWeapon.name = original.weapons[ i ].name;
  200. this.root.add( meshWeapon );
  201. this.weapons[ i ] = meshWeapon;
  202. this.meshWeapon = meshWeapon;
  203. this.meshes.push( meshWeapon );
  204. }
  205. }
  206. /**
  207. * Loads the character model for the given config.
  208. *
  209. * @param {Object} config - The config which defines the model and textures paths.
  210. */
  211. loadParts( config ) {
  212. const scope = this;
  213. function loadTextures( baseUrl, textureUrls ) {
  214. const textureLoader = new TextureLoader();
  215. const textures = [];
  216. for ( let i = 0; i < textureUrls.length; i ++ ) {
  217. textures[ i ] = textureLoader.load( baseUrl + textureUrls[ i ], checkLoadingComplete );
  218. textures[ i ].mapping = UVMapping;
  219. textures[ i ].name = textureUrls[ i ];
  220. textures[ i ].colorSpace = SRGBColorSpace;
  221. }
  222. return textures;
  223. }
  224. function checkLoadingComplete() {
  225. scope.loadCounter -= 1;
  226. if ( scope.loadCounter === 0 ) scope.onLoadComplete();
  227. }
  228. this.animations = config.animations;
  229. this.walkSpeed = config.walkSpeed;
  230. this.crouchSpeed = config.crouchSpeed;
  231. this.loadCounter = config.weapons.length * 2 + config.skins.length + 1;
  232. const weaponsTextures = [];
  233. for ( let i = 0; i < config.weapons.length; i ++ ) weaponsTextures[ i ] = config.weapons[ i ][ 1 ];
  234. // SKINS
  235. this.skinsBody = loadTextures( config.baseUrl + 'skins/', config.skins );
  236. this.skinsWeapon = loadTextures( config.baseUrl + 'skins/', weaponsTextures );
  237. // BODY
  238. const loader = new MD2Loader();
  239. loader.load( config.baseUrl + config.body, function ( geo ) {
  240. const boundingBox = new Box3();
  241. boundingBox.setFromBufferAttribute( geo.attributes.position );
  242. scope.root.position.y = - scope.scale * boundingBox.min.y;
  243. const mesh = scope._createPart( geo, scope.skinsBody[ 0 ] );
  244. mesh.scale.set( scope.scale, scope.scale, scope.scale );
  245. scope.root.add( mesh );
  246. scope.meshBody = mesh;
  247. scope.meshes.push( mesh );
  248. checkLoadingComplete();
  249. } );
  250. // WEAPONS
  251. const generateCallback = function ( index, name ) {
  252. return function ( geo ) {
  253. const mesh = scope._createPart( geo, scope.skinsWeapon[ index ] );
  254. mesh.scale.set( scope.scale, scope.scale, scope.scale );
  255. mesh.visible = false;
  256. mesh.name = name;
  257. scope.root.add( mesh );
  258. scope.weapons[ index ] = mesh;
  259. scope.meshWeapon = mesh;
  260. scope.meshes.push( mesh );
  261. checkLoadingComplete();
  262. };
  263. };
  264. for ( let i = 0; i < config.weapons.length; i ++ ) {
  265. loader.load( config.baseUrl + config.weapons[ i ][ 0 ], generateCallback( i, config.weapons[ i ][ 0 ] ) );
  266. }
  267. }
  268. /**
  269. * Sets the animation playback rate.
  270. *
  271. * @param {number} rate - The playback rate to set.
  272. */
  273. setPlaybackRate( rate ) {
  274. if ( this.meshBody ) this.meshBody.duration = this.meshBody.baseDuration / rate;
  275. if ( this.meshWeapon ) this.meshWeapon.duration = this.meshWeapon.baseDuration / rate;
  276. }
  277. /**
  278. * Sets the wireframe material flag.
  279. *
  280. * @param {boolean} wireframeEnabled - Whether to enable wireframe rendering or not.
  281. */
  282. setWireframe( wireframeEnabled ) {
  283. if ( wireframeEnabled ) {
  284. if ( this.meshBody ) this.meshBody.material = this.meshBody.materialWireframe;
  285. if ( this.meshWeapon ) this.meshWeapon.material = this.meshWeapon.materialWireframe;
  286. } else {
  287. if ( this.meshBody ) this.meshBody.material = this.meshBody.materialTexture;
  288. if ( this.meshWeapon ) this.meshWeapon.material = this.meshWeapon.materialTexture;
  289. }
  290. }
  291. /**
  292. * Sets the skin defined by the given skin index. This will result in a different texture
  293. * for the body mesh.
  294. *
  295. * @param {number} index - The skin index.
  296. */
  297. setSkin( index ) {
  298. if ( this.meshBody && this.meshBody.material.wireframe === false ) {
  299. this.meshBody.material.map = this.skinsBody[ index ];
  300. this.currentSkin = index;
  301. }
  302. }
  303. /**
  304. * Sets the weapon defined by the given weapon index. This will result in a different weapon
  305. * hold by the character.
  306. *
  307. * @param {number} index - The weapon index.
  308. */
  309. setWeapon( index ) {
  310. for ( let i = 0; i < this.weapons.length; i ++ ) this.weapons[ i ].visible = false;
  311. const activeWeapon = this.weapons[ index ];
  312. if ( activeWeapon ) {
  313. activeWeapon.visible = true;
  314. this.meshWeapon = activeWeapon;
  315. if ( this.activeAnimation ) {
  316. activeWeapon.playAnimation( this.activeAnimation );
  317. this.meshWeapon.setAnimationTime( this.activeAnimation, this.meshBody.getAnimationTime( this.activeAnimation ) );
  318. }
  319. }
  320. }
  321. /**
  322. * Sets the defined animation clip as the active animation.
  323. *
  324. * @param {string} animationName - The name of the animation clip.
  325. */
  326. setAnimation( animationName ) {
  327. if ( animationName === this.activeAnimation || ! animationName ) return;
  328. if ( this.meshBody ) {
  329. this.meshBody.setAnimationWeight( animationName, 0 );
  330. this.meshBody.playAnimation( animationName );
  331. this.oldAnimation = this.activeAnimation;
  332. this.activeAnimation = animationName;
  333. this.blendCounter = this.transitionFrames;
  334. }
  335. if ( this.meshWeapon ) {
  336. this.meshWeapon.setAnimationWeight( animationName, 0 );
  337. this.meshWeapon.playAnimation( animationName );
  338. }
  339. }
  340. update( delta ) {
  341. if ( this.controls ) this.updateMovementModel( delta );
  342. if ( this.animations ) {
  343. this.updateBehaviors();
  344. this.updateAnimations( delta );
  345. }
  346. }
  347. /**
  348. * Updates the animations of the mesh. Must be called inside the animation loop.
  349. *
  350. * @param {number} delta - The delta time in seconds.
  351. */
  352. updateAnimations( delta ) {
  353. let mix = 1;
  354. if ( this.blendCounter > 0 ) {
  355. mix = ( this.transitionFrames - this.blendCounter ) / this.transitionFrames;
  356. this.blendCounter -= 1;
  357. }
  358. if ( this.meshBody ) {
  359. this.meshBody.update( delta );
  360. this.meshBody.setAnimationWeight( this.activeAnimation, mix );
  361. this.meshBody.setAnimationWeight( this.oldAnimation, 1 - mix );
  362. }
  363. if ( this.meshWeapon ) {
  364. this.meshWeapon.update( delta );
  365. this.meshWeapon.setAnimationWeight( this.activeAnimation, mix );
  366. this.meshWeapon.setAnimationWeight( this.oldAnimation, 1 - mix );
  367. }
  368. }
  369. /**
  370. * Updates the animation state based on the control inputs.
  371. */
  372. updateBehaviors() {
  373. const controls = this.controls;
  374. const animations = this.animations;
  375. let moveAnimation, idleAnimation;
  376. // crouch vs stand
  377. if ( controls.crouch ) {
  378. moveAnimation = animations[ 'crouchMove' ];
  379. idleAnimation = animations[ 'crouchIdle' ];
  380. } else {
  381. moveAnimation = animations[ 'move' ];
  382. idleAnimation = animations[ 'idle' ];
  383. }
  384. // actions
  385. if ( controls.jump ) {
  386. moveAnimation = animations[ 'jump' ];
  387. idleAnimation = animations[ 'jump' ];
  388. }
  389. if ( controls.attack ) {
  390. if ( controls.crouch ) {
  391. moveAnimation = animations[ 'crouchAttack' ];
  392. idleAnimation = animations[ 'crouchAttack' ];
  393. } else {
  394. moveAnimation = animations[ 'attack' ];
  395. idleAnimation = animations[ 'attack' ];
  396. }
  397. }
  398. // set animations
  399. if ( controls.moveForward || controls.moveBackward || controls.moveLeft || controls.moveRight ) {
  400. if ( this.activeAnimation !== moveAnimation ) {
  401. this.setAnimation( moveAnimation );
  402. }
  403. }
  404. if ( Math.abs( this.speed ) < 0.2 * this.maxSpeed && ! ( controls.moveLeft || controls.moveRight || controls.moveForward || controls.moveBackward ) ) {
  405. if ( this.activeAnimation !== idleAnimation ) {
  406. this.setAnimation( idleAnimation );
  407. }
  408. }
  409. // set animation direction
  410. if ( controls.moveForward ) {
  411. if ( this.meshBody ) {
  412. this.meshBody.setAnimationDirectionForward( this.activeAnimation );
  413. this.meshBody.setAnimationDirectionForward( this.oldAnimation );
  414. }
  415. if ( this.meshWeapon ) {
  416. this.meshWeapon.setAnimationDirectionForward( this.activeAnimation );
  417. this.meshWeapon.setAnimationDirectionForward( this.oldAnimation );
  418. }
  419. }
  420. if ( controls.moveBackward ) {
  421. if ( this.meshBody ) {
  422. this.meshBody.setAnimationDirectionBackward( this.activeAnimation );
  423. this.meshBody.setAnimationDirectionBackward( this.oldAnimation );
  424. }
  425. if ( this.meshWeapon ) {
  426. this.meshWeapon.setAnimationDirectionBackward( this.activeAnimation );
  427. this.meshWeapon.setAnimationDirectionBackward( this.oldAnimation );
  428. }
  429. }
  430. }
  431. /**
  432. * Transforms the character model based on the control input.
  433. *
  434. * @param {number} delta - The delta time in seconds.
  435. */
  436. updateMovementModel( delta ) {
  437. function exponentialEaseOut( k ) {
  438. return k === 1 ? 1 : - Math.pow( 2, - 10 * k ) + 1;
  439. }
  440. const controls = this.controls;
  441. // speed based on controls
  442. if ( controls.crouch ) this.maxSpeed = this.crouchSpeed;
  443. else this.maxSpeed = this.walkSpeed;
  444. this.maxReverseSpeed = - this.maxSpeed;
  445. if ( controls.moveForward ) this.speed = MathUtils.clamp( this.speed + delta * this.frontAcceleration, this.maxReverseSpeed, this.maxSpeed );
  446. if ( controls.moveBackward ) this.speed = MathUtils.clamp( this.speed - delta * this.backAcceleration, this.maxReverseSpeed, this.maxSpeed );
  447. // orientation based on controls
  448. // (don't just stand while turning)
  449. const dir = 1;
  450. if ( controls.moveLeft ) {
  451. this.bodyOrientation += delta * this.angularSpeed;
  452. this.speed = MathUtils.clamp( this.speed + dir * delta * this.frontAcceleration, this.maxReverseSpeed, this.maxSpeed );
  453. }
  454. if ( controls.moveRight ) {
  455. this.bodyOrientation -= delta * this.angularSpeed;
  456. this.speed = MathUtils.clamp( this.speed + dir * delta * this.frontAcceleration, this.maxReverseSpeed, this.maxSpeed );
  457. }
  458. // speed decay
  459. if ( ! ( controls.moveForward || controls.moveBackward ) ) {
  460. if ( this.speed > 0 ) {
  461. const k = exponentialEaseOut( this.speed / this.maxSpeed );
  462. this.speed = MathUtils.clamp( this.speed - k * delta * this.frontDeceleration, 0, this.maxSpeed );
  463. } else {
  464. const k = exponentialEaseOut( this.speed / this.maxReverseSpeed );
  465. this.speed = MathUtils.clamp( this.speed + k * delta * this.backAcceleration, this.maxReverseSpeed, 0 );
  466. }
  467. }
  468. // displacement
  469. const forwardDelta = this.speed * delta;
  470. this.root.position.x += Math.sin( this.bodyOrientation ) * forwardDelta;
  471. this.root.position.z += Math.cos( this.bodyOrientation ) * forwardDelta;
  472. // steering
  473. this.root.rotation.y = this.bodyOrientation;
  474. }
  475. // internal
  476. _createPart( geometry, skinMap ) {
  477. const materialWireframe = new MeshLambertMaterial( { color: 0xffaa00, wireframe: true } );
  478. const materialTexture = new MeshLambertMaterial( { color: 0xffffff, wireframe: false, map: skinMap } );
  479. //
  480. const mesh = new MorphBlendMesh( geometry, materialTexture );
  481. mesh.rotation.y = - Math.PI / 2;
  482. //
  483. mesh.materialTexture = materialTexture;
  484. mesh.materialWireframe = materialWireframe;
  485. //
  486. mesh.autoCreateAnimations( this.animationFPS );
  487. return mesh;
  488. }
  489. }
  490. export { MD2CharacterComplex };