MMDLoader.js 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067
  1. import {
  2. AddOperation,
  3. AnimationClip,
  4. Bone,
  5. BufferGeometry,
  6. Color,
  7. CustomBlending,
  8. DoubleSide,
  9. DstAlphaFactor,
  10. Euler,
  11. FileLoader,
  12. Float32BufferAttribute,
  13. FrontSide,
  14. Interpolant,
  15. Loader,
  16. LoaderUtils,
  17. MeshToonMaterial,
  18. MultiplyOperation,
  19. NearestFilter,
  20. NumberKeyframeTrack,
  21. OneMinusSrcAlphaFactor,
  22. Quaternion,
  23. QuaternionKeyframeTrack,
  24. RepeatWrapping,
  25. Skeleton,
  26. SkinnedMesh,
  27. SrcAlphaFactor,
  28. TextureLoader,
  29. Uint16BufferAttribute,
  30. Vector3,
  31. VectorKeyframeTrack,
  32. RGB_S3TC_DXT1_Format,
  33. RGB_PVRTC_4BPPV1_Format,
  34. RGB_PVRTC_2BPPV1_Format,
  35. RGB_ETC1_Format,
  36. RGB_ETC2_Format
  37. } from '../../../build/three.module.js';
  38. import { TGALoader } from '../loaders/TGALoader.js';
  39. import { MMDParser } from '../libs/mmdparser.module.js';
  40. /**
  41. * Dependencies
  42. * - mmd-parser https://github.com/takahirox/mmd-parser
  43. * - TGALoader
  44. * - OutlineEffect
  45. *
  46. * MMDLoader creates Three.js Objects from MMD resources as
  47. * PMD, PMX, VMD, and VPD files.
  48. *
  49. * PMD/PMX is a model data format, VMD is a motion data format
  50. * VPD is a posing data format used in MMD(Miku Miku Dance).
  51. *
  52. * MMD official site
  53. * - https://sites.google.com/view/evpvp/
  54. *
  55. * PMD, VMD format (in Japanese)
  56. * - http://blog.goo.ne.jp/torisu_tetosuki/e/209ad341d3ece2b1b4df24abf619d6e4
  57. *
  58. * PMX format
  59. * - https://gist.github.com/felixjones/f8a06bd48f9da9a4539f
  60. *
  61. * TODO
  62. * - light motion in vmd support.
  63. * - SDEF support.
  64. * - uv/material/bone morphing support.
  65. * - more precise grant skinning support.
  66. * - shadow support.
  67. */
  68. /**
  69. * @param {THREE.LoadingManager} manager
  70. */
  71. class MMDLoader extends Loader {
  72. constructor( manager ) {
  73. super( manager );
  74. this.loader = new FileLoader( this.manager );
  75. this.parser = null; // lazy generation
  76. this.meshBuilder = new MeshBuilder( this.manager );
  77. this.animationBuilder = new AnimationBuilder();
  78. }
  79. /**
  80. * @param {string} animationPath
  81. * @return {MMDLoader}
  82. */
  83. setAnimationPath( animationPath ) {
  84. this.animationPath = animationPath;
  85. return this;
  86. }
  87. // Load MMD assets as Three.js Object
  88. /**
  89. * Loads Model file (.pmd or .pmx) as a SkinnedMesh.
  90. *
  91. * @param {string} url - url to Model(.pmd or .pmx) file
  92. * @param {function} onLoad
  93. * @param {function} onProgress
  94. * @param {function} onError
  95. */
  96. load( url, onLoad, onProgress, onError ) {
  97. const builder = this.meshBuilder.setCrossOrigin( this.crossOrigin );
  98. // resource path
  99. let resourcePath;
  100. if ( this.resourcePath !== '' ) {
  101. resourcePath = this.resourcePath;
  102. } else if ( this.path !== '' ) {
  103. resourcePath = this.path;
  104. } else {
  105. resourcePath = LoaderUtils.extractUrlBase( url );
  106. }
  107. const modelExtension = this._extractExtension( url ).toLowerCase();
  108. // Should I detect by seeing header?
  109. if ( modelExtension !== 'pmd' && modelExtension !== 'pmx' ) {
  110. if ( onError ) onError( new Error( 'THREE.MMDLoader: Unknown model file extension .' + modelExtension + '.' ) );
  111. return;
  112. }
  113. this[ modelExtension === 'pmd' ? 'loadPMD' : 'loadPMX' ]( url, function ( data ) {
  114. onLoad( builder.build( data, resourcePath, onProgress, onError ) );
  115. }, onProgress, onError );
  116. }
  117. /**
  118. * Loads Motion file(s) (.vmd) as a AnimationClip.
  119. * If two or more files are specified, they'll be merged.
  120. *
  121. * @param {string|Array<string>} url - url(s) to animation(.vmd) file(s)
  122. * @param {SkinnedMesh|THREE.Camera} object - tracks will be fitting to this object
  123. * @param {function} onLoad
  124. * @param {function} onProgress
  125. * @param {function} onError
  126. */
  127. loadAnimation( url, object, onLoad, onProgress, onError ) {
  128. const builder = this.animationBuilder;
  129. this.loadVMD( url, function ( vmd ) {
  130. onLoad( object.isCamera
  131. ? builder.buildCameraAnimation( vmd )
  132. : builder.build( vmd, object ) );
  133. }, onProgress, onError );
  134. }
  135. /**
  136. * Loads mode file and motion file(s) as an object containing
  137. * a SkinnedMesh and a AnimationClip.
  138. * Tracks of AnimationClip are fitting to the model.
  139. *
  140. * @param {string} modelUrl - url to Model(.pmd or .pmx) file
  141. * @param {string|Array{string}} vmdUrl - url(s) to animation(.vmd) file
  142. * @param {function} onLoad
  143. * @param {function} onProgress
  144. * @param {function} onError
  145. */
  146. loadWithAnimation( modelUrl, vmdUrl, onLoad, onProgress, onError ) {
  147. const scope = this;
  148. this.load( modelUrl, function ( mesh ) {
  149. scope.loadAnimation( vmdUrl, mesh, function ( animation ) {
  150. onLoad( {
  151. mesh: mesh,
  152. animation: animation
  153. } );
  154. }, onProgress, onError );
  155. }, onProgress, onError );
  156. }
  157. // Load MMD assets as Object data parsed by MMDParser
  158. /**
  159. * Loads .pmd file as an Object.
  160. *
  161. * @param {string} url - url to .pmd file
  162. * @param {function} onLoad
  163. * @param {function} onProgress
  164. * @param {function} onError
  165. */
  166. loadPMD( url, onLoad, onProgress, onError ) {
  167. const parser = this._getParser();
  168. this.loader
  169. .setMimeType( undefined )
  170. .setPath( this.path )
  171. .setResponseType( 'arraybuffer' )
  172. .setRequestHeader( this.requestHeader )
  173. .setWithCredentials( this.withCredentials )
  174. .load( url, function ( buffer ) {
  175. onLoad( parser.parsePmd( buffer, true ) );
  176. }, onProgress, onError );
  177. }
  178. /**
  179. * Loads .pmx file as an Object.
  180. *
  181. * @param {string} url - url to .pmx file
  182. * @param {function} onLoad
  183. * @param {function} onProgress
  184. * @param {function} onError
  185. */
  186. loadPMX( url, onLoad, onProgress, onError ) {
  187. const parser = this._getParser();
  188. this.loader
  189. .setMimeType( undefined )
  190. .setPath( this.path )
  191. .setResponseType( 'arraybuffer' )
  192. .setRequestHeader( this.requestHeader )
  193. .setWithCredentials( this.withCredentials )
  194. .load( url, function ( buffer ) {
  195. onLoad( parser.parsePmx( buffer, true ) );
  196. }, onProgress, onError );
  197. }
  198. /**
  199. * Loads .vmd file as an Object. If two or more files are specified
  200. * they'll be merged.
  201. *
  202. * @param {string|Array<string>} url - url(s) to .vmd file(s)
  203. * @param {function} onLoad
  204. * @param {function} onProgress
  205. * @param {function} onError
  206. */
  207. loadVMD( url, onLoad, onProgress, onError ) {
  208. const urls = Array.isArray( url ) ? url : [ url ];
  209. const vmds = [];
  210. const vmdNum = urls.length;
  211. const parser = this._getParser();
  212. this.loader
  213. .setMimeType( undefined )
  214. .setPath( this.animationPath )
  215. .setResponseType( 'arraybuffer' )
  216. .setRequestHeader( this.requestHeader )
  217. .setWithCredentials( this.withCredentials );
  218. for ( let i = 0, il = urls.length; i < il; i ++ ) {
  219. this.loader.load( urls[ i ], function ( buffer ) {
  220. vmds.push( parser.parseVmd( buffer, true ) );
  221. if ( vmds.length === vmdNum ) onLoad( parser.mergeVmds( vmds ) );
  222. }, onProgress, onError );
  223. }
  224. }
  225. /**
  226. * Loads .vpd file as an Object.
  227. *
  228. * @param {string} url - url to .vpd file
  229. * @param {boolean} isUnicode
  230. * @param {function} onLoad
  231. * @param {function} onProgress
  232. * @param {function} onError
  233. */
  234. loadVPD( url, isUnicode, onLoad, onProgress, onError ) {
  235. const parser = this._getParser();
  236. this.loader
  237. .setMimeType( isUnicode ? undefined : 'text/plain; charset=shift_jis' )
  238. .setPath( this.animationPath )
  239. .setResponseType( 'text' )
  240. .setRequestHeader( this.requestHeader )
  241. .setWithCredentials( this.withCredentials )
  242. .load( url, function ( text ) {
  243. onLoad( parser.parseVpd( text, true ) );
  244. }, onProgress, onError );
  245. }
  246. // private methods
  247. _extractExtension( url ) {
  248. const index = url.lastIndexOf( '.' );
  249. return index < 0 ? '' : url.slice( index + 1 );
  250. }
  251. _getParser() {
  252. if ( this.parser === null ) {
  253. if ( typeof MMDParser === 'undefined' ) {
  254. throw new Error( 'THREE.MMDLoader: Import MMDParser https://github.com/takahirox/mmd-parser' );
  255. }
  256. this.parser = new MMDParser.Parser(); // eslint-disable-line no-undef
  257. }
  258. return this.parser;
  259. }
  260. }
  261. // Utilities
  262. /*
  263. * base64 encoded defalut toon textures toon00.bmp - toon10.bmp.
  264. * We don't need to request external toon image files.
  265. * This idea is from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mmd.three.js
  266. */
  267. const DEFAULT_TOON_TEXTURES = [
  268. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=',
  269. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAN0lEQVRYR+3WQREAMBACsZ5/bWiiMvgEBTt5cW37hjsBBAgQIECAwFwgyfYPCCBAgAABAgTWAh8aBHZBl14e8wAAAABJRU5ErkJggg==',
  270. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAOUlEQVRYR+3WMREAMAwDsYY/yoDI7MLwIiP40+RJklfcCCBAgAABAgTqArfb/QMCCBAgQIAAgbbAB3z/e0F3js2cAAAAAElFTkSuQmCC',
  271. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAN0lEQVRYR+3WQREAMBACsZ5/B5ilMvgEBTt5cW37hjsBBAgQIECAwFwgyfYPCCBAgAABAgTWAh81dWyx0gFwKAAAAABJRU5ErkJggg==',
  272. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAOklEQVRYR+3WoREAMAwDsWb/UQtCy9wxTOQJ/oQ8SXKKGwEECBAgQIBAXeDt7f4BAQQIECBAgEBb4AOz8Hzx7WLY4wAAAABJRU5ErkJggg==',
  273. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABPUlEQVRYR+1XwW7CMAy1+f9fZOMysSEOEweEOPRNdm3HbdOyIhAcklPrOs/PLy9RygBALxzcCDQFmgJNgaZAU6Ap0BR4PwX8gsRMVLssMRH5HcpzJEaWL7EVg9F1IHRlyqQohgVr4FGUlUcMJSjcUlDw0zvjeun70cLWmneoyf7NgBTQSniBTQQSuJAZsOnnaczjIMb5hCiuHKxokCrJfVnrctyZL0PkJAJe1HMil4nxeyi3Ypfn1kX51jpPvo/JeCNC4PhVdHdJw2XjBR8brF8PEIhNVn12AgP7uHsTBguBn53MUZCqv7Lp07Pn5k1Ro+uWmUNn7D+M57rtk7aG0Vo73xyF/fbFf0bPJjDXngnGocDTdFhygZjwUQrMNrDcmZlQT50VJ/g/UwNyHpu778+yW+/ksOz/BFo54P4AsUXMfRq7XWsAAAAASUVORK5CYII=',
  274. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACMElEQVRYR+2Xv4pTQRTGf2dubhLdICiii2KnYKHVolhauKWPoGAnNr6BD6CvIVaihYuI2i1ia0BY0MZGRHQXjZj/mSPnnskfNWiWZUlzJ5k7M2cm833nO5Mziej2DWWJRUoCpQKlAntSQCqgw39/iUWAGmh37jrRnVsKlgpiqmkoGVABA7E57fvY+pJDdgKqF6HzFCSADkDq+F6AHABtQ+UMVE5D7zXod7fFNhTEckTbj5XQgHzNN+5tQvc5NG7C6BNkp6D3EmpXHDR+dQAjFLchW3VS9rlw3JBh+B7ys5Cf9z0GW1C/7P32AyBAOAz1q4jGliIH3YPuBnSfQX4OGreTIgEYQb/pBDtPnEQ4CivXYPAWBk13oHrB54yA9QuSn2H4AcKRpEILDt0BUzj+RLR1V5EqjD66NPRBVpLcQwjHoHYJOhsQv6U4mnzmrIXJCFr4LDwm/xBUoboG9XX4cc9VKdYoSA2yk5NQLJaKDUjTBoveG3Z2TElTxwjNK4M3LEZgUdDdruvcXzKBpStgp2NPiWi3ks9ZXxIoFVi+AvHLdc9TqtjL3/aYjpPlrzOcEnK62Szhimdd7xX232zFDTgtxezOu3WNMRLjiKgjtOhHVMd1loynVHvOgjuIIJMaELEqhJAV/RCSLbWTcfPFakFgFlALTRRvx+ok6Hlp/Q+v3fmx90bMyUzaEAhmM3KvHlXTL5DxnbGf/1M8RNNACLL5MNtPxP/mypJAqcDSFfgFhpYqWUzhTEAAAAAASUVORK5CYII=',
  275. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=',
  276. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=',
  277. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=',
  278. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII='
  279. ];
  280. const NON_ALPHA_CHANNEL_FORMATS = [
  281. RGB_S3TC_DXT1_Format,
  282. RGB_PVRTC_4BPPV1_Format,
  283. RGB_PVRTC_2BPPV1_Format,
  284. RGB_ETC1_Format,
  285. RGB_ETC2_Format
  286. ];
  287. // Builders. They build Three.js object from Object data parsed by MMDParser.
  288. /**
  289. * @param {THREE.LoadingManager} manager
  290. */
  291. class MeshBuilder {
  292. constructor( manager ) {
  293. this.crossOrigin = 'anonymous';
  294. this.geometryBuilder = new GeometryBuilder();
  295. this.materialBuilder = new MaterialBuilder( manager );
  296. }
  297. /**
  298. * @param {string} crossOrigin
  299. * @return {MeshBuilder}
  300. */
  301. setCrossOrigin( crossOrigin ) {
  302. this.crossOrigin = crossOrigin;
  303. return this;
  304. }
  305. /**
  306. * @param {Object} data - parsed PMD/PMX data
  307. * @param {string} resourcePath
  308. * @param {function} onProgress
  309. * @param {function} onError
  310. * @return {SkinnedMesh}
  311. */
  312. build( data, resourcePath, onProgress, onError ) {
  313. const geometry = this.geometryBuilder.build( data );
  314. const material = this.materialBuilder
  315. .setCrossOrigin( this.crossOrigin )
  316. .setResourcePath( resourcePath )
  317. .build( data, geometry, onProgress, onError );
  318. const mesh = new SkinnedMesh( geometry, material );
  319. const skeleton = new Skeleton( initBones( mesh ) );
  320. mesh.bind( skeleton );
  321. // console.log( mesh ); // for console debug
  322. return mesh;
  323. }
  324. }
  325. // TODO: Try to remove this function
  326. function initBones( mesh ) {
  327. const geometry = mesh.geometry;
  328. const bones = [];
  329. if ( geometry && geometry.bones !== undefined ) {
  330. // first, create array of 'Bone' objects from geometry data
  331. for ( let i = 0, il = geometry.bones.length; i < il; i ++ ) {
  332. const gbone = geometry.bones[ i ];
  333. // create new 'Bone' object
  334. const bone = new Bone();
  335. bones.push( bone );
  336. // apply values
  337. bone.name = gbone.name;
  338. bone.position.fromArray( gbone.pos );
  339. bone.quaternion.fromArray( gbone.rotq );
  340. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  341. }
  342. // second, create bone hierarchy
  343. for ( let i = 0, il = geometry.bones.length; i < il; i ++ ) {
  344. const gbone = geometry.bones[ i ];
  345. if ( ( gbone.parent !== - 1 ) && ( gbone.parent !== null ) && ( bones[ gbone.parent ] !== undefined ) ) {
  346. // subsequent bones in the hierarchy
  347. bones[ gbone.parent ].add( bones[ i ] );
  348. } else {
  349. // topmost bone, immediate child of the skinned mesh
  350. mesh.add( bones[ i ] );
  351. }
  352. }
  353. }
  354. // now the bones are part of the scene graph and children of the skinned mesh.
  355. // let's update the corresponding matrices
  356. mesh.updateMatrixWorld( true );
  357. return bones;
  358. }
  359. //
  360. class GeometryBuilder {
  361. /**
  362. * @param {Object} data - parsed PMD/PMX data
  363. * @return {BufferGeometry}
  364. */
  365. build( data ) {
  366. // for geometry
  367. const positions = [];
  368. const uvs = [];
  369. const normals = [];
  370. const indices = [];
  371. const groups = [];
  372. const bones = [];
  373. const skinIndices = [];
  374. const skinWeights = [];
  375. const morphTargets = [];
  376. const morphPositions = [];
  377. const iks = [];
  378. const grants = [];
  379. const rigidBodies = [];
  380. const constraints = [];
  381. // for work
  382. let offset = 0;
  383. const boneTypeTable = {};
  384. // positions, normals, uvs, skinIndices, skinWeights
  385. for ( let i = 0; i < data.metadata.vertexCount; i ++ ) {
  386. const v = data.vertices[ i ];
  387. for ( let j = 0, jl = v.position.length; j < jl; j ++ ) {
  388. positions.push( v.position[ j ] );
  389. }
  390. for ( let j = 0, jl = v.normal.length; j < jl; j ++ ) {
  391. normals.push( v.normal[ j ] );
  392. }
  393. for ( let j = 0, jl = v.uv.length; j < jl; j ++ ) {
  394. uvs.push( v.uv[ j ] );
  395. }
  396. for ( let j = 0; j < 4; j ++ ) {
  397. skinIndices.push( v.skinIndices.length - 1 >= j ? v.skinIndices[ j ] : 0.0 );
  398. }
  399. for ( let j = 0; j < 4; j ++ ) {
  400. skinWeights.push( v.skinWeights.length - 1 >= j ? v.skinWeights[ j ] : 0.0 );
  401. }
  402. }
  403. // indices
  404. for ( let i = 0; i < data.metadata.faceCount; i ++ ) {
  405. const face = data.faces[ i ];
  406. for ( let j = 0, jl = face.indices.length; j < jl; j ++ ) {
  407. indices.push( face.indices[ j ] );
  408. }
  409. }
  410. // groups
  411. for ( let i = 0; i < data.metadata.materialCount; i ++ ) {
  412. const material = data.materials[ i ];
  413. groups.push( {
  414. offset: offset * 3,
  415. count: material.faceCount * 3
  416. } );
  417. offset += material.faceCount;
  418. }
  419. // bones
  420. for ( let i = 0; i < data.metadata.rigidBodyCount; i ++ ) {
  421. const body = data.rigidBodies[ i ];
  422. let value = boneTypeTable[ body.boneIndex ];
  423. // keeps greater number if already value is set without any special reasons
  424. value = value === undefined ? body.type : Math.max( body.type, value );
  425. boneTypeTable[ body.boneIndex ] = value;
  426. }
  427. for ( let i = 0; i < data.metadata.boneCount; i ++ ) {
  428. const boneData = data.bones[ i ];
  429. const bone = {
  430. index: i,
  431. transformationClass: boneData.transformationClass,
  432. parent: boneData.parentIndex,
  433. name: boneData.name,
  434. pos: boneData.position.slice( 0, 3 ),
  435. rotq: [ 0, 0, 0, 1 ],
  436. scl: [ 1, 1, 1 ],
  437. rigidBodyType: boneTypeTable[ i ] !== undefined ? boneTypeTable[ i ] : - 1
  438. };
  439. if ( bone.parent !== - 1 ) {
  440. bone.pos[ 0 ] -= data.bones[ bone.parent ].position[ 0 ];
  441. bone.pos[ 1 ] -= data.bones[ bone.parent ].position[ 1 ];
  442. bone.pos[ 2 ] -= data.bones[ bone.parent ].position[ 2 ];
  443. }
  444. bones.push( bone );
  445. }
  446. // iks
  447. // TODO: remove duplicated codes between PMD and PMX
  448. if ( data.metadata.format === 'pmd' ) {
  449. for ( let i = 0; i < data.metadata.ikCount; i ++ ) {
  450. const ik = data.iks[ i ];
  451. const param = {
  452. target: ik.target,
  453. effector: ik.effector,
  454. iteration: ik.iteration,
  455. maxAngle: ik.maxAngle * 4,
  456. links: []
  457. };
  458. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  459. const link = {};
  460. link.index = ik.links[ j ].index;
  461. link.enabled = true;
  462. if ( data.bones[ link.index ].name.indexOf( 'ひざ' ) >= 0 ) {
  463. link.limitation = new Vector3( 1.0, 0.0, 0.0 );
  464. }
  465. param.links.push( link );
  466. }
  467. iks.push( param );
  468. }
  469. } else {
  470. for ( let i = 0; i < data.metadata.boneCount; i ++ ) {
  471. const ik = data.bones[ i ].ik;
  472. if ( ik === undefined ) continue;
  473. const param = {
  474. target: i,
  475. effector: ik.effector,
  476. iteration: ik.iteration,
  477. maxAngle: ik.maxAngle,
  478. links: []
  479. };
  480. for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) {
  481. const link = {};
  482. link.index = ik.links[ j ].index;
  483. link.enabled = true;
  484. if ( ik.links[ j ].angleLimitation === 1 ) {
  485. // Revert if rotationMin/Max doesn't work well
  486. // link.limitation = new Vector3( 1.0, 0.0, 0.0 );
  487. const rotationMin = ik.links[ j ].lowerLimitationAngle;
  488. const rotationMax = ik.links[ j ].upperLimitationAngle;
  489. // Convert Left to Right coordinate by myself because
  490. // MMDParser doesn't convert. It's a MMDParser's bug
  491. const tmp1 = - rotationMax[ 0 ];
  492. const tmp2 = - rotationMax[ 1 ];
  493. rotationMax[ 0 ] = - rotationMin[ 0 ];
  494. rotationMax[ 1 ] = - rotationMin[ 1 ];
  495. rotationMin[ 0 ] = tmp1;
  496. rotationMin[ 1 ] = tmp2;
  497. link.rotationMin = new Vector3().fromArray( rotationMin );
  498. link.rotationMax = new Vector3().fromArray( rotationMax );
  499. }
  500. param.links.push( link );
  501. }
  502. iks.push( param );
  503. // Save the reference even from bone data for efficiently
  504. // simulating PMX animation system
  505. bones[ i ].ik = param;
  506. }
  507. }
  508. // grants
  509. if ( data.metadata.format === 'pmx' ) {
  510. // bone index -> grant entry map
  511. const grantEntryMap = {};
  512. for ( let i = 0; i < data.metadata.boneCount; i ++ ) {
  513. const boneData = data.bones[ i ];
  514. const grant = boneData.grant;
  515. if ( grant === undefined ) continue;
  516. const param = {
  517. index: i,
  518. parentIndex: grant.parentIndex,
  519. ratio: grant.ratio,
  520. isLocal: grant.isLocal,
  521. affectRotation: grant.affectRotation,
  522. affectPosition: grant.affectPosition,
  523. transformationClass: boneData.transformationClass
  524. };
  525. grantEntryMap[ i ] = { parent: null, children: [], param: param, visited: false };
  526. }
  527. const rootEntry = { parent: null, children: [], param: null, visited: false };
  528. // Build a tree representing grant hierarchy
  529. for ( const boneIndex in grantEntryMap ) {
  530. const grantEntry = grantEntryMap[ boneIndex ];
  531. const parentGrantEntry = grantEntryMap[ grantEntry.parentIndex ] || rootEntry;
  532. grantEntry.parent = parentGrantEntry;
  533. parentGrantEntry.children.push( grantEntry );
  534. }
  535. // Sort grant parameters from parents to children because
  536. // grant uses parent's transform that parent's grant is already applied
  537. // so grant should be applied in order from parents to children
  538. function traverse( entry ) {
  539. if ( entry.param ) {
  540. grants.push( entry.param );
  541. // Save the reference even from bone data for efficiently
  542. // simulating PMX animation system
  543. bones[ entry.param.index ].grant = entry.param;
  544. }
  545. entry.visited = true;
  546. for ( let i = 0, il = entry.children.length; i < il; i ++ ) {
  547. const child = entry.children[ i ];
  548. // Cut off a loop if exists. (Is a grant loop invalid?)
  549. if ( ! child.visited ) traverse( child );
  550. }
  551. }
  552. traverse( rootEntry );
  553. }
  554. // morph
  555. function updateAttributes( attribute, morph, ratio ) {
  556. for ( let i = 0; i < morph.elementCount; i ++ ) {
  557. const element = morph.elements[ i ];
  558. let index;
  559. if ( data.metadata.format === 'pmd' ) {
  560. index = data.morphs[ 0 ].elements[ element.index ].index;
  561. } else {
  562. index = element.index;
  563. }
  564. attribute.array[ index * 3 + 0 ] += element.position[ 0 ] * ratio;
  565. attribute.array[ index * 3 + 1 ] += element.position[ 1 ] * ratio;
  566. attribute.array[ index * 3 + 2 ] += element.position[ 2 ] * ratio;
  567. }
  568. }
  569. for ( let i = 0; i < data.metadata.morphCount; i ++ ) {
  570. const morph = data.morphs[ i ];
  571. const params = { name: morph.name };
  572. const attribute = new Float32BufferAttribute( data.metadata.vertexCount * 3, 3 );
  573. attribute.name = morph.name;
  574. for ( let j = 0; j < data.metadata.vertexCount * 3; j ++ ) {
  575. attribute.array[ j ] = positions[ j ];
  576. }
  577. if ( data.metadata.format === 'pmd' ) {
  578. if ( i !== 0 ) {
  579. updateAttributes( attribute, morph, 1.0 );
  580. }
  581. } else {
  582. if ( morph.type === 0 ) { // group
  583. for ( let j = 0; j < morph.elementCount; j ++ ) {
  584. const morph2 = data.morphs[ morph.elements[ j ].index ];
  585. const ratio = morph.elements[ j ].ratio;
  586. if ( morph2.type === 1 ) {
  587. updateAttributes( attribute, morph2, ratio );
  588. } else {
  589. // TODO: implement
  590. }
  591. }
  592. } else if ( morph.type === 1 ) { // vertex
  593. updateAttributes( attribute, morph, 1.0 );
  594. } else if ( morph.type === 2 ) { // bone
  595. // TODO: implement
  596. } else if ( morph.type === 3 ) { // uv
  597. // TODO: implement
  598. } else if ( morph.type === 4 ) { // additional uv1
  599. // TODO: implement
  600. } else if ( morph.type === 5 ) { // additional uv2
  601. // TODO: implement
  602. } else if ( morph.type === 6 ) { // additional uv3
  603. // TODO: implement
  604. } else if ( morph.type === 7 ) { // additional uv4
  605. // TODO: implement
  606. } else if ( morph.type === 8 ) { // material
  607. // TODO: implement
  608. }
  609. }
  610. morphTargets.push( params );
  611. morphPositions.push( attribute );
  612. }
  613. // rigid bodies from rigidBodies field.
  614. for ( let i = 0; i < data.metadata.rigidBodyCount; i ++ ) {
  615. const rigidBody = data.rigidBodies[ i ];
  616. const params = {};
  617. for ( const key in rigidBody ) {
  618. params[ key ] = rigidBody[ key ];
  619. }
  620. /*
  621. * RigidBody position parameter in PMX seems global position
  622. * while the one in PMD seems offset from corresponding bone.
  623. * So unify being offset.
  624. */
  625. if ( data.metadata.format === 'pmx' ) {
  626. if ( params.boneIndex !== - 1 ) {
  627. const bone = data.bones[ params.boneIndex ];
  628. params.position[ 0 ] -= bone.position[ 0 ];
  629. params.position[ 1 ] -= bone.position[ 1 ];
  630. params.position[ 2 ] -= bone.position[ 2 ];
  631. }
  632. }
  633. rigidBodies.push( params );
  634. }
  635. // constraints from constraints field.
  636. for ( let i = 0; i < data.metadata.constraintCount; i ++ ) {
  637. const constraint = data.constraints[ i ];
  638. const params = {};
  639. for ( const key in constraint ) {
  640. params[ key ] = constraint[ key ];
  641. }
  642. const bodyA = rigidBodies[ params.rigidBodyIndex1 ];
  643. const bodyB = rigidBodies[ params.rigidBodyIndex2 ];
  644. // Refer to http://www20.atpages.jp/katwat/wp/?p=4135
  645. if ( bodyA.type !== 0 && bodyB.type === 2 ) {
  646. if ( bodyA.boneIndex !== - 1 && bodyB.boneIndex !== - 1 &&
  647. data.bones[ bodyB.boneIndex ].parentIndex === bodyA.boneIndex ) {
  648. bodyB.type = 1;
  649. }
  650. }
  651. constraints.push( params );
  652. }
  653. // build BufferGeometry.
  654. const geometry = new BufferGeometry();
  655. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  656. geometry.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  657. geometry.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  658. geometry.setAttribute( 'skinIndex', new Uint16BufferAttribute( skinIndices, 4 ) );
  659. geometry.setAttribute( 'skinWeight', new Float32BufferAttribute( skinWeights, 4 ) );
  660. geometry.setIndex( indices );
  661. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  662. geometry.addGroup( groups[ i ].offset, groups[ i ].count, i );
  663. }
  664. geometry.bones = bones;
  665. geometry.morphTargets = morphTargets;
  666. geometry.morphAttributes.position = morphPositions;
  667. geometry.morphTargetsRelative = false;
  668. geometry.userData.MMD = {
  669. bones: bones,
  670. iks: iks,
  671. grants: grants,
  672. rigidBodies: rigidBodies,
  673. constraints: constraints,
  674. format: data.metadata.format
  675. };
  676. geometry.computeBoundingSphere();
  677. return geometry;
  678. }
  679. }
  680. //
  681. /**
  682. * @param {THREE.LoadingManager} manager
  683. */
  684. class MaterialBuilder {
  685. constructor( manager ) {
  686. this.manager = manager;
  687. this.textureLoader = new TextureLoader( this.manager );
  688. this.tgaLoader = null; // lazy generation
  689. this.crossOrigin = 'anonymous';
  690. this.resourcePath = undefined;
  691. }
  692. /**
  693. * @param {string} crossOrigin
  694. * @return {MaterialBuilder}
  695. */
  696. setCrossOrigin( crossOrigin ) {
  697. this.crossOrigin = crossOrigin;
  698. return this;
  699. }
  700. /**
  701. * @param {string} resourcePath
  702. * @return {MaterialBuilder}
  703. */
  704. setResourcePath( resourcePath ) {
  705. this.resourcePath = resourcePath;
  706. return this;
  707. }
  708. /**
  709. * @param {Object} data - parsed PMD/PMX data
  710. * @param {BufferGeometry} geometry - some properties are dependend on geometry
  711. * @param {function} onProgress
  712. * @param {function} onError
  713. * @return {Array<MeshToonMaterial>}
  714. */
  715. build( data, geometry /*, onProgress, onError */ ) {
  716. const materials = [];
  717. const textures = {};
  718. this.textureLoader.setCrossOrigin( this.crossOrigin );
  719. // materials
  720. for ( let i = 0; i < data.metadata.materialCount; i ++ ) {
  721. const material = data.materials[ i ];
  722. const params = { userData: {} };
  723. if ( material.name !== undefined ) params.name = material.name;
  724. /*
  725. * Color
  726. *
  727. * MMD MeshToonMaterial
  728. * diffuse - color
  729. * ambient - emissive * a
  730. * (a = 1.0 without map texture or 0.2 with map texture)
  731. *
  732. * MeshToonMaterial doesn't have ambient. Set it to emissive instead.
  733. * It'll be too bright if material has map texture so using coef 0.2.
  734. */
  735. params.color = new Color().fromArray( material.diffuse );
  736. params.opacity = material.diffuse[ 3 ];
  737. params.emissive = new Color().fromArray( material.ambient );
  738. params.transparent = params.opacity !== 1.0;
  739. //
  740. params.morphTargets = geometry.morphTargets.length > 0 ? true : false;
  741. params.fog = true;
  742. // blend
  743. params.blending = CustomBlending;
  744. params.blendSrc = SrcAlphaFactor;
  745. params.blendDst = OneMinusSrcAlphaFactor;
  746. params.blendSrcAlpha = SrcAlphaFactor;
  747. params.blendDstAlpha = DstAlphaFactor;
  748. // side
  749. if ( data.metadata.format === 'pmx' && ( material.flag & 0x1 ) === 1 ) {
  750. params.side = DoubleSide;
  751. } else {
  752. params.side = params.opacity === 1.0 ? FrontSide : DoubleSide;
  753. }
  754. if ( data.metadata.format === 'pmd' ) {
  755. // map, envMap
  756. if ( material.fileName ) {
  757. const fileName = material.fileName;
  758. const fileNames = fileName.split( '*' );
  759. // fileNames[ 0 ]: mapFileName
  760. // fileNames[ 1 ]: envMapFileName( optional )
  761. params.map = this._loadTexture( fileNames[ 0 ], textures );
  762. if ( fileNames.length > 1 ) {
  763. const extension = fileNames[ 1 ].slice( - 4 ).toLowerCase();
  764. params.envMap = this._loadTexture(
  765. fileNames[ 1 ],
  766. textures
  767. );
  768. params.combine = extension === '.sph'
  769. ? MultiplyOperation
  770. : AddOperation;
  771. }
  772. }
  773. // gradientMap
  774. const toonFileName = ( material.toonIndex === - 1 )
  775. ? 'toon00.bmp'
  776. : data.toonTextures[ material.toonIndex ].fileName;
  777. params.gradientMap = this._loadTexture(
  778. toonFileName,
  779. textures,
  780. {
  781. isToonTexture: true,
  782. isDefaultToonTexture: this._isDefaultToonTexture( toonFileName )
  783. }
  784. );
  785. // parameters for OutlineEffect
  786. params.userData.outlineParameters = {
  787. thickness: material.edgeFlag === 1 ? 0.003 : 0.0,
  788. color: [ 0, 0, 0 ],
  789. alpha: 1.0,
  790. visible: material.edgeFlag === 1
  791. };
  792. } else {
  793. // map
  794. if ( material.textureIndex !== - 1 ) {
  795. params.map = this._loadTexture( data.textures[ material.textureIndex ], textures );
  796. }
  797. // envMap TODO: support m.envFlag === 3
  798. if ( material.envTextureIndex !== - 1 && ( material.envFlag === 1 || material.envFlag == 2 ) ) {
  799. params.envMap = this._loadTexture(
  800. data.textures[ material.envTextureIndex ],
  801. textures
  802. );
  803. params.combine = material.envFlag === 1
  804. ? MultiplyOperation
  805. : AddOperation;
  806. }
  807. // gradientMap
  808. let toonFileName, isDefaultToon;
  809. if ( material.toonIndex === - 1 || material.toonFlag !== 0 ) {
  810. toonFileName = 'toon' + ( '0' + ( material.toonIndex + 1 ) ).slice( - 2 ) + '.bmp';
  811. isDefaultToon = true;
  812. } else {
  813. toonFileName = data.textures[ material.toonIndex ];
  814. isDefaultToon = false;
  815. }
  816. params.gradientMap = this._loadTexture(
  817. toonFileName,
  818. textures,
  819. {
  820. isToonTexture: true,
  821. isDefaultToonTexture: isDefaultToon
  822. }
  823. );
  824. // parameters for OutlineEffect
  825. params.userData.outlineParameters = {
  826. thickness: material.edgeSize / 300, // TODO: better calculation?
  827. color: material.edgeColor.slice( 0, 3 ),
  828. alpha: material.edgeColor[ 3 ],
  829. visible: ( material.flag & 0x10 ) !== 0 && material.edgeSize > 0.0
  830. };
  831. }
  832. if ( params.map !== undefined ) {
  833. if ( ! params.transparent ) {
  834. this._checkImageTransparency( params.map, geometry, i );
  835. }
  836. params.emissive.multiplyScalar( 0.2 );
  837. }
  838. materials.push( new MeshToonMaterial( params ) );
  839. }
  840. if ( data.metadata.format === 'pmx' ) {
  841. // set transparent true if alpha morph is defined.
  842. function checkAlphaMorph( elements, materials ) {
  843. for ( let i = 0, il = elements.length; i < il; i ++ ) {
  844. const element = elements[ i ];
  845. if ( element.index === - 1 ) continue;
  846. const material = materials[ element.index ];
  847. if ( material.opacity !== element.diffuse[ 3 ] ) {
  848. material.transparent = true;
  849. }
  850. }
  851. }
  852. for ( let i = 0, il = data.morphs.length; i < il; i ++ ) {
  853. const morph = data.morphs[ i ];
  854. const elements = morph.elements;
  855. if ( morph.type === 0 ) {
  856. for ( let j = 0, jl = elements.length; j < jl; j ++ ) {
  857. const morph2 = data.morphs[ elements[ j ].index ];
  858. if ( morph2.type !== 8 ) continue;
  859. checkAlphaMorph( morph2.elements, materials );
  860. }
  861. } else if ( morph.type === 8 ) {
  862. checkAlphaMorph( elements, materials );
  863. }
  864. }
  865. }
  866. return materials;
  867. }
  868. // private methods
  869. _getTGALoader() {
  870. if ( this.tgaLoader === null ) {
  871. if ( TGALoader === undefined ) {
  872. throw new Error( 'THREE.MMDLoader: Import TGALoader' );
  873. }
  874. this.tgaLoader = new TGALoader( this.manager );
  875. }
  876. return this.tgaLoader;
  877. }
  878. _isDefaultToonTexture( name ) {
  879. if ( name.length !== 10 ) return false;
  880. return /toon(10|0[0-9])\.bmp/.test( name );
  881. }
  882. _loadTexture( filePath, textures, params, onProgress, onError ) {
  883. params = params || {};
  884. const scope = this;
  885. let fullPath;
  886. if ( params.isDefaultToonTexture === true ) {
  887. let index;
  888. try {
  889. index = parseInt( filePath.match( /toon([0-9]{2})\.bmp$/ )[ 1 ] );
  890. } catch ( e ) {
  891. console.warn( 'THREE.MMDLoader: ' + filePath + ' seems like a '
  892. + 'not right default texture path. Using toon00.bmp instead.' );
  893. index = 0;
  894. }
  895. fullPath = DEFAULT_TOON_TEXTURES[ index ];
  896. } else {
  897. fullPath = this.resourcePath + filePath;
  898. }
  899. if ( textures[ fullPath ] !== undefined ) return textures[ fullPath ];
  900. let loader = this.manager.getHandler( fullPath );
  901. if ( loader === null ) {
  902. loader = ( filePath.slice( - 4 ).toLowerCase() === '.tga' )
  903. ? this._getTGALoader()
  904. : this.textureLoader;
  905. }
  906. const texture = loader.load( fullPath, function ( t ) {
  907. // MMD toon texture is Axis-Y oriented
  908. // but Three.js gradient map is Axis-X oriented.
  909. // So here replaces the toon texture image with the rotated one.
  910. if ( params.isToonTexture === true ) {
  911. t.image = scope._getRotatedImage( t.image );
  912. t.magFilter = NearestFilter;
  913. t.minFilter = NearestFilter;
  914. }
  915. t.flipY = false;
  916. t.wrapS = RepeatWrapping;
  917. t.wrapT = RepeatWrapping;
  918. for ( let i = 0; i < texture.readyCallbacks.length; i ++ ) {
  919. texture.readyCallbacks[ i ]( texture );
  920. }
  921. delete texture.readyCallbacks;
  922. }, onProgress, onError );
  923. texture.readyCallbacks = [];
  924. textures[ fullPath ] = texture;
  925. return texture;
  926. }
  927. _getRotatedImage( image ) {
  928. const canvas = document.createElement( 'canvas' );
  929. const context = canvas.getContext( '2d' );
  930. const width = image.width;
  931. const height = image.height;
  932. canvas.width = width;
  933. canvas.height = height;
  934. context.clearRect( 0, 0, width, height );
  935. context.translate( width / 2.0, height / 2.0 );
  936. context.rotate( 0.5 * Math.PI ); // 90.0 * Math.PI / 180.0
  937. context.translate( - width / 2.0, - height / 2.0 );
  938. context.drawImage( image, 0, 0 );
  939. return context.getImageData( 0, 0, width, height );
  940. }
  941. // Check if the partial image area used by the texture is transparent.
  942. _checkImageTransparency( map, geometry, groupIndex ) {
  943. map.readyCallbacks.push( function ( texture ) {
  944. // Is there any efficient ways?
  945. function createImageData( image ) {
  946. const canvas = document.createElement( 'canvas' );
  947. canvas.width = image.width;
  948. canvas.height = image.height;
  949. const context = canvas.getContext( '2d' );
  950. context.drawImage( image, 0, 0 );
  951. return context.getImageData( 0, 0, canvas.width, canvas.height );
  952. }
  953. function detectImageTransparency( image, uvs, indices ) {
  954. const width = image.width;
  955. const height = image.height;
  956. const data = image.data;
  957. const threshold = 253;
  958. if ( data.length / ( width * height ) !== 4 ) return false;
  959. for ( let i = 0; i < indices.length; i += 3 ) {
  960. const centerUV = { x: 0.0, y: 0.0 };
  961. for ( let j = 0; j < 3; j ++ ) {
  962. const index = indices[ i * 3 + j ];
  963. const uv = { x: uvs[ index * 2 + 0 ], y: uvs[ index * 2 + 1 ] };
  964. if ( getAlphaByUv( image, uv ) < threshold ) return true;
  965. centerUV.x += uv.x;
  966. centerUV.y += uv.y;
  967. }
  968. centerUV.x /= 3;
  969. centerUV.y /= 3;
  970. if ( getAlphaByUv( image, centerUV ) < threshold ) return true;
  971. }
  972. return false;
  973. }
  974. /*
  975. * This method expects
  976. * texture.flipY = false
  977. * texture.wrapS = RepeatWrapping
  978. * texture.wrapT = RepeatWrapping
  979. * TODO: more precise
  980. */
  981. function getAlphaByUv( image, uv ) {
  982. const width = image.width;
  983. const height = image.height;
  984. let x = Math.round( uv.x * width ) % width;
  985. let y = Math.round( uv.y * height ) % height;
  986. if ( x < 0 ) x += width;
  987. if ( y < 0 ) y += height;
  988. const index = y * width + x;
  989. return image.data[ index * 4 + 3 ];
  990. }
  991. if ( texture.isCompressedTexture === true ) {
  992. if ( NON_ALPHA_CHANNEL_FORMATS.includes( texture.format ) ) {
  993. map.transparent = false;
  994. } else {
  995. // any other way to check transparency of CompressedTexture?
  996. map.transparent = true;
  997. }
  998. return;
  999. }
  1000. const imageData = texture.image.data !== undefined
  1001. ? texture.image
  1002. : createImageData( texture.image );
  1003. const group = geometry.groups[ groupIndex ];
  1004. if ( detectImageTransparency(
  1005. imageData,
  1006. geometry.attributes.uv.array,
  1007. geometry.index.array.slice( group.start, group.start + group.count ) ) ) {
  1008. map.transparent = true;
  1009. }
  1010. } );
  1011. }
  1012. }
  1013. //
  1014. class AnimationBuilder {
  1015. /**
  1016. * @param {Object} vmd - parsed VMD data
  1017. * @param {SkinnedMesh} mesh - tracks will be fitting to mesh
  1018. * @return {AnimationClip}
  1019. */
  1020. build( vmd, mesh ) {
  1021. // combine skeletal and morph animations
  1022. const tracks = this.buildSkeletalAnimation( vmd, mesh ).tracks;
  1023. const tracks2 = this.buildMorphAnimation( vmd, mesh ).tracks;
  1024. for ( let i = 0, il = tracks2.length; i < il; i ++ ) {
  1025. tracks.push( tracks2[ i ] );
  1026. }
  1027. return new AnimationClip( '', - 1, tracks );
  1028. }
  1029. /**
  1030. * @param {Object} vmd - parsed VMD data
  1031. * @param {SkinnedMesh} mesh - tracks will be fitting to mesh
  1032. * @return {AnimationClip}
  1033. */
  1034. buildSkeletalAnimation( vmd, mesh ) {
  1035. function pushInterpolation( array, interpolation, index ) {
  1036. array.push( interpolation[ index + 0 ] / 127 ); // x1
  1037. array.push( interpolation[ index + 8 ] / 127 ); // x2
  1038. array.push( interpolation[ index + 4 ] / 127 ); // y1
  1039. array.push( interpolation[ index + 12 ] / 127 ); // y2
  1040. }
  1041. const tracks = [];
  1042. const motions = {};
  1043. const bones = mesh.skeleton.bones;
  1044. const boneNameDictionary = {};
  1045. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  1046. boneNameDictionary[ bones[ i ].name ] = true;
  1047. }
  1048. for ( let i = 0; i < vmd.metadata.motionCount; i ++ ) {
  1049. const motion = vmd.motions[ i ];
  1050. const boneName = motion.boneName;
  1051. if ( boneNameDictionary[ boneName ] === undefined ) continue;
  1052. motions[ boneName ] = motions[ boneName ] || [];
  1053. motions[ boneName ].push( motion );
  1054. }
  1055. for ( const key in motions ) {
  1056. const array = motions[ key ];
  1057. array.sort( function ( a, b ) {
  1058. return a.frameNum - b.frameNum;
  1059. } );
  1060. const times = [];
  1061. const positions = [];
  1062. const rotations = [];
  1063. const pInterpolations = [];
  1064. const rInterpolations = [];
  1065. const basePosition = mesh.skeleton.getBoneByName( key ).position.toArray();
  1066. for ( let i = 0, il = array.length; i < il; i ++ ) {
  1067. const time = array[ i ].frameNum / 30;
  1068. const position = array[ i ].position;
  1069. const rotation = array[ i ].rotation;
  1070. const interpolation = array[ i ].interpolation;
  1071. times.push( time );
  1072. for ( let j = 0; j < 3; j ++ ) positions.push( basePosition[ j ] + position[ j ] );
  1073. for ( let j = 0; j < 4; j ++ ) rotations.push( rotation[ j ] );
  1074. for ( let j = 0; j < 3; j ++ ) pushInterpolation( pInterpolations, interpolation, j );
  1075. pushInterpolation( rInterpolations, interpolation, 3 );
  1076. }
  1077. const targetName = '.bones[' + key + ']';
  1078. tracks.push( this._createTrack( targetName + '.position', VectorKeyframeTrack, times, positions, pInterpolations ) );
  1079. tracks.push( this._createTrack( targetName + '.quaternion', QuaternionKeyframeTrack, times, rotations, rInterpolations ) );
  1080. }
  1081. return new AnimationClip( '', - 1, tracks );
  1082. }
  1083. /**
  1084. * @param {Object} vmd - parsed VMD data
  1085. * @param {SkinnedMesh} mesh - tracks will be fitting to mesh
  1086. * @return {AnimationClip}
  1087. */
  1088. buildMorphAnimation( vmd, mesh ) {
  1089. const tracks = [];
  1090. const morphs = {};
  1091. const morphTargetDictionary = mesh.morphTargetDictionary;
  1092. for ( let i = 0; i < vmd.metadata.morphCount; i ++ ) {
  1093. const morph = vmd.morphs[ i ];
  1094. const morphName = morph.morphName;
  1095. if ( morphTargetDictionary[ morphName ] === undefined ) continue;
  1096. morphs[ morphName ] = morphs[ morphName ] || [];
  1097. morphs[ morphName ].push( morph );
  1098. }
  1099. for ( const key in morphs ) {
  1100. const array = morphs[ key ];
  1101. array.sort( function ( a, b ) {
  1102. return a.frameNum - b.frameNum;
  1103. } );
  1104. const times = [];
  1105. const values = [];
  1106. for ( let i = 0, il = array.length; i < il; i ++ ) {
  1107. times.push( array[ i ].frameNum / 30 );
  1108. values.push( array[ i ].weight );
  1109. }
  1110. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluences[' + morphTargetDictionary[ key ] + ']', times, values ) );
  1111. }
  1112. return new AnimationClip( '', - 1, tracks );
  1113. }
  1114. /**
  1115. * @param {Object} vmd - parsed VMD data
  1116. * @return {AnimationClip}
  1117. */
  1118. buildCameraAnimation( vmd ) {
  1119. function pushVector3( array, vec ) {
  1120. array.push( vec.x );
  1121. array.push( vec.y );
  1122. array.push( vec.z );
  1123. }
  1124. function pushQuaternion( array, q ) {
  1125. array.push( q.x );
  1126. array.push( q.y );
  1127. array.push( q.z );
  1128. array.push( q.w );
  1129. }
  1130. function pushInterpolation( array, interpolation, index ) {
  1131. array.push( interpolation[ index * 4 + 0 ] / 127 ); // x1
  1132. array.push( interpolation[ index * 4 + 1 ] / 127 ); // x2
  1133. array.push( interpolation[ index * 4 + 2 ] / 127 ); // y1
  1134. array.push( interpolation[ index * 4 + 3 ] / 127 ); // y2
  1135. }
  1136. const cameras = vmd.cameras === undefined ? [] : vmd.cameras.slice();
  1137. cameras.sort( function ( a, b ) {
  1138. return a.frameNum - b.frameNum;
  1139. } );
  1140. const times = [];
  1141. const centers = [];
  1142. const quaternions = [];
  1143. const positions = [];
  1144. const fovs = [];
  1145. const cInterpolations = [];
  1146. const qInterpolations = [];
  1147. const pInterpolations = [];
  1148. const fInterpolations = [];
  1149. const quaternion = new Quaternion();
  1150. const euler = new Euler();
  1151. const position = new Vector3();
  1152. const center = new Vector3();
  1153. for ( let i = 0, il = cameras.length; i < il; i ++ ) {
  1154. const motion = cameras[ i ];
  1155. const time = motion.frameNum / 30;
  1156. const pos = motion.position;
  1157. const rot = motion.rotation;
  1158. const distance = motion.distance;
  1159. const fov = motion.fov;
  1160. const interpolation = motion.interpolation;
  1161. times.push( time );
  1162. position.set( 0, 0, - distance );
  1163. center.set( pos[ 0 ], pos[ 1 ], pos[ 2 ] );
  1164. euler.set( - rot[ 0 ], - rot[ 1 ], - rot[ 2 ] );
  1165. quaternion.setFromEuler( euler );
  1166. position.add( center );
  1167. position.applyQuaternion( quaternion );
  1168. pushVector3( centers, center );
  1169. pushQuaternion( quaternions, quaternion );
  1170. pushVector3( positions, position );
  1171. fovs.push( fov );
  1172. for ( let j = 0; j < 3; j ++ ) {
  1173. pushInterpolation( cInterpolations, interpolation, j );
  1174. }
  1175. pushInterpolation( qInterpolations, interpolation, 3 );
  1176. // use the same parameter for x, y, z axis.
  1177. for ( let j = 0; j < 3; j ++ ) {
  1178. pushInterpolation( pInterpolations, interpolation, 4 );
  1179. }
  1180. pushInterpolation( fInterpolations, interpolation, 5 );
  1181. }
  1182. const tracks = [];
  1183. // I expect an object whose name 'target' exists under THREE.Camera
  1184. tracks.push( this._createTrack( 'target.position', VectorKeyframeTrack, times, centers, cInterpolations ) );
  1185. tracks.push( this._createTrack( '.quaternion', QuaternionKeyframeTrack, times, quaternions, qInterpolations ) );
  1186. tracks.push( this._createTrack( '.position', VectorKeyframeTrack, times, positions, pInterpolations ) );
  1187. tracks.push( this._createTrack( '.fov', NumberKeyframeTrack, times, fovs, fInterpolations ) );
  1188. return new AnimationClip( '', - 1, tracks );
  1189. }
  1190. // private method
  1191. _createTrack( node, typedKeyframeTrack, times, values, interpolations ) {
  1192. /*
  1193. * optimizes here not to let KeyframeTrackPrototype optimize
  1194. * because KeyframeTrackPrototype optimizes times and values but
  1195. * doesn't optimize interpolations.
  1196. */
  1197. if ( times.length > 2 ) {
  1198. times = times.slice();
  1199. values = values.slice();
  1200. interpolations = interpolations.slice();
  1201. const stride = values.length / times.length;
  1202. const interpolateStride = interpolations.length / times.length;
  1203. let index = 1;
  1204. for ( let aheadIndex = 2, endIndex = times.length; aheadIndex < endIndex; aheadIndex ++ ) {
  1205. for ( let i = 0; i < stride; i ++ ) {
  1206. if ( values[ index * stride + i ] !== values[ ( index - 1 ) * stride + i ] ||
  1207. values[ index * stride + i ] !== values[ aheadIndex * stride + i ] ) {
  1208. index ++;
  1209. break;
  1210. }
  1211. }
  1212. if ( aheadIndex > index ) {
  1213. times[ index ] = times[ aheadIndex ];
  1214. for ( let i = 0; i < stride; i ++ ) {
  1215. values[ index * stride + i ] = values[ aheadIndex * stride + i ];
  1216. }
  1217. for ( let i = 0; i < interpolateStride; i ++ ) {
  1218. interpolations[ index * interpolateStride + i ] = interpolations[ aheadIndex * interpolateStride + i ];
  1219. }
  1220. }
  1221. }
  1222. times.length = index + 1;
  1223. values.length = ( index + 1 ) * stride;
  1224. interpolations.length = ( index + 1 ) * interpolateStride;
  1225. }
  1226. const track = new typedKeyframeTrack( node, times, values );
  1227. track.createInterpolant = function InterpolantFactoryMethodCubicBezier( result ) {
  1228. return new CubicBezierInterpolation( this.times, this.values, this.getValueSize(), result, new Float32Array( interpolations ) );
  1229. };
  1230. return track;
  1231. }
  1232. }
  1233. // interpolation
  1234. class CubicBezierInterpolation extends Interpolant {
  1235. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer, params ) {
  1236. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  1237. this.interpolationParams = params;
  1238. }
  1239. interpolate_( i1, t0, t, t1 ) {
  1240. const result = this.resultBuffer;
  1241. const values = this.sampleValues;
  1242. const stride = this.valueSize;
  1243. const params = this.interpolationParams;
  1244. const offset1 = i1 * stride;
  1245. const offset0 = offset1 - stride;
  1246. // No interpolation if next key frame is in one frame in 30fps.
  1247. // This is from MMD animation spec.
  1248. // '1.5' is for precision loss. times are Float32 in Three.js Animation system.
  1249. const weight1 = ( ( t1 - t0 ) < 1 / 30 * 1.5 ) ? 0.0 : ( t - t0 ) / ( t1 - t0 );
  1250. if ( stride === 4 ) { // Quaternion
  1251. const x1 = params[ i1 * 4 + 0 ];
  1252. const x2 = params[ i1 * 4 + 1 ];
  1253. const y1 = params[ i1 * 4 + 2 ];
  1254. const y2 = params[ i1 * 4 + 3 ];
  1255. const ratio = this._calculate( x1, x2, y1, y2, weight1 );
  1256. Quaternion.slerpFlat( result, 0, values, offset0, values, offset1, ratio );
  1257. } else if ( stride === 3 ) { // Vector3
  1258. for ( let i = 0; i !== stride; ++ i ) {
  1259. const x1 = params[ i1 * 12 + i * 4 + 0 ];
  1260. const x2 = params[ i1 * 12 + i * 4 + 1 ];
  1261. const y1 = params[ i1 * 12 + i * 4 + 2 ];
  1262. const y2 = params[ i1 * 12 + i * 4 + 3 ];
  1263. const ratio = this._calculate( x1, x2, y1, y2, weight1 );
  1264. result[ i ] = values[ offset0 + i ] * ( 1 - ratio ) + values[ offset1 + i ] * ratio;
  1265. }
  1266. } else { // Number
  1267. const x1 = params[ i1 * 4 + 0 ];
  1268. const x2 = params[ i1 * 4 + 1 ];
  1269. const y1 = params[ i1 * 4 + 2 ];
  1270. const y2 = params[ i1 * 4 + 3 ];
  1271. const ratio = this._calculate( x1, x2, y1, y2, weight1 );
  1272. result[ 0 ] = values[ offset0 ] * ( 1 - ratio ) + values[ offset1 ] * ratio;
  1273. }
  1274. return result;
  1275. }
  1276. _calculate( x1, x2, y1, y2, x ) {
  1277. /*
  1278. * Cubic Bezier curves
  1279. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Cubic_B.C3.A9zier_curves
  1280. *
  1281. * B(t) = ( 1 - t ) ^ 3 * P0
  1282. * + 3 * ( 1 - t ) ^ 2 * t * P1
  1283. * + 3 * ( 1 - t ) * t^2 * P2
  1284. * + t ^ 3 * P3
  1285. * ( 0 <= t <= 1 )
  1286. *
  1287. * MMD uses Cubic Bezier curves for bone and camera animation interpolation.
  1288. * http://d.hatena.ne.jp/edvakf/20111016/1318716097
  1289. *
  1290. * x = ( 1 - t ) ^ 3 * x0
  1291. * + 3 * ( 1 - t ) ^ 2 * t * x1
  1292. * + 3 * ( 1 - t ) * t^2 * x2
  1293. * + t ^ 3 * x3
  1294. * y = ( 1 - t ) ^ 3 * y0
  1295. * + 3 * ( 1 - t ) ^ 2 * t * y1
  1296. * + 3 * ( 1 - t ) * t^2 * y2
  1297. * + t ^ 3 * y3
  1298. * ( x0 = 0, y0 = 0 )
  1299. * ( x3 = 1, y3 = 1 )
  1300. * ( 0 <= t, x1, x2, y1, y2 <= 1 )
  1301. *
  1302. * Here solves this equation with Bisection method,
  1303. * https://en.wikipedia.org/wiki/Bisection_method
  1304. * gets t, and then calculate y.
  1305. *
  1306. * f(t) = 3 * ( 1 - t ) ^ 2 * t * x1
  1307. * + 3 * ( 1 - t ) * t^2 * x2
  1308. * + t ^ 3 - x = 0
  1309. *
  1310. * (Another option: Newton's method
  1311. * https://en.wikipedia.org/wiki/Newton%27s_method)
  1312. */
  1313. let c = 0.5;
  1314. let t = c;
  1315. let s = 1.0 - t;
  1316. const loop = 15;
  1317. const eps = 1e-5;
  1318. const math = Math;
  1319. let sst3, stt3, ttt;
  1320. for ( let i = 0; i < loop; i ++ ) {
  1321. sst3 = 3.0 * s * s * t;
  1322. stt3 = 3.0 * s * t * t;
  1323. ttt = t * t * t;
  1324. const ft = ( sst3 * x1 ) + ( stt3 * x2 ) + ( ttt ) - x;
  1325. if ( math.abs( ft ) < eps ) break;
  1326. c /= 2.0;
  1327. t += ( ft < 0 ) ? c : - c;
  1328. s = 1.0 - t;
  1329. }
  1330. return ( sst3 * y1 ) + ( stt3 * y2 ) + ttt;
  1331. }
  1332. }
  1333. export { MMDLoader };