MMDLoader.js 51 KB

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