2
0

export_dae.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  1. # ##### BEGIN GPL LICENSE BLOCK #####
  2. #
  3. # This program is free software; you can redistribute it and/or
  4. # modify it under the terms of the GNU General Public License
  5. # as published by the Free Software Foundation; either version 2
  6. # of the License, or (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with this program; if not, write to the Free Software Foundation,
  15. # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  16. #
  17. # ##### END GPL LICENSE BLOCK #####
  18. # <pep8 compliant>
  19. # Script copyright (C) Juan Linietsky
  20. # Contact Info: [email protected]
  21. """
  22. This script is an exporter to the Khronos Collada file format.
  23. http://www.khronos.org/collada/
  24. """
  25. # TODO:
  26. # Materials & Textures
  27. # Optionally export Vertex Colors
  28. # Morph Targets
  29. # Control bone removal
  30. # Copy textures
  31. # Export Keyframe Optimization
  32. # --
  33. # Morph Targets
  34. # Blender native material? (?)
  35. import os
  36. import time
  37. import math # math.pi
  38. import shutil
  39. import bpy
  40. from mathutils import Vector, Matrix
  41. #according to collada spec, order matters
  42. S_ASSET=0
  43. S_IMGS=1
  44. S_FX=2
  45. S_MATS=3
  46. S_GEOM=4
  47. S_CONT=5
  48. S_CAMS=6
  49. S_LAMPS=7
  50. S_ANIM_CLIPS=8
  51. S_NODES=9
  52. S_ANIM=10
  53. CMP_EPSILON=0.0001
  54. def snap_tup(tup):
  55. ret=()
  56. for x in tup:
  57. ret+=( x-math.fmod(x,0.0001), )
  58. return tup
  59. def strmtx(mtx):
  60. s=" "
  61. for x in range(4):
  62. for y in range(4):
  63. s+=str(mtx[x][y])
  64. s+=" "
  65. s+=" "
  66. return s
  67. def numarr(a,mult=1.0):
  68. s=" "
  69. for x in a:
  70. s+=" "+str(x*mult)
  71. s+=" "
  72. return s
  73. def strarr(arr):
  74. s=" "
  75. for x in arr:
  76. s+=" "+str(x)
  77. s+=" "
  78. return s
  79. class DaeExporter:
  80. def validate_id(self,d):
  81. if (d.find("id-")==0):
  82. return "z"+d
  83. return d
  84. def new_id(self,t):
  85. self.last_id+=1
  86. return "id-"+t+"-"+str(self.last_id)
  87. class Vertex:
  88. def close_to(v):
  89. if ( (self.vertex-v.vertex).length() > CMP_EPSILON ):
  90. return False
  91. if ( (self.normal-v.normal).length() > CMP_EPSILON ):
  92. return False
  93. if ( (self.uv-v.uv).length() > CMP_EPSILON ):
  94. return False
  95. if ( (self.uv2-v.uv2).length() > CMP_EPSILON ):
  96. return False
  97. return True
  98. def get_tup(self):
  99. tup = (self.vertex.x,self.vertex.y,self.vertex.z,self.normal.x,self.normal.y,self.normal.z)
  100. for t in self.uv:
  101. tup = tup + (t.x,t.y)
  102. return tup
  103. def __init__(self):
  104. self.vertex = Vector( (0.0,0.0,0.0) )
  105. self.normal = Vector( (0.0,0.0,0.0) )
  106. self.color = Vector( (0.0,0.0,0.0) )
  107. self.uv = []
  108. self.uv2 = Vector( (0.0,0.0) )
  109. self.bones=[]
  110. self.weights=[]
  111. def writel(self,section,indent,text):
  112. if (not (section in self.sections)):
  113. self.sections[section]=[]
  114. line=""
  115. for x in range(indent):
  116. line+="\t"
  117. line+=text
  118. self.sections[section].append(line)
  119. def export_image(self,image):
  120. if (image in self.image_cache):
  121. return self.image_cache[image]
  122. imgpath = image.filepath
  123. if (imgpath.find("//")==0 or imgpath.find("\\\\")==0):
  124. #if relative, convert to absolute
  125. imgpath = bpy.path.abspath(imgpath)
  126. #path is absolute, now do something!
  127. if (self.config["use_copy_images"]):
  128. #copy image
  129. basedir = os.path.dirname(self.path)+"/images"
  130. if (not os.path.isdir(basedir)):
  131. os.makedirs(basedir)
  132. dstfile=basedir+"/"+os.path.basename(imgpath)
  133. if (not os.path.isfile(dstfile)):
  134. shutil.copy(imgpath,dstfile)
  135. imgpath="images/"+os.path.basename(imgpath)
  136. else:
  137. #export relative, always, no one wants absolute paths.
  138. imgpath = os.path.relpath(imgpath,os.path.dirname(self.path)).replace("\\","/") # export unix compatible always
  139. imgid = self.new_id("image")
  140. self.writel(S_IMGS,1,'<image id="'+imgid+'" name="'+image.name+'">')
  141. self.writel(S_IMGS,2,'<init_from>'+imgpath+'</init_from>"/>')
  142. self.writel(S_IMGS,1,'</image>')
  143. self.image_cache[image]=imgid
  144. return imgid
  145. def export_material(self,material,double_sided_hint=True):
  146. if (material in self.material_cache):
  147. return self.material_cache[material]
  148. fxid = self.new_id("fx")
  149. self.writel(S_FX,1,'<effect id="'+fxid+'" name="'+material.name+'-fx">')
  150. self.writel(S_FX,2,'<profile_COMMON>')
  151. #Find and fetch the textures and create sources
  152. sampler_table={}
  153. diffuse_tex=None
  154. specular_tex=None
  155. emission_tex=None
  156. normal_tex=None
  157. for i in range(len(material.texture_slots)):
  158. ts=material.texture_slots[i]
  159. if (not ts):
  160. continue
  161. if (not ts.use):
  162. continue
  163. if (not ts.texture):
  164. continue
  165. if (ts.texture.type!="IMAGE"):
  166. continue
  167. if (ts.texture.image==None):
  168. continue
  169. #image
  170. imgid = self.export_image(ts.texture.image)
  171. #surface
  172. surface_sid = self.new_id("fx_surf")
  173. self.writel(S_FX,3,'<newparam sid="'+surface_sid+'">')
  174. self.writel(S_FX,4,'<surface type="2D">')
  175. self.writel(S_FX,5,'<init_from>'+imgid+'</init_from>') #this is sooo weird
  176. self.writel(S_FX,5,'<format>A8R8G8B8</format>')
  177. self.writel(S_FX,4,'</surface>')
  178. self.writel(S_FX,3,'</newparam>')
  179. #sampler, collada sure likes it difficult
  180. sampler_sid = self.new_id("fx_sampler")
  181. self.writel(S_FX,3,'<newparam sid="'+sampler_sid+'">')
  182. self.writel(S_FX,4,'<sampler2D>')
  183. self.writel(S_FX,5,'<source>'+surface_sid+'</source>')
  184. self.writel(S_FX,4,'</sampler2D>')
  185. self.writel(S_FX,3,'</newparam>')
  186. sampler_table[i]=sampler_sid
  187. if (ts.use_map_color_diffuse and diffuse_tex==None):
  188. diffuse_tex=sampler_sid
  189. if (ts.use_map_color_spec and specular_tex==None):
  190. specular_tex=sampler_sid
  191. if (ts.use_map_emit and emission_tex==None):
  192. emission_tex=sampler_sid
  193. if (ts.use_map_normal and normal_tex==None):
  194. normal_tex=sampler_sid
  195. self.writel(S_FX,3,'<technique sid="common">')
  196. shtype="blinn"
  197. self.writel(S_FX,4,'<'+shtype+'>')
  198. #ambient? from where?
  199. self.writel(S_FX,5,'<emission>')
  200. if (emission_tex!=None):
  201. self.writel(S_FX,6,'<texture texture="'+emission_tex+'" texcoord="CHANNEL1"/>')
  202. else:
  203. self.writel(S_FX,6,'<color>'+numarr(material.diffuse_color,material.emit)+' </color>') # not totally right but good enough
  204. self.writel(S_FX,5,'</emission>')
  205. self.writel(S_FX,5,'<ambient>')
  206. self.writel(S_FX,6,'<color>'+numarr(self.scene.world.ambient_color,material.ambient)+' </color>')
  207. self.writel(S_FX,5,'</ambient>')
  208. self.writel(S_FX,5,'<diffuse>')
  209. if (diffuse_tex!=None):
  210. self.writel(S_FX,6,'<texture texture="'+diffuse_tex+'" texcoord="CHANNEL1"/>')
  211. else:
  212. self.writel(S_FX,6,'<color>'+numarr(material.diffuse_color,material.diffuse_intensity)+'</color>')
  213. self.writel(S_FX,5,'</diffuse>')
  214. self.writel(S_FX,5,'<specular>')
  215. if (specular_tex!=None):
  216. self.writel(S_FX,6,'<texture texture="'+specular_tex+'" texcoord="CHANNEL1"/>')
  217. else:
  218. self.writel(S_FX,6,'<color>'+numarr(material.specular_color,material.specular_intensity)+'</color>')
  219. self.writel(S_FX,5,'</specular>')
  220. self.writel(S_FX,5,'<shininess>')
  221. self.writel(S_FX,6,'<float>'+str(material.specular_hardness)+'</float>')
  222. self.writel(S_FX,5,'</shininess>')
  223. self.writel(S_FX,5,'<reflective>')
  224. self.writel(S_FX,6,'<color>'+strarr(material.mirror_color)+'</color>')
  225. self.writel(S_FX,5,'</reflective>')
  226. if (material.use_transparency):
  227. self.writel(S_FX,5,'<transparency>')
  228. self.writel(S_FX,6,'<float>'+str(material.alpha)+'</float>')
  229. self.writel(S_FX,5,'</transparency>')
  230. self.writel(S_FX,5,'<index_of_refraction>'+str(material.specular_ior)+'</index_of_refraction>')
  231. self.writel(S_FX,4,'</'+shtype+'>')
  232. self.writel(S_FX,4,'<extra>')
  233. self.writel(S_FX,5,'<technique profile="FCOLLADA">')
  234. if (normal_tex):
  235. self.writel(S_FX,6,'<bump bumptype="NORMALMAP">')
  236. self.writel(S_FX,7,'<texture texture="'+normal_tex+'" texcoord="CHANNEL1"/>')
  237. self.writel(S_FX,6,'</bump>')
  238. self.writel(S_FX,5,'</technique>')
  239. self.writel(S_FX,4,'</extra>')
  240. self.writel(S_FX,3,'</technique>')
  241. self.writel(S_FX,2,'</profile_COMMON>')
  242. self.writel(S_FX,1,'</effect>')
  243. # Also export blender material in all it's glory (if set as active)
  244. #Material
  245. matid = self.new_id("material")
  246. self.writel(S_MATS,1,'<material id="'+matid+'" name="'+material.name+'">')
  247. self.writel(S_MATS,2,'<instance_effect url="#'+fxid+'"/>')
  248. self.writel(S_MATS,1,'</material>')
  249. self.material_cache[material]=matid
  250. return matid
  251. def export_mesh(self,node,armature=None):
  252. if (len(node.modifiers) and self.config["use_mesh_modifiers"]):
  253. mesh=node.to_mesh(self.scene,True,"RENDER") #is this allright?
  254. else:
  255. mesh=node.data
  256. if (mesh in self.mesh_cache):
  257. return self.mesh_cache[mesh]
  258. mesh.update(calc_tessface=True)
  259. vertices=[]
  260. vertex_map={}
  261. surface_indices={}
  262. materials={}
  263. materials={}
  264. si=None
  265. if (armature!=None):
  266. si=self.skeleton_info[armature]
  267. has_uv=False
  268. has_uv2=False
  269. has_weights=armature!=None
  270. has_colors=False
  271. mat_assign=[]
  272. uv_layer_count=len(mesh.uv_textures)
  273. for fi in range(len(mesh.tessfaces)):
  274. f=mesh.tessfaces[fi]
  275. if (not (f.material_index in surface_indices)):
  276. surface_indices[f.material_index]=[]
  277. print("Type: "+str(type(f.material_index)))
  278. print("IDX: "+str(f.material_index)+"/"+str(len(mesh.materials)))
  279. try:
  280. #Bizarre blender behavior i don't understand, so catching exception
  281. mat = mesh.materials[f.material_index]
  282. except:
  283. mat= None
  284. if (mat!=None):
  285. materials[f.material_index]=self.export_material( mat )
  286. else:
  287. materials[f.material_index]=None #weird, has no material?
  288. indices = surface_indices[f.material_index]
  289. vi=[]
  290. #make triangles always
  291. if (len(f.vertices)==3):
  292. vi.append(0)
  293. vi.append(1)
  294. vi.append(2)
  295. elif (len(f.vertices)==4):
  296. vi.append(0)
  297. vi.append(1)
  298. vi.append(2)
  299. vi.append(0)
  300. vi.append(2)
  301. vi.append(3)
  302. for x in vi:
  303. mv = mesh.vertices[f.vertices[x]]
  304. v = self.Vertex()
  305. v.vertex = Vector( mv.co )
  306. for xt in mesh.tessface_uv_textures:
  307. d = xt.data[fi]
  308. uvsrc = [d.uv1,d.uv2,d.uv3,d.uv4]
  309. v.uv.append( Vector( uvsrc[x] ) )
  310. if (f.use_smooth):
  311. v.normal=Vector( mv.normal )
  312. else:
  313. v.normal=Vector( f.normal )
  314. # if (armature):
  315. # v.vertex = node.matrix_world * v.vertex
  316. #v.color=Vertex(mv. ???
  317. if (armature!=None):
  318. wsum=0.0
  319. for vg in mv.groups:
  320. if vg.group >= len(node.vertex_groups):
  321. continue;
  322. name = node.vertex_groups[vg.group].name
  323. if (name in si["bone_index"]):
  324. if (vg.weight>0.001): #blender has a lot of zero weight stuff
  325. v.bones.append(si["bone_index"][name])
  326. v.weights.append(vg.weight)
  327. wsum+=vg.weight
  328. tup = v.get_tup()
  329. idx = 0
  330. if (tup in vertex_map):
  331. idx = vertex_map[tup]
  332. else:
  333. idx = len(vertices)
  334. vertices.append(v)
  335. vertex_map[tup]=idx
  336. indices.append(idx)
  337. meshid = self.new_id("mesh")
  338. self.writel(S_GEOM,1,'<geometry id="'+meshid+'" name="'+mesh.name+'">')
  339. self.writel(S_GEOM,2,'<mesh>')
  340. # Vertex Array
  341. self.writel(S_GEOM,3,'<source id="'+meshid+'-positions">')
  342. float_values=""
  343. for v in vertices:
  344. float_values+=" "+str(v.vertex.x)+" "+str(v.vertex.y)+" "+str(v.vertex.z)
  345. self.writel(S_GEOM,4,'<float_array id="'+meshid+'-positions-array" count="'+str(len(vertices)*3)+'">'+float_values+'</float_array>')
  346. self.writel(S_GEOM,4,'<technique_common>')
  347. self.writel(S_GEOM,4,'<accessor source="#'+meshid+'-positions-array" count="'+str(len(vertices))+'" stride="3">')
  348. self.writel(S_GEOM,5,'<param name="X" type="float"/>')
  349. self.writel(S_GEOM,5,'<param name="Y" type="float"/>')
  350. self.writel(S_GEOM,5,'<param name="Z" type="float"/>')
  351. self.writel(S_GEOM,4,'</accessor>')
  352. self.writel(S_GEOM,4,'</technique_common>')
  353. self.writel(S_GEOM,3,'</source>')
  354. # Normal Array
  355. self.writel(S_GEOM,3,'<source id="'+meshid+'-normals">')
  356. float_values=""
  357. for v in vertices:
  358. float_values+=" "+str(v.normal.x)+" "+str(v.normal.y)+" "+str(v.normal.z)
  359. self.writel(S_GEOM,4,'<float_array id="'+meshid+'-normals-array" count="'+str(len(vertices)*3)+'">'+float_values+'</float_array>')
  360. self.writel(S_GEOM,4,'<technique_common>')
  361. self.writel(S_GEOM,4,'<accessor source="#'+meshid+'-normals-array" count="'+str(len(vertices))+'" stride="3">')
  362. self.writel(S_GEOM,5,'<param name="X" type="float"/>')
  363. self.writel(S_GEOM,5,'<param name="Y" type="float"/>')
  364. self.writel(S_GEOM,5,'<param name="Z" type="float"/>')
  365. self.writel(S_GEOM,4,'</accessor>')
  366. self.writel(S_GEOM,4,'</technique_common>')
  367. self.writel(S_GEOM,3,'</source>')
  368. # UV Arrays
  369. for uvi in range(uv_layer_count):
  370. self.writel(S_GEOM,3,'<source id="'+meshid+'-texcoord-'+str(uvi)+'">')
  371. float_values=""
  372. for v in vertices:
  373. float_values+=" "+str(v.uv[uvi].x)+" "+str(v.uv[uvi].y)
  374. self.writel(S_GEOM,4,'<float_array id="'+meshid+'-texcoord-'+str(uvi)+'-array" count="'+str(len(vertices)*2)+'">'+float_values+'</float_array>')
  375. self.writel(S_GEOM,4,'<technique_common>')
  376. self.writel(S_GEOM,4,'<accessor source="#'+meshid+'-texcoord-'+str(uvi)+'-array" count="'+str(len(vertices))+'" stride="2">')
  377. self.writel(S_GEOM,5,'<param name="S" type="float"/>')
  378. self.writel(S_GEOM,5,'<param name="T" type="float"/>')
  379. self.writel(S_GEOM,4,'</accessor>')
  380. self.writel(S_GEOM,4,'</technique_common>')
  381. self.writel(S_GEOM,3,'</source>')
  382. # Triangle Lists
  383. self.writel(S_GEOM,3,'<vertices id="'+meshid+'-vertices">')
  384. self.writel(S_GEOM,4,'<input semantic="POSITION" source="#'+meshid+'-positions"/>')
  385. self.writel(S_GEOM,3,'</vertices>')
  386. for m in surface_indices:
  387. indices = surface_indices[m]
  388. mat = materials[m]
  389. if (mat!=None):
  390. matref = self.new_id("trimat")
  391. self.writel(S_GEOM,3,'<triangles count="'+str(int(len(indices)/3))+'" material="'+matref+'">') # todo material
  392. mat_assign.append( (mat,matref) )
  393. else:
  394. self.writel(S_GEOM,3,'<triangles count="'+str(int(len(indices)/3))+'">') # todo material
  395. self.writel(S_GEOM,4,'<input semantic="VERTEX" source="#'+meshid+'-vertices" offset="0"/>')
  396. self.writel(S_GEOM,4,'<input semantic="NORMAL" source="#'+meshid+'-normals" offset="1"/>')
  397. extra_indices=0
  398. for uvi in range(uv_layer_count):
  399. self.writel(S_GEOM,4,'<input semantic="TEXCOORD" source="#'+meshid+'-texcoord-'+str(uvi)+'" offset="'+str(2+uvi)+'" set="'+str(uvi)+'"/>')
  400. extra_indices+=1
  401. int_values="<p>"
  402. for i in range(len(indices)):
  403. int_values+=" "+str(indices[i]) # vertex index
  404. int_values+=" "+str(indices[i]) # normal index
  405. for e in range(extra_indices):
  406. int_values+=" "+str(indices[i]) # normal index
  407. int_values+="</p>"
  408. self.writel(S_GEOM,4,int_values)
  409. self.writel(S_GEOM,3,'</triangles>')
  410. self.writel(S_GEOM,2,'</mesh>')
  411. self.writel(S_GEOM,1,'</geometry>')
  412. meshdata={}
  413. meshdata["id"]=meshid
  414. meshdata["material_assign"]=mat_assign
  415. self.mesh_cache[mesh]=meshdata
  416. # Export armature data (if armature exists)
  417. if (armature!=None):
  418. contid = self.new_id("controller")
  419. self.writel(S_CONT,1,'<controller id="'+contid+'">')
  420. self.writel(S_CONT,2,'<skin source="'+meshid+'">')
  421. self.writel(S_CONT,3,'<bind_shape_matrix>'+strmtx(node.matrix_world)+'</bind_shape_matrix>')
  422. #Joint Names
  423. self.writel(S_CONT,3,'<source id="'+contid+'-joints">')
  424. name_values=""
  425. for v in si["bone_names"]:
  426. name_values+=" "+v
  427. self.writel(S_CONT,4,'<Name_array id="'+contid+'-joints-array" count="'+str(len(si["bone_names"]))+'">'+name_values+'</Name_array>')
  428. self.writel(S_CONT,4,'<technique_common>')
  429. self.writel(S_CONT,4,'<accessor source="#'+contid+'-joints-array" count="'+str(len(si["bone_names"]))+'" stride="1">')
  430. self.writel(S_CONT,5,'<param name="JOINT" type="Name"/>')
  431. self.writel(S_CONT,4,'</accessor>')
  432. self.writel(S_CONT,4,'</technique_common>')
  433. self.writel(S_CONT,3,'</source>')
  434. #Pose Matrices!
  435. self.writel(S_CONT,3,'<source id="'+contid+'-bind_poses">')
  436. pose_values=""
  437. for v in si["bone_bind_poses"]:
  438. pose_values+=" "+strmtx(v)
  439. self.writel(S_CONT,4,'<float_array id="'+contid+'-bind_poses-array" count="'+str(len(si["bone_bind_poses"])*16)+'">'+pose_values+'</float_array>')
  440. self.writel(S_CONT,4,'<technique_common>')
  441. self.writel(S_CONT,4,'<accessor source="#'+contid+'-bind_poses-array" count="'+str(len(si["bone_bind_poses"]))+'" stride="16">')
  442. self.writel(S_CONT,5,'<param name="TRANSFORM" type="float4x4"/>')
  443. self.writel(S_CONT,4,'</accessor>')
  444. self.writel(S_CONT,4,'</technique_common>')
  445. self.writel(S_CONT,3,'</source>')
  446. #Skin Weights!
  447. self.writel(S_CONT,3,'<source id="'+contid+'-skin_weights">')
  448. skin_weights=""
  449. skin_weights_total=0
  450. for v in vertices:
  451. skin_weights_total+=len(v.weights)
  452. for w in v.weights:
  453. skin_weights+=" "+str(w)
  454. self.writel(S_CONT,4,'<float_array id="'+contid+'-skin_weights-array" count="'+str(skin_weights_total)+'">'+skin_weights+'</float_array>')
  455. self.writel(S_CONT,4,'<technique_common>')
  456. self.writel(S_CONT,4,'<accessor source="#'+contid+'-skin_weights-array" count="'+str(skin_weights_total)+'" stride="1">')
  457. self.writel(S_CONT,5,'<param name="WEIGHT" type="float"/>')
  458. self.writel(S_CONT,4,'</accessor>')
  459. self.writel(S_CONT,4,'</technique_common>')
  460. self.writel(S_CONT,3,'</source>')
  461. self.writel(S_CONT,3,'<joints>')
  462. self.writel(S_CONT,4,'<input semantic="JOINT" source="#'+contid+'-joints"/>')
  463. self.writel(S_CONT,4,'<input semantic="INV_BIND_MATRIX" source="#'+contid+'-bind_poses"/>')
  464. self.writel(S_CONT,3,'</joints>')
  465. self.writel(S_CONT,3,'<vertex_weights count="'+str(len(vertices))+'">')
  466. self.writel(S_CONT,4,'<input semantic="JOINT" source="#'+contid+'-joints" offset="0"/>')
  467. self.writel(S_CONT,4,'<input semantic="WEIGHT" source="#'+contid+'-skin_weights" offset="1"/>')
  468. vcounts=""
  469. vs=""
  470. vcount=0
  471. for v in vertices:
  472. vcounts+=" "+str(len(v.weights))
  473. for b in v.bones:
  474. vs+=" "+str(b)
  475. vs+=" "+str(vcount)
  476. vcount+=1
  477. self.writel(S_CONT,4,'<vcount>'+vcounts+'</vcount>')
  478. self.writel(S_CONT,4,'<v>'+vs+'</v>')
  479. self.writel(S_CONT,3,'</vertex_weights>')
  480. self.writel(S_CONT,2,'</skin>')
  481. self.writel(S_CONT,1,'</controller>')
  482. meshdata["skin_id"]=contid
  483. return meshdata
  484. def export_mesh_node(self,node,il):
  485. if (node.data==None):
  486. return
  487. armature=None
  488. if (node.parent!=None):
  489. if (node.parent.type=="ARMATURE"):
  490. armature=node.parent
  491. meshdata = self.export_mesh(node,armature)
  492. if (armature==None):
  493. self.writel(S_NODES,il,'<instance_geometry url="#'+meshdata["id"]+'">')
  494. else:
  495. self.writel(S_NODES,il,'<instance_controller url="#'+meshdata["skin_id"]+'">')
  496. for sn in self.skeleton_info[armature]["skeleton_nodes"]:
  497. self.writel(S_NODES,il+1,'<skeleton>#'+sn+'</skeleton>')
  498. if (len(meshdata["material_assign"])>0):
  499. self.writel(S_NODES,il+1,'<bind_material>')
  500. self.writel(S_NODES,il+2,'<technique_common>')
  501. for m in meshdata["material_assign"]:
  502. self.writel(S_NODES,il+3,'<instance_material symbol="'+m[1]+'" target="#'+m[0]+'"/>')
  503. self.writel(S_NODES,il+2,'</technique_common>')
  504. self.writel(S_NODES,il+1,'</bind_material>')
  505. if (armature==None):
  506. self.writel(S_NODES,il,'</instance_geometry>')
  507. else:
  508. self.writel(S_NODES,il,'</instance_controller>')
  509. def export_armature_bone(self,bone,il,si):
  510. boneid = self.new_id("bone")
  511. boneidx = si["bone_count"]
  512. si["bone_count"]+=1
  513. bonesid = si["name"]+"-"+str(boneidx)
  514. si["bone_index"][bone.name]=boneidx
  515. si["bone_ids"][bone]=boneid
  516. si["bone_names"].append(bonesid)
  517. self.writel(S_NODES,il,'<node id="'+boneid+'" sid="'+bonesid+'" name="'+bone.name+'" type="JOINT">')
  518. il+=1
  519. xform = bone.matrix_local
  520. si["bone_bind_poses"].append((si["armature_xform"] * xform).inverted())
  521. if (bone.parent!=None):
  522. xform = bone.parent.matrix_local.inverted() * xform
  523. else:
  524. si["skeleton_nodes"].append(boneid)
  525. self.writel(S_NODES,il,'<matrix sid="transform">'+strmtx(xform)+'</matrix>')
  526. for c in bone.children:
  527. self.export_armature_bone(c,il,si)
  528. il-=1
  529. self.writel(S_NODES,il,'</node>')
  530. def export_armature_node(self,node,il):
  531. if (node.data==None):
  532. return
  533. self.skeletons.append(node)
  534. armature = node.data
  535. self.skeleton_info[node]={ "bone_count":0, "name":node.name, "bone_index":{},"bone_ids":{},"bone_names":[],"bone_bind_poses":[],"skeleton_nodes":[],"armature_xform":node.matrix_world }
  536. for b in armature.bones:
  537. if (b.parent!=None):
  538. continue
  539. self.export_armature_bone(b,il,self.skeleton_info[node])
  540. if (node.pose):
  541. for b in node.pose.bones:
  542. for x in b.constraints:
  543. if (x.type=='ACTION'):
  544. self.action_constraints.append(x.action)
  545. def export_camera_node(self,node,il):
  546. if (node.data==None):
  547. return
  548. camera=node.data
  549. camid=self.new_id("camera")
  550. self.writel(S_CAMS,1,'<camera id="'+camid+'" name="'+camera.name+'">')
  551. self.writel(S_CAMS,2,'<optics>')
  552. self.writel(S_CAMS,3,'<technique_common>')
  553. if (camera.type=="PERSP"):
  554. self.writel(S_CAMS,4,'<perspective>')
  555. self.writel(S_CAMS,5,'<yfov> '+str(math.degrees(camera.angle))+' </yfov>') # I think?
  556. self.writel(S_CAMS,5,'<aspect_ratio> '+str(self.scene.render.resolution_x / self.scene.render.resolution_y)+' </aspect_ratio>')
  557. self.writel(S_CAMS,5,'<znear> '+str(camera.clip_start)+' </znear>')
  558. self.writel(S_CAMS,5,'<zfar> '+str(camera.clip_end)+' </zfar>')
  559. self.writel(S_CAMS,4,'</perspective>')
  560. else:
  561. self.writel(S_CAMS,4,'<orthografic>')
  562. self.writel(S_CAMS,5,'<xmag> '+str(camera.ortho_scale)+' </xmag>') # I think?
  563. self.writel(S_CAMS,5,'<aspect_ratio> '+str(self.scene.render.resolution_x / self.scene.render.resolution_y)+' </aspect_ratio>')
  564. self.writel(S_CAMS,5,'<znear> '+str(camera.clip_start)+' </znear>')
  565. self.writel(S_CAMS,5,'<zfar> '+str(camera.clip_end)+' </zfar>')
  566. self.writel(S_CAMS,4,'</orthografic>')
  567. self.writel(S_CAMS,3,'</technique_common>')
  568. self.writel(S_CAMS,2,'</optics>')
  569. self.writel(S_CAMS,1,'</camera>')
  570. self.writel(S_NODES,il,'<instance_camera url="#'+camid+'"/>')
  571. def export_lamp_node(self,node,il):
  572. if (node.data==None):
  573. return
  574. light=node.data
  575. lightid=self.new_id("light")
  576. self.writel(S_LAMPS,1,'<light id="'+lightid+'" name="'+light.name+'">')
  577. self.writel(S_LAMPS,2,'<optics>')
  578. self.writel(S_LAMPS,3,'<technique_common>')
  579. if (light.type=="POINT" or light.type=="HEMI"):
  580. self.writel(S_LAMPS,4,'<point>')
  581. self.writel(S_LAMPS,5,'<color>'+strarr(light.color)+'</color>')
  582. att_by_distance = 2.0 / light.distance # convert to linear attenuation
  583. self.writel(S_LAMPS,5,'<linear_attenuation>'+str(att_by_distance)+'</linear_attenuation>')
  584. if (light.use_sphere):
  585. self.writel(S_LAMPS,5,'<zfar>'+str(light.distance)+'</zfar>')
  586. self.writel(S_LAMPS,4,'</point>')
  587. elif (light.type=="SPOT"):
  588. self.writel(S_LAMPS,4,'<spot>')
  589. self.writel(S_LAMPS,5,'<color>'+strarr(light.color)+'</color>')
  590. att_by_distance = 2.0 / light.distance # convert to linear attenuation
  591. self.writel(S_LAMPS,5,'<linear_attenuation>'+str(att_by_distance)+'</linear_attenuation>')
  592. self.writel(S_LAMPS,5,'<falloff_angle>'+str(math.degrees(light.spot_size))+'</falloff_angle>')
  593. self.writel(S_LAMPS,4,'</spot>')
  594. else: #write a sun lamp for everything else (not supported)
  595. self.writel(S_LAMPS,4,'<directional>')
  596. self.writel(S_LAMPS,5,'<color>'+strarr(light.color)+'</color>')
  597. self.writel(S_LAMPS,4,'</directional>')
  598. self.writel(S_LAMPS,3,'</technique_common>')
  599. self.writel(S_LAMPS,2,'</optics>')
  600. self.writel(S_LAMPS,1,'</light>')
  601. self.writel(S_NODES,il,'<instance_light url="#'+lightid+'"/>')
  602. def export_curve(self,curve):
  603. splineid = self.new_id("spline")
  604. self.writel(S_GEOM,1,'<geometry id="'+splineid+'" name="'+curve.name+'">')
  605. self.writel(S_GEOM,2,'<spline closed="0">')
  606. points=[]
  607. interps=[]
  608. handles_in=[]
  609. handles_out=[]
  610. tilts=[]
  611. for cs in curve.splines:
  612. if (cs.type=="BEZIER"):
  613. for s in cs.bezier_points:
  614. points.append(s.co[0])
  615. points.append(s.co[1])
  616. points.append(s.co[2])
  617. handles_in.append(s.handle_left[0])
  618. handles_in.append(s.handle_left[1])
  619. handles_in.append(s.handle_left[2])
  620. handles_out.append(s.handle_right[0])
  621. handles_out.append(s.handle_right[1])
  622. handles_out.append(s.handle_right[2])
  623. tilts.append(s.tilt)
  624. interps.append("BEZIER")
  625. else:
  626. for s in cs.points:
  627. points.append(s.co[0])
  628. points.append(s.co[1])
  629. points.append(s.co[2])
  630. handles_in.append(s.co[0])
  631. handles_in.append(s.co[1])
  632. handles_in.append(s.co[2])
  633. handles_out.append(s.co[0])
  634. handles_out.append(s.co[1])
  635. handles_out.append(s.co[2])
  636. tilts.append(s.tilt)
  637. interps.append("LINEAR")
  638. self.writel(S_GEOM,3,'<source id="'+splineid+'-positions">')
  639. position_values=""
  640. for x in points:
  641. position_values+=" "+str(x)
  642. self.writel(S_GEOM,4,'<float_array id="'+splineid+'-positions-array" count="'+str(len(points))+'">'+position_values+'</float_array>')
  643. self.writel(S_GEOM,4,'<technique_common>')
  644. self.writel(S_GEOM,4,'<accessor source="#'+splineid+'-positions-array" count="'+str(len(points)/3)+'" stride="3">')
  645. self.writel(S_GEOM,5,'<param name="X" type="float"/>')
  646. self.writel(S_GEOM,5,'<param name="Y" type="float"/>')
  647. self.writel(S_GEOM,5,'<param name="Z" type="float"/>')
  648. self.writel(S_GEOM,4,'</accessor>')
  649. self.writel(S_GEOM,3,'</source>')
  650. self.writel(S_GEOM,3,'<source id="'+splineid+'-intangents">')
  651. intangent_values=""
  652. for x in handles_in:
  653. intangent_values+=" "+str(x)
  654. self.writel(S_GEOM,4,'<float_array id="'+splineid+'-intangents-array" count="'+str(len(points))+'">'+intangent_values+'</float_array>')
  655. self.writel(S_GEOM,4,'<technique_common>')
  656. self.writel(S_GEOM,4,'<accessor source="#'+splineid+'-intangents-array" count="'+str(len(points)/3)+'" stride="3">')
  657. self.writel(S_GEOM,5,'<param name="X" type="float"/>')
  658. self.writel(S_GEOM,5,'<param name="Y" type="float"/>')
  659. self.writel(S_GEOM,5,'<param name="Z" type="float"/>')
  660. self.writel(S_GEOM,4,'</accessor>')
  661. self.writel(S_GEOM,3,'</source>')
  662. self.writel(S_GEOM,3,'<source id="'+splineid+'-outtangents">')
  663. outtangent_values=""
  664. for x in handles_out:
  665. outtangent_values+=" "+str(x)
  666. self.writel(S_GEOM,4,'<float_array id="'+splineid+'-outtangents-array" count="'+str(len(points))+'">'+outtangent_values+'</float_array>')
  667. self.writel(S_GEOM,4,'<technique_common>')
  668. self.writel(S_GEOM,4,'<accessor source="#'+splineid+'-outtangents-array" count="'+str(len(points)/3)+'" stride="3">')
  669. self.writel(S_GEOM,5,'<param name="X" type="float"/>')
  670. self.writel(S_GEOM,5,'<param name="Y" type="float"/>')
  671. self.writel(S_GEOM,5,'<param name="Z" type="float"/>')
  672. self.writel(S_GEOM,4,'</accessor>')
  673. self.writel(S_GEOM,3,'</source>')
  674. self.writel(S_GEOM,3,'<source id="'+splineid+'-interpolations">')
  675. interpolation_values=""
  676. for x in interps:
  677. interpolation_values+=" "+x
  678. self.writel(S_GEOM,4,'<Name_array id="'+splineid+'-interpolations-array" count="'+str(len(interps))+'">'+interpolation_values+'</Name_array>')
  679. self.writel(S_GEOM,4,'<technique_common>')
  680. self.writel(S_GEOM,4,'<accessor source="#'+splineid+'-interpolations-array" count="'+str(len(interps))+'" stride="1">')
  681. self.writel(S_GEOM,5,'<param name="INTERPOLATION" type="name"/>')
  682. self.writel(S_GEOM,4,'</accessor>')
  683. self.writel(S_GEOM,3,'</source>')
  684. self.writel(S_GEOM,3,'<source id="'+splineid+'-tilts">')
  685. tilt_values=""
  686. for x in tilts:
  687. tilt_values+=" "+str(x)
  688. self.writel(S_GEOM,4,'<float_array id="'+splineid+'-tilts-array" count="'+str(len(tilts))+'">'+tilt_values+'</float_array>')
  689. self.writel(S_GEOM,4,'<technique_common>')
  690. self.writel(S_GEOM,4,'<accessor source="#'+splineid+'-tilts-array" count="'+str(len(tilts))+'" stride="1">')
  691. self.writel(S_GEOM,5,'<param name="TILT" type="float"/>')
  692. self.writel(S_GEOM,4,'</accessor>')
  693. self.writel(S_GEOM,3,'</source>')
  694. self.writel(S_GEOM,3,'<control_vertices>')
  695. self.writel(S_GEOM,4,'<input semantic="POSITION" source="#'+splineid+'-positions"/>')
  696. self.writel(S_GEOM,4,'<input semantic="IN_TANGENT" source="#'+splineid+'-intangents"/>')
  697. self.writel(S_GEOM,4,'<input semantic="OUT_TANGENT" source="#'+splineid+'-outtangents"/>')
  698. self.writel(S_GEOM,4,'<input semantic="INTERPOLATION" source="#'+splineid+'-interpolations"/>')
  699. self.writel(S_GEOM,4,'<input semantic="TILT" source="#'+splineid+'-tilts"/>')
  700. self.writel(S_GEOM,3,'</control_vertices>')
  701. self.writel(S_GEOM,2,'</spline>')
  702. self.writel(S_GEOM,1,'</geometry>')
  703. return splineid
  704. def export_curve_node(self,node,il):
  705. if (node.data==None):
  706. return
  707. curveid = self.export_curve(node.data)
  708. self.writel(S_NODES,il,'<instance_geometry url="#'+curveid+'">')
  709. self.writel(S_NODES,il,'</instance_geometry>')
  710. def export_node(self,node,il):
  711. if (not self.is_node_valid(node)):
  712. return
  713. self.writel(S_NODES,il,'<node id="'+self.validate_id(node.name)+'" name="'+node.name+'" type="NODE">')
  714. il+=1
  715. self.writel(S_NODES,il,'<matrix sid="transform">'+strmtx(node.matrix_local)+'</matrix>')
  716. print("NODE TYPE: "+node.type+" NAME: "+node.name)
  717. if (node.type=="MESH"):
  718. self.export_mesh_node(node,il)
  719. elif (node.type=="CURVE"):
  720. self.export_curve_node(node,il)
  721. elif (node.type=="ARMATURE"):
  722. self.export_armature_node(node,il)
  723. elif (node.type=="CAMERA"):
  724. self.export_camera_node(node,il)
  725. elif (node.type=="LAMP"):
  726. self.export_lamp_node(node,il)
  727. self.valid_nodes.append(node)
  728. for x in node.children:
  729. self.export_node(x,il)
  730. il-=1
  731. self.writel(S_NODES,il,'</node>')
  732. def is_node_valid(self,node):
  733. if (not node.type in self.config["object_types"]):
  734. return False
  735. if (self.config["use_active_layers"]):
  736. valid=False
  737. for i in range(20):
  738. if (node.layers[i] and self.scene.layers[i]):
  739. valid=True
  740. break
  741. if (not valid):
  742. return False
  743. if (self.config["use_export_selected"] and not node.select):
  744. return False
  745. return True
  746. def export_scene(self):
  747. self.writel(S_NODES,0,'<library_visual_scenes>')
  748. self.writel(S_NODES,1,'<visual_scene id="'+self.scene_name+'" name="scene">')
  749. for obj in self.scene.objects:
  750. if (obj.parent==None):
  751. self.export_node(obj,2)
  752. self.writel(S_NODES,1,'</visual_scene>')
  753. self.writel(S_NODES,0,'</library_visual_scenes>')
  754. def export_asset(self):
  755. self.writel(S_ASSET,0,'<asset>')
  756. # Why is this time stuff mandatory?, no one could care less...
  757. self.writel(S_ASSET,1,'<contributor>')
  758. self.writel(S_ASSET,2,'<author> Anonymous </author>') #Who made Collada, the FBI ?
  759. self.writel(S_ASSET,2,'<authoring_tool> Collada Exporter for Blender 2.6+, by Juan Linietsky ([email protected]) </authoring_tool>') #Who made Collada, the FBI ?
  760. self.writel(S_ASSET,1,'</contributor>')
  761. self.writel(S_ASSET,1,'<created>'+time.strftime("%Y-%m-%dT%H:%M:%SZ ")+'</created>')
  762. self.writel(S_ASSET,1,'<modified>'+time.strftime("%Y-%m-%dT%H:%M:%SZ")+'</modified>')
  763. self.writel(S_ASSET,1,'<unit meter="1.0" name="meter"/>')
  764. self.writel(S_ASSET,1,'<up_axis>Z_UP</up_axis>')
  765. self.writel(S_ASSET,0,'</asset>')
  766. def export_animation_transform_channel(self,target,transform_keys):
  767. frame_total=len(transform_keys)
  768. anim_id=self.new_id("anim")
  769. self.writel(S_ANIM,1,'<animation id="'+anim_id+'">')
  770. source_frames = ""
  771. source_transforms = ""
  772. source_interps = ""
  773. for k in transform_keys:
  774. source_frames += " "+str(k[0])
  775. source_transforms += " "+strmtx(k[1])
  776. source_interps +=" LINEAR"
  777. # Time Source
  778. self.writel(S_ANIM,2,'<source id="'+anim_id+'-input">')
  779. self.writel(S_ANIM,3,'<float_array id="'+anim_id+'-input-array" count="'+str(frame_total)+'">'+source_frames+'</float_array>')
  780. self.writel(S_ANIM,3,'<technique_common>')
  781. self.writel(S_ANIM,4,'<accessor source="'+anim_id+'-input-array" count="'+str(frame_total)+'" stride="1">')
  782. self.writel(S_ANIM,5,'<param name="TIME" type="float"/>')
  783. self.writel(S_ANIM,4,'</accessor>')
  784. self.writel(S_ANIM,3,'</technique_common>')
  785. self.writel(S_ANIM,2,'</source>')
  786. # Transform Source
  787. self.writel(S_ANIM,2,'<source id="'+anim_id+'-transform-output">')
  788. self.writel(S_ANIM,3,'<float_array id="'+anim_id+'-transform-output-array" count="'+str(frame_total*16)+'">'+source_transforms+'</float_array>')
  789. self.writel(S_ANIM,3,'<technique_common>')
  790. self.writel(S_ANIM,4,'<accessor source="'+anim_id+'-transform-output-array" count="'+str(frame_total)+'" stride="16">')
  791. self.writel(S_ANIM,5,'<param name="TRANSFORM" type="float4x4"/>')
  792. self.writel(S_ANIM,4,'</accessor>')
  793. self.writel(S_ANIM,3,'</technique_common>')
  794. self.writel(S_ANIM,2,'</source>')
  795. # Interpolation Source
  796. self.writel(S_ANIM,2,'<source id="'+anim_id+'-interpolation-output">')
  797. self.writel(S_ANIM,3,'<Name_array id="'+anim_id+'-interpolation-output-array" count="'+str(frame_total)+'">'+source_interps+'</Name_array>')
  798. self.writel(S_ANIM,3,'<technique_common>')
  799. self.writel(S_ANIM,4,'<accessor source="'+anim_id+'-interpolation-output-array" count="'+str(frame_total)+'" stride="1">')
  800. self.writel(S_ANIM,5,'<param name="INTERPOLATION" type="Name"/>')
  801. self.writel(S_ANIM,4,'</accessor>')
  802. self.writel(S_ANIM,3,'</technique_common>')
  803. self.writel(S_ANIM,2,'</source>')
  804. self.writel(S_ANIM,2,'<sampler id="'+anim_id+'-sampler">')
  805. self.writel(S_ANIM,3,'<input semantic="INPUT" source="#'+anim_id+'-input"/>')
  806. self.writel(S_ANIM,3,'<input semantic="OUTPUT" source="#'+anim_id+'-transform-output"/>')
  807. self.writel(S_ANIM,3,'<input semantic="INTERPOLATION" source="#'+anim_id+'-interpolation-output"/>')
  808. self.writel(S_ANIM,2,'</sampler>')
  809. self.writel(S_ANIM,2,'<channel source="#'+anim_id+'-sampler" target="'+target+'/transform"/>')
  810. self.writel(S_ANIM,1,'</animation>')
  811. return [anim_id]
  812. def export_animation(self,start,end):
  813. #Blender -> Collada frames needs a little work
  814. #Collada starts from 0, blender usually from 1
  815. #The last frame must be included also
  816. frame_len = 1.0 / self.scene.render.fps
  817. frame_total = end - start + 1
  818. frame_sub = 0
  819. if (start>0):
  820. frame_sub=start*frame_len
  821. tcn = []
  822. xform_cache={}
  823. # Change frames first, export objects last
  824. # This improves performance enormously
  825. print("anim from: "+str(start)+" to "+str(end))
  826. for t in range(start,end+1):
  827. self.scene.frame_set(t)
  828. key = t * frame_len - frame_sub
  829. # print("Export Anim Frame "+str(t)+"/"+str(self.scene.frame_end+1))
  830. for node in self.scene.objects:
  831. if (not node in self.valid_nodes):
  832. continue
  833. if (node.type=="MESH" and node.parent and node.parent.type=="ARMATURE"):
  834. continue #In Collada, nodes that have skin modifier must not export animation, animate the skin instead.
  835. if (len(node.constraints)>0 or node.animation_data!=None):
  836. #If the node has constraints, or animation data, then export a sampled animation track
  837. name=self.validate_id(node.name)
  838. if (not (name in xform_cache)):
  839. xform_cache[name]=[]
  840. mtx = node.matrix_world.copy()
  841. if (node.parent):
  842. mtx = node.parent.matrix_world.inverted() * mtx
  843. xform_cache[name].append( (key,mtx) )
  844. if (node.type=="ARMATURE"):
  845. #All bones exported for now
  846. for bone in node.data.bones:
  847. bone_name=self.skeleton_info[node]["bone_ids"][bone]
  848. if (not (bone_name in xform_cache)):
  849. xform_cache[bone_name]=[]
  850. posebone = node.pose.bones[bone.name]
  851. parent_posebone=None
  852. mtx = posebone.matrix.copy()
  853. if (bone.parent):
  854. parent_posebone=node.pose.bones[bone.parent.name]
  855. mtx = parent_posebone.matrix.inverted() * mtx
  856. xform_cache[bone_name].append( (key,mtx) )
  857. #export animation xml
  858. for nid in xform_cache:
  859. tcn+=self.export_animation_transform_channel(nid,xform_cache[nid])
  860. return tcn
  861. def export_animations(self):
  862. self.writel(S_ANIM,0,'<library_animations>')
  863. if (self.config["use_anim_action_all"] and len(self.skeletons)):
  864. self.writel(S_ANIM_CLIPS,0,'<library_animation_clips>')
  865. for x in bpy.data.actions[:]:
  866. if x in self.action_constraints:
  867. continue
  868. for y in self.skeletons:
  869. if (y.animation_data):
  870. y.animation_data.action=x;
  871. tcn = self.export_animation(int(x.frame_range[0]),int(x.frame_range[1]))
  872. framelen=(1.0/self.scene.render.fps)
  873. start = x.frame_range[0]*framelen
  874. end = x.frame_range[1]*framelen
  875. print("Export anim: "+x.name)
  876. self.writel(S_ANIM_CLIPS,1,'<animation_clip name="'+x.name+'" start="'+str(start)+'" end="'+str(end)+'">')
  877. for z in tcn:
  878. self.writel(S_ANIM_CLIPS,2,'<instance_animation url="#'+z+'">')
  879. self.writel(S_ANIM_CLIPS,1,'</animation_clip>')
  880. self.writel(S_ANIM_CLIPS,0,'</library_animation_clips>')
  881. else:
  882. self.export_animation(self.scene.frame_start,self.scene.frame_end)
  883. self.writel(S_ANIM,0,'</library_animations>')
  884. def export(self):
  885. self.writel(S_GEOM,0,'<library_geometries>')
  886. self.writel(S_CONT,0,'<library_controllers>')
  887. self.writel(S_CAMS,0,'<library_cameras>')
  888. self.writel(S_LAMPS,0,'<library_lights>')
  889. self.writel(S_IMGS,0,'<library_images>')
  890. self.writel(S_MATS,0,'<library_materials>')
  891. self.writel(S_FX,0,'<library_effects>')
  892. self.skeletons=[]
  893. self.action_constraints=[]
  894. self.export_asset()
  895. self.export_scene()
  896. self.writel(S_GEOM,0,'</library_geometries>')
  897. self.writel(S_CONT,0,'</library_controllers>')
  898. self.writel(S_CAMS,0,'</library_cameras>')
  899. self.writel(S_LAMPS,0,'</library_lights>')
  900. self.writel(S_IMGS,0,'</library_images>')
  901. self.writel(S_MATS,0,'</library_materials>')
  902. self.writel(S_FX,0,'</library_effects>')
  903. if (self.config["use_anim"]):
  904. self.export_animations()
  905. try:
  906. f = open(self.path,"wb")
  907. except:
  908. return False
  909. f.write(bytes('<?xml version="1.0" encoding="utf-8"?>\n',"UTF-8"))
  910. f.write(bytes('<COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">\n',"UTF-8"))
  911. s=[]
  912. for x in self.sections.keys():
  913. s.append(x)
  914. s.sort()
  915. for x in s:
  916. for l in self.sections[x]:
  917. f.write(bytes(l+"\n","UTF-8"))
  918. f.write(bytes('<scene>\n',"UTF-8"))
  919. f.write(bytes('\t<instance_visual_scene url="#'+self.scene_name+'" />\n',"UTF-8"))
  920. f.write(bytes('</scene>\n',"UTF-8"))
  921. f.write(bytes('</COLLADA>\n',"UTF-8"))
  922. return True
  923. def __init__(self,path,kwargs):
  924. self.scene=bpy.context.scene
  925. self.last_id=0
  926. self.scene_name=self.new_id("scene")
  927. self.sections={}
  928. self.path=path
  929. self.mesh_cache={}
  930. self.curve_cache={}
  931. self.material_cache={}
  932. self.image_cache={}
  933. self.skeleton_info={}
  934. self.config=kwargs
  935. self.valid_nodes=[]
  936. def save(operator, context,
  937. filepath="",
  938. use_selection=False,
  939. **kwargs
  940. ):
  941. exp = DaeExporter(filepath,kwargs)
  942. exp.export()
  943. return {'FINISHED'} # so the script wont run after we have batch exported.