ColladaLoader.js 80 KB

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