MMDLoader.js 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663
  1. /**
  2. * @author takahiro / https://github.com/takahirox
  3. *
  4. * Dependencies
  5. * - mmd-parser https://github.com/takahirox/mmd-parser
  6. * - ammo.js https://github.com/kripken/ammo.js
  7. * - THREE.TGALoader
  8. * - THREE.MMDPhysics
  9. * - THREE.CCDIKSolver
  10. * - THREE.OutlineEffect
  11. *
  12. *
  13. * This loader loads and parses PMD/PMX and VMD binary files
  14. * then creates mesh for Three.js.
  15. *
  16. * PMD/PMX is a model data format and VMD is a motion data format
  17. * used in MMD(Miku Miku Dance).
  18. *
  19. * MMD is a 3D CG animation tool which is popular in Japan.
  20. *
  21. *
  22. * MMD official site
  23. * http://www.geocities.jp/higuchuu4/index_e.htm
  24. *
  25. * PMD, VMD format
  26. * http://blog.goo.ne.jp/torisu_tetosuki/e/209ad341d3ece2b1b4df24abf619d6e4
  27. *
  28. * PMX format
  29. * http://gulshan-i-raz.geo.jp/labs/2012/10/17/pmx-format1/
  30. *
  31. *
  32. * TODO
  33. * - light motion in vmd support.
  34. * - SDEF support.
  35. * - uv/material/bone morphing support.
  36. * - more precise grant skinning support.
  37. * - shadow support.
  38. */
  39. THREE.MMDLoader = function ( manager ) {
  40. THREE.Loader.call( this );
  41. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  42. this.parser = new MMDParser.Parser();
  43. this.textureCrossOrigin = null;
  44. };
  45. THREE.MMDLoader.prototype = Object.create( THREE.Loader.prototype );
  46. THREE.MMDLoader.prototype.constructor = THREE.MMDLoader;
  47. /*
  48. * base64 encoded defalut toon textures toon00.bmp - toon10.bmp
  49. * Users don't need to prepare default texture files.
  50. *
  51. * This idea is from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mmd.three.js
  52. */
  53. THREE.MMDLoader.prototype.defaultToonTextures = [
  54. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=',
  55. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAN0lEQVRYR+3WQREAMBACsZ5/bWiiMvgEBTt5cW37hjsBBAgQIECAwFwgyfYPCCBAgAABAgTWAh8aBHZBl14e8wAAAABJRU5ErkJggg==',
  56. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAOUlEQVRYR+3WMREAMAwDsYY/yoDI7MLwIiP40+RJklfcCCBAgAABAgTqArfb/QMCCBAgQIAAgbbAB3z/e0F3js2cAAAAAElFTkSuQmCC',
  57. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAN0lEQVRYR+3WQREAMBACsZ5/B5ilMvgEBTt5cW37hjsBBAgQIECAwFwgyfYPCCBAgAABAgTWAh81dWyx0gFwKAAAAABJRU5ErkJggg==',
  58. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAOklEQVRYR+3WoREAMAwDsWb/UQtCy9wxTOQJ/oQ8SXKKGwEECBAgQIBAXeDt7f4BAQQIECBAgEBb4AOz8Hzx7WLY4wAAAABJRU5ErkJggg==',
  59. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABPUlEQVRYR+1XwW7CMAy1+f9fZOMysSEOEweEOPRNdm3HbdOyIhAcklPrOs/PLy9RygBALxzcCDQFmgJNgaZAU6Ap0BR4PwX8gsRMVLssMRH5HcpzJEaWL7EVg9F1IHRlyqQohgVr4FGUlUcMJSjcUlDw0zvjeun70cLWmneoyf7NgBTQSniBTQQSuJAZsOnnaczjIMb5hCiuHKxokCrJfVnrctyZL0PkJAJe1HMil4nxeyi3Ypfn1kX51jpPvo/JeCNC4PhVdHdJw2XjBR8brF8PEIhNVn12AgP7uHsTBguBn53MUZCqv7Lp07Pn5k1Ro+uWmUNn7D+M57rtk7aG0Vo73xyF/fbFf0bPJjDXngnGocDTdFhygZjwUQrMNrDcmZlQT50VJ/g/UwNyHpu778+yW+/ksOz/BFo54P4AsUXMfRq7XWsAAAAASUVORK5CYII=',
  60. '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=',
  61. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=',
  62. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=',
  63. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=',
  64. 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII='
  65. ];
  66. /*
  67. * Set 'anonymous' for the the texture image file in other domain
  68. * even if server responds with "Access-Control-Allow-Origin: *"
  69. * because some image operation fails in MMDLoader.
  70. */
  71. THREE.MMDLoader.prototype.setTextureCrossOrigin = function ( value ) {
  72. this.textureCrossOrigin = value;
  73. };
  74. THREE.MMDLoader.prototype.load = function ( modelUrl, vmdUrls, callback, onProgress, onError ) {
  75. var scope = this;
  76. this.loadModel( modelUrl, function ( mesh ) {
  77. scope.loadVmds( vmdUrls, function ( vmd ) {
  78. scope.pourVmdIntoModel( mesh, vmd );
  79. callback( mesh );
  80. }, onProgress, onError );
  81. }, onProgress, onError );
  82. };
  83. THREE.MMDLoader.prototype.loadModel = function ( url, callback, onProgress, onError ) {
  84. var scope = this;
  85. var texturePath = THREE.LoaderUtils.extractUrlBase( url );
  86. var modelExtension = this.extractExtension( url );
  87. this.loadFileAsBuffer( url, function ( buffer ) {
  88. callback( scope.createModel( buffer, modelExtension, texturePath, onProgress, onError ) );
  89. }, onProgress, onError );
  90. };
  91. THREE.MMDLoader.prototype.createModel = function ( buffer, modelExtension, texturePath, onProgress, onError ) {
  92. return this.createMesh( this.parseModel( buffer, modelExtension ), texturePath, onProgress, onError );
  93. };
  94. THREE.MMDLoader.prototype.loadVmd = function ( url, callback, onProgress, onError ) {
  95. var scope = this;
  96. this.loadFileAsBuffer( url, function ( buffer ) {
  97. callback( scope.parseVmd( buffer ) );
  98. }, onProgress, onError );
  99. };
  100. THREE.MMDLoader.prototype.loadVmds = function ( urls, callback, onProgress, onError ) {
  101. var scope = this;
  102. var vmds = [];
  103. urls = urls.slice();
  104. function run() {
  105. var url = urls.shift();
  106. scope.loadVmd( url, function ( vmd ) {
  107. vmds.push( vmd );
  108. if ( urls.length > 0 ) {
  109. run();
  110. } else {
  111. callback( scope.mergeVmds( vmds ) );
  112. }
  113. }, onProgress, onError );
  114. }
  115. run();
  116. };
  117. THREE.MMDLoader.prototype.loadAudio = function ( url, callback, onProgress, onError ) {
  118. var listener = new THREE.AudioListener();
  119. var audio = new THREE.Audio( listener );
  120. var loader = new THREE.AudioLoader( this.manager );
  121. loader.load( url, function ( buffer ) {
  122. audio.setBuffer( buffer );
  123. callback( audio, listener );
  124. }, onProgress, onError );
  125. };
  126. THREE.MMDLoader.prototype.loadVpd = function ( url, callback, onProgress, onError, params ) {
  127. var scope = this;
  128. var func = ( ( params && params.charcode === 'unicode' ) ? this.loadFileAsText : this.loadFileAsShiftJISText ).bind( this );
  129. func( url, function ( text ) {
  130. callback( scope.parseVpd( text ) );
  131. }, onProgress, onError );
  132. };
  133. THREE.MMDLoader.prototype.parseModel = function ( buffer, modelExtension ) {
  134. // Should I judge from model data header?
  135. switch ( modelExtension.toLowerCase() ) {
  136. case 'pmd':
  137. return this.parsePmd( buffer );
  138. case 'pmx':
  139. return this.parsePmx( buffer );
  140. default:
  141. throw 'extension ' + modelExtension + ' is not supported.';
  142. }
  143. };
  144. THREE.MMDLoader.prototype.parsePmd = function ( buffer ) {
  145. return this.parser.parsePmd( buffer, true );
  146. };
  147. THREE.MMDLoader.prototype.parsePmx = function ( buffer ) {
  148. return this.parser.parsePmx( buffer, true );
  149. };
  150. THREE.MMDLoader.prototype.parseVmd = function ( buffer ) {
  151. return this.parser.parseVmd( buffer, true );
  152. };
  153. THREE.MMDLoader.prototype.parseVpd = function ( text ) {
  154. return this.parser.parseVpd( text, true );
  155. };
  156. THREE.MMDLoader.prototype.mergeVmds = function ( vmds ) {
  157. return this.parser.mergeVmds( vmds );
  158. };
  159. THREE.MMDLoader.prototype.pourVmdIntoModel = function ( mesh, vmd, name ) {
  160. this.createAnimation( mesh, vmd, name );
  161. };
  162. THREE.MMDLoader.prototype.pourVmdIntoCamera = function ( camera, vmd, name ) {
  163. var helper = new THREE.MMDLoader.DataCreationHelper();
  164. var initAnimation = function () {
  165. var orderedMotions = helper.createOrderedMotionArray( vmd.cameras );
  166. var times = [];
  167. var centers = [];
  168. var quaternions = [];
  169. var positions = [];
  170. var fovs = [];
  171. var cInterpolations = [];
  172. var qInterpolations = [];
  173. var pInterpolations = [];
  174. var fInterpolations = [];
  175. var quaternion = new THREE.Quaternion();
  176. var euler = new THREE.Euler();
  177. var position = new THREE.Vector3();
  178. var center = new THREE.Vector3();
  179. var pushVector3 = function ( array, vec ) {
  180. array.push( vec.x );
  181. array.push( vec.y );
  182. array.push( vec.z );
  183. };
  184. var pushQuaternion = function ( array, q ) {
  185. array.push( q.x );
  186. array.push( q.y );
  187. array.push( q.z );
  188. array.push( q.w );
  189. };
  190. var pushInterpolation = function ( array, interpolation, index ) {
  191. array.push( interpolation[ index * 4 + 0 ] / 127 ); // x1
  192. array.push( interpolation[ index * 4 + 1 ] / 127 ); // x2
  193. array.push( interpolation[ index * 4 + 2 ] / 127 ); // y1
  194. array.push( interpolation[ index * 4 + 3 ] / 127 ); // y2
  195. };
  196. var createTrack = function ( node, type, times, values, interpolations ) {
  197. /*
  198. * optimizes here not to let KeyframeTrackPrototype optimize
  199. * because KeyframeTrackPrototype optimizes times and values but
  200. * doesn't optimize interpolations.
  201. */
  202. if ( times.length > 2 ) {
  203. times = times.slice();
  204. values = values.slice();
  205. interpolations = interpolations.slice();
  206. var stride = values.length / times.length;
  207. var interpolateStride = ( stride === 3 ) ? 12 : 4; // 3: Vector3, others: Quaternion or Number
  208. var index = 1;
  209. for ( var aheadIndex = 2, endIndex = times.length; aheadIndex < endIndex; aheadIndex ++ ) {
  210. for ( var i = 0; i < stride; i ++ ) {
  211. if ( values[ index * stride + i ] !== values[ ( index - 1 ) * stride + i ] ||
  212. values[ index * stride + i ] !== values[ aheadIndex * stride + i ] ) {
  213. index ++;
  214. break;
  215. }
  216. }
  217. if ( aheadIndex > index ) {
  218. times[ index ] = times[ aheadIndex ];
  219. for ( var i = 0; i < stride; i ++ ) {
  220. values[ index * stride + i ] = values[ aheadIndex * stride + i ];
  221. }
  222. for ( var i = 0; i < interpolateStride; i ++ ) {
  223. interpolations[ index * interpolateStride + i ] = interpolations[ aheadIndex * interpolateStride + i ];
  224. }
  225. }
  226. }
  227. times.length = index + 1;
  228. values.length = ( index + 1 ) * stride;
  229. interpolations.length = ( index + 1 ) * interpolateStride;
  230. }
  231. var track = new THREE[ type ]( node, times, values );
  232. track.createInterpolant = function InterpolantFactoryMethodCubicBezier( result ) {
  233. return new THREE.MMDLoader.CubicBezierInterpolation( this.times, this.values, this.getValueSize(), result, new Float32Array( interpolations ) );
  234. };
  235. return track;
  236. };
  237. for ( var i = 0; i < orderedMotions.length; i ++ ) {
  238. var m = orderedMotions[ i ];
  239. var time = m.frameNum / 30;
  240. var pos = m.position;
  241. var rot = m.rotation;
  242. var distance = m.distance;
  243. var fov = m.fov;
  244. var interpolation = m.interpolation;
  245. position.set( 0, 0, - distance );
  246. center.set( pos[ 0 ], pos[ 1 ], pos[ 2 ] );
  247. euler.set( - rot[ 0 ], - rot[ 1 ], - rot[ 2 ] );
  248. quaternion.setFromEuler( euler );
  249. position.add( center );
  250. position.applyQuaternion( quaternion );
  251. times.push( time );
  252. pushVector3( centers, center );
  253. pushQuaternion( quaternions, quaternion );
  254. pushVector3( positions, position );
  255. fovs.push( fov );
  256. for ( var j = 0; j < 3; j ++ ) {
  257. pushInterpolation( cInterpolations, interpolation, j );
  258. }
  259. pushInterpolation( qInterpolations, interpolation, 3 );
  260. // use same one parameter for x, y, z axis.
  261. for ( var j = 0; j < 3; j ++ ) {
  262. pushInterpolation( pInterpolations, interpolation, 4 );
  263. }
  264. pushInterpolation( fInterpolations, interpolation, 5 );
  265. }
  266. if ( times.length === 0 ) return;
  267. var tracks = [];
  268. tracks.push( createTrack( '.center', 'VectorKeyframeTrack', times, centers, cInterpolations ) );
  269. tracks.push( createTrack( '.quaternion', 'QuaternionKeyframeTrack', times, quaternions, qInterpolations ) );
  270. tracks.push( createTrack( '.position', 'VectorKeyframeTrack', times, positions, pInterpolations ) );
  271. tracks.push( createTrack( '.fov', 'NumberKeyframeTrack', times, fovs, fInterpolations ) );
  272. var clip = new THREE.AnimationClip( name === undefined ? THREE.Math.generateUUID() : name, - 1, tracks );
  273. if ( camera.center === undefined ) camera.center = new THREE.Vector3( 0, 0, 0 );
  274. if ( camera.animations === undefined ) camera.animations = [];
  275. camera.animations.push( clip );
  276. };
  277. initAnimation();
  278. };
  279. THREE.MMDLoader.prototype.extractExtension = function ( url ) {
  280. var index = url.lastIndexOf( '.' );
  281. if ( index < 0 ) {
  282. return null;
  283. }
  284. return url.slice( index + 1 );
  285. };
  286. THREE.MMDLoader.prototype.loadFile = function ( url, onLoad, onProgress, onError, responseType, mimeType ) {
  287. var loader = new THREE.FileLoader( this.manager );
  288. if ( mimeType !== undefined ) loader.setMimeType( mimeType );
  289. loader.setResponseType( responseType );
  290. var request = loader.load( url, function ( result ) {
  291. onLoad( result );
  292. }, onProgress, onError );
  293. return request;
  294. };
  295. THREE.MMDLoader.prototype.loadFileAsBuffer = function ( url, onLoad, onProgress, onError ) {
  296. this.loadFile( url, onLoad, onProgress, onError, 'arraybuffer' );
  297. };
  298. THREE.MMDLoader.prototype.loadFileAsText = function ( url, onLoad, onProgress, onError ) {
  299. this.loadFile( url, onLoad, onProgress, onError, 'text' );
  300. };
  301. THREE.MMDLoader.prototype.loadFileAsShiftJISText = function ( url, onLoad, onProgress, onError ) {
  302. this.loadFile( url, onLoad, onProgress, onError, 'text', 'text/plain; charset=shift_jis' );
  303. };
  304. THREE.MMDLoader.prototype.createMesh = function ( model, texturePath, onProgress, onError ) {
  305. var scope = this;
  306. var geometry = new THREE.BufferGeometry();
  307. var materials = [];
  308. var buffer = {};
  309. buffer.vertices = [];
  310. buffer.uvs = [];
  311. buffer.normals = [];
  312. buffer.skinIndices = [];
  313. buffer.skinWeights = [];
  314. buffer.indices = [];
  315. var initVartices = function () {
  316. for ( var i = 0; i < model.metadata.vertexCount; i ++ ) {
  317. var v = model.vertices[ i ];
  318. for ( var j = 0, jl = v.position.length; j < jl; j ++ ) {
  319. buffer.vertices.push( v.position[ j ] );
  320. }
  321. for ( var j = 0, jl = v.normal.length; j < jl; j ++ ) {
  322. buffer.normals.push( v.normal[ j ] );
  323. }
  324. for ( var j = 0, jl = v.uv.length; j < jl; j ++ ) {
  325. buffer.uvs.push( v.uv[ j ] );
  326. }
  327. for ( var j = 0; j < 4; j ++ ) {
  328. buffer.skinIndices.push( v.skinIndices.length - 1 >= j ? v.skinIndices[ j ] : 0.0 );
  329. }
  330. for ( var j = 0; j < 4; j ++ ) {
  331. buffer.skinWeights.push( v.skinWeights.length - 1 >= j ? v.skinWeights[ j ] : 0.0 );
  332. }
  333. }
  334. };
  335. var initFaces = function () {
  336. for ( var i = 0; i < model.metadata.faceCount; i ++ ) {
  337. var f = model.faces[ i ];
  338. for ( var j = 0, jl = f.indices.length; j < jl; j ++ ) {
  339. buffer.indices.push( f.indices[ j ] );
  340. }
  341. }
  342. };
  343. var initBones = function () {
  344. var bones = [];
  345. var rigidBodies = model.rigidBodies;
  346. var dictionary = {};
  347. for ( var i = 0, il = rigidBodies.length; i < il; i ++ ) {
  348. var body = rigidBodies[ i ];
  349. var value = dictionary[ body.boneIndex ];
  350. // keeps greater number if already value is set without any special reasons
  351. value = value === undefined ? body.type : Math.max( body.type, value );
  352. dictionary[ body.boneIndex ] = value;
  353. }
  354. for ( var i = 0; i < model.metadata.boneCount; i ++ ) {
  355. var bone = {};
  356. var b = model.bones[ i ];
  357. bone.parent = b.parentIndex;
  358. bone.name = b.name;
  359. bone.pos = [ b.position[ 0 ], b.position[ 1 ], b.position[ 2 ] ];
  360. bone.rotq = [ 0, 0, 0, 1 ];
  361. bone.scl = [ 1, 1, 1 ];
  362. if ( bone.parent !== - 1 ) {
  363. bone.pos[ 0 ] -= model.bones[ bone.parent ].position[ 0 ];
  364. bone.pos[ 1 ] -= model.bones[ bone.parent ].position[ 1 ];
  365. bone.pos[ 2 ] -= model.bones[ bone.parent ].position[ 2 ];
  366. }
  367. bone.rigidBodyType = dictionary[ i ] !== undefined ? dictionary[ i ] : - 1;
  368. bones.push( bone );
  369. }
  370. geometry.bones = bones;
  371. };
  372. var initIKs = function () {
  373. var iks = [];
  374. // TODO: remove duplicated codes between PMD and PMX
  375. if ( model.metadata.format === 'pmd' ) {
  376. for ( var i = 0; i < model.metadata.ikCount; i ++ ) {
  377. var ik = model.iks[ i ];
  378. var param = {};
  379. param.target = ik.target;
  380. param.effector = ik.effector;
  381. param.iteration = ik.iteration;
  382. param.maxAngle = ik.maxAngle * 4;
  383. param.links = [];
  384. for ( var j = 0; j < ik.links.length; j ++ ) {
  385. var link = {};
  386. link.index = ik.links[ j ].index;
  387. if ( model.bones[ link.index ].name.indexOf( 'ひざ' ) >= 0 ) {
  388. link.limitation = new THREE.Vector3( 1.0, 0.0, 0.0 );
  389. }
  390. param.links.push( link );
  391. }
  392. iks.push( param );
  393. }
  394. } else {
  395. for ( var i = 0; i < model.metadata.boneCount; i ++ ) {
  396. var b = model.bones[ i ];
  397. var ik = b.ik;
  398. if ( ik === undefined ) {
  399. continue;
  400. }
  401. var param = {};
  402. param.target = i;
  403. param.effector = ik.effector;
  404. param.iteration = ik.iteration;
  405. param.maxAngle = ik.maxAngle;
  406. param.links = [];
  407. for ( var j = 0; j < ik.links.length; j ++ ) {
  408. var link = {};
  409. link.index = ik.links[ j ].index;
  410. link.enabled = true;
  411. if ( ik.links[ j ].angleLimitation === 1 ) {
  412. link.limitation = new THREE.Vector3( 1.0, 0.0, 0.0 );
  413. // TODO: use limitation angles
  414. // link.lowerLimitationAngle;
  415. // link.upperLimitationAngle;
  416. }
  417. param.links.push( link );
  418. }
  419. iks.push( param );
  420. }
  421. }
  422. geometry.iks = iks;
  423. };
  424. var initGrants = function () {
  425. if ( model.metadata.format === 'pmd' ) {
  426. return;
  427. }
  428. var grants = [];
  429. for ( var i = 0; i < model.metadata.boneCount; i ++ ) {
  430. var b = model.bones[ i ];
  431. var grant = b.grant;
  432. if ( grant === undefined ) {
  433. continue;
  434. }
  435. var param = {};
  436. param.index = i;
  437. param.parentIndex = grant.parentIndex;
  438. param.ratio = grant.ratio;
  439. param.isLocal = grant.isLocal;
  440. param.affectRotation = grant.affectRotation;
  441. param.affectPosition = grant.affectPosition;
  442. param.transformationClass = b.transformationClass;
  443. grants.push( param );
  444. }
  445. grants.sort( function ( a, b ) {
  446. return a.transformationClass - b.transformationClass;
  447. } );
  448. geometry.grants = grants;
  449. };
  450. var initMorphs = function () {
  451. function updateVertex( attribute, index, v, ratio ) {
  452. attribute.array[ index * 3 + 0 ] += v.position[ 0 ] * ratio;
  453. attribute.array[ index * 3 + 1 ] += v.position[ 1 ] * ratio;
  454. attribute.array[ index * 3 + 2 ] += v.position[ 2 ] * ratio;
  455. }
  456. function updateVertices( attribute, m, ratio ) {
  457. for ( var i = 0; i < m.elementCount; i ++ ) {
  458. var v = m.elements[ i ];
  459. var index;
  460. if ( model.metadata.format === 'pmd' ) {
  461. index = model.morphs[ 0 ].elements[ v.index ].index;
  462. } else {
  463. index = v.index;
  464. }
  465. updateVertex( attribute, index, v, ratio );
  466. }
  467. }
  468. var morphTargets = [];
  469. var attributes = [];
  470. for ( var i = 0; i < model.metadata.morphCount; i ++ ) {
  471. var m = model.morphs[ i ];
  472. var params = { name: m.name };
  473. var attribute = new THREE.Float32BufferAttribute( model.metadata.vertexCount * 3, 3 );
  474. attribute.name = m.name;
  475. for ( var j = 0; j < model.metadata.vertexCount * 3; j ++ ) {
  476. attribute.array[ j ] = buffer.vertices[ j ];
  477. }
  478. if ( model.metadata.format === 'pmd' ) {
  479. if ( i !== 0 ) {
  480. updateVertices( attribute, m, 1.0 );
  481. }
  482. } else {
  483. if ( m.type === 0 ) { // group
  484. for ( var j = 0; j < m.elementCount; j ++ ) {
  485. var m2 = model.morphs[ m.elements[ j ].index ];
  486. var ratio = m.elements[ j ].ratio;
  487. if ( m2.type === 1 ) {
  488. updateVertices( attribute, m2, ratio );
  489. } else {
  490. // TODO: implement
  491. }
  492. }
  493. } else if ( m.type === 1 ) { // vertex
  494. updateVertices( attribute, m, 1.0 );
  495. } else if ( m.type === 2 ) { // bone
  496. // TODO: implement
  497. } else if ( m.type === 3 ) { // uv
  498. // TODO: implement
  499. } else if ( m.type === 4 ) { // additional uv1
  500. // TODO: implement
  501. } else if ( m.type === 5 ) { // additional uv2
  502. // TODO: implement
  503. } else if ( m.type === 6 ) { // additional uv3
  504. // TODO: implement
  505. } else if ( m.type === 7 ) { // additional uv4
  506. // TODO: implement
  507. } else if ( m.type === 8 ) { // material
  508. // TODO: implement
  509. }
  510. }
  511. morphTargets.push( params );
  512. attributes.push( attribute );
  513. }
  514. geometry.morphTargets = morphTargets;
  515. geometry.morphAttributes.position = attributes;
  516. };
  517. var initMaterials = function () {
  518. var textures = {};
  519. var textureLoader = new THREE.TextureLoader( scope.manager );
  520. var tgaLoader = new THREE.TGALoader( scope.manager );
  521. var canvas = document.createElement( 'canvas' );
  522. var context = canvas.getContext( '2d' );
  523. var offset = 0;
  524. var materialParams = [];
  525. if ( scope.textureCrossOrigin !== null ) textureLoader.setCrossOrigin( scope.textureCrossOrigin );
  526. function loadTexture( filePath, params ) {
  527. if ( params === undefined ) {
  528. params = {};
  529. }
  530. var fullPath;
  531. if ( params.defaultTexturePath === true ) {
  532. try {
  533. fullPath = scope.defaultToonTextures[ parseInt( filePath.match( 'toon([0-9]{2})\.bmp$' )[ 1 ] ) ];
  534. } catch ( e ) {
  535. console.warn( 'THREE.MMDLoader: ' + filePath + ' seems like not right default texture path. Using toon00.bmp instead.' );
  536. fullPath = scope.defaultToonTextures[ 0 ];
  537. }
  538. } else {
  539. fullPath = texturePath + filePath;
  540. }
  541. if ( textures[ fullPath ] !== undefined ) return fullPath;
  542. var loader = THREE.Loader.Handlers.get( fullPath );
  543. if ( loader === null ) {
  544. loader = ( filePath.indexOf( '.tga' ) >= 0 ) ? tgaLoader : textureLoader;
  545. }
  546. var texture = loader.load( fullPath, function ( t ) {
  547. // MMD toon texture is Axis-Y oriented
  548. // but Three.js gradient map is Axis-X oriented.
  549. // So here replaces the toon texture image with the rotated one.
  550. if ( params.isToonTexture === true ) {
  551. var image = t.image;
  552. var width = image.width;
  553. var height = image.height;
  554. canvas.width = width;
  555. canvas.height = height;
  556. context.clearRect( 0, 0, width, height );
  557. context.translate( width / 2.0, height / 2.0 );
  558. context.rotate( 0.5 * Math.PI ); // 90.0 * Math.PI / 180.0
  559. context.translate( - width / 2.0, - height / 2.0 );
  560. context.drawImage( image, 0, 0 );
  561. t.image = context.getImageData( 0, 0, width, height );
  562. }
  563. t.flipY = false;
  564. t.wrapS = THREE.RepeatWrapping;
  565. t.wrapT = THREE.RepeatWrapping;
  566. for ( var i = 0; i < texture.readyCallbacks.length; i ++ ) {
  567. texture.readyCallbacks[ i ]( texture );
  568. }
  569. delete texture.readyCallbacks;
  570. }, onProgress, onError );
  571. if ( params.sphericalReflectionMapping === true ) {
  572. texture.mapping = THREE.SphericalReflectionMapping;
  573. }
  574. texture.readyCallbacks = [];
  575. textures[ fullPath ] = texture;
  576. return fullPath;
  577. }
  578. function getTexture( name, textures ) {
  579. if ( textures[ name ] === undefined ) {
  580. console.warn( 'THREE.MMDLoader: Undefined texture', name );
  581. }
  582. return textures[ name ];
  583. }
  584. for ( var i = 0; i < model.metadata.materialCount; i ++ ) {
  585. var m = model.materials[ i ];
  586. var params = {};
  587. params.faceOffset = offset;
  588. params.faceNum = m.faceCount;
  589. offset += m.faceCount;
  590. params.name = m.name;
  591. /*
  592. * Color
  593. *
  594. * MMD MeshToonMaterial
  595. * diffuse - color
  596. * specular - specular
  597. * ambient - emissive * a
  598. * (a = 1.0 without map texture or 0.2 with map texture)
  599. *
  600. * MeshToonMaterial doesn't have ambient. Set it to emissive instead.
  601. * It'll be too bright if material has map texture so using coef 0.2.
  602. */
  603. params.color = new THREE.Color( m.diffuse[ 0 ], m.diffuse[ 1 ], m.diffuse[ 2 ] );
  604. params.opacity = m.diffuse[ 3 ];
  605. params.specular = new THREE.Color( m.specular[ 0 ], m.specular[ 1 ], m.specular[ 2 ] );
  606. params.shininess = m.shininess;
  607. if ( params.opacity === 1.0 ) {
  608. params.side = THREE.FrontSide;
  609. params.transparent = false;
  610. } else {
  611. params.side = THREE.DoubleSide;
  612. params.transparent = true;
  613. }
  614. if ( model.metadata.format === 'pmd' ) {
  615. if ( m.fileName ) {
  616. var fileName = m.fileName;
  617. var fileNames = [];
  618. var index = fileName.lastIndexOf( '*' );
  619. if ( index >= 0 ) {
  620. fileNames.push( fileName.slice( 0, index ) );
  621. fileNames.push( fileName.slice( index + 1 ) );
  622. } else {
  623. fileNames.push( fileName );
  624. }
  625. for ( var j = 0; j < fileNames.length; j ++ ) {
  626. var n = fileNames[ j ];
  627. if ( n.indexOf( '.sph' ) >= 0 || n.indexOf( '.spa' ) >= 0 ) {
  628. params.envMap = loadTexture( n, { sphericalReflectionMapping: true } );
  629. if ( n.indexOf( '.sph' ) >= 0 ) {
  630. params.envMapType = THREE.MultiplyOperation;
  631. } else {
  632. params.envMapType = THREE.AddOperation;
  633. }
  634. } else {
  635. params.map = loadTexture( n );
  636. }
  637. }
  638. }
  639. } else {
  640. if ( m.textureIndex !== - 1 ) {
  641. var n = model.textures[ m.textureIndex ];
  642. params.map = loadTexture( n );
  643. }
  644. // TODO: support m.envFlag === 3
  645. if ( m.envTextureIndex !== - 1 && ( m.envFlag === 1 || m.envFlag == 2 ) ) {
  646. var n = model.textures[ m.envTextureIndex ];
  647. params.envMap = loadTexture( n, { sphericalReflectionMapping: true } );
  648. if ( m.envFlag === 1 ) {
  649. params.envMapType = THREE.MultiplyOperation;
  650. } else {
  651. params.envMapType = THREE.AddOperation;
  652. }
  653. }
  654. }
  655. var coef = ( params.map === undefined ) ? 1.0 : 0.2;
  656. params.emissive = new THREE.Color( m.ambient[ 0 ] * coef, m.ambient[ 1 ] * coef, m.ambient[ 2 ] * coef );
  657. materialParams.push( params );
  658. }
  659. for ( var i = 0; i < materialParams.length; i ++ ) {
  660. var p = materialParams[ i ];
  661. var p2 = model.materials[ i ];
  662. var m = new THREE.MeshToonMaterial();
  663. geometry.addGroup( p.faceOffset * 3, p.faceNum * 3, i );
  664. if ( p.name !== undefined ) m.name = p.name;
  665. m.skinning = geometry.bones.length > 0 ? true : false;
  666. m.morphTargets = geometry.morphTargets.length > 0 ? true : false;
  667. m.lights = true;
  668. m.side = ( model.metadata.format === 'pmx' && ( p2.flag & 0x1 ) === 1 ) ? THREE.DoubleSide : p.side;
  669. m.transparent = p.transparent;
  670. m.fog = true;
  671. m.blending = THREE.CustomBlending;
  672. m.blendSrc = THREE.SrcAlphaFactor;
  673. m.blendDst = THREE.OneMinusSrcAlphaFactor;
  674. m.blendSrcAlpha = THREE.SrcAlphaFactor;
  675. m.blendDstAlpha = THREE.DstAlphaFactor;
  676. if ( p.map !== undefined ) {
  677. m.faceOffset = p.faceOffset;
  678. m.faceNum = p.faceNum;
  679. // Check if this part of the texture image the material uses requires transparency
  680. function checkTextureTransparency( m ) {
  681. m.map.readyCallbacks.push( function ( t ) {
  682. // Is there any efficient ways?
  683. function createImageData( image ) {
  684. var c = document.createElement( 'canvas' );
  685. c.width = image.width;
  686. c.height = image.height;
  687. var ctx = c.getContext( '2d' );
  688. ctx.drawImage( image, 0, 0 );
  689. return ctx.getImageData( 0, 0, c.width, c.height );
  690. }
  691. function detectTextureTransparency( image, uvs, indices ) {
  692. var width = image.width;
  693. var height = image.height;
  694. var data = image.data;
  695. var threshold = 253;
  696. if ( data.length / ( width * height ) !== 4 ) {
  697. return false;
  698. }
  699. for ( var i = 0; i < indices.length; i += 3 ) {
  700. var centerUV = { x: 0.0, y: 0.0 };
  701. for ( var j = 0; j < 3; j ++ ) {
  702. var index = indices[ i * 3 + j ];
  703. var uv = { x: uvs[ index * 2 + 0 ], y: uvs[ index * 2 + 1 ] };
  704. if ( getAlphaByUv( image, uv ) < threshold ) {
  705. return true;
  706. }
  707. centerUV.x += uv.x;
  708. centerUV.y += uv.y;
  709. }
  710. centerUV.x /= 3;
  711. centerUV.y /= 3;
  712. if ( getAlphaByUv( image, centerUV ) < threshold ) {
  713. return true;
  714. }
  715. }
  716. return false;
  717. }
  718. /*
  719. * This method expects
  720. * t.flipY = false
  721. * t.wrapS = THREE.RepeatWrapping
  722. * t.wrapT = THREE.RepeatWrapping
  723. * TODO: more precise
  724. */
  725. function getAlphaByUv( image, uv ) {
  726. var width = image.width;
  727. var height = image.height;
  728. var x = Math.round( uv.x * width ) % width;
  729. var y = Math.round( uv.y * height ) % height;
  730. if ( x < 0 ) {
  731. x += width;
  732. }
  733. if ( y < 0 ) {
  734. y += height;
  735. }
  736. var index = y * width + x;
  737. return image.data[ index * 4 + 3 ];
  738. }
  739. var imageData = t.image.data !== undefined ? t.image : createImageData( t.image );
  740. var indices = geometry.index.array.slice( m.faceOffset * 3, m.faceOffset * 3 + m.faceNum * 3 );
  741. if ( detectTextureTransparency( imageData, geometry.attributes.uv.array, indices ) ) m.transparent = true;
  742. delete m.faceOffset;
  743. delete m.faceNum;
  744. } );
  745. }
  746. m.map = getTexture( p.map, textures );
  747. checkTextureTransparency( m );
  748. }
  749. if ( p.envMap !== undefined ) {
  750. m.envMap = getTexture( p.envMap, textures );
  751. m.combine = p.envMapType;
  752. }
  753. m.opacity = p.opacity;
  754. m.color = p.color;
  755. if ( p.emissive !== undefined ) {
  756. m.emissive = p.emissive;
  757. }
  758. m.specular = p.specular;
  759. m.shininess = Math.max( p.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  760. if ( model.metadata.format === 'pmd' ) {
  761. function isDefaultToonTexture( n ) {
  762. if ( n.length !== 10 ) {
  763. return false;
  764. }
  765. return n.match( /toon(10|0[0-9]).bmp/ ) === null ? false : true;
  766. }
  767. // parameters for OutlineEffect
  768. m.outlineParameters = {
  769. thickness: p2.edgeFlag === 1 ? 0.003 : 0.0,
  770. color: new THREE.Color( 0.0, 0.0, 0.0 ),
  771. alpha: 1.0
  772. };
  773. if ( m.outlineParameters.thickness === 0.0 ) m.outlineParameters.visible = false;
  774. var toonFileName = ( p2.toonIndex === - 1 ) ? 'toon00.bmp' : model.toonTextures[ p2.toonIndex ].fileName;
  775. var uuid = loadTexture( toonFileName, { isToonTexture: true, defaultTexturePath: isDefaultToonTexture( toonFileName ) } );
  776. m.gradientMap = getTexture( uuid, textures );
  777. } else {
  778. // parameters for OutlineEffect
  779. m.outlineParameters = {
  780. thickness: p2.edgeSize / 300,
  781. color: new THREE.Color( p2.edgeColor[ 0 ], p2.edgeColor[ 1 ], p2.edgeColor[ 2 ] ),
  782. alpha: p2.edgeColor[ 3 ]
  783. };
  784. if ( ( p2.flag & 0x10 ) === 0 || m.outlineParameters.thickness === 0.0 ) m.outlineParameters.visible = false;
  785. var toonFileName, isDefaultToon;
  786. if ( p2.toonIndex === - 1 || p2.toonFlag !== 0 ) {
  787. var num = p2.toonIndex + 1;
  788. toonFileName = 'toon' + ( num < 10 ? '0' + num : num ) + '.bmp';
  789. isDefaultToon = true;
  790. } else {
  791. toonFileName = model.textures[ p2.toonIndex ];
  792. isDefaultToon = false;
  793. }
  794. var uuid = loadTexture( toonFileName, { isToonTexture: true, defaultTexturePath: isDefaultToon } );
  795. m.gradientMap = getTexture( uuid, textures );
  796. }
  797. materials.push( m );
  798. }
  799. if ( model.metadata.format === 'pmx' ) {
  800. function checkAlphaMorph( morph, elements ) {
  801. if ( morph.type !== 8 ) {
  802. return;
  803. }
  804. for ( var i = 0; i < elements.length; i ++ ) {
  805. var e = elements[ i ];
  806. if ( e.index === - 1 ) {
  807. continue;
  808. }
  809. var m = materials[ e.index ];
  810. if ( m.opacity !== e.diffuse[ 3 ] ) {
  811. m.transparent = true;
  812. }
  813. }
  814. }
  815. for ( var i = 0; i < model.morphs.length; i ++ ) {
  816. var morph = model.morphs[ i ];
  817. var elements = morph.elements;
  818. if ( morph.type === 0 ) {
  819. for ( var j = 0; j < elements.length; j ++ ) {
  820. var morph2 = model.morphs[ elements[ j ].index ];
  821. var elements2 = morph2.elements;
  822. checkAlphaMorph( morph2, elements2 );
  823. }
  824. } else {
  825. checkAlphaMorph( morph, elements );
  826. }
  827. }
  828. }
  829. };
  830. var initPhysics = function () {
  831. var rigidBodies = [];
  832. var constraints = [];
  833. for ( var i = 0; i < model.metadata.rigidBodyCount; i ++ ) {
  834. var b = model.rigidBodies[ i ];
  835. var keys = Object.keys( b );
  836. var p = {};
  837. for ( var j = 0; j < keys.length; j ++ ) {
  838. var key = keys[ j ];
  839. p[ key ] = b[ key ];
  840. }
  841. /*
  842. * RigidBody position parameter in PMX seems global position
  843. * while the one in PMD seems offset from corresponding bone.
  844. * So unify being offset.
  845. */
  846. if ( model.metadata.format === 'pmx' ) {
  847. if ( p.boneIndex !== - 1 ) {
  848. var bone = model.bones[ p.boneIndex ];
  849. p.position[ 0 ] -= bone.position[ 0 ];
  850. p.position[ 1 ] -= bone.position[ 1 ];
  851. p.position[ 2 ] -= bone.position[ 2 ];
  852. }
  853. }
  854. rigidBodies.push( p );
  855. }
  856. for ( var i = 0; i < model.metadata.constraintCount; i ++ ) {
  857. var c = model.constraints[ i ];
  858. var keys = Object.keys( c );
  859. var p = {};
  860. for ( var j = 0; j < keys.length; j ++ ) {
  861. var key = keys[ j ];
  862. p[ key ] = c[ key ];
  863. }
  864. var bodyA = rigidBodies[ p.rigidBodyIndex1 ];
  865. var bodyB = rigidBodies[ p.rigidBodyIndex2 ];
  866. /*
  867. * Refer to http://www20.atpages.jp/katwat/wp/?p=4135
  868. */
  869. if ( bodyA.type !== 0 && bodyB.type === 2 ) {
  870. if ( bodyA.boneIndex !== - 1 && bodyB.boneIndex !== - 1 &&
  871. model.bones[ bodyB.boneIndex ].parentIndex === bodyA.boneIndex ) {
  872. bodyB.type = 1;
  873. }
  874. }
  875. constraints.push( p );
  876. }
  877. geometry.rigidBodies = rigidBodies;
  878. geometry.constraints = constraints;
  879. };
  880. var initGeometry = function () {
  881. geometry.setIndex( buffer.indices );
  882. geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( buffer.vertices, 3 ) );
  883. geometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( buffer.normals, 3 ) );
  884. geometry.addAttribute( 'uv', new THREE.Float32BufferAttribute( buffer.uvs, 2 ) );
  885. geometry.addAttribute( 'skinIndex', new THREE.Uint16BufferAttribute( buffer.skinIndices, 4 ) );
  886. geometry.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( buffer.skinWeights, 4 ) );
  887. geometry.computeBoundingSphere();
  888. geometry.mmdFormat = model.metadata.format;
  889. };
  890. initVartices();
  891. initFaces();
  892. initBones();
  893. initIKs();
  894. initGrants();
  895. initMorphs();
  896. initMaterials();
  897. initPhysics();
  898. initGeometry();
  899. var mesh = new THREE.SkinnedMesh( geometry, materials );
  900. // console.log( mesh ); // for console debug
  901. return mesh;
  902. };
  903. THREE.MMDLoader.prototype.createAnimation = function ( mesh, vmd, name ) {
  904. var helper = new THREE.MMDLoader.DataCreationHelper();
  905. var initMotionAnimations = function () {
  906. if ( vmd.metadata.motionCount === 0 ) {
  907. return;
  908. }
  909. var bones = mesh.geometry.bones;
  910. var orderedMotions = helper.createOrderedMotionArrays( bones, vmd.motions, 'boneName' );
  911. var tracks = [];
  912. var pushInterpolation = function ( array, interpolation, index ) {
  913. array.push( interpolation[ index + 0 ] / 127 ); // x1
  914. array.push( interpolation[ index + 8 ] / 127 ); // x2
  915. array.push( interpolation[ index + 4 ] / 127 ); // y1
  916. array.push( interpolation[ index + 12 ] / 127 ); // y2
  917. };
  918. var createTrack = function ( node, type, times, values, interpolations ) {
  919. var track = new THREE[ type ]( node, times, values );
  920. track.createInterpolant = function InterpolantFactoryMethodCubicBezier( result ) {
  921. return new THREE.MMDLoader.CubicBezierInterpolation( this.times, this.values, this.getValueSize(), result, new Float32Array( interpolations ) );
  922. };
  923. return track;
  924. };
  925. for ( var i = 0; i < orderedMotions.length; i ++ ) {
  926. var times = [];
  927. var positions = [];
  928. var rotations = [];
  929. var pInterpolations = [];
  930. var rInterpolations = [];
  931. var bone = bones[ i ];
  932. var array = orderedMotions[ i ];
  933. for ( var j = 0; j < array.length; j ++ ) {
  934. var time = array[ j ].frameNum / 30;
  935. var pos = array[ j ].position;
  936. var rot = array[ j ].rotation;
  937. var interpolation = array[ j ].interpolation;
  938. times.push( time );
  939. for ( var k = 0; k < 3; k ++ ) {
  940. positions.push( bone.pos[ k ] + pos[ k ] );
  941. }
  942. for ( var k = 0; k < 4; k ++ ) {
  943. rotations.push( rot[ k ] );
  944. }
  945. for ( var k = 0; k < 3; k ++ ) {
  946. pushInterpolation( pInterpolations, interpolation, k );
  947. }
  948. pushInterpolation( rInterpolations, interpolation, 3 );
  949. }
  950. if ( times.length === 0 ) continue;
  951. var boneName = '.bones[' + bone.name + ']';
  952. tracks.push( createTrack( boneName + '.position', 'VectorKeyframeTrack', times, positions, pInterpolations ) );
  953. tracks.push( createTrack( boneName + '.quaternion', 'QuaternionKeyframeTrack', times, rotations, rInterpolations ) );
  954. }
  955. var clip = new THREE.AnimationClip( name === undefined ? THREE.Math.generateUUID() : name, - 1, tracks );
  956. if ( mesh.geometry.animations === undefined ) mesh.geometry.animations = [];
  957. mesh.geometry.animations.push( clip );
  958. };
  959. var initMorphAnimations = function () {
  960. if ( vmd.metadata.morphCount === 0 ) {
  961. return;
  962. }
  963. var orderedMorphs = helper.createOrderedMotionArrays( mesh.geometry.morphTargets, vmd.morphs, 'morphName' );
  964. var tracks = [];
  965. for ( var i = 0; i < orderedMorphs.length; i ++ ) {
  966. var times = [];
  967. var values = [];
  968. var array = orderedMorphs[ i ];
  969. for ( var j = 0; j < array.length; j ++ ) {
  970. times.push( array[ j ].frameNum / 30 );
  971. values.push( array[ j ].weight );
  972. }
  973. if ( times.length === 0 ) continue;
  974. tracks.push( new THREE.NumberKeyframeTrack( '.morphTargetInfluences[' + i + ']', times, values ) );
  975. }
  976. var clip = new THREE.AnimationClip( name === undefined ? THREE.Math.generateUUID() : name + 'Morph', - 1, tracks );
  977. if ( mesh.geometry.animations === undefined ) mesh.geometry.animations = [];
  978. mesh.geometry.animations.push( clip );
  979. };
  980. initMotionAnimations();
  981. initMorphAnimations();
  982. };
  983. THREE.MMDLoader.DataCreationHelper = function () {
  984. };
  985. THREE.MMDLoader.DataCreationHelper.prototype = {
  986. constructor: THREE.MMDLoader.DataCreationHelper,
  987. /*
  988. * Note: Sometimes to use Japanese Unicode characters runs into problems in Three.js.
  989. * In such a case, use this method to convert it to Unicode hex charcode strings,
  990. * like 'あいう' -> '0x30420x30440x3046'
  991. */
  992. toCharcodeStrings: function ( s ) {
  993. var str = '';
  994. for ( var i = 0; i < s.length; i ++ ) {
  995. str += '0x' + ( '0000' + s[ i ].charCodeAt().toString( 16 ) ).substr( - 4 );
  996. }
  997. return str;
  998. },
  999. createDictionary: function ( array ) {
  1000. var dict = {};
  1001. for ( var i = 0; i < array.length; i ++ ) {
  1002. dict[ array[ i ].name ] = i;
  1003. }
  1004. return dict;
  1005. },
  1006. initializeMotionArrays: function ( array ) {
  1007. var result = [];
  1008. for ( var i = 0; i < array.length; i ++ ) {
  1009. result[ i ] = [];
  1010. }
  1011. return result;
  1012. },
  1013. sortMotionArray: function ( array ) {
  1014. array.sort( function ( a, b ) {
  1015. return a.frameNum - b.frameNum;
  1016. } );
  1017. },
  1018. sortMotionArrays: function ( arrays ) {
  1019. for ( var i = 0; i < arrays.length; i ++ ) {
  1020. this.sortMotionArray( arrays[ i ] );
  1021. }
  1022. },
  1023. createMotionArray: function ( array ) {
  1024. var result = [];
  1025. for ( var i = 0; i < array.length; i ++ ) {
  1026. result.push( array[ i ] );
  1027. }
  1028. return result;
  1029. },
  1030. createMotionArrays: function ( array, result, dict, key ) {
  1031. for ( var i = 0; i < array.length; i ++ ) {
  1032. var a = array[ i ];
  1033. var num = dict[ a[ key ] ];
  1034. if ( num === undefined ) {
  1035. continue;
  1036. }
  1037. result[ num ].push( a );
  1038. }
  1039. },
  1040. createOrderedMotionArray: function ( array ) {
  1041. var result = this.createMotionArray( array );
  1042. this.sortMotionArray( result );
  1043. return result;
  1044. },
  1045. createOrderedMotionArrays: function ( targetArray, motionArray, key ) {
  1046. var dict = this.createDictionary( targetArray );
  1047. var result = this.initializeMotionArrays( targetArray );
  1048. this.createMotionArrays( motionArray, result, dict, key );
  1049. this.sortMotionArrays( result );
  1050. return result;
  1051. }
  1052. };
  1053. THREE.MMDLoader.CubicBezierInterpolation = function ( parameterPositions, sampleValues, sampleSize, resultBuffer, params ) {
  1054. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  1055. this.params = params;
  1056. };
  1057. THREE.MMDLoader.CubicBezierInterpolation.prototype = Object.create( THREE.LinearInterpolant.prototype );
  1058. THREE.MMDLoader.CubicBezierInterpolation.prototype.constructor = THREE.MMDLoader.CubicBezierInterpolation;
  1059. THREE.MMDLoader.CubicBezierInterpolation.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  1060. var result = this.resultBuffer;
  1061. var values = this.sampleValues;
  1062. var stride = this.valueSize;
  1063. var offset1 = i1 * stride;
  1064. var offset0 = offset1 - stride;
  1065. // No interpolation if next key frame is in one frame in 30fps. This is from MMD animation spec.
  1066. var weight1 = ( ( t1 - t0 ) < 1 / 30 * 1.5 ) ? 0.0 : ( t - t0 ) / ( t1 - t0 );
  1067. if ( stride === 4 ) { // Quaternion
  1068. var x1 = this.params[ i1 * 4 + 0 ];
  1069. var x2 = this.params[ i1 * 4 + 1 ];
  1070. var y1 = this.params[ i1 * 4 + 2 ];
  1071. var y2 = this.params[ i1 * 4 + 3 ];
  1072. var ratio = this._calculate( x1, x2, y1, y2, weight1 );
  1073. THREE.Quaternion.slerpFlat( result, 0, values, offset0, values, offset1, ratio );
  1074. } else if ( stride === 3 ) { // Vector3
  1075. for ( var i = 0; i !== stride; ++ i ) {
  1076. var x1 = this.params[ i1 * 12 + i * 4 + 0 ];
  1077. var x2 = this.params[ i1 * 12 + i * 4 + 1 ];
  1078. var y1 = this.params[ i1 * 12 + i * 4 + 2 ];
  1079. var y2 = this.params[ i1 * 12 + i * 4 + 3 ];
  1080. var ratio = this._calculate( x1, x2, y1, y2, weight1 );
  1081. result[ i ] = values[ offset0 + i ] * ( 1 - ratio ) + values[ offset1 + i ] * ratio;
  1082. }
  1083. } else { // Number
  1084. var x1 = this.params[ i1 * 4 + 0 ];
  1085. var x2 = this.params[ i1 * 4 + 1 ];
  1086. var y1 = this.params[ i1 * 4 + 2 ];
  1087. var y2 = this.params[ i1 * 4 + 3 ];
  1088. var ratio = this._calculate( x1, x2, y1, y2, weight1 );
  1089. result[ 0 ] = values[ offset0 ] * ( 1 - ratio ) + values[ offset1 ] * ratio;
  1090. }
  1091. return result;
  1092. };
  1093. THREE.MMDLoader.CubicBezierInterpolation.prototype._calculate = function ( x1, x2, y1, y2, x ) {
  1094. /*
  1095. * Cubic Bezier curves
  1096. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Cubic_B.C3.A9zier_curves
  1097. *
  1098. * B(t) = ( 1 - t ) ^ 3 * P0
  1099. * + 3 * ( 1 - t ) ^ 2 * t * P1
  1100. * + 3 * ( 1 - t ) * t^2 * P2
  1101. * + t ^ 3 * P3
  1102. * ( 0 <= t <= 1 )
  1103. *
  1104. * MMD uses Cubic Bezier curves for bone and camera animation interpolation.
  1105. * http://d.hatena.ne.jp/edvakf/20111016/1318716097
  1106. *
  1107. * x = ( 1 - t ) ^ 3 * x0
  1108. * + 3 * ( 1 - t ) ^ 2 * t * x1
  1109. * + 3 * ( 1 - t ) * t^2 * x2
  1110. * + t ^ 3 * x3
  1111. * y = ( 1 - t ) ^ 3 * y0
  1112. * + 3 * ( 1 - t ) ^ 2 * t * y1
  1113. * + 3 * ( 1 - t ) * t^2 * y2
  1114. * + t ^ 3 * y3
  1115. * ( x0 = 0, y0 = 0 )
  1116. * ( x3 = 1, y3 = 1 )
  1117. * ( 0 <= t, x1, x2, y1, y2 <= 1 )
  1118. *
  1119. * Here solves this equation with Bisection method,
  1120. * https://en.wikipedia.org/wiki/Bisection_method
  1121. * gets t, and then calculate y.
  1122. *
  1123. * f(t) = 3 * ( 1 - t ) ^ 2 * t * x1
  1124. * + 3 * ( 1 - t ) * t^2 * x2
  1125. * + t ^ 3 - x = 0
  1126. *
  1127. * (Another option: Newton's method
  1128. * https://en.wikipedia.org/wiki/Newton%27s_method)
  1129. */
  1130. var c = 0.5;
  1131. var t = c;
  1132. var s = 1.0 - t;
  1133. var loop = 15;
  1134. var eps = 1e-5;
  1135. var math = Math;
  1136. var sst3, stt3, ttt;
  1137. for ( var i = 0; i < loop; i ++ ) {
  1138. sst3 = 3.0 * s * s * t;
  1139. stt3 = 3.0 * s * t * t;
  1140. ttt = t * t * t;
  1141. var ft = ( sst3 * x1 ) + ( stt3 * x2 ) + ( ttt ) - x;
  1142. if ( math.abs( ft ) < eps ) break;
  1143. c /= 2.0;
  1144. t += ( ft < 0 ) ? c : - c;
  1145. s = 1.0 - t;
  1146. }
  1147. return ( sst3 * y1 ) + ( stt3 * y2 ) + ttt;
  1148. };
  1149. THREE.MMDAudioManager = function ( audio, listener, p ) {
  1150. var params = ( p === null || p === undefined ) ? {} : p;
  1151. this.audio = audio;
  1152. this.listener = listener;
  1153. this.elapsedTime = 0.0;
  1154. this.currentTime = 0.0;
  1155. this.delayTime = params.delayTime !== undefined ? params.delayTime : 0.0;
  1156. this.audioDuration = this.audio.buffer.duration;
  1157. this.duration = this.audioDuration + this.delayTime;
  1158. };
  1159. THREE.MMDAudioManager.prototype = {
  1160. constructor: THREE.MMDAudioManager,
  1161. control: function ( delta ) {
  1162. this.elapsed += delta;
  1163. this.currentTime += delta;
  1164. if ( this.checkIfStopAudio() ) {
  1165. this.audio.stop();
  1166. }
  1167. if ( this.checkIfStartAudio() ) {
  1168. this.audio.play();
  1169. }
  1170. },
  1171. checkIfStartAudio: function () {
  1172. if ( this.audio.isPlaying ) {
  1173. return false;
  1174. }
  1175. while ( this.currentTime >= this.duration ) {
  1176. this.currentTime -= this.duration;
  1177. }
  1178. if ( this.currentTime < this.delayTime ) {
  1179. return false;
  1180. }
  1181. this.audio.startTime = this.currentTime - this.delayTime;
  1182. return true;
  1183. },
  1184. checkIfStopAudio: function () {
  1185. if ( ! this.audio.isPlaying ) {
  1186. return false;
  1187. }
  1188. if ( this.currentTime >= this.duration ) {
  1189. return true;
  1190. }
  1191. return false;
  1192. }
  1193. };
  1194. THREE.MMDGrantSolver = function ( mesh ) {
  1195. this.mesh = mesh;
  1196. };
  1197. THREE.MMDGrantSolver.prototype = {
  1198. constructor: THREE.MMDGrantSolver,
  1199. update: function () {
  1200. var q = new THREE.Quaternion();
  1201. return function () {
  1202. for ( var i = 0; i < this.mesh.geometry.grants.length; i ++ ) {
  1203. var g = this.mesh.geometry.grants[ i ];
  1204. var b = this.mesh.skeleton.bones[ g.index ];
  1205. var pb = this.mesh.skeleton.bones[ g.parentIndex ];
  1206. if ( g.isLocal ) {
  1207. // TODO: implement
  1208. if ( g.affectPosition ) {
  1209. }
  1210. // TODO: implement
  1211. if ( g.affectRotation ) {
  1212. }
  1213. } else {
  1214. // TODO: implement
  1215. if ( g.affectPosition ) {
  1216. }
  1217. if ( g.affectRotation ) {
  1218. q.set( 0, 0, 0, 1 );
  1219. q.slerp( pb.quaternion, g.ratio );
  1220. b.quaternion.multiply( q );
  1221. }
  1222. }
  1223. }
  1224. };
  1225. }()
  1226. };
  1227. THREE.MMDHelper = function () {
  1228. this.meshes = [];
  1229. this.doAnimation = true;
  1230. this.doIk = true;
  1231. this.doGrant = true;
  1232. this.doPhysics = true;
  1233. this.doCameraAnimation = true;
  1234. this.sharedPhysics = false;
  1235. this.masterPhysics = null;
  1236. this.audioManager = null;
  1237. this.camera = null;
  1238. };
  1239. THREE.MMDHelper.prototype = {
  1240. constructor: THREE.MMDHelper,
  1241. add: function ( mesh ) {
  1242. if ( ! ( mesh instanceof THREE.SkinnedMesh ) ) {
  1243. throw new Error( 'THREE.MMDHelper.add() accepts only THREE.SkinnedMesh instance.' );
  1244. }
  1245. if ( mesh.mixer === undefined ) mesh.mixer = null;
  1246. if ( mesh.ikSolver === undefined ) mesh.ikSolver = null;
  1247. if ( mesh.grantSolver === undefined ) mesh.grantSolver = null;
  1248. if ( mesh.physics === undefined ) mesh.physics = null;
  1249. if ( mesh.looped === undefined ) mesh.looped = false;
  1250. this.meshes.push( mesh );
  1251. // workaround until I make IK and Physics Animation plugin
  1252. this.initBackupBones( mesh );
  1253. },
  1254. setAudio: function ( audio, listener, params ) {
  1255. this.audioManager = new THREE.MMDAudioManager( audio, listener, params );
  1256. },
  1257. setCamera: function ( camera ) {
  1258. camera.mixer = null;
  1259. this.camera = camera;
  1260. },
  1261. setPhysicses: function ( params ) {
  1262. for ( var i = 0; i < this.meshes.length; i ++ ) {
  1263. this.setPhysics( this.meshes[ i ], params );
  1264. }
  1265. },
  1266. setPhysics: function ( mesh, params ) {
  1267. params = ( params === undefined ) ? {} : Object.assign( {}, params );
  1268. if ( params.world === undefined && this.sharedPhysics ) {
  1269. var masterPhysics = this.getMasterPhysics();
  1270. if ( masterPhysics !== null ) params.world = masterPhysics.world;
  1271. }
  1272. var warmup = params.warmup !== undefined ? params.warmup : 60;
  1273. var physics = new THREE.MMDPhysics( mesh, params );
  1274. if ( mesh.mixer !== null && mesh.mixer !== undefined && params.preventAnimationWarmup !== true ) {
  1275. this.animateOneMesh( 0, mesh );
  1276. physics.reset();
  1277. }
  1278. physics.warmup( warmup );
  1279. this.updateIKParametersDependingOnPhysicsEnabled( mesh, true );
  1280. mesh.physics = physics;
  1281. },
  1282. getMasterPhysics: function () {
  1283. if ( this.masterPhysics !== null ) return this.masterPhysics;
  1284. for ( var i = 0, il = this.meshes.length; i < il; i ++ ) {
  1285. var physics = this.meshes[ i ].physics;
  1286. if ( physics !== undefined && physics !== null ) {
  1287. this.masterPhysics = physics;
  1288. return this.masterPhysics;
  1289. }
  1290. }
  1291. return null;
  1292. },
  1293. enablePhysics: function ( enabled ) {
  1294. if ( enabled === true ) {
  1295. this.doPhysics = true;
  1296. } else {
  1297. this.doPhysics = false;
  1298. }
  1299. for ( var i = 0, il = this.meshes.length; i < il; i ++ ) {
  1300. this.updateIKParametersDependingOnPhysicsEnabled( this.meshes[ i ], enabled );
  1301. }
  1302. },
  1303. updateIKParametersDependingOnPhysicsEnabled: function ( mesh, physicsEnabled ) {
  1304. var iks = mesh.geometry.iks;
  1305. var bones = mesh.geometry.bones;
  1306. for ( var j = 0, jl = iks.length; j < jl; j ++ ) {
  1307. var ik = iks[ j ];
  1308. var links = ik.links;
  1309. for ( var k = 0, kl = links.length; k < kl; k ++ ) {
  1310. var link = links[ k ];
  1311. if ( physicsEnabled === true ) {
  1312. // disable IK of the bone the corresponding rigidBody type of which is 1 or 2
  1313. // because its rotation will be overriden by physics
  1314. link.enabled = bones[ link.index ].rigidBodyType > 0 ? false : true;
  1315. } else {
  1316. link.enabled = true;
  1317. }
  1318. }
  1319. }
  1320. },
  1321. setAnimations: function () {
  1322. for ( var i = 0; i < this.meshes.length; i ++ ) {
  1323. this.setAnimation( this.meshes[ i ] );
  1324. }
  1325. },
  1326. setAnimation: function ( mesh ) {
  1327. if ( mesh.geometry.animations !== undefined ) {
  1328. mesh.mixer = new THREE.AnimationMixer( mesh );
  1329. // TODO: find a workaround not to access (seems like) private properties
  1330. // the name of them begins with "_".
  1331. mesh.mixer.addEventListener( 'loop', function ( e ) {
  1332. if ( e.action._clip.tracks.length > 0 &&
  1333. e.action._clip.tracks[ 0 ].name.indexOf( '.bones' ) !== 0 ) return;
  1334. var mesh = e.target._root;
  1335. mesh.looped = true;
  1336. } );
  1337. var foundAnimation = false;
  1338. var foundMorphAnimation = false;
  1339. for ( var i = 0; i < mesh.geometry.animations.length; i ++ ) {
  1340. var clip = mesh.geometry.animations[ i ];
  1341. var action = mesh.mixer.clipAction( clip );
  1342. if ( clip.tracks.length > 0 && clip.tracks[ 0 ].name.indexOf( '.morphTargetInfluences' ) === 0 ) {
  1343. if ( ! foundMorphAnimation ) {
  1344. action.play();
  1345. foundMorphAnimation = true;
  1346. }
  1347. } else {
  1348. if ( ! foundAnimation ) {
  1349. action.play();
  1350. foundAnimation = true;
  1351. }
  1352. }
  1353. }
  1354. if ( foundAnimation ) {
  1355. mesh.ikSolver = new THREE.CCDIKSolver( mesh );
  1356. if ( mesh.geometry.grants !== undefined ) {
  1357. mesh.grantSolver = new THREE.MMDGrantSolver( mesh );
  1358. }
  1359. }
  1360. }
  1361. },
  1362. setCameraAnimation: function ( camera ) {
  1363. if ( camera.animations !== undefined ) {
  1364. camera.mixer = new THREE.AnimationMixer( camera );
  1365. camera.mixer.clipAction( camera.animations[ 0 ] ).play();
  1366. }
  1367. },
  1368. /*
  1369. * detect the longest duration among model, camera, and audio animations and then
  1370. * set it to them to sync.
  1371. * TODO: touching private properties ( ._actions and ._clip ) so consider better way
  1372. * to access them for safe and modularity.
  1373. */
  1374. unifyAnimationDuration: function ( params ) {
  1375. params = params === undefined ? {} : params;
  1376. var max = 0.0;
  1377. var camera = this.camera;
  1378. var audioManager = this.audioManager;
  1379. // check the longest duration
  1380. for ( var i = 0; i < this.meshes.length; i ++ ) {
  1381. var mesh = this.meshes[ i ];
  1382. var mixer = mesh.mixer;
  1383. if ( mixer === null ) {
  1384. continue;
  1385. }
  1386. for ( var j = 0; j < mixer._actions.length; j ++ ) {
  1387. var action = mixer._actions[ j ];
  1388. max = Math.max( max, action._clip.duration );
  1389. }
  1390. }
  1391. if ( camera !== null && camera.mixer !== null ) {
  1392. var mixer = camera.mixer;
  1393. for ( var i = 0; i < mixer._actions.length; i ++ ) {
  1394. var action = mixer._actions[ i ];
  1395. max = Math.max( max, action._clip.duration );
  1396. }
  1397. }
  1398. if ( audioManager !== null ) {
  1399. max = Math.max( max, audioManager.duration );
  1400. }
  1401. if ( params.afterglow !== undefined ) {
  1402. max += params.afterglow;
  1403. }
  1404. // set the duration
  1405. for ( var i = 0; i < this.meshes.length; i ++ ) {
  1406. var mesh = this.meshes[ i ];
  1407. var mixer = mesh.mixer;
  1408. if ( mixer === null ) {
  1409. continue;
  1410. }
  1411. for ( var j = 0; j < mixer._actions.length; j ++ ) {
  1412. var action = mixer._actions[ j ];
  1413. action._clip.duration = max;
  1414. }
  1415. }
  1416. if ( camera !== null && camera.mixer !== null ) {
  1417. var mixer = camera.mixer;
  1418. for ( var i = 0; i < mixer._actions.length; i ++ ) {
  1419. var action = mixer._actions[ i ];
  1420. action._clip.duration = max;
  1421. }
  1422. }
  1423. if ( audioManager !== null ) {
  1424. audioManager.duration = max;
  1425. }
  1426. },
  1427. controlAudio: function ( delta ) {
  1428. if ( this.audioManager === null ) {
  1429. return;
  1430. }
  1431. this.audioManager.control( delta );
  1432. },
  1433. animate: function ( delta ) {
  1434. this.controlAudio( delta );
  1435. for ( var i = 0; i < this.meshes.length; i ++ ) {
  1436. this.animateOneMesh( delta, this.meshes[ i ] );
  1437. }
  1438. if ( this.sharedPhysics ) this.updateSharedPhysics( delta );
  1439. this.animateCamera( delta );
  1440. },
  1441. animateOneMesh: function ( delta, mesh ) {
  1442. var mixer = mesh.mixer;
  1443. var ikSolver = mesh.ikSolver;
  1444. var grantSolver = mesh.grantSolver;
  1445. var physics = mesh.physics;
  1446. if ( mixer !== null && this.doAnimation === true ) {
  1447. // restore/backupBones are workaround
  1448. // until I make IK, Grant, and Physics Animation plugin
  1449. this.restoreBones( mesh );
  1450. mixer.update( delta );
  1451. this.backupBones( mesh );
  1452. }
  1453. if ( ikSolver !== null && this.doIk === true ) {
  1454. ikSolver.update();
  1455. }
  1456. if ( grantSolver !== null && this.doGrant === true ) {
  1457. grantSolver.update();
  1458. }
  1459. if ( mesh.looped === true ) {
  1460. if ( physics !== null ) physics.reset();
  1461. mesh.looped = false;
  1462. }
  1463. if ( physics !== null && this.doPhysics && ! this.sharedPhysics ) {
  1464. physics.update( delta );
  1465. }
  1466. },
  1467. updateSharedPhysics: function ( delta ) {
  1468. if ( this.meshes.length === 0 || ! this.doPhysics || ! this.sharedPhysics ) return;
  1469. var physics = this.getMasterPhysics();
  1470. if ( physics === null ) return;
  1471. for ( var i = 0, il = this.meshes.length; i < il; i ++ ) {
  1472. var p = this.meshes[ i ].physics;
  1473. if ( p !== null && p !== undefined ) {
  1474. p.updateRigidBodies();
  1475. }
  1476. }
  1477. physics.stepSimulation( delta );
  1478. for ( var i = 0, il = this.meshes.length; i < il; i ++ ) {
  1479. var p = this.meshes[ i ].physics;
  1480. if ( p !== null && p !== undefined ) {
  1481. p.updateBones();
  1482. }
  1483. }
  1484. },
  1485. animateCamera: function ( delta ) {
  1486. if ( this.camera === null ) {
  1487. return;
  1488. }
  1489. var mixer = this.camera.mixer;
  1490. if ( mixer !== null && this.camera.center !== undefined && this.doCameraAnimation === true ) {
  1491. mixer.update( delta );
  1492. // TODO: Let PerspectiveCamera automatically update?
  1493. this.camera.updateProjectionMatrix();
  1494. this.camera.up.set( 0, 1, 0 );
  1495. this.camera.up.applyQuaternion( this.camera.quaternion );
  1496. this.camera.lookAt( this.camera.center );
  1497. }
  1498. },
  1499. poseAsVpd: function ( mesh, vpd, params ) {
  1500. if ( params === undefined ) params = {};
  1501. if ( params.preventResetPose !== true ) mesh.pose();
  1502. var bones = mesh.skeleton.bones;
  1503. var bones2 = vpd.bones;
  1504. var table = {};
  1505. for ( var i = 0; i < bones.length; i ++ ) {
  1506. table[ bones[ i ].name ] = i;
  1507. }
  1508. var thV = new THREE.Vector3();
  1509. var thQ = new THREE.Quaternion();
  1510. for ( var i = 0; i < bones2.length; i ++ ) {
  1511. var b = bones2[ i ];
  1512. var index = table[ b.name ];
  1513. if ( index === undefined ) continue;
  1514. var b2 = bones[ index ];
  1515. var t = b.translation;
  1516. var q = b.quaternion;
  1517. thV.set( t[ 0 ], t[ 1 ], t[ 2 ] );
  1518. thQ.set( q[ 0 ], q[ 1 ], q[ 2 ], q[ 3 ] );
  1519. b2.position.add( thV );
  1520. b2.quaternion.multiply( thQ );
  1521. }
  1522. mesh.updateMatrixWorld( true );
  1523. if ( params.preventIk !== true ) {
  1524. var solver = new THREE.CCDIKSolver( mesh );
  1525. solver.update( params.saveOriginalBonesBeforeIK );
  1526. }
  1527. if ( params.preventGrant !== true && mesh.geometry.grants !== undefined ) {
  1528. var solver = new THREE.MMDGrantSolver( mesh );
  1529. solver.update();
  1530. }
  1531. },
  1532. /*
  1533. * Note: These following three functions are workaround for r74dev.
  1534. * THREE.PropertyMixer.apply() seems to save values into buffer cache
  1535. * when mixer.update() is called.
  1536. * ikSolver.update() and physics.update() change bone position/quaternion
  1537. * without mixer.update() then buffer cache will be inconsistent.
  1538. * So trying to avoid buffer cache inconsistency by doing
  1539. * backup bones position/quaternion right after mixer.update() call
  1540. * and then restore them after rendering.
  1541. */
  1542. initBackupBones: function ( mesh ) {
  1543. mesh.skeleton.backupBones = [];
  1544. for ( var i = 0; i < mesh.skeleton.bones.length; i ++ ) {
  1545. mesh.skeleton.backupBones.push( mesh.skeleton.bones[ i ].clone() );
  1546. }
  1547. },
  1548. backupBones: function ( mesh ) {
  1549. mesh.skeleton.backupBoneIsSaved = true;
  1550. for ( var i = 0; i < mesh.skeleton.bones.length; i ++ ) {
  1551. var b = mesh.skeleton.backupBones[ i ];
  1552. var b2 = mesh.skeleton.bones[ i ];
  1553. b.position.copy( b2.position );
  1554. b.quaternion.copy( b2.quaternion );
  1555. }
  1556. },
  1557. restoreBones: function ( mesh ) {
  1558. if ( mesh.skeleton.backupBoneIsSaved !== true ) {
  1559. return;
  1560. }
  1561. mesh.skeleton.backupBoneIsSaved = false;
  1562. for ( var i = 0; i < mesh.skeleton.bones.length; i ++ ) {
  1563. var b = mesh.skeleton.bones[ i ];
  1564. var b2 = mesh.skeleton.backupBones[ i ];
  1565. b.position.copy( b2.position );
  1566. b.quaternion.copy( b2.quaternion );
  1567. }
  1568. }
  1569. };