ColladaLoader.js 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154
  1. import {
  2. AmbientLight,
  3. AnimationClip,
  4. Bone,
  5. BufferGeometry,
  6. ClampToEdgeWrapping,
  7. Color,
  8. ColorManagement,
  9. DirectionalLight,
  10. DoubleSide,
  11. FileLoader,
  12. Float32BufferAttribute,
  13. FrontSide,
  14. Group,
  15. Line,
  16. LineBasicMaterial,
  17. LineSegments,
  18. Loader,
  19. LoaderUtils,
  20. MathUtils,
  21. Matrix4,
  22. Mesh,
  23. MeshBasicMaterial,
  24. MeshLambertMaterial,
  25. MeshPhongMaterial,
  26. OrthographicCamera,
  27. PerspectiveCamera,
  28. PointLight,
  29. Quaternion,
  30. QuaternionKeyframeTrack,
  31. RepeatWrapping,
  32. Scene,
  33. Skeleton,
  34. SkinnedMesh,
  35. SpotLight,
  36. TextureLoader,
  37. Vector2,
  38. Vector3,
  39. VectorKeyframeTrack,
  40. SRGBColorSpace
  41. } from 'three';
  42. import { TGALoader } from '../loaders/TGALoader.js';
  43. /**
  44. * A loader for the Collada format.
  45. *
  46. * The Collada format is very complex so this loader only supports a subset of what
  47. * is defined in the [official specification]{@link https://www.khronos.org/files/collada_spec_1_5.pdf}.
  48. *
  49. * Assets with a Z-UP coordinate system are transformed it into Y-UP by a simple rotation.
  50. * The vertex data are not converted.
  51. *
  52. * ```js
  53. * const loader = new ColladaLoader();
  54. *
  55. * const result = await loader.loadAsync( './models/collada/elf/elf.dae' );
  56. * scene.add( result.scene );
  57. * ```
  58. *
  59. * @augments Loader
  60. */
  61. class ColladaLoader extends Loader {
  62. /**
  63. * Starts loading from the given URL and passes the loaded Collada asset
  64. * to the `onLoad()` callback.
  65. *
  66. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  67. * @param {function({scene:Group,animations:Array<AnimationClip>,kinematics:Object})} onLoad - Executed when the loading process has been finished.
  68. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  69. * @param {onErrorCallback} onError - Executed when errors occur.
  70. */
  71. load( url, onLoad, onProgress, onError ) {
  72. const scope = this;
  73. const path = ( scope.path === '' ) ? LoaderUtils.extractUrlBase( url ) : scope.path;
  74. const loader = new FileLoader( scope.manager );
  75. loader.setPath( scope.path );
  76. loader.setRequestHeader( scope.requestHeader );
  77. loader.setWithCredentials( scope.withCredentials );
  78. loader.load( url, function ( text ) {
  79. try {
  80. onLoad( scope.parse( text, path ) );
  81. } catch ( e ) {
  82. if ( onError ) {
  83. onError( e );
  84. } else {
  85. console.error( e );
  86. }
  87. scope.manager.itemError( url );
  88. }
  89. }, onProgress, onError );
  90. }
  91. /**
  92. * Parses the given Collada data and returns a result oject holding the parsed scene,
  93. * an array of animation clips and kinematics.
  94. *
  95. * @param {string} text - The raw Collada data as a string.
  96. * @param {string} path - The asset path.
  97. * @return {{scene:Group,animations:Array<AnimationClip>,kinematics:Object}} An object representing the parsed asset.
  98. */
  99. parse( text, path ) {
  100. function getElementsByTagName( xml, name ) {
  101. // Non recursive xml.getElementsByTagName() ...
  102. const array = [];
  103. const childNodes = xml.childNodes;
  104. for ( let i = 0, l = childNodes.length; i < l; i ++ ) {
  105. const child = childNodes[ i ];
  106. if ( child.nodeName === name ) {
  107. array.push( child );
  108. }
  109. }
  110. return array;
  111. }
  112. function parseStrings( text ) {
  113. if ( text.length === 0 ) return [];
  114. const parts = text.trim().split( /\s+/ );
  115. const array = new Array( parts.length );
  116. for ( let i = 0, l = parts.length; i < l; i ++ ) {
  117. array[ i ] = parts[ i ];
  118. }
  119. return array;
  120. }
  121. function parseFloats( text ) {
  122. if ( text.length === 0 ) return [];
  123. const parts = text.trim().split( /\s+/ );
  124. const array = new Array( parts.length );
  125. for ( let i = 0, l = parts.length; i < l; i ++ ) {
  126. array[ i ] = parseFloat( parts[ i ] );
  127. }
  128. return array;
  129. }
  130. function parseInts( text ) {
  131. if ( text.length === 0 ) return [];
  132. const parts = text.trim().split( /\s+/ );
  133. const array = new Array( parts.length );
  134. for ( let i = 0, l = parts.length; i < l; i ++ ) {
  135. array[ i ] = parseInt( parts[ i ] );
  136. }
  137. return array;
  138. }
  139. function parseId( text ) {
  140. return text.substring( 1 );
  141. }
  142. function generateId() {
  143. return 'three_default_' + ( count ++ );
  144. }
  145. function isEmpty( object ) {
  146. return Object.keys( object ).length === 0;
  147. }
  148. // asset
  149. function parseAsset( xml ) {
  150. return {
  151. unit: parseAssetUnit( getElementsByTagName( xml, 'unit' )[ 0 ] ),
  152. upAxis: parseAssetUpAxis( getElementsByTagName( xml, 'up_axis' )[ 0 ] )
  153. };
  154. }
  155. function parseAssetUnit( xml ) {
  156. if ( ( xml !== undefined ) && ( xml.hasAttribute( 'meter' ) === true ) ) {
  157. return parseFloat( xml.getAttribute( 'meter' ) );
  158. } else {
  159. return 1; // default 1 meter
  160. }
  161. }
  162. function parseAssetUpAxis( xml ) {
  163. return xml !== undefined ? xml.textContent : 'Y_UP';
  164. }
  165. // library
  166. function parseLibrary( xml, libraryName, nodeName, parser ) {
  167. const library = getElementsByTagName( xml, libraryName )[ 0 ];
  168. if ( library !== undefined ) {
  169. const elements = getElementsByTagName( library, nodeName );
  170. for ( let i = 0; i < elements.length; i ++ ) {
  171. parser( elements[ i ] );
  172. }
  173. }
  174. }
  175. function buildLibrary( data, builder ) {
  176. for ( const name in data ) {
  177. const object = data[ name ];
  178. object.build = builder( data[ name ] );
  179. }
  180. }
  181. // get
  182. function getBuild( data, builder ) {
  183. if ( data.build !== undefined ) return data.build;
  184. data.build = builder( data );
  185. return data.build;
  186. }
  187. // animation
  188. function parseAnimation( xml ) {
  189. const data = {
  190. sources: {},
  191. samplers: {},
  192. channels: {}
  193. };
  194. let hasChildren = false;
  195. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  196. const child = xml.childNodes[ i ];
  197. if ( child.nodeType !== 1 ) continue;
  198. let id;
  199. switch ( child.nodeName ) {
  200. case 'source':
  201. id = child.getAttribute( 'id' );
  202. data.sources[ id ] = parseSource( child );
  203. break;
  204. case 'sampler':
  205. id = child.getAttribute( 'id' );
  206. data.samplers[ id ] = parseAnimationSampler( child );
  207. break;
  208. case 'channel':
  209. id = child.getAttribute( 'target' );
  210. data.channels[ id ] = parseAnimationChannel( child );
  211. break;
  212. case 'animation':
  213. // hierarchy of related animations
  214. parseAnimation( child );
  215. hasChildren = true;
  216. break;
  217. default:
  218. console.log( child );
  219. }
  220. }
  221. if ( hasChildren === false ) {
  222. // since 'id' attributes can be optional, it's necessary to generate a UUID for unique assignment
  223. library.animations[ xml.getAttribute( 'id' ) || MathUtils.generateUUID() ] = data;
  224. }
  225. }
  226. function parseAnimationSampler( xml ) {
  227. const data = {
  228. inputs: {},
  229. };
  230. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  231. const child = xml.childNodes[ i ];
  232. if ( child.nodeType !== 1 ) continue;
  233. switch ( child.nodeName ) {
  234. case 'input':
  235. const id = parseId( child.getAttribute( 'source' ) );
  236. const semantic = child.getAttribute( 'semantic' );
  237. data.inputs[ semantic ] = id;
  238. break;
  239. }
  240. }
  241. return data;
  242. }
  243. function parseAnimationChannel( xml ) {
  244. const data = {};
  245. const target = xml.getAttribute( 'target' );
  246. // parsing SID Addressing Syntax
  247. let parts = target.split( '/' );
  248. const id = parts.shift();
  249. let sid = parts.shift();
  250. // check selection syntax
  251. const arraySyntax = ( sid.indexOf( '(' ) !== - 1 );
  252. const memberSyntax = ( sid.indexOf( '.' ) !== - 1 );
  253. if ( memberSyntax ) {
  254. // member selection access
  255. parts = sid.split( '.' );
  256. sid = parts.shift();
  257. data.member = parts.shift();
  258. } else if ( arraySyntax ) {
  259. // array-access syntax. can be used to express fields in one-dimensional vectors or two-dimensional matrices.
  260. const indices = sid.split( '(' );
  261. sid = indices.shift();
  262. for ( let i = 0; i < indices.length; i ++ ) {
  263. indices[ i ] = parseInt( indices[ i ].replace( /\)/, '' ) );
  264. }
  265. data.indices = indices;
  266. }
  267. data.id = id;
  268. data.sid = sid;
  269. data.arraySyntax = arraySyntax;
  270. data.memberSyntax = memberSyntax;
  271. data.sampler = parseId( xml.getAttribute( 'source' ) );
  272. return data;
  273. }
  274. function buildAnimation( data ) {
  275. const tracks = [];
  276. const channels = data.channels;
  277. const samplers = data.samplers;
  278. const sources = data.sources;
  279. for ( const target in channels ) {
  280. if ( channels.hasOwnProperty( target ) ) {
  281. const channel = channels[ target ];
  282. const sampler = samplers[ channel.sampler ];
  283. const inputId = sampler.inputs.INPUT;
  284. const outputId = sampler.inputs.OUTPUT;
  285. const inputSource = sources[ inputId ];
  286. const outputSource = sources[ outputId ];
  287. const animation = buildAnimationChannel( channel, inputSource, outputSource );
  288. createKeyframeTracks( animation, tracks );
  289. }
  290. }
  291. return tracks;
  292. }
  293. function getAnimation( id ) {
  294. return getBuild( library.animations[ id ], buildAnimation );
  295. }
  296. function buildAnimationChannel( channel, inputSource, outputSource ) {
  297. const node = library.nodes[ channel.id ];
  298. const object3D = getNode( node.id );
  299. const transform = node.transforms[ channel.sid ];
  300. const defaultMatrix = node.matrix.clone().transpose();
  301. let time, stride;
  302. let i, il, j, jl;
  303. const data = {};
  304. // the collada spec allows the animation of data in various ways.
  305. // depending on the transform type (matrix, translate, rotate, scale), we execute different logic
  306. switch ( transform ) {
  307. case 'matrix':
  308. for ( i = 0, il = inputSource.array.length; i < il; i ++ ) {
  309. time = inputSource.array[ i ];
  310. stride = i * outputSource.stride;
  311. if ( data[ time ] === undefined ) data[ time ] = {};
  312. if ( channel.arraySyntax === true ) {
  313. const value = outputSource.array[ stride ];
  314. const index = channel.indices[ 0 ] + 4 * channel.indices[ 1 ];
  315. data[ time ][ index ] = value;
  316. } else {
  317. for ( j = 0, jl = outputSource.stride; j < jl; j ++ ) {
  318. data[ time ][ j ] = outputSource.array[ stride + j ];
  319. }
  320. }
  321. }
  322. break;
  323. case 'translate':
  324. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  325. break;
  326. case 'rotate':
  327. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  328. break;
  329. case 'scale':
  330. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  331. break;
  332. }
  333. const keyframes = prepareAnimationData( data, defaultMatrix );
  334. const animation = {
  335. name: object3D.uuid,
  336. keyframes: keyframes
  337. };
  338. return animation;
  339. }
  340. function prepareAnimationData( data, defaultMatrix ) {
  341. const keyframes = [];
  342. // transfer data into a sortable array
  343. for ( const time in data ) {
  344. keyframes.push( { time: parseFloat( time ), value: data[ time ] } );
  345. }
  346. // ensure keyframes are sorted by time
  347. keyframes.sort( ascending );
  348. // now we clean up all animation data, so we can use them for keyframe tracks
  349. for ( let i = 0; i < 16; i ++ ) {
  350. transformAnimationData( keyframes, i, defaultMatrix.elements[ i ] );
  351. }
  352. return keyframes;
  353. // array sort function
  354. function ascending( a, b ) {
  355. return a.time - b.time;
  356. }
  357. }
  358. const position = new Vector3();
  359. const scale = new Vector3();
  360. const quaternion = new Quaternion();
  361. function createKeyframeTracks( animation, tracks ) {
  362. const keyframes = animation.keyframes;
  363. const name = animation.name;
  364. const times = [];
  365. const positionData = [];
  366. const quaternionData = [];
  367. const scaleData = [];
  368. for ( let i = 0, l = keyframes.length; i < l; i ++ ) {
  369. const keyframe = keyframes[ i ];
  370. const time = keyframe.time;
  371. const value = keyframe.value;
  372. matrix.fromArray( value ).transpose();
  373. matrix.decompose( position, quaternion, scale );
  374. times.push( time );
  375. positionData.push( position.x, position.y, position.z );
  376. quaternionData.push( quaternion.x, quaternion.y, quaternion.z, quaternion.w );
  377. scaleData.push( scale.x, scale.y, scale.z );
  378. }
  379. if ( positionData.length > 0 ) tracks.push( new VectorKeyframeTrack( name + '.position', times, positionData ) );
  380. if ( quaternionData.length > 0 ) tracks.push( new QuaternionKeyframeTrack( name + '.quaternion', times, quaternionData ) );
  381. if ( scaleData.length > 0 ) tracks.push( new VectorKeyframeTrack( name + '.scale', times, scaleData ) );
  382. return tracks;
  383. }
  384. function transformAnimationData( keyframes, property, defaultValue ) {
  385. let keyframe;
  386. let empty = true;
  387. let i, l;
  388. // check, if values of a property are missing in our keyframes
  389. for ( i = 0, l = keyframes.length; i < l; i ++ ) {
  390. keyframe = keyframes[ i ];
  391. if ( keyframe.value[ property ] === undefined ) {
  392. keyframe.value[ property ] = null; // mark as missing
  393. } else {
  394. empty = false;
  395. }
  396. }
  397. if ( empty === true ) {
  398. // no values at all, so we set a default value
  399. for ( i = 0, l = keyframes.length; i < l; i ++ ) {
  400. keyframe = keyframes[ i ];
  401. keyframe.value[ property ] = defaultValue;
  402. }
  403. } else {
  404. // filling gaps
  405. createMissingKeyframes( keyframes, property );
  406. }
  407. }
  408. function createMissingKeyframes( keyframes, property ) {
  409. let prev, next;
  410. for ( let i = 0, l = keyframes.length; i < l; i ++ ) {
  411. const keyframe = keyframes[ i ];
  412. if ( keyframe.value[ property ] === null ) {
  413. prev = getPrev( keyframes, i, property );
  414. next = getNext( keyframes, i, property );
  415. if ( prev === null ) {
  416. keyframe.value[ property ] = next.value[ property ];
  417. continue;
  418. }
  419. if ( next === null ) {
  420. keyframe.value[ property ] = prev.value[ property ];
  421. continue;
  422. }
  423. interpolate( keyframe, prev, next, property );
  424. }
  425. }
  426. }
  427. function getPrev( keyframes, i, property ) {
  428. while ( i >= 0 ) {
  429. const keyframe = keyframes[ i ];
  430. if ( keyframe.value[ property ] !== null ) return keyframe;
  431. i --;
  432. }
  433. return null;
  434. }
  435. function getNext( keyframes, i, property ) {
  436. while ( i < keyframes.length ) {
  437. const keyframe = keyframes[ i ];
  438. if ( keyframe.value[ property ] !== null ) return keyframe;
  439. i ++;
  440. }
  441. return null;
  442. }
  443. function interpolate( key, prev, next, property ) {
  444. if ( ( next.time - prev.time ) === 0 ) {
  445. key.value[ property ] = prev.value[ property ];
  446. return;
  447. }
  448. key.value[ property ] = ( ( key.time - prev.time ) * ( next.value[ property ] - prev.value[ property ] ) / ( next.time - prev.time ) ) + prev.value[ property ];
  449. }
  450. // animation clips
  451. function parseAnimationClip( xml ) {
  452. const data = {
  453. name: xml.getAttribute( 'id' ) || 'default',
  454. start: parseFloat( xml.getAttribute( 'start' ) || 0 ),
  455. end: parseFloat( xml.getAttribute( 'end' ) || 0 ),
  456. animations: []
  457. };
  458. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  459. const child = xml.childNodes[ i ];
  460. if ( child.nodeType !== 1 ) continue;
  461. switch ( child.nodeName ) {
  462. case 'instance_animation':
  463. data.animations.push( parseId( child.getAttribute( 'url' ) ) );
  464. break;
  465. }
  466. }
  467. library.clips[ xml.getAttribute( 'id' ) ] = data;
  468. }
  469. function buildAnimationClip( data ) {
  470. const tracks = [];
  471. const name = data.name;
  472. const duration = ( data.end - data.start ) || - 1;
  473. const animations = data.animations;
  474. for ( let i = 0, il = animations.length; i < il; i ++ ) {
  475. const animationTracks = getAnimation( animations[ i ] );
  476. for ( let j = 0, jl = animationTracks.length; j < jl; j ++ ) {
  477. tracks.push( animationTracks[ j ] );
  478. }
  479. }
  480. return new AnimationClip( name, duration, tracks );
  481. }
  482. function getAnimationClip( id ) {
  483. return getBuild( library.clips[ id ], buildAnimationClip );
  484. }
  485. // controller
  486. function parseController( xml ) {
  487. const data = {};
  488. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  489. const child = xml.childNodes[ i ];
  490. if ( child.nodeType !== 1 ) continue;
  491. switch ( child.nodeName ) {
  492. case 'skin':
  493. // there is exactly one skin per controller
  494. data.id = parseId( child.getAttribute( 'source' ) );
  495. data.skin = parseSkin( child );
  496. break;
  497. case 'morph':
  498. data.id = parseId( child.getAttribute( 'source' ) );
  499. console.warn( 'THREE.ColladaLoader: Morph target animation not supported yet.' );
  500. break;
  501. }
  502. }
  503. library.controllers[ xml.getAttribute( 'id' ) ] = data;
  504. }
  505. function parseSkin( xml ) {
  506. const data = {
  507. sources: {}
  508. };
  509. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  510. const child = xml.childNodes[ i ];
  511. if ( child.nodeType !== 1 ) continue;
  512. switch ( child.nodeName ) {
  513. case 'bind_shape_matrix':
  514. data.bindShapeMatrix = parseFloats( child.textContent );
  515. break;
  516. case 'source':
  517. const id = child.getAttribute( 'id' );
  518. data.sources[ id ] = parseSource( child );
  519. break;
  520. case 'joints':
  521. data.joints = parseJoints( child );
  522. break;
  523. case 'vertex_weights':
  524. data.vertexWeights = parseVertexWeights( child );
  525. break;
  526. }
  527. }
  528. return data;
  529. }
  530. function parseJoints( xml ) {
  531. const data = {
  532. inputs: {}
  533. };
  534. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  535. const child = xml.childNodes[ i ];
  536. if ( child.nodeType !== 1 ) continue;
  537. switch ( child.nodeName ) {
  538. case 'input':
  539. const semantic = child.getAttribute( 'semantic' );
  540. const id = parseId( child.getAttribute( 'source' ) );
  541. data.inputs[ semantic ] = id;
  542. break;
  543. }
  544. }
  545. return data;
  546. }
  547. function parseVertexWeights( xml ) {
  548. const data = {
  549. inputs: {}
  550. };
  551. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  552. const child = xml.childNodes[ i ];
  553. if ( child.nodeType !== 1 ) continue;
  554. switch ( child.nodeName ) {
  555. case 'input':
  556. const semantic = child.getAttribute( 'semantic' );
  557. const id = parseId( child.getAttribute( 'source' ) );
  558. const offset = parseInt( child.getAttribute( 'offset' ) );
  559. data.inputs[ semantic ] = { id: id, offset: offset };
  560. break;
  561. case 'vcount':
  562. data.vcount = parseInts( child.textContent );
  563. break;
  564. case 'v':
  565. data.v = parseInts( child.textContent );
  566. break;
  567. }
  568. }
  569. return data;
  570. }
  571. function buildController( data ) {
  572. const build = {
  573. id: data.id
  574. };
  575. const geometry = library.geometries[ build.id ];
  576. if ( data.skin !== undefined ) {
  577. build.skin = buildSkin( data.skin );
  578. // we enhance the 'sources' property of the corresponding geometry with our skin data
  579. geometry.sources.skinIndices = build.skin.indices;
  580. geometry.sources.skinWeights = build.skin.weights;
  581. }
  582. return build;
  583. }
  584. function buildSkin( data ) {
  585. const BONE_LIMIT = 4;
  586. const build = {
  587. joints: [], // this must be an array to preserve the joint order
  588. indices: {
  589. array: [],
  590. stride: BONE_LIMIT
  591. },
  592. weights: {
  593. array: [],
  594. stride: BONE_LIMIT
  595. }
  596. };
  597. const sources = data.sources;
  598. const vertexWeights = data.vertexWeights;
  599. const vcount = vertexWeights.vcount;
  600. const v = vertexWeights.v;
  601. const jointOffset = vertexWeights.inputs.JOINT.offset;
  602. const weightOffset = vertexWeights.inputs.WEIGHT.offset;
  603. const jointSource = data.sources[ data.joints.inputs.JOINT ];
  604. const inverseSource = data.sources[ data.joints.inputs.INV_BIND_MATRIX ];
  605. const weights = sources[ vertexWeights.inputs.WEIGHT.id ].array;
  606. let stride = 0;
  607. let i, j, l;
  608. // process skin data for each vertex
  609. for ( i = 0, l = vcount.length; i < l; i ++ ) {
  610. const jointCount = vcount[ i ]; // this is the amount of joints that affect a single vertex
  611. const vertexSkinData = [];
  612. for ( j = 0; j < jointCount; j ++ ) {
  613. const skinIndex = v[ stride + jointOffset ];
  614. const weightId = v[ stride + weightOffset ];
  615. const skinWeight = weights[ weightId ];
  616. vertexSkinData.push( { index: skinIndex, weight: skinWeight } );
  617. stride += 2;
  618. }
  619. // we sort the joints in descending order based on the weights.
  620. // this ensures, we only proceed the most important joints of the vertex
  621. vertexSkinData.sort( descending );
  622. // now we provide for each vertex a set of four index and weight values.
  623. // the order of the skin data matches the order of vertices
  624. for ( j = 0; j < BONE_LIMIT; j ++ ) {
  625. const d = vertexSkinData[ j ];
  626. if ( d !== undefined ) {
  627. build.indices.array.push( d.index );
  628. build.weights.array.push( d.weight );
  629. } else {
  630. build.indices.array.push( 0 );
  631. build.weights.array.push( 0 );
  632. }
  633. }
  634. }
  635. // setup bind matrix
  636. if ( data.bindShapeMatrix ) {
  637. build.bindMatrix = new Matrix4().fromArray( data.bindShapeMatrix ).transpose();
  638. } else {
  639. build.bindMatrix = new Matrix4().identity();
  640. }
  641. // process bones and inverse bind matrix data
  642. for ( i = 0, l = jointSource.array.length; i < l; i ++ ) {
  643. const name = jointSource.array[ i ];
  644. const boneInverse = new Matrix4().fromArray( inverseSource.array, i * inverseSource.stride ).transpose();
  645. build.joints.push( { name: name, boneInverse: boneInverse } );
  646. }
  647. return build;
  648. // array sort function
  649. function descending( a, b ) {
  650. return b.weight - a.weight;
  651. }
  652. }
  653. function getController( id ) {
  654. return getBuild( library.controllers[ id ], buildController );
  655. }
  656. // image
  657. function parseImage( xml ) {
  658. const data = {
  659. init_from: getElementsByTagName( xml, 'init_from' )[ 0 ].textContent
  660. };
  661. library.images[ xml.getAttribute( 'id' ) ] = data;
  662. }
  663. function buildImage( data ) {
  664. if ( data.build !== undefined ) return data.build;
  665. return data.init_from;
  666. }
  667. function getImage( id ) {
  668. const data = library.images[ id ];
  669. if ( data !== undefined ) {
  670. return getBuild( data, buildImage );
  671. }
  672. console.warn( 'THREE.ColladaLoader: Couldn\'t find image with ID:', id );
  673. return null;
  674. }
  675. // effect
  676. function parseEffect( xml ) {
  677. const data = {};
  678. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  679. const child = xml.childNodes[ i ];
  680. if ( child.nodeType !== 1 ) continue;
  681. switch ( child.nodeName ) {
  682. case 'profile_COMMON':
  683. data.profile = parseEffectProfileCOMMON( child );
  684. break;
  685. }
  686. }
  687. library.effects[ xml.getAttribute( 'id' ) ] = data;
  688. }
  689. function parseEffectProfileCOMMON( xml ) {
  690. const data = {
  691. surfaces: {},
  692. samplers: {}
  693. };
  694. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  695. const child = xml.childNodes[ i ];
  696. if ( child.nodeType !== 1 ) continue;
  697. switch ( child.nodeName ) {
  698. case 'newparam':
  699. parseEffectNewparam( child, data );
  700. break;
  701. case 'technique':
  702. data.technique = parseEffectTechnique( child );
  703. break;
  704. case 'extra':
  705. data.extra = parseEffectExtra( child );
  706. break;
  707. }
  708. }
  709. return data;
  710. }
  711. function parseEffectNewparam( xml, data ) {
  712. const sid = xml.getAttribute( 'sid' );
  713. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  714. const child = xml.childNodes[ i ];
  715. if ( child.nodeType !== 1 ) continue;
  716. switch ( child.nodeName ) {
  717. case 'surface':
  718. data.surfaces[ sid ] = parseEffectSurface( child );
  719. break;
  720. case 'sampler2D':
  721. data.samplers[ sid ] = parseEffectSampler( child );
  722. break;
  723. }
  724. }
  725. }
  726. function parseEffectSurface( xml ) {
  727. const data = {};
  728. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  729. const child = xml.childNodes[ i ];
  730. if ( child.nodeType !== 1 ) continue;
  731. switch ( child.nodeName ) {
  732. case 'init_from':
  733. data.init_from = child.textContent;
  734. break;
  735. }
  736. }
  737. return data;
  738. }
  739. function parseEffectSampler( xml ) {
  740. const data = {};
  741. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  742. const child = xml.childNodes[ i ];
  743. if ( child.nodeType !== 1 ) continue;
  744. switch ( child.nodeName ) {
  745. case 'source':
  746. data.source = child.textContent;
  747. break;
  748. }
  749. }
  750. return data;
  751. }
  752. function parseEffectTechnique( xml ) {
  753. const data = {};
  754. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  755. const child = xml.childNodes[ i ];
  756. if ( child.nodeType !== 1 ) continue;
  757. switch ( child.nodeName ) {
  758. case 'constant':
  759. case 'lambert':
  760. case 'blinn':
  761. case 'phong':
  762. data.type = child.nodeName;
  763. data.parameters = parseEffectParameters( child );
  764. break;
  765. case 'extra':
  766. data.extra = parseEffectExtra( child );
  767. break;
  768. }
  769. }
  770. return data;
  771. }
  772. function parseEffectParameters( xml ) {
  773. const data = {};
  774. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  775. const child = xml.childNodes[ i ];
  776. if ( child.nodeType !== 1 ) continue;
  777. switch ( child.nodeName ) {
  778. case 'emission':
  779. case 'diffuse':
  780. case 'specular':
  781. case 'bump':
  782. case 'ambient':
  783. case 'shininess':
  784. case 'transparency':
  785. data[ child.nodeName ] = parseEffectParameter( child );
  786. break;
  787. case 'transparent':
  788. data[ child.nodeName ] = {
  789. opaque: child.hasAttribute( 'opaque' ) ? child.getAttribute( 'opaque' ) : 'A_ONE',
  790. data: parseEffectParameter( child )
  791. };
  792. break;
  793. }
  794. }
  795. return data;
  796. }
  797. function parseEffectParameter( xml ) {
  798. const data = {};
  799. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  800. const child = xml.childNodes[ i ];
  801. if ( child.nodeType !== 1 ) continue;
  802. switch ( child.nodeName ) {
  803. case 'color':
  804. data[ child.nodeName ] = parseFloats( child.textContent );
  805. break;
  806. case 'float':
  807. data[ child.nodeName ] = parseFloat( child.textContent );
  808. break;
  809. case 'texture':
  810. data[ child.nodeName ] = { id: child.getAttribute( 'texture' ), extra: parseEffectParameterTexture( child ) };
  811. break;
  812. }
  813. }
  814. return data;
  815. }
  816. function parseEffectParameterTexture( xml ) {
  817. const data = {
  818. technique: {}
  819. };
  820. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  821. const child = xml.childNodes[ i ];
  822. if ( child.nodeType !== 1 ) continue;
  823. switch ( child.nodeName ) {
  824. case 'extra':
  825. parseEffectParameterTextureExtra( child, data );
  826. break;
  827. }
  828. }
  829. return data;
  830. }
  831. function parseEffectParameterTextureExtra( xml, data ) {
  832. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  833. const child = xml.childNodes[ i ];
  834. if ( child.nodeType !== 1 ) continue;
  835. switch ( child.nodeName ) {
  836. case 'technique':
  837. parseEffectParameterTextureExtraTechnique( child, data );
  838. break;
  839. }
  840. }
  841. }
  842. function parseEffectParameterTextureExtraTechnique( xml, data ) {
  843. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  844. const child = xml.childNodes[ i ];
  845. if ( child.nodeType !== 1 ) continue;
  846. switch ( child.nodeName ) {
  847. case 'repeatU':
  848. case 'repeatV':
  849. case 'offsetU':
  850. case 'offsetV':
  851. data.technique[ child.nodeName ] = parseFloat( child.textContent );
  852. break;
  853. case 'wrapU':
  854. case 'wrapV':
  855. // some files have values for wrapU/wrapV which become NaN via parseInt
  856. if ( child.textContent.toUpperCase() === 'TRUE' ) {
  857. data.technique[ child.nodeName ] = 1;
  858. } else if ( child.textContent.toUpperCase() === 'FALSE' ) {
  859. data.technique[ child.nodeName ] = 0;
  860. } else {
  861. data.technique[ child.nodeName ] = parseInt( child.textContent );
  862. }
  863. break;
  864. case 'bump':
  865. data[ child.nodeName ] = parseEffectExtraTechniqueBump( child );
  866. break;
  867. }
  868. }
  869. }
  870. function parseEffectExtra( xml ) {
  871. const data = {};
  872. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  873. const child = xml.childNodes[ i ];
  874. if ( child.nodeType !== 1 ) continue;
  875. switch ( child.nodeName ) {
  876. case 'technique':
  877. data.technique = parseEffectExtraTechnique( child );
  878. break;
  879. }
  880. }
  881. return data;
  882. }
  883. function parseEffectExtraTechnique( xml ) {
  884. const data = {};
  885. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  886. const child = xml.childNodes[ i ];
  887. if ( child.nodeType !== 1 ) continue;
  888. switch ( child.nodeName ) {
  889. case 'double_sided':
  890. data[ child.nodeName ] = parseInt( child.textContent );
  891. break;
  892. case 'bump':
  893. data[ child.nodeName ] = parseEffectExtraTechniqueBump( child );
  894. break;
  895. }
  896. }
  897. return data;
  898. }
  899. function parseEffectExtraTechniqueBump( xml ) {
  900. const data = {};
  901. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  902. const child = xml.childNodes[ i ];
  903. if ( child.nodeType !== 1 ) continue;
  904. switch ( child.nodeName ) {
  905. case 'texture':
  906. data[ child.nodeName ] = { id: child.getAttribute( 'texture' ), texcoord: child.getAttribute( 'texcoord' ), extra: parseEffectParameterTexture( child ) };
  907. break;
  908. }
  909. }
  910. return data;
  911. }
  912. function buildEffect( data ) {
  913. return data;
  914. }
  915. function getEffect( id ) {
  916. return getBuild( library.effects[ id ], buildEffect );
  917. }
  918. // material
  919. function parseMaterial( xml ) {
  920. const data = {
  921. name: xml.getAttribute( 'name' )
  922. };
  923. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  924. const child = xml.childNodes[ i ];
  925. if ( child.nodeType !== 1 ) continue;
  926. switch ( child.nodeName ) {
  927. case 'instance_effect':
  928. data.url = parseId( child.getAttribute( 'url' ) );
  929. break;
  930. }
  931. }
  932. library.materials[ xml.getAttribute( 'id' ) ] = data;
  933. }
  934. function getTextureLoader( image ) {
  935. let loader;
  936. let extension = image.slice( ( image.lastIndexOf( '.' ) - 1 >>> 0 ) + 2 ); // http://www.jstips.co/en/javascript/get-file-extension/
  937. extension = extension.toLowerCase();
  938. switch ( extension ) {
  939. case 'tga':
  940. loader = tgaLoader;
  941. break;
  942. default:
  943. loader = textureLoader;
  944. }
  945. return loader;
  946. }
  947. function buildMaterial( data ) {
  948. const effect = getEffect( data.url );
  949. const technique = effect.profile.technique;
  950. let material;
  951. switch ( technique.type ) {
  952. case 'phong':
  953. case 'blinn':
  954. material = new MeshPhongMaterial();
  955. break;
  956. case 'lambert':
  957. material = new MeshLambertMaterial();
  958. break;
  959. default:
  960. material = new MeshBasicMaterial();
  961. break;
  962. }
  963. material.name = data.name || '';
  964. function getTexture( textureObject, colorSpace = null ) {
  965. const sampler = effect.profile.samplers[ textureObject.id ];
  966. let image = null;
  967. // get image
  968. if ( sampler !== undefined ) {
  969. const surface = effect.profile.surfaces[ sampler.source ];
  970. image = getImage( surface.init_from );
  971. } else {
  972. console.warn( 'THREE.ColladaLoader: Undefined sampler. Access image directly (see #12530).' );
  973. image = getImage( textureObject.id );
  974. }
  975. // create texture if image is available
  976. if ( image !== null ) {
  977. const loader = getTextureLoader( image );
  978. if ( loader !== undefined ) {
  979. const texture = loader.load( image );
  980. const extra = textureObject.extra;
  981. if ( extra !== undefined && extra.technique !== undefined && isEmpty( extra.technique ) === false ) {
  982. const technique = extra.technique;
  983. texture.wrapS = technique.wrapU ? RepeatWrapping : ClampToEdgeWrapping;
  984. texture.wrapT = technique.wrapV ? RepeatWrapping : ClampToEdgeWrapping;
  985. texture.offset.set( technique.offsetU || 0, technique.offsetV || 0 );
  986. texture.repeat.set( technique.repeatU || 1, technique.repeatV || 1 );
  987. } else {
  988. texture.wrapS = RepeatWrapping;
  989. texture.wrapT = RepeatWrapping;
  990. }
  991. if ( colorSpace !== null ) {
  992. texture.colorSpace = colorSpace;
  993. }
  994. return texture;
  995. } else {
  996. console.warn( 'THREE.ColladaLoader: Loader for texture %s not found.', image );
  997. return null;
  998. }
  999. } else {
  1000. console.warn( 'THREE.ColladaLoader: Couldn\'t create texture with ID:', textureObject.id );
  1001. return null;
  1002. }
  1003. }
  1004. const parameters = technique.parameters;
  1005. for ( const key in parameters ) {
  1006. const parameter = parameters[ key ];
  1007. switch ( key ) {
  1008. case 'diffuse':
  1009. if ( parameter.color ) material.color.fromArray( parameter.color );
  1010. if ( parameter.texture ) material.map = getTexture( parameter.texture, SRGBColorSpace );
  1011. break;
  1012. case 'specular':
  1013. if ( parameter.color && material.specular ) material.specular.fromArray( parameter.color );
  1014. if ( parameter.texture ) material.specularMap = getTexture( parameter.texture );
  1015. break;
  1016. case 'bump':
  1017. if ( parameter.texture ) material.normalMap = getTexture( parameter.texture );
  1018. break;
  1019. case 'ambient':
  1020. if ( parameter.texture ) material.lightMap = getTexture( parameter.texture, SRGBColorSpace );
  1021. break;
  1022. case 'shininess':
  1023. if ( parameter.float && material.shininess ) material.shininess = parameter.float;
  1024. break;
  1025. case 'emission':
  1026. if ( parameter.color && material.emissive ) material.emissive.fromArray( parameter.color );
  1027. if ( parameter.texture ) material.emissiveMap = getTexture( parameter.texture, SRGBColorSpace );
  1028. break;
  1029. }
  1030. }
  1031. ColorManagement.toWorkingColorSpace( material.color, SRGBColorSpace );
  1032. if ( material.specular ) ColorManagement.toWorkingColorSpace( material.specular, SRGBColorSpace );
  1033. if ( material.emissive ) ColorManagement.toWorkingColorSpace( material.emissive, SRGBColorSpace );
  1034. //
  1035. let transparent = parameters[ 'transparent' ];
  1036. let transparency = parameters[ 'transparency' ];
  1037. // <transparency> does not exist but <transparent>
  1038. if ( transparency === undefined && transparent ) {
  1039. transparency = {
  1040. float: 1
  1041. };
  1042. }
  1043. // <transparent> does not exist but <transparency>
  1044. if ( transparent === undefined && transparency ) {
  1045. transparent = {
  1046. opaque: 'A_ONE',
  1047. data: {
  1048. color: [ 1, 1, 1, 1 ]
  1049. } };
  1050. }
  1051. if ( transparent && transparency ) {
  1052. // handle case if a texture exists but no color
  1053. if ( transparent.data.texture ) {
  1054. // we do not set an alpha map (see #13792)
  1055. material.transparent = true;
  1056. } else {
  1057. const color = transparent.data.color;
  1058. switch ( transparent.opaque ) {
  1059. case 'A_ONE':
  1060. material.opacity = color[ 3 ] * transparency.float;
  1061. break;
  1062. case 'RGB_ZERO':
  1063. material.opacity = 1 - ( color[ 0 ] * transparency.float );
  1064. break;
  1065. case 'A_ZERO':
  1066. material.opacity = 1 - ( color[ 3 ] * transparency.float );
  1067. break;
  1068. case 'RGB_ONE':
  1069. material.opacity = color[ 0 ] * transparency.float;
  1070. break;
  1071. default:
  1072. console.warn( 'THREE.ColladaLoader: Invalid opaque type "%s" of transparent tag.', transparent.opaque );
  1073. }
  1074. if ( material.opacity < 1 ) material.transparent = true;
  1075. }
  1076. }
  1077. //
  1078. if ( technique.extra !== undefined && technique.extra.technique !== undefined ) {
  1079. const techniques = technique.extra.technique;
  1080. for ( const k in techniques ) {
  1081. const v = techniques[ k ];
  1082. switch ( k ) {
  1083. case 'double_sided':
  1084. material.side = ( v === 1 ? DoubleSide : FrontSide );
  1085. break;
  1086. case 'bump':
  1087. material.normalMap = getTexture( v.texture );
  1088. material.normalScale = new Vector2( 1, 1 );
  1089. break;
  1090. }
  1091. }
  1092. }
  1093. return material;
  1094. }
  1095. function getMaterial( id ) {
  1096. return getBuild( library.materials[ id ], buildMaterial );
  1097. }
  1098. // camera
  1099. function parseCamera( xml ) {
  1100. const data = {
  1101. name: xml.getAttribute( 'name' )
  1102. };
  1103. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1104. const child = xml.childNodes[ i ];
  1105. if ( child.nodeType !== 1 ) continue;
  1106. switch ( child.nodeName ) {
  1107. case 'optics':
  1108. data.optics = parseCameraOptics( child );
  1109. break;
  1110. }
  1111. }
  1112. library.cameras[ xml.getAttribute( 'id' ) ] = data;
  1113. }
  1114. function parseCameraOptics( xml ) {
  1115. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1116. const child = xml.childNodes[ i ];
  1117. switch ( child.nodeName ) {
  1118. case 'technique_common':
  1119. return parseCameraTechnique( child );
  1120. }
  1121. }
  1122. return {};
  1123. }
  1124. function parseCameraTechnique( xml ) {
  1125. const data = {};
  1126. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1127. const child = xml.childNodes[ i ];
  1128. switch ( child.nodeName ) {
  1129. case 'perspective':
  1130. case 'orthographic':
  1131. data.technique = child.nodeName;
  1132. data.parameters = parseCameraParameters( child );
  1133. break;
  1134. }
  1135. }
  1136. return data;
  1137. }
  1138. function parseCameraParameters( xml ) {
  1139. const data = {};
  1140. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1141. const child = xml.childNodes[ i ];
  1142. switch ( child.nodeName ) {
  1143. case 'xfov':
  1144. case 'yfov':
  1145. case 'xmag':
  1146. case 'ymag':
  1147. case 'znear':
  1148. case 'zfar':
  1149. case 'aspect_ratio':
  1150. data[ child.nodeName ] = parseFloat( child.textContent );
  1151. break;
  1152. }
  1153. }
  1154. return data;
  1155. }
  1156. function buildCamera( data ) {
  1157. let camera;
  1158. switch ( data.optics.technique ) {
  1159. case 'perspective':
  1160. camera = new PerspectiveCamera(
  1161. data.optics.parameters.yfov,
  1162. data.optics.parameters.aspect_ratio,
  1163. data.optics.parameters.znear,
  1164. data.optics.parameters.zfar
  1165. );
  1166. break;
  1167. case 'orthographic':
  1168. let ymag = data.optics.parameters.ymag;
  1169. let xmag = data.optics.parameters.xmag;
  1170. const aspectRatio = data.optics.parameters.aspect_ratio;
  1171. xmag = ( xmag === undefined ) ? ( ymag * aspectRatio ) : xmag;
  1172. ymag = ( ymag === undefined ) ? ( xmag / aspectRatio ) : ymag;
  1173. xmag *= 0.5;
  1174. ymag *= 0.5;
  1175. camera = new OrthographicCamera(
  1176. - xmag, xmag, ymag, - ymag, // left, right, top, bottom
  1177. data.optics.parameters.znear,
  1178. data.optics.parameters.zfar
  1179. );
  1180. break;
  1181. default:
  1182. camera = new PerspectiveCamera();
  1183. break;
  1184. }
  1185. camera.name = data.name || '';
  1186. return camera;
  1187. }
  1188. function getCamera( id ) {
  1189. const data = library.cameras[ id ];
  1190. if ( data !== undefined ) {
  1191. return getBuild( data, buildCamera );
  1192. }
  1193. console.warn( 'THREE.ColladaLoader: Couldn\'t find camera with ID:', id );
  1194. return null;
  1195. }
  1196. // light
  1197. function parseLight( xml ) {
  1198. let data = {};
  1199. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1200. const child = xml.childNodes[ i ];
  1201. if ( child.nodeType !== 1 ) continue;
  1202. switch ( child.nodeName ) {
  1203. case 'technique_common':
  1204. data = parseLightTechnique( child );
  1205. break;
  1206. }
  1207. }
  1208. library.lights[ xml.getAttribute( 'id' ) ] = data;
  1209. }
  1210. function parseLightTechnique( xml ) {
  1211. const data = {};
  1212. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1213. const child = xml.childNodes[ i ];
  1214. if ( child.nodeType !== 1 ) continue;
  1215. switch ( child.nodeName ) {
  1216. case 'directional':
  1217. case 'point':
  1218. case 'spot':
  1219. case 'ambient':
  1220. data.technique = child.nodeName;
  1221. data.parameters = parseLightParameters( child );
  1222. }
  1223. }
  1224. return data;
  1225. }
  1226. function parseLightParameters( xml ) {
  1227. const data = {};
  1228. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1229. const child = xml.childNodes[ i ];
  1230. if ( child.nodeType !== 1 ) continue;
  1231. switch ( child.nodeName ) {
  1232. case 'color':
  1233. const array = parseFloats( child.textContent );
  1234. data.color = new Color().fromArray( array );
  1235. ColorManagement.toWorkingColorSpace( data.color, SRGBColorSpace );
  1236. break;
  1237. case 'falloff_angle':
  1238. data.falloffAngle = parseFloat( child.textContent );
  1239. break;
  1240. case 'quadratic_attenuation':
  1241. const f = parseFloat( child.textContent );
  1242. data.distance = f ? Math.sqrt( 1 / f ) : 0;
  1243. break;
  1244. }
  1245. }
  1246. return data;
  1247. }
  1248. function buildLight( data ) {
  1249. let light;
  1250. switch ( data.technique ) {
  1251. case 'directional':
  1252. light = new DirectionalLight();
  1253. break;
  1254. case 'point':
  1255. light = new PointLight();
  1256. break;
  1257. case 'spot':
  1258. light = new SpotLight();
  1259. break;
  1260. case 'ambient':
  1261. light = new AmbientLight();
  1262. break;
  1263. }
  1264. if ( data.parameters.color ) light.color.copy( data.parameters.color );
  1265. if ( data.parameters.distance ) light.distance = data.parameters.distance;
  1266. return light;
  1267. }
  1268. function getLight( id ) {
  1269. const data = library.lights[ id ];
  1270. if ( data !== undefined ) {
  1271. return getBuild( data, buildLight );
  1272. }
  1273. console.warn( 'THREE.ColladaLoader: Couldn\'t find light with ID:', id );
  1274. return null;
  1275. }
  1276. // geometry
  1277. function parseGeometry( xml ) {
  1278. const data = {
  1279. name: xml.getAttribute( 'name' ),
  1280. sources: {},
  1281. vertices: {},
  1282. primitives: []
  1283. };
  1284. const mesh = getElementsByTagName( xml, 'mesh' )[ 0 ];
  1285. // the following tags inside geometry are not supported yet (see https://github.com/mrdoob/three.js/pull/12606): convex_mesh, spline, brep
  1286. if ( mesh === undefined ) return;
  1287. for ( let i = 0; i < mesh.childNodes.length; i ++ ) {
  1288. const child = mesh.childNodes[ i ];
  1289. if ( child.nodeType !== 1 ) continue;
  1290. const id = child.getAttribute( 'id' );
  1291. switch ( child.nodeName ) {
  1292. case 'source':
  1293. data.sources[ id ] = parseSource( child );
  1294. break;
  1295. case 'vertices':
  1296. // data.sources[ id ] = data.sources[ parseId( getElementsByTagName( child, 'input' )[ 0 ].getAttribute( 'source' ) ) ];
  1297. data.vertices = parseGeometryVertices( child );
  1298. break;
  1299. case 'polygons':
  1300. console.warn( 'THREE.ColladaLoader: Unsupported primitive type: ', child.nodeName );
  1301. break;
  1302. case 'lines':
  1303. case 'linestrips':
  1304. case 'polylist':
  1305. case 'triangles':
  1306. data.primitives.push( parseGeometryPrimitive( child ) );
  1307. break;
  1308. default:
  1309. console.log( child );
  1310. }
  1311. }
  1312. library.geometries[ xml.getAttribute( 'id' ) ] = data;
  1313. }
  1314. function parseSource( xml ) {
  1315. const data = {
  1316. array: [],
  1317. stride: 3
  1318. };
  1319. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1320. const child = xml.childNodes[ i ];
  1321. if ( child.nodeType !== 1 ) continue;
  1322. switch ( child.nodeName ) {
  1323. case 'float_array':
  1324. data.array = parseFloats( child.textContent );
  1325. break;
  1326. case 'Name_array':
  1327. data.array = parseStrings( child.textContent );
  1328. break;
  1329. case 'technique_common':
  1330. const accessor = getElementsByTagName( child, 'accessor' )[ 0 ];
  1331. if ( accessor !== undefined ) {
  1332. data.stride = parseInt( accessor.getAttribute( 'stride' ) );
  1333. }
  1334. break;
  1335. }
  1336. }
  1337. return data;
  1338. }
  1339. function parseGeometryVertices( xml ) {
  1340. const data = {};
  1341. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1342. const child = xml.childNodes[ i ];
  1343. if ( child.nodeType !== 1 ) continue;
  1344. data[ child.getAttribute( 'semantic' ) ] = parseId( child.getAttribute( 'source' ) );
  1345. }
  1346. return data;
  1347. }
  1348. function parseGeometryPrimitive( xml ) {
  1349. const primitive = {
  1350. type: xml.nodeName,
  1351. material: xml.getAttribute( 'material' ),
  1352. count: parseInt( xml.getAttribute( 'count' ) ),
  1353. inputs: {},
  1354. stride: 0,
  1355. hasUV: false
  1356. };
  1357. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1358. const child = xml.childNodes[ i ];
  1359. if ( child.nodeType !== 1 ) continue;
  1360. switch ( child.nodeName ) {
  1361. case 'input':
  1362. const id = parseId( child.getAttribute( 'source' ) );
  1363. const semantic = child.getAttribute( 'semantic' );
  1364. const offset = parseInt( child.getAttribute( 'offset' ) );
  1365. const set = parseInt( child.getAttribute( 'set' ) );
  1366. const inputname = ( set > 0 ? semantic + set : semantic );
  1367. primitive.inputs[ inputname ] = { id: id, offset: offset };
  1368. primitive.stride = Math.max( primitive.stride, offset + 1 );
  1369. if ( semantic === 'TEXCOORD' ) primitive.hasUV = true;
  1370. break;
  1371. case 'vcount':
  1372. primitive.vcount = parseInts( child.textContent );
  1373. break;
  1374. case 'p':
  1375. primitive.p = parseInts( child.textContent );
  1376. break;
  1377. }
  1378. }
  1379. return primitive;
  1380. }
  1381. function groupPrimitives( primitives ) {
  1382. const build = {};
  1383. for ( let i = 0; i < primitives.length; i ++ ) {
  1384. const primitive = primitives[ i ];
  1385. if ( build[ primitive.type ] === undefined ) build[ primitive.type ] = [];
  1386. build[ primitive.type ].push( primitive );
  1387. }
  1388. return build;
  1389. }
  1390. function checkUVCoordinates( primitives ) {
  1391. let count = 0;
  1392. for ( let i = 0, l = primitives.length; i < l; i ++ ) {
  1393. const primitive = primitives[ i ];
  1394. if ( primitive.hasUV === true ) {
  1395. count ++;
  1396. }
  1397. }
  1398. if ( count > 0 && count < primitives.length ) {
  1399. primitives.uvsNeedsFix = true;
  1400. }
  1401. }
  1402. function buildGeometry( data ) {
  1403. const build = {};
  1404. const sources = data.sources;
  1405. const vertices = data.vertices;
  1406. const primitives = data.primitives;
  1407. if ( primitives.length === 0 ) return {};
  1408. // our goal is to create one buffer geometry for a single type of primitives
  1409. // first, we group all primitives by their type
  1410. const groupedPrimitives = groupPrimitives( primitives );
  1411. for ( const type in groupedPrimitives ) {
  1412. const primitiveType = groupedPrimitives[ type ];
  1413. // second, ensure consistent uv coordinates for each type of primitives (polylist,triangles or lines)
  1414. checkUVCoordinates( primitiveType );
  1415. // third, create a buffer geometry for each type of primitives
  1416. build[ type ] = buildGeometryType( primitiveType, sources, vertices );
  1417. }
  1418. return build;
  1419. }
  1420. function buildGeometryType( primitives, sources, vertices ) {
  1421. const build = {};
  1422. const position = { array: [], stride: 0 };
  1423. const normal = { array: [], stride: 0 };
  1424. const uv = { array: [], stride: 0 };
  1425. const uv1 = { array: [], stride: 0 };
  1426. const color = { array: [], stride: 0 };
  1427. const skinIndex = { array: [], stride: 4 };
  1428. const skinWeight = { array: [], stride: 4 };
  1429. const geometry = new BufferGeometry();
  1430. const materialKeys = [];
  1431. let start = 0;
  1432. for ( let p = 0; p < primitives.length; p ++ ) {
  1433. const primitive = primitives[ p ];
  1434. const inputs = primitive.inputs;
  1435. // groups
  1436. let count = 0;
  1437. switch ( primitive.type ) {
  1438. case 'lines':
  1439. case 'linestrips':
  1440. count = primitive.count * 2;
  1441. break;
  1442. case 'triangles':
  1443. count = primitive.count * 3;
  1444. break;
  1445. case 'polylist':
  1446. for ( let g = 0; g < primitive.count; g ++ ) {
  1447. const vc = primitive.vcount[ g ];
  1448. switch ( vc ) {
  1449. case 3:
  1450. count += 3; // single triangle
  1451. break;
  1452. case 4:
  1453. count += 6; // quad, subdivided into two triangles
  1454. break;
  1455. default:
  1456. count += ( vc - 2 ) * 3; // polylist with more than four vertices
  1457. break;
  1458. }
  1459. }
  1460. break;
  1461. default:
  1462. console.warn( 'THREE.ColladaLoader: Unknown primitive type:', primitive.type );
  1463. }
  1464. geometry.addGroup( start, count, p );
  1465. start += count;
  1466. // material
  1467. if ( primitive.material ) {
  1468. materialKeys.push( primitive.material );
  1469. }
  1470. // geometry data
  1471. for ( const name in inputs ) {
  1472. const input = inputs[ name ];
  1473. switch ( name ) {
  1474. case 'VERTEX':
  1475. for ( const key in vertices ) {
  1476. const id = vertices[ key ];
  1477. switch ( key ) {
  1478. case 'POSITION':
  1479. const prevLength = position.array.length;
  1480. buildGeometryData( primitive, sources[ id ], input.offset, position.array );
  1481. position.stride = sources[ id ].stride;
  1482. if ( sources.skinWeights && sources.skinIndices ) {
  1483. buildGeometryData( primitive, sources.skinIndices, input.offset, skinIndex.array );
  1484. buildGeometryData( primitive, sources.skinWeights, input.offset, skinWeight.array );
  1485. }
  1486. // see #3803
  1487. if ( primitive.hasUV === false && primitives.uvsNeedsFix === true ) {
  1488. const count = ( position.array.length - prevLength ) / position.stride;
  1489. for ( let i = 0; i < count; i ++ ) {
  1490. // fill missing uv coordinates
  1491. uv.array.push( 0, 0 );
  1492. }
  1493. }
  1494. break;
  1495. case 'NORMAL':
  1496. buildGeometryData( primitive, sources[ id ], input.offset, normal.array );
  1497. normal.stride = sources[ id ].stride;
  1498. break;
  1499. case 'COLOR':
  1500. buildGeometryData( primitive, sources[ id ], input.offset, color.array );
  1501. color.stride = sources[ id ].stride;
  1502. break;
  1503. case 'TEXCOORD':
  1504. buildGeometryData( primitive, sources[ id ], input.offset, uv.array );
  1505. uv.stride = sources[ id ].stride;
  1506. break;
  1507. case 'TEXCOORD1':
  1508. buildGeometryData( primitive, sources[ id ], input.offset, uv1.array );
  1509. uv.stride = sources[ id ].stride;
  1510. break;
  1511. default:
  1512. console.warn( 'THREE.ColladaLoader: Semantic "%s" not handled in geometry build process.', key );
  1513. }
  1514. }
  1515. break;
  1516. case 'NORMAL':
  1517. buildGeometryData( primitive, sources[ input.id ], input.offset, normal.array );
  1518. normal.stride = sources[ input.id ].stride;
  1519. break;
  1520. case 'COLOR':
  1521. buildGeometryData( primitive, sources[ input.id ], input.offset, color.array, true );
  1522. color.stride = sources[ input.id ].stride;
  1523. break;
  1524. case 'TEXCOORD':
  1525. buildGeometryData( primitive, sources[ input.id ], input.offset, uv.array );
  1526. uv.stride = sources[ input.id ].stride;
  1527. break;
  1528. case 'TEXCOORD1':
  1529. buildGeometryData( primitive, sources[ input.id ], input.offset, uv1.array );
  1530. uv1.stride = sources[ input.id ].stride;
  1531. break;
  1532. }
  1533. }
  1534. }
  1535. // build geometry
  1536. if ( position.array.length > 0 ) geometry.setAttribute( 'position', new Float32BufferAttribute( position.array, position.stride ) );
  1537. if ( normal.array.length > 0 ) geometry.setAttribute( 'normal', new Float32BufferAttribute( normal.array, normal.stride ) );
  1538. if ( color.array.length > 0 ) geometry.setAttribute( 'color', new Float32BufferAttribute( color.array, color.stride ) );
  1539. if ( uv.array.length > 0 ) geometry.setAttribute( 'uv', new Float32BufferAttribute( uv.array, uv.stride ) );
  1540. if ( uv1.array.length > 0 ) geometry.setAttribute( 'uv1', new Float32BufferAttribute( uv1.array, uv1.stride ) );
  1541. if ( skinIndex.array.length > 0 ) geometry.setAttribute( 'skinIndex', new Float32BufferAttribute( skinIndex.array, skinIndex.stride ) );
  1542. if ( skinWeight.array.length > 0 ) geometry.setAttribute( 'skinWeight', new Float32BufferAttribute( skinWeight.array, skinWeight.stride ) );
  1543. build.data = geometry;
  1544. build.type = primitives[ 0 ].type;
  1545. build.materialKeys = materialKeys;
  1546. return build;
  1547. }
  1548. function buildGeometryData( primitive, source, offset, array, isColor = false ) {
  1549. const indices = primitive.p;
  1550. const stride = primitive.stride;
  1551. const vcount = primitive.vcount;
  1552. function pushVector( i ) {
  1553. let index = indices[ i + offset ] * sourceStride;
  1554. const length = index + sourceStride;
  1555. for ( ; index < length; index ++ ) {
  1556. array.push( sourceArray[ index ] );
  1557. }
  1558. if ( isColor ) {
  1559. // convert the vertex colors from srgb to linear if present
  1560. const startIndex = array.length - sourceStride - 1;
  1561. tempColor.setRGB(
  1562. array[ startIndex + 0 ],
  1563. array[ startIndex + 1 ],
  1564. array[ startIndex + 2 ],
  1565. SRGBColorSpace
  1566. );
  1567. array[ startIndex + 0 ] = tempColor.r;
  1568. array[ startIndex + 1 ] = tempColor.g;
  1569. array[ startIndex + 2 ] = tempColor.b;
  1570. }
  1571. }
  1572. const sourceArray = source.array;
  1573. const sourceStride = source.stride;
  1574. if ( primitive.vcount !== undefined ) {
  1575. let index = 0;
  1576. for ( let i = 0, l = vcount.length; i < l; i ++ ) {
  1577. const count = vcount[ i ];
  1578. if ( count === 4 ) {
  1579. const a = index + stride * 0;
  1580. const b = index + stride * 1;
  1581. const c = index + stride * 2;
  1582. const d = index + stride * 3;
  1583. pushVector( a ); pushVector( b ); pushVector( d );
  1584. pushVector( b ); pushVector( c ); pushVector( d );
  1585. } else if ( count === 3 ) {
  1586. const a = index + stride * 0;
  1587. const b = index + stride * 1;
  1588. const c = index + stride * 2;
  1589. pushVector( a ); pushVector( b ); pushVector( c );
  1590. } else if ( count > 4 ) {
  1591. for ( let k = 1, kl = ( count - 2 ); k <= kl; k ++ ) {
  1592. const a = index + stride * 0;
  1593. const b = index + stride * k;
  1594. const c = index + stride * ( k + 1 );
  1595. pushVector( a ); pushVector( b ); pushVector( c );
  1596. }
  1597. }
  1598. index += stride * count;
  1599. }
  1600. } else {
  1601. for ( let i = 0, l = indices.length; i < l; i += stride ) {
  1602. pushVector( i );
  1603. }
  1604. }
  1605. }
  1606. function getGeometry( id ) {
  1607. return getBuild( library.geometries[ id ], buildGeometry );
  1608. }
  1609. // kinematics
  1610. function parseKinematicsModel( xml ) {
  1611. const data = {
  1612. name: xml.getAttribute( 'name' ) || '',
  1613. joints: {},
  1614. links: []
  1615. };
  1616. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1617. const child = xml.childNodes[ i ];
  1618. if ( child.nodeType !== 1 ) continue;
  1619. switch ( child.nodeName ) {
  1620. case 'technique_common':
  1621. parseKinematicsTechniqueCommon( child, data );
  1622. break;
  1623. }
  1624. }
  1625. library.kinematicsModels[ xml.getAttribute( 'id' ) ] = data;
  1626. }
  1627. function buildKinematicsModel( data ) {
  1628. if ( data.build !== undefined ) return data.build;
  1629. return data;
  1630. }
  1631. function getKinematicsModel( id ) {
  1632. return getBuild( library.kinematicsModels[ id ], buildKinematicsModel );
  1633. }
  1634. function parseKinematicsTechniqueCommon( xml, data ) {
  1635. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1636. const child = xml.childNodes[ i ];
  1637. if ( child.nodeType !== 1 ) continue;
  1638. switch ( child.nodeName ) {
  1639. case 'joint':
  1640. data.joints[ child.getAttribute( 'sid' ) ] = parseKinematicsJoint( child );
  1641. break;
  1642. case 'link':
  1643. data.links.push( parseKinematicsLink( child ) );
  1644. break;
  1645. }
  1646. }
  1647. }
  1648. function parseKinematicsJoint( xml ) {
  1649. let data;
  1650. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1651. const child = xml.childNodes[ i ];
  1652. if ( child.nodeType !== 1 ) continue;
  1653. switch ( child.nodeName ) {
  1654. case 'prismatic':
  1655. case 'revolute':
  1656. data = parseKinematicsJointParameter( child );
  1657. break;
  1658. }
  1659. }
  1660. return data;
  1661. }
  1662. function parseKinematicsJointParameter( xml ) {
  1663. const data = {
  1664. sid: xml.getAttribute( 'sid' ),
  1665. name: xml.getAttribute( 'name' ) || '',
  1666. axis: new Vector3(),
  1667. limits: {
  1668. min: 0,
  1669. max: 0
  1670. },
  1671. type: xml.nodeName,
  1672. static: false,
  1673. zeroPosition: 0,
  1674. middlePosition: 0
  1675. };
  1676. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1677. const child = xml.childNodes[ i ];
  1678. if ( child.nodeType !== 1 ) continue;
  1679. switch ( child.nodeName ) {
  1680. case 'axis':
  1681. const array = parseFloats( child.textContent );
  1682. data.axis.fromArray( array );
  1683. break;
  1684. case 'limits':
  1685. const max = child.getElementsByTagName( 'max' )[ 0 ];
  1686. const min = child.getElementsByTagName( 'min' )[ 0 ];
  1687. data.limits.max = parseFloat( max.textContent );
  1688. data.limits.min = parseFloat( min.textContent );
  1689. break;
  1690. }
  1691. }
  1692. // if min is equal to or greater than max, consider the joint static
  1693. if ( data.limits.min >= data.limits.max ) {
  1694. data.static = true;
  1695. }
  1696. // calculate middle position
  1697. data.middlePosition = ( data.limits.min + data.limits.max ) / 2.0;
  1698. return data;
  1699. }
  1700. function parseKinematicsLink( xml ) {
  1701. const data = {
  1702. sid: xml.getAttribute( 'sid' ),
  1703. name: xml.getAttribute( 'name' ) || '',
  1704. attachments: [],
  1705. transforms: []
  1706. };
  1707. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1708. const child = xml.childNodes[ i ];
  1709. if ( child.nodeType !== 1 ) continue;
  1710. switch ( child.nodeName ) {
  1711. case 'attachment_full':
  1712. data.attachments.push( parseKinematicsAttachment( child ) );
  1713. break;
  1714. case 'matrix':
  1715. case 'translate':
  1716. case 'rotate':
  1717. data.transforms.push( parseKinematicsTransform( child ) );
  1718. break;
  1719. }
  1720. }
  1721. return data;
  1722. }
  1723. function parseKinematicsAttachment( xml ) {
  1724. const data = {
  1725. joint: xml.getAttribute( 'joint' ).split( '/' ).pop(),
  1726. transforms: [],
  1727. links: []
  1728. };
  1729. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1730. const child = xml.childNodes[ i ];
  1731. if ( child.nodeType !== 1 ) continue;
  1732. switch ( child.nodeName ) {
  1733. case 'link':
  1734. data.links.push( parseKinematicsLink( child ) );
  1735. break;
  1736. case 'matrix':
  1737. case 'translate':
  1738. case 'rotate':
  1739. data.transforms.push( parseKinematicsTransform( child ) );
  1740. break;
  1741. }
  1742. }
  1743. return data;
  1744. }
  1745. function parseKinematicsTransform( xml ) {
  1746. const data = {
  1747. type: xml.nodeName
  1748. };
  1749. const array = parseFloats( xml.textContent );
  1750. switch ( data.type ) {
  1751. case 'matrix':
  1752. data.obj = new Matrix4();
  1753. data.obj.fromArray( array ).transpose();
  1754. break;
  1755. case 'translate':
  1756. data.obj = new Vector3();
  1757. data.obj.fromArray( array );
  1758. break;
  1759. case 'rotate':
  1760. data.obj = new Vector3();
  1761. data.obj.fromArray( array );
  1762. data.angle = MathUtils.degToRad( array[ 3 ] );
  1763. break;
  1764. }
  1765. return data;
  1766. }
  1767. // physics
  1768. function parsePhysicsModel( xml ) {
  1769. const data = {
  1770. name: xml.getAttribute( 'name' ) || '',
  1771. rigidBodies: {}
  1772. };
  1773. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1774. const child = xml.childNodes[ i ];
  1775. if ( child.nodeType !== 1 ) continue;
  1776. switch ( child.nodeName ) {
  1777. case 'rigid_body':
  1778. data.rigidBodies[ child.getAttribute( 'name' ) ] = {};
  1779. parsePhysicsRigidBody( child, data.rigidBodies[ child.getAttribute( 'name' ) ] );
  1780. break;
  1781. }
  1782. }
  1783. library.physicsModels[ xml.getAttribute( 'id' ) ] = data;
  1784. }
  1785. function parsePhysicsRigidBody( xml, data ) {
  1786. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1787. const child = xml.childNodes[ i ];
  1788. if ( child.nodeType !== 1 ) continue;
  1789. switch ( child.nodeName ) {
  1790. case 'technique_common':
  1791. parsePhysicsTechniqueCommon( child, data );
  1792. break;
  1793. }
  1794. }
  1795. }
  1796. function parsePhysicsTechniqueCommon( xml, data ) {
  1797. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1798. const child = xml.childNodes[ i ];
  1799. if ( child.nodeType !== 1 ) continue;
  1800. switch ( child.nodeName ) {
  1801. case 'inertia':
  1802. data.inertia = parseFloats( child.textContent );
  1803. break;
  1804. case 'mass':
  1805. data.mass = parseFloats( child.textContent )[ 0 ];
  1806. break;
  1807. }
  1808. }
  1809. }
  1810. // scene
  1811. function parseKinematicsScene( xml ) {
  1812. const data = {
  1813. bindJointAxis: []
  1814. };
  1815. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1816. const child = xml.childNodes[ i ];
  1817. if ( child.nodeType !== 1 ) continue;
  1818. switch ( child.nodeName ) {
  1819. case 'bind_joint_axis':
  1820. data.bindJointAxis.push( parseKinematicsBindJointAxis( child ) );
  1821. break;
  1822. }
  1823. }
  1824. library.kinematicsScenes[ parseId( xml.getAttribute( 'url' ) ) ] = data;
  1825. }
  1826. function parseKinematicsBindJointAxis( xml ) {
  1827. const data = {
  1828. target: xml.getAttribute( 'target' ).split( '/' ).pop()
  1829. };
  1830. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1831. const child = xml.childNodes[ i ];
  1832. if ( child.nodeType !== 1 ) continue;
  1833. switch ( child.nodeName ) {
  1834. case 'axis':
  1835. const param = child.getElementsByTagName( 'param' )[ 0 ];
  1836. data.axis = param.textContent;
  1837. const tmpJointIndex = data.axis.split( 'inst_' ).pop().split( 'axis' )[ 0 ];
  1838. data.jointIndex = tmpJointIndex.substring( 0, tmpJointIndex.length - 1 );
  1839. break;
  1840. }
  1841. }
  1842. return data;
  1843. }
  1844. function buildKinematicsScene( data ) {
  1845. if ( data.build !== undefined ) return data.build;
  1846. return data;
  1847. }
  1848. function getKinematicsScene( id ) {
  1849. return getBuild( library.kinematicsScenes[ id ], buildKinematicsScene );
  1850. }
  1851. function setupKinematics() {
  1852. const kinematicsModelId = Object.keys( library.kinematicsModels )[ 0 ];
  1853. const kinematicsSceneId = Object.keys( library.kinematicsScenes )[ 0 ];
  1854. const visualSceneId = Object.keys( library.visualScenes )[ 0 ];
  1855. if ( kinematicsModelId === undefined || kinematicsSceneId === undefined ) return;
  1856. const kinematicsModel = getKinematicsModel( kinematicsModelId );
  1857. const kinematicsScene = getKinematicsScene( kinematicsSceneId );
  1858. const visualScene = getVisualScene( visualSceneId );
  1859. const bindJointAxis = kinematicsScene.bindJointAxis;
  1860. const jointMap = {};
  1861. for ( let i = 0, l = bindJointAxis.length; i < l; i ++ ) {
  1862. const axis = bindJointAxis[ i ];
  1863. // the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix'
  1864. const targetElement = collada.querySelector( '[sid="' + axis.target + '"]' );
  1865. if ( targetElement ) {
  1866. // get the parent of the transform element
  1867. const parentVisualElement = targetElement.parentElement;
  1868. // connect the joint of the kinematics model with the element in the visual scene
  1869. connect( axis.jointIndex, parentVisualElement );
  1870. }
  1871. }
  1872. function connect( jointIndex, visualElement ) {
  1873. const visualElementName = visualElement.getAttribute( 'name' );
  1874. const joint = kinematicsModel.joints[ jointIndex ];
  1875. visualScene.traverse( function ( object ) {
  1876. if ( object.name === visualElementName ) {
  1877. jointMap[ jointIndex ] = {
  1878. object: object,
  1879. transforms: buildTransformList( visualElement ),
  1880. joint: joint,
  1881. position: joint.zeroPosition
  1882. };
  1883. }
  1884. } );
  1885. }
  1886. const m0 = new Matrix4();
  1887. kinematics = {
  1888. joints: kinematicsModel && kinematicsModel.joints,
  1889. getJointValue: function ( jointIndex ) {
  1890. const jointData = jointMap[ jointIndex ];
  1891. if ( jointData ) {
  1892. return jointData.position;
  1893. } else {
  1894. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' doesn\'t exist.' );
  1895. }
  1896. },
  1897. setJointValue: function ( jointIndex, value ) {
  1898. const jointData = jointMap[ jointIndex ];
  1899. if ( jointData ) {
  1900. const joint = jointData.joint;
  1901. if ( value > joint.limits.max || value < joint.limits.min ) {
  1902. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ').' );
  1903. } else if ( joint.static ) {
  1904. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' is static.' );
  1905. } else {
  1906. const object = jointData.object;
  1907. const axis = joint.axis;
  1908. const transforms = jointData.transforms;
  1909. matrix.identity();
  1910. // each update, we have to apply all transforms in the correct order
  1911. for ( let i = 0; i < transforms.length; i ++ ) {
  1912. const transform = transforms[ i ];
  1913. // if there is a connection of the transform node with a joint, apply the joint value
  1914. if ( transform.sid && transform.sid.indexOf( jointIndex ) !== - 1 ) {
  1915. switch ( joint.type ) {
  1916. case 'revolute':
  1917. matrix.multiply( m0.makeRotationAxis( axis, MathUtils.degToRad( value ) ) );
  1918. break;
  1919. case 'prismatic':
  1920. matrix.multiply( m0.makeTranslation( axis.x * value, axis.y * value, axis.z * value ) );
  1921. break;
  1922. default:
  1923. console.warn( 'THREE.ColladaLoader: Unknown joint type: ' + joint.type );
  1924. break;
  1925. }
  1926. } else {
  1927. switch ( transform.type ) {
  1928. case 'matrix':
  1929. matrix.multiply( transform.obj );
  1930. break;
  1931. case 'translate':
  1932. matrix.multiply( m0.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
  1933. break;
  1934. case 'scale':
  1935. matrix.scale( transform.obj );
  1936. break;
  1937. case 'rotate':
  1938. matrix.multiply( m0.makeRotationAxis( transform.obj, transform.angle ) );
  1939. break;
  1940. }
  1941. }
  1942. }
  1943. object.matrix.copy( matrix );
  1944. object.matrix.decompose( object.position, object.quaternion, object.scale );
  1945. jointMap[ jointIndex ].position = value;
  1946. }
  1947. } else {
  1948. console.log( 'THREE.ColladaLoader: ' + jointIndex + ' does not exist.' );
  1949. }
  1950. }
  1951. };
  1952. }
  1953. function buildTransformList( node ) {
  1954. const transforms = [];
  1955. const xml = collada.querySelector( '[id="' + node.id + '"]' );
  1956. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1957. const child = xml.childNodes[ i ];
  1958. if ( child.nodeType !== 1 ) continue;
  1959. let array, vector;
  1960. switch ( child.nodeName ) {
  1961. case 'matrix':
  1962. array = parseFloats( child.textContent );
  1963. const matrix = new Matrix4().fromArray( array ).transpose();
  1964. transforms.push( {
  1965. sid: child.getAttribute( 'sid' ),
  1966. type: child.nodeName,
  1967. obj: matrix
  1968. } );
  1969. break;
  1970. case 'translate':
  1971. case 'scale':
  1972. array = parseFloats( child.textContent );
  1973. vector = new Vector3().fromArray( array );
  1974. transforms.push( {
  1975. sid: child.getAttribute( 'sid' ),
  1976. type: child.nodeName,
  1977. obj: vector
  1978. } );
  1979. break;
  1980. case 'rotate':
  1981. array = parseFloats( child.textContent );
  1982. vector = new Vector3().fromArray( array );
  1983. const angle = MathUtils.degToRad( array[ 3 ] );
  1984. transforms.push( {
  1985. sid: child.getAttribute( 'sid' ),
  1986. type: child.nodeName,
  1987. obj: vector,
  1988. angle: angle
  1989. } );
  1990. break;
  1991. }
  1992. }
  1993. return transforms;
  1994. }
  1995. // nodes
  1996. function prepareNodes( xml ) {
  1997. const elements = xml.getElementsByTagName( 'node' );
  1998. // ensure all node elements have id attributes
  1999. for ( let i = 0; i < elements.length; i ++ ) {
  2000. const element = elements[ i ];
  2001. if ( element.hasAttribute( 'id' ) === false ) {
  2002. element.setAttribute( 'id', generateId() );
  2003. }
  2004. }
  2005. }
  2006. const matrix = new Matrix4();
  2007. const vector = new Vector3();
  2008. function parseNode( xml ) {
  2009. const data = {
  2010. name: xml.getAttribute( 'name' ) || '',
  2011. type: xml.getAttribute( 'type' ),
  2012. id: xml.getAttribute( 'id' ),
  2013. sid: xml.getAttribute( 'sid' ),
  2014. matrix: new Matrix4(),
  2015. nodes: [],
  2016. instanceCameras: [],
  2017. instanceControllers: [],
  2018. instanceLights: [],
  2019. instanceGeometries: [],
  2020. instanceNodes: [],
  2021. transforms: {}
  2022. };
  2023. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  2024. const child = xml.childNodes[ i ];
  2025. if ( child.nodeType !== 1 ) continue;
  2026. let array;
  2027. switch ( child.nodeName ) {
  2028. case 'node':
  2029. data.nodes.push( child.getAttribute( 'id' ) );
  2030. parseNode( child );
  2031. break;
  2032. case 'instance_camera':
  2033. data.instanceCameras.push( parseId( child.getAttribute( 'url' ) ) );
  2034. break;
  2035. case 'instance_controller':
  2036. data.instanceControllers.push( parseNodeInstance( child ) );
  2037. break;
  2038. case 'instance_light':
  2039. data.instanceLights.push( parseId( child.getAttribute( 'url' ) ) );
  2040. break;
  2041. case 'instance_geometry':
  2042. data.instanceGeometries.push( parseNodeInstance( child ) );
  2043. break;
  2044. case 'instance_node':
  2045. data.instanceNodes.push( parseId( child.getAttribute( 'url' ) ) );
  2046. break;
  2047. case 'matrix':
  2048. array = parseFloats( child.textContent );
  2049. data.matrix.multiply( matrix.fromArray( array ).transpose() );
  2050. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  2051. break;
  2052. case 'translate':
  2053. array = parseFloats( child.textContent );
  2054. vector.fromArray( array );
  2055. data.matrix.multiply( matrix.makeTranslation( vector.x, vector.y, vector.z ) );
  2056. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  2057. break;
  2058. case 'rotate':
  2059. array = parseFloats( child.textContent );
  2060. const angle = MathUtils.degToRad( array[ 3 ] );
  2061. data.matrix.multiply( matrix.makeRotationAxis( vector.fromArray( array ), angle ) );
  2062. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  2063. break;
  2064. case 'scale':
  2065. array = parseFloats( child.textContent );
  2066. data.matrix.scale( vector.fromArray( array ) );
  2067. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  2068. break;
  2069. case 'extra':
  2070. break;
  2071. default:
  2072. console.log( child );
  2073. }
  2074. }
  2075. if ( hasNode( data.id ) ) {
  2076. console.warn( 'THREE.ColladaLoader: There is already a node with ID %s. Exclude current node from further processing.', data.id );
  2077. } else {
  2078. library.nodes[ data.id ] = data;
  2079. }
  2080. return data;
  2081. }
  2082. function parseNodeInstance( xml ) {
  2083. const data = {
  2084. id: parseId( xml.getAttribute( 'url' ) ),
  2085. materials: {},
  2086. skeletons: []
  2087. };
  2088. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  2089. const child = xml.childNodes[ i ];
  2090. switch ( child.nodeName ) {
  2091. case 'bind_material':
  2092. const instances = child.getElementsByTagName( 'instance_material' );
  2093. for ( let j = 0; j < instances.length; j ++ ) {
  2094. const instance = instances[ j ];
  2095. const symbol = instance.getAttribute( 'symbol' );
  2096. const target = instance.getAttribute( 'target' );
  2097. data.materials[ symbol ] = parseId( target );
  2098. }
  2099. break;
  2100. case 'skeleton':
  2101. data.skeletons.push( parseId( child.textContent ) );
  2102. break;
  2103. default:
  2104. break;
  2105. }
  2106. }
  2107. return data;
  2108. }
  2109. function buildSkeleton( skeletons, joints ) {
  2110. const boneData = [];
  2111. const sortedBoneData = [];
  2112. let i, j, data;
  2113. // a skeleton can have multiple root bones. collada expresses this
  2114. // situation with multiple "skeleton" tags per controller instance
  2115. for ( i = 0; i < skeletons.length; i ++ ) {
  2116. const skeleton = skeletons[ i ];
  2117. let root;
  2118. if ( hasNode( skeleton ) ) {
  2119. root = getNode( skeleton );
  2120. buildBoneHierarchy( root, joints, boneData );
  2121. } else if ( hasVisualScene( skeleton ) ) {
  2122. // handle case where the skeleton refers to the visual scene (#13335)
  2123. const visualScene = library.visualScenes[ skeleton ];
  2124. const children = visualScene.children;
  2125. for ( let j = 0; j < children.length; j ++ ) {
  2126. const child = children[ j ];
  2127. if ( child.type === 'JOINT' ) {
  2128. const root = getNode( child.id );
  2129. buildBoneHierarchy( root, joints, boneData );
  2130. }
  2131. }
  2132. } else {
  2133. console.error( 'THREE.ColladaLoader: Unable to find root bone of skeleton with ID:', skeleton );
  2134. }
  2135. }
  2136. // sort bone data (the order is defined in the corresponding controller)
  2137. for ( i = 0; i < joints.length; i ++ ) {
  2138. for ( j = 0; j < boneData.length; j ++ ) {
  2139. data = boneData[ j ];
  2140. if ( data.bone.name === joints[ i ].name ) {
  2141. sortedBoneData[ i ] = data;
  2142. data.processed = true;
  2143. break;
  2144. }
  2145. }
  2146. }
  2147. // add unprocessed bone data at the end of the list
  2148. for ( i = 0; i < boneData.length; i ++ ) {
  2149. data = boneData[ i ];
  2150. if ( data.processed === false ) {
  2151. sortedBoneData.push( data );
  2152. data.processed = true;
  2153. }
  2154. }
  2155. // setup arrays for skeleton creation
  2156. const bones = [];
  2157. const boneInverses = [];
  2158. for ( i = 0; i < sortedBoneData.length; i ++ ) {
  2159. data = sortedBoneData[ i ];
  2160. bones.push( data.bone );
  2161. boneInverses.push( data.boneInverse );
  2162. }
  2163. return new Skeleton( bones, boneInverses );
  2164. }
  2165. function buildBoneHierarchy( root, joints, boneData ) {
  2166. // setup bone data from visual scene
  2167. root.traverse( function ( object ) {
  2168. if ( object.isBone === true ) {
  2169. let boneInverse;
  2170. // retrieve the boneInverse from the controller data
  2171. for ( let i = 0; i < joints.length; i ++ ) {
  2172. const joint = joints[ i ];
  2173. if ( joint.name === object.name ) {
  2174. boneInverse = joint.boneInverse;
  2175. break;
  2176. }
  2177. }
  2178. if ( boneInverse === undefined ) {
  2179. // Unfortunately, there can be joints in the visual scene that are not part of the
  2180. // corresponding controller. In this case, we have to create a dummy boneInverse matrix
  2181. // for the respective bone. This bone won't affect any vertices, because there are no skin indices
  2182. // and weights defined for it. But we still have to add the bone to the sorted bone list in order to
  2183. // ensure a correct animation of the model.
  2184. boneInverse = new Matrix4();
  2185. }
  2186. boneData.push( { bone: object, boneInverse: boneInverse, processed: false } );
  2187. }
  2188. } );
  2189. }
  2190. function buildNode( data ) {
  2191. const objects = [];
  2192. const matrix = data.matrix;
  2193. const nodes = data.nodes;
  2194. const type = data.type;
  2195. const instanceCameras = data.instanceCameras;
  2196. const instanceControllers = data.instanceControllers;
  2197. const instanceLights = data.instanceLights;
  2198. const instanceGeometries = data.instanceGeometries;
  2199. const instanceNodes = data.instanceNodes;
  2200. // nodes
  2201. for ( let i = 0, l = nodes.length; i < l; i ++ ) {
  2202. objects.push( getNode( nodes[ i ] ) );
  2203. }
  2204. // instance cameras
  2205. for ( let i = 0, l = instanceCameras.length; i < l; i ++ ) {
  2206. const instanceCamera = getCamera( instanceCameras[ i ] );
  2207. if ( instanceCamera !== null ) {
  2208. objects.push( instanceCamera.clone() );
  2209. }
  2210. }
  2211. // instance controllers
  2212. for ( let i = 0, l = instanceControllers.length; i < l; i ++ ) {
  2213. const instance = instanceControllers[ i ];
  2214. const controller = getController( instance.id );
  2215. const geometries = getGeometry( controller.id );
  2216. const newObjects = buildObjects( geometries, instance.materials );
  2217. const skeletons = instance.skeletons;
  2218. const joints = controller.skin.joints;
  2219. const skeleton = buildSkeleton( skeletons, joints );
  2220. for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) {
  2221. const object = newObjects[ j ];
  2222. if ( object.isSkinnedMesh ) {
  2223. object.bind( skeleton, controller.skin.bindMatrix );
  2224. object.normalizeSkinWeights();
  2225. }
  2226. objects.push( object );
  2227. }
  2228. }
  2229. // instance lights
  2230. for ( let i = 0, l = instanceLights.length; i < l; i ++ ) {
  2231. const instanceLight = getLight( instanceLights[ i ] );
  2232. if ( instanceLight !== null ) {
  2233. objects.push( instanceLight.clone() );
  2234. }
  2235. }
  2236. // instance geometries
  2237. for ( let i = 0, l = instanceGeometries.length; i < l; i ++ ) {
  2238. const instance = instanceGeometries[ i ];
  2239. // a single geometry instance in collada can lead to multiple object3Ds.
  2240. // this is the case when primitives are combined like triangles and lines
  2241. const geometries = getGeometry( instance.id );
  2242. const newObjects = buildObjects( geometries, instance.materials );
  2243. for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) {
  2244. objects.push( newObjects[ j ] );
  2245. }
  2246. }
  2247. // instance nodes
  2248. for ( let i = 0, l = instanceNodes.length; i < l; i ++ ) {
  2249. objects.push( getNode( instanceNodes[ i ] ).clone() );
  2250. }
  2251. let object;
  2252. if ( nodes.length === 0 && objects.length === 1 ) {
  2253. object = objects[ 0 ];
  2254. } else {
  2255. object = ( type === 'JOINT' ) ? new Bone() : new Group();
  2256. for ( let i = 0; i < objects.length; i ++ ) {
  2257. object.add( objects[ i ] );
  2258. }
  2259. }
  2260. object.name = ( type === 'JOINT' ) ? data.sid : data.name;
  2261. object.matrix.copy( matrix );
  2262. object.matrix.decompose( object.position, object.quaternion, object.scale );
  2263. return object;
  2264. }
  2265. const fallbackMaterial = new MeshBasicMaterial( {
  2266. name: Loader.DEFAULT_MATERIAL_NAME,
  2267. color: 0xff00ff
  2268. } );
  2269. function resolveMaterialBinding( keys, instanceMaterials ) {
  2270. const materials = [];
  2271. for ( let i = 0, l = keys.length; i < l; i ++ ) {
  2272. const id = instanceMaterials[ keys[ i ] ];
  2273. if ( id === undefined ) {
  2274. console.warn( 'THREE.ColladaLoader: Material with key %s not found. Apply fallback material.', keys[ i ] );
  2275. materials.push( fallbackMaterial );
  2276. } else {
  2277. materials.push( getMaterial( id ) );
  2278. }
  2279. }
  2280. return materials;
  2281. }
  2282. function buildObjects( geometries, instanceMaterials ) {
  2283. const objects = [];
  2284. for ( const type in geometries ) {
  2285. const geometry = geometries[ type ];
  2286. const materials = resolveMaterialBinding( geometry.materialKeys, instanceMaterials );
  2287. // handle case if no materials are defined
  2288. if ( materials.length === 0 ) {
  2289. if ( type === 'lines' || type === 'linestrips' ) {
  2290. materials.push( new LineBasicMaterial() );
  2291. } else {
  2292. materials.push( new MeshPhongMaterial() );
  2293. }
  2294. }
  2295. // Collada allows to use phong and lambert materials with lines. Replacing these cases with LineBasicMaterial.
  2296. if ( type === 'lines' || type === 'linestrips' ) {
  2297. for ( let i = 0, l = materials.length; i < l; i ++ ) {
  2298. const material = materials[ i ];
  2299. if ( material.isMeshPhongMaterial === true || material.isMeshLambertMaterial === true ) {
  2300. const lineMaterial = new LineBasicMaterial();
  2301. // copy compatible properties
  2302. lineMaterial.color.copy( material.color );
  2303. lineMaterial.opacity = material.opacity;
  2304. lineMaterial.transparent = material.transparent;
  2305. // replace material
  2306. materials[ i ] = lineMaterial;
  2307. }
  2308. }
  2309. }
  2310. // regard skinning
  2311. const skinning = ( geometry.data.attributes.skinIndex !== undefined );
  2312. // choose between a single or multi materials (material array)
  2313. const material = ( materials.length === 1 ) ? materials[ 0 ] : materials;
  2314. // now create a specific 3D object
  2315. let object;
  2316. switch ( type ) {
  2317. case 'lines':
  2318. object = new LineSegments( geometry.data, material );
  2319. break;
  2320. case 'linestrips':
  2321. object = new Line( geometry.data, material );
  2322. break;
  2323. case 'triangles':
  2324. case 'polylist':
  2325. if ( skinning ) {
  2326. object = new SkinnedMesh( geometry.data, material );
  2327. } else {
  2328. object = new Mesh( geometry.data, material );
  2329. }
  2330. break;
  2331. }
  2332. objects.push( object );
  2333. }
  2334. return objects;
  2335. }
  2336. function hasNode( id ) {
  2337. return library.nodes[ id ] !== undefined;
  2338. }
  2339. function getNode( id ) {
  2340. return getBuild( library.nodes[ id ], buildNode );
  2341. }
  2342. // visual scenes
  2343. function parseVisualScene( xml ) {
  2344. const data = {
  2345. name: xml.getAttribute( 'name' ),
  2346. children: []
  2347. };
  2348. prepareNodes( xml );
  2349. const elements = getElementsByTagName( xml, 'node' );
  2350. for ( let i = 0; i < elements.length; i ++ ) {
  2351. data.children.push( parseNode( elements[ i ] ) );
  2352. }
  2353. library.visualScenes[ xml.getAttribute( 'id' ) ] = data;
  2354. }
  2355. function buildVisualScene( data ) {
  2356. const group = new Group();
  2357. group.name = data.name;
  2358. const children = data.children;
  2359. for ( let i = 0; i < children.length; i ++ ) {
  2360. const child = children[ i ];
  2361. group.add( getNode( child.id ) );
  2362. }
  2363. return group;
  2364. }
  2365. function hasVisualScene( id ) {
  2366. return library.visualScenes[ id ] !== undefined;
  2367. }
  2368. function getVisualScene( id ) {
  2369. return getBuild( library.visualScenes[ id ], buildVisualScene );
  2370. }
  2371. // scenes
  2372. function parseScene( xml ) {
  2373. const instance = getElementsByTagName( xml, 'instance_visual_scene' )[ 0 ];
  2374. return getVisualScene( parseId( instance.getAttribute( 'url' ) ) );
  2375. }
  2376. function setupAnimations() {
  2377. const clips = library.clips;
  2378. if ( isEmpty( clips ) === true ) {
  2379. if ( isEmpty( library.animations ) === false ) {
  2380. // if there are animations but no clips, we create a default clip for playback
  2381. const tracks = [];
  2382. for ( const id in library.animations ) {
  2383. const animationTracks = getAnimation( id );
  2384. for ( let i = 0, l = animationTracks.length; i < l; i ++ ) {
  2385. tracks.push( animationTracks[ i ] );
  2386. }
  2387. }
  2388. animations.push( new AnimationClip( 'default', - 1, tracks ) );
  2389. }
  2390. } else {
  2391. for ( const id in clips ) {
  2392. animations.push( getAnimationClip( id ) );
  2393. }
  2394. }
  2395. }
  2396. // convert the parser error element into text with each child elements text
  2397. // separated by new lines.
  2398. function parserErrorToText( parserError ) {
  2399. let result = '';
  2400. const stack = [ parserError ];
  2401. while ( stack.length ) {
  2402. const node = stack.shift();
  2403. if ( node.nodeType === Node.TEXT_NODE ) {
  2404. result += node.textContent;
  2405. } else {
  2406. result += '\n';
  2407. stack.push( ...node.childNodes );
  2408. }
  2409. }
  2410. return result.trim();
  2411. }
  2412. if ( text.length === 0 ) {
  2413. return { scene: new Scene() };
  2414. }
  2415. const xml = new DOMParser().parseFromString( text, 'application/xml' );
  2416. const collada = getElementsByTagName( xml, 'COLLADA' )[ 0 ];
  2417. const parserError = xml.getElementsByTagName( 'parsererror' )[ 0 ];
  2418. if ( parserError !== undefined ) {
  2419. // Chrome will return parser error with a div in it
  2420. const errorElement = getElementsByTagName( parserError, 'div' )[ 0 ];
  2421. let errorText;
  2422. if ( errorElement ) {
  2423. errorText = errorElement.textContent;
  2424. } else {
  2425. errorText = parserErrorToText( parserError );
  2426. }
  2427. console.error( 'THREE.ColladaLoader: Failed to parse collada file.\n', errorText );
  2428. return null;
  2429. }
  2430. // metadata
  2431. const version = collada.getAttribute( 'version' );
  2432. console.debug( 'THREE.ColladaLoader: File version', version );
  2433. const asset = parseAsset( getElementsByTagName( collada, 'asset' )[ 0 ] );
  2434. const textureLoader = new TextureLoader( this.manager );
  2435. textureLoader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
  2436. let tgaLoader;
  2437. if ( TGALoader ) {
  2438. tgaLoader = new TGALoader( this.manager );
  2439. tgaLoader.setPath( this.resourcePath || path );
  2440. }
  2441. //
  2442. const tempColor = new Color();
  2443. const animations = [];
  2444. let kinematics = {};
  2445. let count = 0;
  2446. //
  2447. const library = {
  2448. animations: {},
  2449. clips: {},
  2450. controllers: {},
  2451. images: {},
  2452. effects: {},
  2453. materials: {},
  2454. cameras: {},
  2455. lights: {},
  2456. geometries: {},
  2457. nodes: {},
  2458. visualScenes: {},
  2459. kinematicsModels: {},
  2460. physicsModels: {},
  2461. kinematicsScenes: {}
  2462. };
  2463. parseLibrary( collada, 'library_animations', 'animation', parseAnimation );
  2464. parseLibrary( collada, 'library_animation_clips', 'animation_clip', parseAnimationClip );
  2465. parseLibrary( collada, 'library_controllers', 'controller', parseController );
  2466. parseLibrary( collada, 'library_images', 'image', parseImage );
  2467. parseLibrary( collada, 'library_effects', 'effect', parseEffect );
  2468. parseLibrary( collada, 'library_materials', 'material', parseMaterial );
  2469. parseLibrary( collada, 'library_cameras', 'camera', parseCamera );
  2470. parseLibrary( collada, 'library_lights', 'light', parseLight );
  2471. parseLibrary( collada, 'library_geometries', 'geometry', parseGeometry );
  2472. parseLibrary( collada, 'library_nodes', 'node', parseNode );
  2473. parseLibrary( collada, 'library_visual_scenes', 'visual_scene', parseVisualScene );
  2474. parseLibrary( collada, 'library_kinematics_models', 'kinematics_model', parseKinematicsModel );
  2475. parseLibrary( collada, 'library_physics_models', 'physics_model', parsePhysicsModel );
  2476. parseLibrary( collada, 'scene', 'instance_kinematics_scene', parseKinematicsScene );
  2477. buildLibrary( library.animations, buildAnimation );
  2478. buildLibrary( library.clips, buildAnimationClip );
  2479. buildLibrary( library.controllers, buildController );
  2480. buildLibrary( library.images, buildImage );
  2481. buildLibrary( library.effects, buildEffect );
  2482. buildLibrary( library.materials, buildMaterial );
  2483. buildLibrary( library.cameras, buildCamera );
  2484. buildLibrary( library.lights, buildLight );
  2485. buildLibrary( library.geometries, buildGeometry );
  2486. buildLibrary( library.visualScenes, buildVisualScene );
  2487. setupAnimations();
  2488. setupKinematics();
  2489. const scene = parseScene( getElementsByTagName( collada, 'scene' )[ 0 ] );
  2490. scene.animations = animations;
  2491. if ( asset.upAxis === 'Z_UP' ) {
  2492. console.warn( 'THREE.ColladaLoader: You are loading an asset with a Z-UP coordinate system. The loader just rotates the asset to transform it into Y-UP. The vertex data are not converted, see #24289.' );
  2493. scene.rotation.set( - Math.PI / 2, 0, 0 );
  2494. }
  2495. scene.scale.multiplyScalar( asset.unit );
  2496. return {
  2497. get animations() {
  2498. console.warn( 'THREE.ColladaLoader: Please access animations over scene.animations now.' );
  2499. return animations;
  2500. },
  2501. kinematics: kinematics,
  2502. library: library,
  2503. scene: scene
  2504. };
  2505. }
  2506. }
  2507. export { ColladaLoader };
粤ICP备19079148号