ColladaLoader.js 79 KB

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