ColladaLoader.js 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063
  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 'three';
  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.hasAttribute( 'opaque' ) ? child.getAttribute( 'opaque' ) : 'A_ONE',
  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. console.warn( 'THREE.ColladaLoader: Invalid opaque type "%s" of transparent tag.', transparent.opaque );
  1034. }
  1035. if ( material.opacity < 1 ) material.transparent = true;
  1036. }
  1037. }
  1038. //
  1039. if ( technique.extra !== undefined && technique.extra.technique !== undefined ) {
  1040. const techniques = technique.extra.technique;
  1041. for ( const k in techniques ) {
  1042. const v = techniques[ k ];
  1043. switch ( k ) {
  1044. case 'double_sided':
  1045. material.side = ( v === 1 ? DoubleSide : FrontSide );
  1046. break;
  1047. case 'bump':
  1048. material.normalMap = getTexture( v.texture );
  1049. material.normalScale = new Vector2( 1, 1 );
  1050. break;
  1051. }
  1052. }
  1053. }
  1054. return material;
  1055. }
  1056. function getMaterial( id ) {
  1057. return getBuild( library.materials[ id ], buildMaterial );
  1058. }
  1059. // camera
  1060. function parseCamera( xml ) {
  1061. const data = {
  1062. name: xml.getAttribute( 'name' )
  1063. };
  1064. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1065. const child = xml.childNodes[ i ];
  1066. if ( child.nodeType !== 1 ) continue;
  1067. switch ( child.nodeName ) {
  1068. case 'optics':
  1069. data.optics = parseCameraOptics( child );
  1070. break;
  1071. }
  1072. }
  1073. library.cameras[ xml.getAttribute( 'id' ) ] = data;
  1074. }
  1075. function parseCameraOptics( xml ) {
  1076. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1077. const child = xml.childNodes[ i ];
  1078. switch ( child.nodeName ) {
  1079. case 'technique_common':
  1080. return parseCameraTechnique( child );
  1081. }
  1082. }
  1083. return {};
  1084. }
  1085. function parseCameraTechnique( xml ) {
  1086. const data = {};
  1087. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1088. const child = xml.childNodes[ i ];
  1089. switch ( child.nodeName ) {
  1090. case 'perspective':
  1091. case 'orthographic':
  1092. data.technique = child.nodeName;
  1093. data.parameters = parseCameraParameters( child );
  1094. break;
  1095. }
  1096. }
  1097. return data;
  1098. }
  1099. function parseCameraParameters( xml ) {
  1100. const data = {};
  1101. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1102. const child = xml.childNodes[ i ];
  1103. switch ( child.nodeName ) {
  1104. case 'xfov':
  1105. case 'yfov':
  1106. case 'xmag':
  1107. case 'ymag':
  1108. case 'znear':
  1109. case 'zfar':
  1110. case 'aspect_ratio':
  1111. data[ child.nodeName ] = parseFloat( child.textContent );
  1112. break;
  1113. }
  1114. }
  1115. return data;
  1116. }
  1117. function buildCamera( data ) {
  1118. let camera;
  1119. switch ( data.optics.technique ) {
  1120. case 'perspective':
  1121. camera = new PerspectiveCamera(
  1122. data.optics.parameters.yfov,
  1123. data.optics.parameters.aspect_ratio,
  1124. data.optics.parameters.znear,
  1125. data.optics.parameters.zfar
  1126. );
  1127. break;
  1128. case 'orthographic':
  1129. let ymag = data.optics.parameters.ymag;
  1130. let xmag = data.optics.parameters.xmag;
  1131. const aspectRatio = data.optics.parameters.aspect_ratio;
  1132. xmag = ( xmag === undefined ) ? ( ymag * aspectRatio ) : xmag;
  1133. ymag = ( ymag === undefined ) ? ( xmag / aspectRatio ) : ymag;
  1134. xmag *= 0.5;
  1135. ymag *= 0.5;
  1136. camera = new OrthographicCamera(
  1137. - xmag, xmag, ymag, - ymag, // left, right, top, bottom
  1138. data.optics.parameters.znear,
  1139. data.optics.parameters.zfar
  1140. );
  1141. break;
  1142. default:
  1143. camera = new PerspectiveCamera();
  1144. break;
  1145. }
  1146. camera.name = data.name || '';
  1147. return camera;
  1148. }
  1149. function getCamera( id ) {
  1150. const data = library.cameras[ id ];
  1151. if ( data !== undefined ) {
  1152. return getBuild( data, buildCamera );
  1153. }
  1154. console.warn( 'THREE.ColladaLoader: Couldn\'t find camera with ID:', id );
  1155. return null;
  1156. }
  1157. // light
  1158. function parseLight( xml ) {
  1159. let data = {};
  1160. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1161. const child = xml.childNodes[ i ];
  1162. if ( child.nodeType !== 1 ) continue;
  1163. switch ( child.nodeName ) {
  1164. case 'technique_common':
  1165. data = parseLightTechnique( child );
  1166. break;
  1167. }
  1168. }
  1169. library.lights[ xml.getAttribute( 'id' ) ] = data;
  1170. }
  1171. function parseLightTechnique( xml ) {
  1172. const data = {};
  1173. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1174. const child = xml.childNodes[ i ];
  1175. if ( child.nodeType !== 1 ) continue;
  1176. switch ( child.nodeName ) {
  1177. case 'directional':
  1178. case 'point':
  1179. case 'spot':
  1180. case 'ambient':
  1181. data.technique = child.nodeName;
  1182. data.parameters = parseLightParameters( child );
  1183. }
  1184. }
  1185. return data;
  1186. }
  1187. function parseLightParameters( xml ) {
  1188. const data = {};
  1189. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1190. const child = xml.childNodes[ i ];
  1191. if ( child.nodeType !== 1 ) continue;
  1192. switch ( child.nodeName ) {
  1193. case 'color':
  1194. const array = parseFloats( child.textContent );
  1195. data.color = new Color().fromArray( array );
  1196. break;
  1197. case 'falloff_angle':
  1198. data.falloffAngle = parseFloat( child.textContent );
  1199. break;
  1200. case 'quadratic_attenuation':
  1201. const f = parseFloat( child.textContent );
  1202. data.distance = f ? Math.sqrt( 1 / f ) : 0;
  1203. break;
  1204. }
  1205. }
  1206. return data;
  1207. }
  1208. function buildLight( data ) {
  1209. let light;
  1210. switch ( data.technique ) {
  1211. case 'directional':
  1212. light = new DirectionalLight();
  1213. break;
  1214. case 'point':
  1215. light = new PointLight();
  1216. break;
  1217. case 'spot':
  1218. light = new SpotLight();
  1219. break;
  1220. case 'ambient':
  1221. light = new AmbientLight();
  1222. break;
  1223. }
  1224. if ( data.parameters.color ) light.color.copy( data.parameters.color );
  1225. if ( data.parameters.distance ) light.distance = data.parameters.distance;
  1226. return light;
  1227. }
  1228. function getLight( id ) {
  1229. const data = library.lights[ id ];
  1230. if ( data !== undefined ) {
  1231. return getBuild( data, buildLight );
  1232. }
  1233. console.warn( 'THREE.ColladaLoader: Couldn\'t find light with ID:', id );
  1234. return null;
  1235. }
  1236. // geometry
  1237. function parseGeometry( xml ) {
  1238. const data = {
  1239. name: xml.getAttribute( 'name' ),
  1240. sources: {},
  1241. vertices: {},
  1242. primitives: []
  1243. };
  1244. const mesh = getElementsByTagName( xml, 'mesh' )[ 0 ];
  1245. // the following tags inside geometry are not supported yet (see https://github.com/mrdoob/three.js/pull/12606): convex_mesh, spline, brep
  1246. if ( mesh === undefined ) return;
  1247. for ( let i = 0; i < mesh.childNodes.length; i ++ ) {
  1248. const child = mesh.childNodes[ i ];
  1249. if ( child.nodeType !== 1 ) continue;
  1250. const id = child.getAttribute( 'id' );
  1251. switch ( child.nodeName ) {
  1252. case 'source':
  1253. data.sources[ id ] = parseSource( child );
  1254. break;
  1255. case 'vertices':
  1256. // data.sources[ id ] = data.sources[ parseId( getElementsByTagName( child, 'input' )[ 0 ].getAttribute( 'source' ) ) ];
  1257. data.vertices = parseGeometryVertices( child );
  1258. break;
  1259. case 'polygons':
  1260. console.warn( 'THREE.ColladaLoader: Unsupported primitive type: ', child.nodeName );
  1261. break;
  1262. case 'lines':
  1263. case 'linestrips':
  1264. case 'polylist':
  1265. case 'triangles':
  1266. data.primitives.push( parseGeometryPrimitive( child ) );
  1267. break;
  1268. default:
  1269. console.log( child );
  1270. }
  1271. }
  1272. library.geometries[ xml.getAttribute( 'id' ) ] = data;
  1273. }
  1274. function parseSource( xml ) {
  1275. const data = {
  1276. array: [],
  1277. stride: 3
  1278. };
  1279. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1280. const child = xml.childNodes[ i ];
  1281. if ( child.nodeType !== 1 ) continue;
  1282. switch ( child.nodeName ) {
  1283. case 'float_array':
  1284. data.array = parseFloats( child.textContent );
  1285. break;
  1286. case 'Name_array':
  1287. data.array = parseStrings( child.textContent );
  1288. break;
  1289. case 'technique_common':
  1290. const accessor = getElementsByTagName( child, 'accessor' )[ 0 ];
  1291. if ( accessor !== undefined ) {
  1292. data.stride = parseInt( accessor.getAttribute( 'stride' ) );
  1293. }
  1294. break;
  1295. }
  1296. }
  1297. return data;
  1298. }
  1299. function parseGeometryVertices( xml ) {
  1300. const data = {};
  1301. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1302. const child = xml.childNodes[ i ];
  1303. if ( child.nodeType !== 1 ) continue;
  1304. data[ child.getAttribute( 'semantic' ) ] = parseId( child.getAttribute( 'source' ) );
  1305. }
  1306. return data;
  1307. }
  1308. function parseGeometryPrimitive( xml ) {
  1309. const primitive = {
  1310. type: xml.nodeName,
  1311. material: xml.getAttribute( 'material' ),
  1312. count: parseInt( xml.getAttribute( 'count' ) ),
  1313. inputs: {},
  1314. stride: 0,
  1315. hasUV: false
  1316. };
  1317. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1318. const child = xml.childNodes[ i ];
  1319. if ( child.nodeType !== 1 ) continue;
  1320. switch ( child.nodeName ) {
  1321. case 'input':
  1322. const id = parseId( child.getAttribute( 'source' ) );
  1323. const semantic = child.getAttribute( 'semantic' );
  1324. const offset = parseInt( child.getAttribute( 'offset' ) );
  1325. const set = parseInt( child.getAttribute( 'set' ) );
  1326. const inputname = ( set > 0 ? semantic + set : semantic );
  1327. primitive.inputs[ inputname ] = { id: id, offset: offset };
  1328. primitive.stride = Math.max( primitive.stride, offset + 1 );
  1329. if ( semantic === 'TEXCOORD' ) primitive.hasUV = true;
  1330. break;
  1331. case 'vcount':
  1332. primitive.vcount = parseInts( child.textContent );
  1333. break;
  1334. case 'p':
  1335. primitive.p = parseInts( child.textContent );
  1336. break;
  1337. }
  1338. }
  1339. return primitive;
  1340. }
  1341. function groupPrimitives( primitives ) {
  1342. const build = {};
  1343. for ( let i = 0; i < primitives.length; i ++ ) {
  1344. const primitive = primitives[ i ];
  1345. if ( build[ primitive.type ] === undefined ) build[ primitive.type ] = [];
  1346. build[ primitive.type ].push( primitive );
  1347. }
  1348. return build;
  1349. }
  1350. function checkUVCoordinates( primitives ) {
  1351. let count = 0;
  1352. for ( let i = 0, l = primitives.length; i < l; i ++ ) {
  1353. const primitive = primitives[ i ];
  1354. if ( primitive.hasUV === true ) {
  1355. count ++;
  1356. }
  1357. }
  1358. if ( count > 0 && count < primitives.length ) {
  1359. primitives.uvsNeedsFix = true;
  1360. }
  1361. }
  1362. function buildGeometry( data ) {
  1363. const build = {};
  1364. const sources = data.sources;
  1365. const vertices = data.vertices;
  1366. const primitives = data.primitives;
  1367. if ( primitives.length === 0 ) return {};
  1368. // our goal is to create one buffer geometry for a single type of primitives
  1369. // first, we group all primitives by their type
  1370. const groupedPrimitives = groupPrimitives( primitives );
  1371. for ( const type in groupedPrimitives ) {
  1372. const primitiveType = groupedPrimitives[ type ];
  1373. // second, ensure consistent uv coordinates for each type of primitives (polylist,triangles or lines)
  1374. checkUVCoordinates( primitiveType );
  1375. // third, create a buffer geometry for each type of primitives
  1376. build[ type ] = buildGeometryType( primitiveType, sources, vertices );
  1377. }
  1378. return build;
  1379. }
  1380. function buildGeometryType( primitives, sources, vertices ) {
  1381. const build = {};
  1382. const position = { array: [], stride: 0 };
  1383. const normal = { array: [], stride: 0 };
  1384. const uv = { array: [], stride: 0 };
  1385. const uv2 = { array: [], stride: 0 };
  1386. const color = { array: [], stride: 0 };
  1387. const skinIndex = { array: [], stride: 4 };
  1388. const skinWeight = { array: [], stride: 4 };
  1389. const geometry = new BufferGeometry();
  1390. const materialKeys = [];
  1391. let start = 0;
  1392. for ( let p = 0; p < primitives.length; p ++ ) {
  1393. const primitive = primitives[ p ];
  1394. const inputs = primitive.inputs;
  1395. // groups
  1396. let count = 0;
  1397. switch ( primitive.type ) {
  1398. case 'lines':
  1399. case 'linestrips':
  1400. count = primitive.count * 2;
  1401. break;
  1402. case 'triangles':
  1403. count = primitive.count * 3;
  1404. break;
  1405. case 'polylist':
  1406. for ( let g = 0; g < primitive.count; g ++ ) {
  1407. const vc = primitive.vcount[ g ];
  1408. switch ( vc ) {
  1409. case 3:
  1410. count += 3; // single triangle
  1411. break;
  1412. case 4:
  1413. count += 6; // quad, subdivided into two triangles
  1414. break;
  1415. default:
  1416. count += ( vc - 2 ) * 3; // polylist with more than four vertices
  1417. break;
  1418. }
  1419. }
  1420. break;
  1421. default:
  1422. console.warn( 'THREE.ColladaLoader: Unknow primitive type:', primitive.type );
  1423. }
  1424. geometry.addGroup( start, count, p );
  1425. start += count;
  1426. // material
  1427. if ( primitive.material ) {
  1428. materialKeys.push( primitive.material );
  1429. }
  1430. // geometry data
  1431. for ( const name in inputs ) {
  1432. const input = inputs[ name ];
  1433. switch ( name ) {
  1434. case 'VERTEX':
  1435. for ( const key in vertices ) {
  1436. const id = vertices[ key ];
  1437. switch ( key ) {
  1438. case 'POSITION':
  1439. const prevLength = position.array.length;
  1440. buildGeometryData( primitive, sources[ id ], input.offset, position.array );
  1441. position.stride = sources[ id ].stride;
  1442. if ( sources.skinWeights && sources.skinIndices ) {
  1443. buildGeometryData( primitive, sources.skinIndices, input.offset, skinIndex.array );
  1444. buildGeometryData( primitive, sources.skinWeights, input.offset, skinWeight.array );
  1445. }
  1446. // see #3803
  1447. if ( primitive.hasUV === false && primitives.uvsNeedsFix === true ) {
  1448. const count = ( position.array.length - prevLength ) / position.stride;
  1449. for ( let i = 0; i < count; i ++ ) {
  1450. // fill missing uv coordinates
  1451. uv.array.push( 0, 0 );
  1452. }
  1453. }
  1454. break;
  1455. case 'NORMAL':
  1456. buildGeometryData( primitive, sources[ id ], input.offset, normal.array );
  1457. normal.stride = sources[ id ].stride;
  1458. break;
  1459. case 'COLOR':
  1460. buildGeometryData( primitive, sources[ id ], input.offset, color.array );
  1461. color.stride = sources[ id ].stride;
  1462. break;
  1463. case 'TEXCOORD':
  1464. buildGeometryData( primitive, sources[ id ], input.offset, uv.array );
  1465. uv.stride = sources[ id ].stride;
  1466. break;
  1467. case 'TEXCOORD1':
  1468. buildGeometryData( primitive, sources[ id ], input.offset, uv2.array );
  1469. uv.stride = sources[ id ].stride;
  1470. break;
  1471. default:
  1472. console.warn( 'THREE.ColladaLoader: Semantic "%s" not handled in geometry build process.', key );
  1473. }
  1474. }
  1475. break;
  1476. case 'NORMAL':
  1477. buildGeometryData( primitive, sources[ input.id ], input.offset, normal.array );
  1478. normal.stride = sources[ input.id ].stride;
  1479. break;
  1480. case 'COLOR':
  1481. buildGeometryData( primitive, sources[ input.id ], input.offset, color.array );
  1482. color.stride = sources[ input.id ].stride;
  1483. break;
  1484. case 'TEXCOORD':
  1485. buildGeometryData( primitive, sources[ input.id ], input.offset, uv.array );
  1486. uv.stride = sources[ input.id ].stride;
  1487. break;
  1488. case 'TEXCOORD1':
  1489. buildGeometryData( primitive, sources[ input.id ], input.offset, uv2.array );
  1490. uv2.stride = sources[ input.id ].stride;
  1491. break;
  1492. }
  1493. }
  1494. }
  1495. // build geometry
  1496. if ( position.array.length > 0 ) geometry.setAttribute( 'position', new Float32BufferAttribute( position.array, position.stride ) );
  1497. if ( normal.array.length > 0 ) geometry.setAttribute( 'normal', new Float32BufferAttribute( normal.array, normal.stride ) );
  1498. if ( color.array.length > 0 ) geometry.setAttribute( 'color', new Float32BufferAttribute( color.array, color.stride ) );
  1499. if ( uv.array.length > 0 ) geometry.setAttribute( 'uv', new Float32BufferAttribute( uv.array, uv.stride ) );
  1500. if ( uv2.array.length > 0 ) geometry.setAttribute( 'uv2', new Float32BufferAttribute( uv2.array, uv2.stride ) );
  1501. if ( skinIndex.array.length > 0 ) geometry.setAttribute( 'skinIndex', new Float32BufferAttribute( skinIndex.array, skinIndex.stride ) );
  1502. if ( skinWeight.array.length > 0 ) geometry.setAttribute( 'skinWeight', new Float32BufferAttribute( skinWeight.array, skinWeight.stride ) );
  1503. build.data = geometry;
  1504. build.type = primitives[ 0 ].type;
  1505. build.materialKeys = materialKeys;
  1506. return build;
  1507. }
  1508. function buildGeometryData( primitive, source, offset, array ) {
  1509. const indices = primitive.p;
  1510. const stride = primitive.stride;
  1511. const vcount = primitive.vcount;
  1512. function pushVector( i ) {
  1513. let index = indices[ i + offset ] * sourceStride;
  1514. const length = index + sourceStride;
  1515. for ( ; index < length; index ++ ) {
  1516. array.push( sourceArray[ index ] );
  1517. }
  1518. }
  1519. const sourceArray = source.array;
  1520. const sourceStride = source.stride;
  1521. if ( primitive.vcount !== undefined ) {
  1522. let index = 0;
  1523. for ( let i = 0, l = vcount.length; i < l; i ++ ) {
  1524. const count = vcount[ i ];
  1525. if ( count === 4 ) {
  1526. const a = index + stride * 0;
  1527. const b = index + stride * 1;
  1528. const c = index + stride * 2;
  1529. const d = index + stride * 3;
  1530. pushVector( a ); pushVector( b ); pushVector( d );
  1531. pushVector( b ); pushVector( c ); pushVector( d );
  1532. } else if ( count === 3 ) {
  1533. const a = index + stride * 0;
  1534. const b = index + stride * 1;
  1535. const c = index + stride * 2;
  1536. pushVector( a ); pushVector( b ); pushVector( c );
  1537. } else if ( count > 4 ) {
  1538. for ( let k = 1, kl = ( count - 2 ); k <= kl; k ++ ) {
  1539. const a = index + stride * 0;
  1540. const b = index + stride * k;
  1541. const c = index + stride * ( k + 1 );
  1542. pushVector( a ); pushVector( b ); pushVector( c );
  1543. }
  1544. }
  1545. index += stride * count;
  1546. }
  1547. } else {
  1548. for ( let i = 0, l = indices.length; i < l; i += stride ) {
  1549. pushVector( i );
  1550. }
  1551. }
  1552. }
  1553. function getGeometry( id ) {
  1554. return getBuild( library.geometries[ id ], buildGeometry );
  1555. }
  1556. // kinematics
  1557. function parseKinematicsModel( xml ) {
  1558. const data = {
  1559. name: xml.getAttribute( 'name' ) || '',
  1560. joints: {},
  1561. links: []
  1562. };
  1563. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1564. const child = xml.childNodes[ i ];
  1565. if ( child.nodeType !== 1 ) continue;
  1566. switch ( child.nodeName ) {
  1567. case 'technique_common':
  1568. parseKinematicsTechniqueCommon( child, data );
  1569. break;
  1570. }
  1571. }
  1572. library.kinematicsModels[ xml.getAttribute( 'id' ) ] = data;
  1573. }
  1574. function buildKinematicsModel( data ) {
  1575. if ( data.build !== undefined ) return data.build;
  1576. return data;
  1577. }
  1578. function getKinematicsModel( id ) {
  1579. return getBuild( library.kinematicsModels[ id ], buildKinematicsModel );
  1580. }
  1581. function parseKinematicsTechniqueCommon( xml, data ) {
  1582. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1583. const child = xml.childNodes[ i ];
  1584. if ( child.nodeType !== 1 ) continue;
  1585. switch ( child.nodeName ) {
  1586. case 'joint':
  1587. data.joints[ child.getAttribute( 'sid' ) ] = parseKinematicsJoint( child );
  1588. break;
  1589. case 'link':
  1590. data.links.push( parseKinematicsLink( child ) );
  1591. break;
  1592. }
  1593. }
  1594. }
  1595. function parseKinematicsJoint( xml ) {
  1596. let data;
  1597. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1598. const child = xml.childNodes[ i ];
  1599. if ( child.nodeType !== 1 ) continue;
  1600. switch ( child.nodeName ) {
  1601. case 'prismatic':
  1602. case 'revolute':
  1603. data = parseKinematicsJointParameter( child );
  1604. break;
  1605. }
  1606. }
  1607. return data;
  1608. }
  1609. function parseKinematicsJointParameter( xml ) {
  1610. const data = {
  1611. sid: xml.getAttribute( 'sid' ),
  1612. name: xml.getAttribute( 'name' ) || '',
  1613. axis: new Vector3(),
  1614. limits: {
  1615. min: 0,
  1616. max: 0
  1617. },
  1618. type: xml.nodeName,
  1619. static: false,
  1620. zeroPosition: 0,
  1621. middlePosition: 0
  1622. };
  1623. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1624. const child = xml.childNodes[ i ];
  1625. if ( child.nodeType !== 1 ) continue;
  1626. switch ( child.nodeName ) {
  1627. case 'axis':
  1628. const array = parseFloats( child.textContent );
  1629. data.axis.fromArray( array );
  1630. break;
  1631. case 'limits':
  1632. const max = child.getElementsByTagName( 'max' )[ 0 ];
  1633. const min = child.getElementsByTagName( 'min' )[ 0 ];
  1634. data.limits.max = parseFloat( max.textContent );
  1635. data.limits.min = parseFloat( min.textContent );
  1636. break;
  1637. }
  1638. }
  1639. // if min is equal to or greater than max, consider the joint static
  1640. if ( data.limits.min >= data.limits.max ) {
  1641. data.static = true;
  1642. }
  1643. // calculate middle position
  1644. data.middlePosition = ( data.limits.min + data.limits.max ) / 2.0;
  1645. return data;
  1646. }
  1647. function parseKinematicsLink( xml ) {
  1648. const data = {
  1649. sid: xml.getAttribute( 'sid' ),
  1650. name: xml.getAttribute( 'name' ) || '',
  1651. attachments: [],
  1652. transforms: []
  1653. };
  1654. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1655. const child = xml.childNodes[ i ];
  1656. if ( child.nodeType !== 1 ) continue;
  1657. switch ( child.nodeName ) {
  1658. case 'attachment_full':
  1659. data.attachments.push( parseKinematicsAttachment( child ) );
  1660. break;
  1661. case 'matrix':
  1662. case 'translate':
  1663. case 'rotate':
  1664. data.transforms.push( parseKinematicsTransform( child ) );
  1665. break;
  1666. }
  1667. }
  1668. return data;
  1669. }
  1670. function parseKinematicsAttachment( xml ) {
  1671. const data = {
  1672. joint: xml.getAttribute( 'joint' ).split( '/' ).pop(),
  1673. transforms: [],
  1674. links: []
  1675. };
  1676. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1677. const child = xml.childNodes[ i ];
  1678. if ( child.nodeType !== 1 ) continue;
  1679. switch ( child.nodeName ) {
  1680. case 'link':
  1681. data.links.push( parseKinematicsLink( child ) );
  1682. break;
  1683. case 'matrix':
  1684. case 'translate':
  1685. case 'rotate':
  1686. data.transforms.push( parseKinematicsTransform( child ) );
  1687. break;
  1688. }
  1689. }
  1690. return data;
  1691. }
  1692. function parseKinematicsTransform( xml ) {
  1693. const data = {
  1694. type: xml.nodeName
  1695. };
  1696. const array = parseFloats( xml.textContent );
  1697. switch ( data.type ) {
  1698. case 'matrix':
  1699. data.obj = new Matrix4();
  1700. data.obj.fromArray( array ).transpose();
  1701. break;
  1702. case 'translate':
  1703. data.obj = new Vector3();
  1704. data.obj.fromArray( array );
  1705. break;
  1706. case 'rotate':
  1707. data.obj = new Vector3();
  1708. data.obj.fromArray( array );
  1709. data.angle = MathUtils.degToRad( array[ 3 ] );
  1710. break;
  1711. }
  1712. return data;
  1713. }
  1714. // physics
  1715. function parsePhysicsModel( xml ) {
  1716. const data = {
  1717. name: xml.getAttribute( 'name' ) || '',
  1718. rigidBodies: {}
  1719. };
  1720. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1721. const child = xml.childNodes[ i ];
  1722. if ( child.nodeType !== 1 ) continue;
  1723. switch ( child.nodeName ) {
  1724. case 'rigid_body':
  1725. data.rigidBodies[ child.getAttribute( 'name' ) ] = {};
  1726. parsePhysicsRigidBody( child, data.rigidBodies[ child.getAttribute( 'name' ) ] );
  1727. break;
  1728. }
  1729. }
  1730. library.physicsModels[ xml.getAttribute( 'id' ) ] = data;
  1731. }
  1732. function parsePhysicsRigidBody( xml, data ) {
  1733. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1734. const child = xml.childNodes[ i ];
  1735. if ( child.nodeType !== 1 ) continue;
  1736. switch ( child.nodeName ) {
  1737. case 'technique_common':
  1738. parsePhysicsTechniqueCommon( child, data );
  1739. break;
  1740. }
  1741. }
  1742. }
  1743. function parsePhysicsTechniqueCommon( xml, data ) {
  1744. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1745. const child = xml.childNodes[ i ];
  1746. if ( child.nodeType !== 1 ) continue;
  1747. switch ( child.nodeName ) {
  1748. case 'inertia':
  1749. data.inertia = parseFloats( child.textContent );
  1750. break;
  1751. case 'mass':
  1752. data.mass = parseFloats( child.textContent )[ 0 ];
  1753. break;
  1754. }
  1755. }
  1756. }
  1757. // scene
  1758. function parseKinematicsScene( xml ) {
  1759. const data = {
  1760. bindJointAxis: []
  1761. };
  1762. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1763. const child = xml.childNodes[ i ];
  1764. if ( child.nodeType !== 1 ) continue;
  1765. switch ( child.nodeName ) {
  1766. case 'bind_joint_axis':
  1767. data.bindJointAxis.push( parseKinematicsBindJointAxis( child ) );
  1768. break;
  1769. }
  1770. }
  1771. library.kinematicsScenes[ parseId( xml.getAttribute( 'url' ) ) ] = data;
  1772. }
  1773. function parseKinematicsBindJointAxis( xml ) {
  1774. const data = {
  1775. target: xml.getAttribute( 'target' ).split( '/' ).pop()
  1776. };
  1777. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1778. const child = xml.childNodes[ i ];
  1779. if ( child.nodeType !== 1 ) continue;
  1780. switch ( child.nodeName ) {
  1781. case 'axis':
  1782. const param = child.getElementsByTagName( 'param' )[ 0 ];
  1783. data.axis = param.textContent;
  1784. const tmpJointIndex = data.axis.split( 'inst_' ).pop().split( 'axis' )[ 0 ];
  1785. data.jointIndex = tmpJointIndex.substr( 0, tmpJointIndex.length - 1 );
  1786. break;
  1787. }
  1788. }
  1789. return data;
  1790. }
  1791. function buildKinematicsScene( data ) {
  1792. if ( data.build !== undefined ) return data.build;
  1793. return data;
  1794. }
  1795. function getKinematicsScene( id ) {
  1796. return getBuild( library.kinematicsScenes[ id ], buildKinematicsScene );
  1797. }
  1798. function setupKinematics() {
  1799. const kinematicsModelId = Object.keys( library.kinematicsModels )[ 0 ];
  1800. const kinematicsSceneId = Object.keys( library.kinematicsScenes )[ 0 ];
  1801. const visualSceneId = Object.keys( library.visualScenes )[ 0 ];
  1802. if ( kinematicsModelId === undefined || kinematicsSceneId === undefined ) return;
  1803. const kinematicsModel = getKinematicsModel( kinematicsModelId );
  1804. const kinematicsScene = getKinematicsScene( kinematicsSceneId );
  1805. const visualScene = getVisualScene( visualSceneId );
  1806. const bindJointAxis = kinematicsScene.bindJointAxis;
  1807. const jointMap = {};
  1808. for ( let i = 0, l = bindJointAxis.length; i < l; i ++ ) {
  1809. const axis = bindJointAxis[ i ];
  1810. // the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix'
  1811. const targetElement = collada.querySelector( '[sid="' + axis.target + '"]' );
  1812. if ( targetElement ) {
  1813. // get the parent of the transform element
  1814. const parentVisualElement = targetElement.parentElement;
  1815. // connect the joint of the kinematics model with the element in the visual scene
  1816. connect( axis.jointIndex, parentVisualElement );
  1817. }
  1818. }
  1819. function connect( jointIndex, visualElement ) {
  1820. const visualElementName = visualElement.getAttribute( 'name' );
  1821. const joint = kinematicsModel.joints[ jointIndex ];
  1822. visualScene.traverse( function ( object ) {
  1823. if ( object.name === visualElementName ) {
  1824. jointMap[ jointIndex ] = {
  1825. object: object,
  1826. transforms: buildTransformList( visualElement ),
  1827. joint: joint,
  1828. position: joint.zeroPosition
  1829. };
  1830. }
  1831. } );
  1832. }
  1833. const m0 = new Matrix4();
  1834. kinematics = {
  1835. joints: kinematicsModel && kinematicsModel.joints,
  1836. getJointValue: function ( jointIndex ) {
  1837. const jointData = jointMap[ jointIndex ];
  1838. if ( jointData ) {
  1839. return jointData.position;
  1840. } else {
  1841. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' doesn\'t exist.' );
  1842. }
  1843. },
  1844. setJointValue: function ( jointIndex, value ) {
  1845. const jointData = jointMap[ jointIndex ];
  1846. if ( jointData ) {
  1847. const joint = jointData.joint;
  1848. if ( value > joint.limits.max || value < joint.limits.min ) {
  1849. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ').' );
  1850. } else if ( joint.static ) {
  1851. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' is static.' );
  1852. } else {
  1853. const object = jointData.object;
  1854. const axis = joint.axis;
  1855. const transforms = jointData.transforms;
  1856. matrix.identity();
  1857. // each update, we have to apply all transforms in the correct order
  1858. for ( let i = 0; i < transforms.length; i ++ ) {
  1859. const transform = transforms[ i ];
  1860. // if there is a connection of the transform node with a joint, apply the joint value
  1861. if ( transform.sid && transform.sid.indexOf( jointIndex ) !== - 1 ) {
  1862. switch ( joint.type ) {
  1863. case 'revolute':
  1864. matrix.multiply( m0.makeRotationAxis( axis, MathUtils.degToRad( value ) ) );
  1865. break;
  1866. case 'prismatic':
  1867. matrix.multiply( m0.makeTranslation( axis.x * value, axis.y * value, axis.z * value ) );
  1868. break;
  1869. default:
  1870. console.warn( 'THREE.ColladaLoader: Unknown joint type: ' + joint.type );
  1871. break;
  1872. }
  1873. } else {
  1874. switch ( transform.type ) {
  1875. case 'matrix':
  1876. matrix.multiply( transform.obj );
  1877. break;
  1878. case 'translate':
  1879. matrix.multiply( m0.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
  1880. break;
  1881. case 'scale':
  1882. matrix.scale( transform.obj );
  1883. break;
  1884. case 'rotate':
  1885. matrix.multiply( m0.makeRotationAxis( transform.obj, transform.angle ) );
  1886. break;
  1887. }
  1888. }
  1889. }
  1890. object.matrix.copy( matrix );
  1891. object.matrix.decompose( object.position, object.quaternion, object.scale );
  1892. jointMap[ jointIndex ].position = value;
  1893. }
  1894. } else {
  1895. console.log( 'THREE.ColladaLoader: ' + jointIndex + ' does not exist.' );
  1896. }
  1897. }
  1898. };
  1899. }
  1900. function buildTransformList( node ) {
  1901. const transforms = [];
  1902. const xml = collada.querySelector( '[id="' + node.id + '"]' );
  1903. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1904. const child = xml.childNodes[ i ];
  1905. if ( child.nodeType !== 1 ) continue;
  1906. let array, vector;
  1907. switch ( child.nodeName ) {
  1908. case 'matrix':
  1909. array = parseFloats( child.textContent );
  1910. const matrix = new Matrix4().fromArray( array ).transpose();
  1911. transforms.push( {
  1912. sid: child.getAttribute( 'sid' ),
  1913. type: child.nodeName,
  1914. obj: matrix
  1915. } );
  1916. break;
  1917. case 'translate':
  1918. case 'scale':
  1919. array = parseFloats( child.textContent );
  1920. vector = new Vector3().fromArray( array );
  1921. transforms.push( {
  1922. sid: child.getAttribute( 'sid' ),
  1923. type: child.nodeName,
  1924. obj: vector
  1925. } );
  1926. break;
  1927. case 'rotate':
  1928. array = parseFloats( child.textContent );
  1929. vector = new Vector3().fromArray( array );
  1930. const angle = MathUtils.degToRad( array[ 3 ] );
  1931. transforms.push( {
  1932. sid: child.getAttribute( 'sid' ),
  1933. type: child.nodeName,
  1934. obj: vector,
  1935. angle: angle
  1936. } );
  1937. break;
  1938. }
  1939. }
  1940. return transforms;
  1941. }
  1942. // nodes
  1943. function prepareNodes( xml ) {
  1944. const elements = xml.getElementsByTagName( 'node' );
  1945. // ensure all node elements have id attributes
  1946. for ( let i = 0; i < elements.length; i ++ ) {
  1947. const element = elements[ i ];
  1948. if ( element.hasAttribute( 'id' ) === false ) {
  1949. element.setAttribute( 'id', generateId() );
  1950. }
  1951. }
  1952. }
  1953. const matrix = new Matrix4();
  1954. const vector = new Vector3();
  1955. function parseNode( xml ) {
  1956. const data = {
  1957. name: xml.getAttribute( 'name' ) || '',
  1958. type: xml.getAttribute( 'type' ),
  1959. id: xml.getAttribute( 'id' ),
  1960. sid: xml.getAttribute( 'sid' ),
  1961. matrix: new Matrix4(),
  1962. nodes: [],
  1963. instanceCameras: [],
  1964. instanceControllers: [],
  1965. instanceLights: [],
  1966. instanceGeometries: [],
  1967. instanceNodes: [],
  1968. transforms: {}
  1969. };
  1970. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1971. const child = xml.childNodes[ i ];
  1972. if ( child.nodeType !== 1 ) continue;
  1973. let array;
  1974. switch ( child.nodeName ) {
  1975. case 'node':
  1976. data.nodes.push( child.getAttribute( 'id' ) );
  1977. parseNode( child );
  1978. break;
  1979. case 'instance_camera':
  1980. data.instanceCameras.push( parseId( child.getAttribute( 'url' ) ) );
  1981. break;
  1982. case 'instance_controller':
  1983. data.instanceControllers.push( parseNodeInstance( child ) );
  1984. break;
  1985. case 'instance_light':
  1986. data.instanceLights.push( parseId( child.getAttribute( 'url' ) ) );
  1987. break;
  1988. case 'instance_geometry':
  1989. data.instanceGeometries.push( parseNodeInstance( child ) );
  1990. break;
  1991. case 'instance_node':
  1992. data.instanceNodes.push( parseId( child.getAttribute( 'url' ) ) );
  1993. break;
  1994. case 'matrix':
  1995. array = parseFloats( child.textContent );
  1996. data.matrix.multiply( matrix.fromArray( array ).transpose() );
  1997. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  1998. break;
  1999. case 'translate':
  2000. array = parseFloats( child.textContent );
  2001. vector.fromArray( array );
  2002. data.matrix.multiply( matrix.makeTranslation( vector.x, vector.y, vector.z ) );
  2003. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  2004. break;
  2005. case 'rotate':
  2006. array = parseFloats( child.textContent );
  2007. const angle = MathUtils.degToRad( array[ 3 ] );
  2008. data.matrix.multiply( matrix.makeRotationAxis( vector.fromArray( array ), angle ) );
  2009. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  2010. break;
  2011. case 'scale':
  2012. array = parseFloats( child.textContent );
  2013. data.matrix.scale( vector.fromArray( array ) );
  2014. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  2015. break;
  2016. case 'extra':
  2017. break;
  2018. default:
  2019. console.log( child );
  2020. }
  2021. }
  2022. if ( hasNode( data.id ) ) {
  2023. console.warn( 'THREE.ColladaLoader: There is already a node with ID %s. Exclude current node from further processing.', data.id );
  2024. } else {
  2025. library.nodes[ data.id ] = data;
  2026. }
  2027. return data;
  2028. }
  2029. function parseNodeInstance( xml ) {
  2030. const data = {
  2031. id: parseId( xml.getAttribute( 'url' ) ),
  2032. materials: {},
  2033. skeletons: []
  2034. };
  2035. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  2036. const child = xml.childNodes[ i ];
  2037. switch ( child.nodeName ) {
  2038. case 'bind_material':
  2039. const instances = child.getElementsByTagName( 'instance_material' );
  2040. for ( let j = 0; j < instances.length; j ++ ) {
  2041. const instance = instances[ j ];
  2042. const symbol = instance.getAttribute( 'symbol' );
  2043. const target = instance.getAttribute( 'target' );
  2044. data.materials[ symbol ] = parseId( target );
  2045. }
  2046. break;
  2047. case 'skeleton':
  2048. data.skeletons.push( parseId( child.textContent ) );
  2049. break;
  2050. default:
  2051. break;
  2052. }
  2053. }
  2054. return data;
  2055. }
  2056. function buildSkeleton( skeletons, joints ) {
  2057. const boneData = [];
  2058. const sortedBoneData = [];
  2059. let i, j, data;
  2060. // a skeleton can have multiple root bones. collada expresses this
  2061. // situtation with multiple "skeleton" tags per controller instance
  2062. for ( i = 0; i < skeletons.length; i ++ ) {
  2063. const skeleton = skeletons[ i ];
  2064. let root;
  2065. if ( hasNode( skeleton ) ) {
  2066. root = getNode( skeleton );
  2067. buildBoneHierarchy( root, joints, boneData );
  2068. } else if ( hasVisualScene( skeleton ) ) {
  2069. // handle case where the skeleton refers to the visual scene (#13335)
  2070. const visualScene = library.visualScenes[ skeleton ];
  2071. const children = visualScene.children;
  2072. for ( let j = 0; j < children.length; j ++ ) {
  2073. const child = children[ j ];
  2074. if ( child.type === 'JOINT' ) {
  2075. const root = getNode( child.id );
  2076. buildBoneHierarchy( root, joints, boneData );
  2077. }
  2078. }
  2079. } else {
  2080. console.error( 'THREE.ColladaLoader: Unable to find root bone of skeleton with ID:', skeleton );
  2081. }
  2082. }
  2083. // sort bone data (the order is defined in the corresponding controller)
  2084. for ( i = 0; i < joints.length; i ++ ) {
  2085. for ( j = 0; j < boneData.length; j ++ ) {
  2086. data = boneData[ j ];
  2087. if ( data.bone.name === joints[ i ].name ) {
  2088. sortedBoneData[ i ] = data;
  2089. data.processed = true;
  2090. break;
  2091. }
  2092. }
  2093. }
  2094. // add unprocessed bone data at the end of the list
  2095. for ( i = 0; i < boneData.length; i ++ ) {
  2096. data = boneData[ i ];
  2097. if ( data.processed === false ) {
  2098. sortedBoneData.push( data );
  2099. data.processed = true;
  2100. }
  2101. }
  2102. // setup arrays for skeleton creation
  2103. const bones = [];
  2104. const boneInverses = [];
  2105. for ( i = 0; i < sortedBoneData.length; i ++ ) {
  2106. data = sortedBoneData[ i ];
  2107. bones.push( data.bone );
  2108. boneInverses.push( data.boneInverse );
  2109. }
  2110. return new Skeleton( bones, boneInverses );
  2111. }
  2112. function buildBoneHierarchy( root, joints, boneData ) {
  2113. // setup bone data from visual scene
  2114. root.traverse( function ( object ) {
  2115. if ( object.isBone === true ) {
  2116. let boneInverse;
  2117. // retrieve the boneInverse from the controller data
  2118. for ( let i = 0; i < joints.length; i ++ ) {
  2119. const joint = joints[ i ];
  2120. if ( joint.name === object.name ) {
  2121. boneInverse = joint.boneInverse;
  2122. break;
  2123. }
  2124. }
  2125. if ( boneInverse === undefined ) {
  2126. // Unfortunately, there can be joints in the visual scene that are not part of the
  2127. // corresponding controller. In this case, we have to create a dummy boneInverse matrix
  2128. // for the respective bone. This bone won't affect any vertices, because there are no skin indices
  2129. // and weights defined for it. But we still have to add the bone to the sorted bone list in order to
  2130. // ensure a correct animation of the model.
  2131. boneInverse = new Matrix4();
  2132. }
  2133. boneData.push( { bone: object, boneInverse: boneInverse, processed: false } );
  2134. }
  2135. } );
  2136. }
  2137. function buildNode( data ) {
  2138. const objects = [];
  2139. const matrix = data.matrix;
  2140. const nodes = data.nodes;
  2141. const type = data.type;
  2142. const instanceCameras = data.instanceCameras;
  2143. const instanceControllers = data.instanceControllers;
  2144. const instanceLights = data.instanceLights;
  2145. const instanceGeometries = data.instanceGeometries;
  2146. const instanceNodes = data.instanceNodes;
  2147. // nodes
  2148. for ( let i = 0, l = nodes.length; i < l; i ++ ) {
  2149. objects.push( getNode( nodes[ i ] ) );
  2150. }
  2151. // instance cameras
  2152. for ( let i = 0, l = instanceCameras.length; i < l; i ++ ) {
  2153. const instanceCamera = getCamera( instanceCameras[ i ] );
  2154. if ( instanceCamera !== null ) {
  2155. objects.push( instanceCamera.clone() );
  2156. }
  2157. }
  2158. // instance controllers
  2159. for ( let i = 0, l = instanceControllers.length; i < l; i ++ ) {
  2160. const instance = instanceControllers[ i ];
  2161. const controller = getController( instance.id );
  2162. const geometries = getGeometry( controller.id );
  2163. const newObjects = buildObjects( geometries, instance.materials );
  2164. const skeletons = instance.skeletons;
  2165. const joints = controller.skin.joints;
  2166. const skeleton = buildSkeleton( skeletons, joints );
  2167. for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) {
  2168. const object = newObjects[ j ];
  2169. if ( object.isSkinnedMesh ) {
  2170. object.bind( skeleton, controller.skin.bindMatrix );
  2171. object.normalizeSkinWeights();
  2172. }
  2173. objects.push( object );
  2174. }
  2175. }
  2176. // instance lights
  2177. for ( let i = 0, l = instanceLights.length; i < l; i ++ ) {
  2178. const instanceLight = getLight( instanceLights[ i ] );
  2179. if ( instanceLight !== null ) {
  2180. objects.push( instanceLight.clone() );
  2181. }
  2182. }
  2183. // instance geometries
  2184. for ( let i = 0, l = instanceGeometries.length; i < l; i ++ ) {
  2185. const instance = instanceGeometries[ i ];
  2186. // a single geometry instance in collada can lead to multiple object3Ds.
  2187. // this is the case when primitives are combined like triangles and lines
  2188. const geometries = getGeometry( instance.id );
  2189. const newObjects = buildObjects( geometries, instance.materials );
  2190. for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) {
  2191. objects.push( newObjects[ j ] );
  2192. }
  2193. }
  2194. // instance nodes
  2195. for ( let i = 0, l = instanceNodes.length; i < l; i ++ ) {
  2196. objects.push( getNode( instanceNodes[ i ] ).clone() );
  2197. }
  2198. let object;
  2199. if ( nodes.length === 0 && objects.length === 1 ) {
  2200. object = objects[ 0 ];
  2201. } else {
  2202. object = ( type === 'JOINT' ) ? new Bone() : new Group();
  2203. for ( let i = 0; i < objects.length; i ++ ) {
  2204. object.add( objects[ i ] );
  2205. }
  2206. }
  2207. object.name = ( type === 'JOINT' ) ? data.sid : data.name;
  2208. object.matrix.copy( matrix );
  2209. object.matrix.decompose( object.position, object.quaternion, object.scale );
  2210. return object;
  2211. }
  2212. const fallbackMaterial = new MeshBasicMaterial( { color: 0xff00ff } );
  2213. function resolveMaterialBinding( keys, instanceMaterials ) {
  2214. const materials = [];
  2215. for ( let i = 0, l = keys.length; i < l; i ++ ) {
  2216. const id = instanceMaterials[ keys[ i ] ];
  2217. if ( id === undefined ) {
  2218. console.warn( 'THREE.ColladaLoader: Material with key %s not found. Apply fallback material.', keys[ i ] );
  2219. materials.push( fallbackMaterial );
  2220. } else {
  2221. materials.push( getMaterial( id ) );
  2222. }
  2223. }
  2224. return materials;
  2225. }
  2226. function buildObjects( geometries, instanceMaterials ) {
  2227. const objects = [];
  2228. for ( const type in geometries ) {
  2229. const geometry = geometries[ type ];
  2230. const materials = resolveMaterialBinding( geometry.materialKeys, instanceMaterials );
  2231. // handle case if no materials are defined
  2232. if ( materials.length === 0 ) {
  2233. if ( type === 'lines' || type === 'linestrips' ) {
  2234. materials.push( new LineBasicMaterial() );
  2235. } else {
  2236. materials.push( new MeshPhongMaterial() );
  2237. }
  2238. }
  2239. // regard skinning
  2240. const skinning = ( geometry.data.attributes.skinIndex !== undefined );
  2241. // choose between a single or multi materials (material array)
  2242. const material = ( materials.length === 1 ) ? materials[ 0 ] : materials;
  2243. // now create a specific 3D object
  2244. let object;
  2245. switch ( type ) {
  2246. case 'lines':
  2247. object = new LineSegments( geometry.data, material );
  2248. break;
  2249. case 'linestrips':
  2250. object = new Line( geometry.data, material );
  2251. break;
  2252. case 'triangles':
  2253. case 'polylist':
  2254. if ( skinning ) {
  2255. object = new SkinnedMesh( geometry.data, material );
  2256. } else {
  2257. object = new Mesh( geometry.data, material );
  2258. }
  2259. break;
  2260. }
  2261. objects.push( object );
  2262. }
  2263. return objects;
  2264. }
  2265. function hasNode( id ) {
  2266. return library.nodes[ id ] !== undefined;
  2267. }
  2268. function getNode( id ) {
  2269. return getBuild( library.nodes[ id ], buildNode );
  2270. }
  2271. // visual scenes
  2272. function parseVisualScene( xml ) {
  2273. const data = {
  2274. name: xml.getAttribute( 'name' ),
  2275. children: []
  2276. };
  2277. prepareNodes( xml );
  2278. const elements = getElementsByTagName( xml, 'node' );
  2279. for ( let i = 0; i < elements.length; i ++ ) {
  2280. data.children.push( parseNode( elements[ i ] ) );
  2281. }
  2282. library.visualScenes[ xml.getAttribute( 'id' ) ] = data;
  2283. }
  2284. function buildVisualScene( data ) {
  2285. const group = new Group();
  2286. group.name = data.name;
  2287. const children = data.children;
  2288. for ( let i = 0; i < children.length; i ++ ) {
  2289. const child = children[ i ];
  2290. group.add( getNode( child.id ) );
  2291. }
  2292. return group;
  2293. }
  2294. function hasVisualScene( id ) {
  2295. return library.visualScenes[ id ] !== undefined;
  2296. }
  2297. function getVisualScene( id ) {
  2298. return getBuild( library.visualScenes[ id ], buildVisualScene );
  2299. }
  2300. // scenes
  2301. function parseScene( xml ) {
  2302. const instance = getElementsByTagName( xml, 'instance_visual_scene' )[ 0 ];
  2303. return getVisualScene( parseId( instance.getAttribute( 'url' ) ) );
  2304. }
  2305. function setupAnimations() {
  2306. const clips = library.clips;
  2307. if ( isEmpty( clips ) === true ) {
  2308. if ( isEmpty( library.animations ) === false ) {
  2309. // if there are animations but no clips, we create a default clip for playback
  2310. const tracks = [];
  2311. for ( const id in library.animations ) {
  2312. const animationTracks = getAnimation( id );
  2313. for ( let i = 0, l = animationTracks.length; i < l; i ++ ) {
  2314. tracks.push( animationTracks[ i ] );
  2315. }
  2316. }
  2317. animations.push( new AnimationClip( 'default', - 1, tracks ) );
  2318. }
  2319. } else {
  2320. for ( const id in clips ) {
  2321. animations.push( getAnimationClip( id ) );
  2322. }
  2323. }
  2324. }
  2325. // convert the parser error element into text with each child elements text
  2326. // separated by new lines.
  2327. function parserErrorToText( parserError ) {
  2328. let result = '';
  2329. const stack = [ parserError ];
  2330. while ( stack.length ) {
  2331. const node = stack.shift();
  2332. if ( node.nodeType === Node.TEXT_NODE ) {
  2333. result += node.textContent;
  2334. } else {
  2335. result += '\n';
  2336. stack.push.apply( stack, node.childNodes );
  2337. }
  2338. }
  2339. return result.trim();
  2340. }
  2341. if ( text.length === 0 ) {
  2342. return { scene: new Scene() };
  2343. }
  2344. const xml = new DOMParser().parseFromString( text, 'application/xml' );
  2345. const collada = getElementsByTagName( xml, 'COLLADA' )[ 0 ];
  2346. const parserError = xml.getElementsByTagName( 'parsererror' )[ 0 ];
  2347. if ( parserError !== undefined ) {
  2348. // Chrome will return parser error with a div in it
  2349. const errorElement = getElementsByTagName( parserError, 'div' )[ 0 ];
  2350. let errorText;
  2351. if ( errorElement ) {
  2352. errorText = errorElement.textContent;
  2353. } else {
  2354. errorText = parserErrorToText( parserError );
  2355. }
  2356. console.error( 'THREE.ColladaLoader: Failed to parse collada file.\n', errorText );
  2357. return null;
  2358. }
  2359. // metadata
  2360. const version = collada.getAttribute( 'version' );
  2361. console.log( 'THREE.ColladaLoader: File version', version );
  2362. const asset = parseAsset( getElementsByTagName( collada, 'asset' )[ 0 ] );
  2363. const textureLoader = new TextureLoader( this.manager );
  2364. textureLoader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
  2365. let tgaLoader;
  2366. if ( TGALoader ) {
  2367. tgaLoader = new TGALoader( this.manager );
  2368. tgaLoader.setPath( this.resourcePath || path );
  2369. }
  2370. //
  2371. const animations = [];
  2372. let kinematics = {};
  2373. let count = 0;
  2374. //
  2375. const library = {
  2376. animations: {},
  2377. clips: {},
  2378. controllers: {},
  2379. images: {},
  2380. effects: {},
  2381. materials: {},
  2382. cameras: {},
  2383. lights: {},
  2384. geometries: {},
  2385. nodes: {},
  2386. visualScenes: {},
  2387. kinematicsModels: {},
  2388. physicsModels: {},
  2389. kinematicsScenes: {}
  2390. };
  2391. parseLibrary( collada, 'library_animations', 'animation', parseAnimation );
  2392. parseLibrary( collada, 'library_animation_clips', 'animation_clip', parseAnimationClip );
  2393. parseLibrary( collada, 'library_controllers', 'controller', parseController );
  2394. parseLibrary( collada, 'library_images', 'image', parseImage );
  2395. parseLibrary( collada, 'library_effects', 'effect', parseEffect );
  2396. parseLibrary( collada, 'library_materials', 'material', parseMaterial );
  2397. parseLibrary( collada, 'library_cameras', 'camera', parseCamera );
  2398. parseLibrary( collada, 'library_lights', 'light', parseLight );
  2399. parseLibrary( collada, 'library_geometries', 'geometry', parseGeometry );
  2400. parseLibrary( collada, 'library_nodes', 'node', parseNode );
  2401. parseLibrary( collada, 'library_visual_scenes', 'visual_scene', parseVisualScene );
  2402. parseLibrary( collada, 'library_kinematics_models', 'kinematics_model', parseKinematicsModel );
  2403. parseLibrary( collada, 'library_physics_models', 'physics_model', parsePhysicsModel );
  2404. parseLibrary( collada, 'scene', 'instance_kinematics_scene', parseKinematicsScene );
  2405. buildLibrary( library.animations, buildAnimation );
  2406. buildLibrary( library.clips, buildAnimationClip );
  2407. buildLibrary( library.controllers, buildController );
  2408. buildLibrary( library.images, buildImage );
  2409. buildLibrary( library.effects, buildEffect );
  2410. buildLibrary( library.materials, buildMaterial );
  2411. buildLibrary( library.cameras, buildCamera );
  2412. buildLibrary( library.lights, buildLight );
  2413. buildLibrary( library.geometries, buildGeometry );
  2414. buildLibrary( library.visualScenes, buildVisualScene );
  2415. setupAnimations();
  2416. setupKinematics();
  2417. const scene = parseScene( getElementsByTagName( collada, 'scene' )[ 0 ] );
  2418. scene.animations = animations;
  2419. if ( asset.upAxis === 'Z_UP' ) {
  2420. scene.quaternion.setFromEuler( new Euler( - Math.PI / 2, 0, 0 ) );
  2421. }
  2422. scene.scale.multiplyScalar( asset.unit );
  2423. return {
  2424. get animations() {
  2425. console.warn( 'THREE.ColladaLoader: Please access animations over scene.animations now.' );
  2426. return animations;
  2427. },
  2428. kinematics: kinematics,
  2429. library: library,
  2430. scene: scene
  2431. };
  2432. }
  2433. }
  2434. export { ColladaLoader };