Fix #29295: Problem with Alpha Channel video in Sequencer and textures
[blender-staging.git] / source / blender / collada / AnimationExporter.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * Contributor(s): Chingiz Dyussenov, Arystanbek Dyussenov, Jan Diederich, Tod Liverseed.
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 #include "GeometryExporter.h"
24 #include "AnimationExporter.h"
25 #include "MaterialExporter.h"
26
27 template<class Functor>
28 void forEachObjectInScene(Scene *sce, Functor &f)
29 {
30         Base *base= (Base*) sce->base.first;
31
32         while(base) {
33                 Object *ob = base->object;
34
35                 f(ob);
36
37                 base= base->next;
38         }
39 }
40
41 void AnimationExporter::exportAnimations(Scene *sce)
42 {
43         if(hasAnimations(sce)) {
44                 this->scene = sce;
45
46                 openLibrary();
47
48                 forEachObjectInScene(sce, *this);
49
50                 closeLibrary();
51         }
52 }
53
54 // called for each exported object
55 void AnimationExporter::operator() (Object *ob) 
56 {
57         FCurve *fcu;
58         char * transformName ;
59         /* bool isMatAnim = false; */ /* UNUSED */
60
61         //Export transform animations
62         if(ob->adt && ob->adt->action)
63         {
64                 fcu = (FCurve*)ob->adt->action->curves.first;
65
66                 //transform matrix export for bones are temporarily disabled here.
67                 if ( ob->type == OB_ARMATURE )
68                 {
69                         bArmature *arm = (bArmature*)ob->data;
70                         for (Bone *bone = (Bone*)arm->bonebase.first; bone; bone = bone->next)
71                                 write_bone_animation_matrix(ob, bone);
72                 }
73
74                 while (fcu) {
75                         //for armature animations as objects
76                         if ( ob->type == OB_ARMATURE )
77                                 transformName =  fcu->rna_path;
78                         else 
79                                 transformName = extract_transform_name( fcu->rna_path );
80
81                         if ((!strcmp(transformName, "location") || !strcmp(transformName, "scale")) ||
82                                 (!strcmp(transformName, "rotation_euler") && ob->rotmode == ROT_MODE_EUL)||
83                                 (!strcmp(transformName, "rotation_quaternion"))) 
84                                 dae_animation(ob ,fcu, transformName, false);
85                         fcu = fcu->next;
86                 }
87
88         }
89
90         //Export Lamp parameter animations
91         if( (ob->type == OB_LAMP ) && ((Lamp*)ob ->data)->adt && ((Lamp*)ob ->data)->adt->action )
92         {
93                 fcu = (FCurve*)(((Lamp*)ob ->data)->adt->action->curves.first);
94                 while (fcu) {
95                         transformName = extract_transform_name( fcu->rna_path );
96
97                         if ((!strcmp(transformName, "color")) || (!strcmp(transformName, "spot_size"))|| (!strcmp(transformName, "spot_blend"))||
98                                 (!strcmp(transformName, "distance")) ) 
99                                 dae_animation(ob , fcu, transformName, true );
100                         fcu = fcu->next;
101                 }
102         }
103
104         //Export Camera parameter animations
105         if( (ob->type == OB_CAMERA ) && ((Camera*)ob ->data)->adt && ((Camera*)ob ->data)->adt->action )
106         {               
107                 fcu = (FCurve*)(((Camera*)ob ->data)->adt->action->curves.first);
108                 while (fcu) {
109                         transformName = extract_transform_name( fcu->rna_path );
110
111                         if ((!strcmp(transformName, "lens"))||
112                                 (!strcmp(transformName, "ortho_scale"))||
113                                 (!strcmp(transformName, "clip_end"))||(!strcmp(transformName, "clip_start"))) 
114                                 dae_animation(ob , fcu, transformName, true );
115                         fcu = fcu->next;
116                 }
117         }
118
119         //Export Material parameter animations.
120         for(int a = 0; a < ob->totcol; a++)
121         {
122                 Material *ma = give_current_material(ob, a+1);
123                 if (!ma) continue;
124                 if(ma->adt && ma->adt->action)
125                 {
126                         /* isMatAnim = true; */
127                         fcu = (FCurve*)ma->adt->action->curves.first;
128                         while (fcu) {
129                                 transformName = extract_transform_name( fcu->rna_path );
130
131                                 if ((!strcmp(transformName, "specular_hardness"))||(!strcmp(transformName, "specular_color"))
132                                         ||(!strcmp(transformName, "diffuse_color"))||(!strcmp(transformName, "alpha"))||
133                                         (!strcmp(transformName, "ior"))) 
134                                         dae_animation(ob ,fcu, transformName, true, ma );
135                                 fcu = fcu->next;
136                         }
137                 }
138
139         }
140 }
141
142 //euler sources from quternion sources
143 float * AnimationExporter::get_eul_source_for_quat(Object *ob )
144 {
145         FCurve *fcu = (FCurve*)ob->adt->action->curves.first;
146         const int keys = fcu->totvert;  
147         float *quat = (float*)MEM_callocN(sizeof(float) * fcu->totvert * 4, "quat output source values");  
148         float *eul = (float*)MEM_callocN(sizeof(float) * fcu->totvert * 3, "quat output source values");
149         float temp_quat[4];
150         float temp_eul[3];
151         while(fcu)
152         {
153                 char * transformName = extract_transform_name( fcu->rna_path );
154
155                 if( !strcmp(transformName, "rotation_quaternion") )     { 
156                         for ( int i = 0 ; i < fcu->totvert ; i++){
157                                 *(quat + ( i * 4 ) + fcu->array_index) = fcu->bezt[i].vec[1][1];
158                         }
159                 }
160                 fcu = fcu->next;
161         }
162
163         for ( int i = 0 ; i < keys ; i++){
164                 for ( int j = 0;j<4;j++)
165                         temp_quat[j] = quat[(i*4)+j];
166
167                 quat_to_eul(temp_eul,temp_quat);
168
169                 for (int k = 0;k<3;k++)
170                         eul[i*3 + k] = temp_eul[k];
171
172         }
173         MEM_freeN(quat);
174         return eul;
175
176 }
177
178 //Get proper name for bones
179 std::string AnimationExporter::getObjectBoneName( Object* ob,const FCurve* fcu ) 
180 {
181         //hard-way to derive the bone name from rna_path. Must find more compact method
182         std::string rna_path = std::string(fcu->rna_path);
183
184         char* boneName = strtok((char *)rna_path.c_str(), "\"");
185         boneName = strtok(NULL,"\"");
186
187         if( boneName != NULL )
188                 return /*id_name(ob) + "_" +*/ std::string(boneName);
189         else            
190                 return id_name(ob);
191 }
192
193 //convert f-curves to animation curves and write
194 void AnimationExporter::dae_animation(Object* ob, FCurve *fcu, char* transformName , bool is_param, Material * ma )
195 {
196         const char *axis_name = NULL;
197         char anim_id[200];
198
199         bool has_tangents = false;
200         bool quatRotation = false;
201
202         if ( !strcmp(transformName, "rotation_quaternion") )
203         {
204                 fprintf(stderr, "quaternion rotation curves are not supported. rotation curve will not be exported\n");
205                 quatRotation = true;
206                 return;
207         }
208
209         //axis names for colors
210         else if ( !strcmp(transformName, "color")||!strcmp(transformName, "specular_color")||!strcmp(transformName, "diffuse_color")||
211                 (!strcmp(transformName, "alpha")))
212         {
213                 const char *axis_names[] = {"R", "G", "B"};
214                 if (fcu->array_index < 3)
215                         axis_name = axis_names[fcu->array_index];
216         }
217
218         //axis names for transforms
219         else if ((!strcmp(transformName, "location") || !strcmp(transformName, "scale")) ||
220                 (!strcmp(transformName, "rotation_euler"))||(!strcmp(transformName, "rotation_quaternion")))
221         {
222                 const char *axis_names[] = {"X", "Y", "Z"};
223                 if (fcu->array_index < 3)
224                         axis_name = axis_names[fcu->array_index];
225         }
226
227         //no axis name. single parameter.
228         else{
229                 axis_name = "";
230         }
231
232         std::string ob_name = std::string("null");
233
234         //Create anim Id
235         if (ob->type == OB_ARMATURE) 
236         {   
237                 ob_name =  getObjectBoneName( ob , fcu);
238                 BLI_snprintf(anim_id, sizeof(anim_id), "%s_%s.%s", (char*)translate_id(ob_name).c_str(),
239                         transformName, axis_name);
240         }
241         else 
242         {
243                 if (ma)
244                         ob_name = id_name(ob) + "_material";
245                 else
246                         ob_name = id_name(ob);
247                 BLI_snprintf(anim_id, sizeof(anim_id), "%s_%s_%s", (char*)translate_id(ob_name).c_str(),
248                         fcu->rna_path, axis_name);
249         }
250
251         openAnimation(anim_id, COLLADABU::Utils::EMPTY_STRING);
252
253         // create input source
254         std::string input_id = create_source_from_fcurve(COLLADASW::InputSemantic::INPUT, fcu, anim_id, axis_name);
255
256         // create output source
257         std::string output_id ;
258
259         //quat rotations are skipped for now, because of complications with determining axis.
260         if(quatRotation) 
261         {
262                 float * eul  = get_eul_source_for_quat(ob);
263                 float * eul_axis = (float*)MEM_callocN(sizeof(float) * fcu->totvert, "quat output source values");
264                 for ( int i = 0 ; i< fcu->totvert ; i++)
265                         eul_axis[i] = eul[i*3 + fcu->array_index];
266                 output_id= create_source_from_array(COLLADASW::InputSemantic::OUTPUT, eul_axis , fcu->totvert, quatRotation, anim_id, axis_name);
267                 MEM_freeN(eul);
268                 MEM_freeN(eul_axis);
269         }
270         else 
271         {
272                 output_id= create_source_from_fcurve(COLLADASW::InputSemantic::OUTPUT, fcu, anim_id, axis_name);
273         }
274         // create interpolations source
275         std::string interpolation_id = create_interpolation_source(fcu, anim_id, axis_name, &has_tangents);
276
277         // handle tangents (if required)
278         std::string intangent_id;
279         std::string outtangent_id;
280
281         if (has_tangents) {
282                 // create in_tangent source
283                 intangent_id = create_source_from_fcurve(COLLADASW::InputSemantic::IN_TANGENT, fcu, anim_id, axis_name);
284
285                 // create out_tangent source
286                 outtangent_id = create_source_from_fcurve(COLLADASW::InputSemantic::OUT_TANGENT, fcu, anim_id, axis_name);
287         }
288
289         std::string sampler_id = std::string(anim_id) + SAMPLER_ID_SUFFIX;
290         COLLADASW::LibraryAnimations::Sampler sampler(sw, sampler_id);
291         std::string empty;
292         sampler.addInput(COLLADASW::InputSemantic::INPUT, COLLADABU::URI(empty, input_id));
293         sampler.addInput(COLLADASW::InputSemantic::OUTPUT, COLLADABU::URI(empty, output_id));
294
295         // this input is required
296         sampler.addInput(COLLADASW::InputSemantic::INTERPOLATION, COLLADABU::URI(empty, interpolation_id));
297
298         if (has_tangents) {
299                 sampler.addInput(COLLADASW::InputSemantic::IN_TANGENT, COLLADABU::URI(empty, intangent_id));
300                 sampler.addInput(COLLADASW::InputSemantic::OUT_TANGENT, COLLADABU::URI(empty, outtangent_id));
301         }
302
303         addSampler(sampler);
304
305         std::string target ;
306
307         if ( !is_param )
308                 target = translate_id(ob_name)
309                 + "/" + get_transform_sid(fcu->rna_path, -1, axis_name, true);
310         else 
311         {
312                 if ( ob->type == OB_LAMP )
313                         target = get_light_id(ob)
314                         + "/" + get_light_param_sid(fcu->rna_path, -1, axis_name, true);
315
316                 if ( ob->type == OB_CAMERA )
317                         target = get_camera_id(ob)
318                         + "/" + get_camera_param_sid(fcu->rna_path, -1, axis_name, true);
319
320                 if( ma ) 
321                         target = translate_id(id_name(ma)) + "-effect"
322                         +"/common/" /*profile common is only supported */ + get_transform_sid(fcu->rna_path, -1, axis_name, true);
323         }
324         addChannel(COLLADABU::URI(empty, sampler_id), target);
325
326         closeAnimation();
327 }
328
329
330
331 //write bone animations in transform matrix sources
332 void AnimationExporter::write_bone_animation_matrix(Object *ob_arm, Bone *bone)
333 {
334         if (!ob_arm->adt)
335                 return;
336
337         //This will only export animations of bones in deform group.
338         /*if(!is_bone_deform_group(bone))
339         return;*/
340
341         sample_and_write_bone_animation_matrix(ob_arm, bone);
342
343         for (Bone *child = (Bone*)bone->childbase.first; child; child = child->next)
344                 write_bone_animation_matrix(ob_arm, child);
345 }
346
347 bool AnimationExporter::is_bone_deform_group(Bone * bone)
348 {   
349         bool is_def;
350         //Check if current bone is deform
351         if((bone->flag & BONE_NO_DEFORM) == 0 ) return true;
352         //Check child bones
353         else 
354         {   
355                 for (Bone *child = (Bone*)bone->childbase.first; child; child = child->next){
356                         //loop through all the children until deform bone is found, and then return
357                         is_def = is_bone_deform_group(child);
358                         if (is_def) return true;
359                 }
360         }
361         //no deform bone found in children also
362         return false;
363 }
364
365 void AnimationExporter::sample_and_write_bone_animation_matrix(Object *ob_arm, Bone *bone)
366 {
367         bArmature *arm = (bArmature*)ob_arm->data;
368         int flag = arm->flag;
369         std::vector<float> fra;
370         //char prefix[256];
371
372         FCurve* fcu = (FCurve*)ob_arm->adt->action->curves.first;
373         while(fcu)
374         {
375                 std::string bone_name = getObjectBoneName(ob_arm,fcu);
376                 int val = BLI_strcasecmp((char*)bone_name.c_str(),bone->name);
377                 if(val==0) break;
378                 fcu = fcu->next;
379         }
380
381         if(!(fcu)) return; 
382         bPoseChannel *pchan = get_pose_channel(ob_arm->pose, bone->name);
383         if (!pchan)
384                 return;
385
386         find_frames(ob_arm, fra);
387
388         if (flag & ARM_RESTPOS) {
389                 arm->flag &= ~ARM_RESTPOS;
390                 where_is_pose(scene, ob_arm);
391         }
392
393         if (fra.size()) {
394                 dae_baked_animation(fra ,ob_arm, bone );
395         }
396
397         if (flag & ARM_RESTPOS) 
398                 arm->flag = flag;
399         where_is_pose(scene, ob_arm);
400 }
401
402 void AnimationExporter::dae_baked_animation(std::vector<float> &fra, Object *ob_arm , Bone *bone)
403 {
404         std::string ob_name = id_name(ob_arm);
405         std::string bone_name = bone->name;
406         char anim_id[200];
407
408         if (!fra.size())
409                 return;
410
411         BLI_snprintf(anim_id, sizeof(anim_id), "%s_%s_%s", (char*)translate_id(ob_name).c_str(),
412                 (char*)translate_id(bone_name).c_str(), "pose_matrix");
413
414         openAnimation(anim_id, COLLADABU::Utils::EMPTY_STRING);
415
416         // create input source
417         std::string input_id = create_source_from_vector(COLLADASW::InputSemantic::INPUT, fra, false, anim_id, "");
418
419         // create output source
420         std::string output_id;
421         output_id = create_4x4_source( fra, ob_arm , bone ,  anim_id);
422
423         // create interpolations source
424         std::string interpolation_id = fake_interpolation_source(fra.size(), anim_id, "");
425
426         std::string sampler_id = std::string(anim_id) + SAMPLER_ID_SUFFIX;
427         COLLADASW::LibraryAnimations::Sampler sampler(sw, sampler_id);
428         std::string empty;
429         sampler.addInput(COLLADASW::InputSemantic::INPUT, COLLADABU::URI(empty, input_id));
430         sampler.addInput(COLLADASW::InputSemantic::OUTPUT, COLLADABU::URI(empty, output_id));
431
432         // TODO create in/out tangents source
433
434         // this input is required
435         sampler.addInput(COLLADASW::InputSemantic::INTERPOLATION, COLLADABU::URI(empty, interpolation_id));
436
437         addSampler(sampler);
438
439         std::string target = translate_id(bone_name) + "/transform";
440         addChannel(COLLADABU::URI(empty, sampler_id), target);
441
442         closeAnimation();
443 }
444
445 // dae_bone_animation -> add_bone_animation
446 // (blend this into dae_bone_animation)
447 void AnimationExporter::dae_bone_animation(std::vector<float> &fra, float *values, int tm_type, int axis, std::string ob_name, std::string bone_name)
448 {
449         const char *axis_names[] = {"X", "Y", "Z"};
450         const char *axis_name = NULL;
451         char anim_id[200];
452         bool is_rot = tm_type == 0;
453
454         if (!fra.size())
455                 return;
456
457         char rna_path[200];
458         BLI_snprintf(rna_path, sizeof(rna_path), "pose.bones[\"%s\"].%s", bone_name.c_str(),
459                 tm_type == 0 ? "rotation_quaternion" : (tm_type == 1 ? "scale" : "location"));
460
461         if (axis > -1)
462                 axis_name = axis_names[axis];
463
464         std::string transform_sid = get_transform_sid(NULL, tm_type, axis_name, false);
465
466         BLI_snprintf(anim_id, sizeof(anim_id), "%s_%s_%s", (char*)translate_id(ob_name).c_str(),
467                 (char*)translate_id(bone_name).c_str(), (char*)transform_sid.c_str());
468
469         openAnimation(anim_id, COLLADABU::Utils::EMPTY_STRING);
470
471         // create input source
472         std::string input_id = create_source_from_vector(COLLADASW::InputSemantic::INPUT, fra, is_rot, anim_id, axis_name);
473
474         // create output source
475         std::string output_id;
476         if (axis == -1)
477                 output_id = create_xyz_source(values, fra.size(), anim_id);
478         else
479                 output_id = create_source_from_array(COLLADASW::InputSemantic::OUTPUT, values, fra.size(), is_rot, anim_id, axis_name);
480
481         // create interpolations source
482         std::string interpolation_id = fake_interpolation_source(fra.size(), anim_id, axis_name);
483
484         std::string sampler_id = std::string(anim_id) + SAMPLER_ID_SUFFIX;
485         COLLADASW::LibraryAnimations::Sampler sampler(sw, sampler_id);
486         std::string empty;
487         sampler.addInput(COLLADASW::InputSemantic::INPUT, COLLADABU::URI(empty, input_id));
488         sampler.addInput(COLLADASW::InputSemantic::OUTPUT, COLLADABU::URI(empty, output_id));
489
490         // TODO create in/out tangents source
491
492         // this input is required
493         sampler.addInput(COLLADASW::InputSemantic::INTERPOLATION, COLLADABU::URI(empty, interpolation_id));
494
495         addSampler(sampler);
496
497         std::string target = translate_id(ob_name + "_" + bone_name) + "/" + transform_sid;
498         addChannel(COLLADABU::URI(empty, sampler_id), target);
499
500         closeAnimation();
501 }
502
503 float AnimationExporter::convert_time(float frame)
504 {
505         return FRA2TIME(frame);
506 }
507
508 float AnimationExporter::convert_angle(float angle)
509 {
510         return COLLADABU::Math::Utils::radToDegF(angle);
511 }
512
513 std::string AnimationExporter::get_semantic_suffix(COLLADASW::InputSemantic::Semantics semantic)
514 {
515         switch(semantic) {
516                 case COLLADASW::InputSemantic::INPUT:
517                         return INPUT_SOURCE_ID_SUFFIX;
518                 case COLLADASW::InputSemantic::OUTPUT:
519                         return OUTPUT_SOURCE_ID_SUFFIX;
520                 case COLLADASW::InputSemantic::INTERPOLATION:
521                         return INTERPOLATION_SOURCE_ID_SUFFIX;
522                 case COLLADASW::InputSemantic::IN_TANGENT:
523                         return INTANGENT_SOURCE_ID_SUFFIX;
524                 case COLLADASW::InputSemantic::OUT_TANGENT:
525                         return OUTTANGENT_SOURCE_ID_SUFFIX;
526                 default:
527                         break;
528         }
529         return "";
530 }
531
532 void AnimationExporter::add_source_parameters(COLLADASW::SourceBase::ParameterNameList& param,
533                                                                                           COLLADASW::InputSemantic::Semantics semantic, bool is_rot, const char *axis, bool transform)
534 {
535         switch(semantic) {
536                 case COLLADASW::InputSemantic::INPUT:
537                         param.push_back("TIME");
538                         break;
539                 case COLLADASW::InputSemantic::OUTPUT:
540                         if (is_rot) {
541                                 param.push_back("ANGLE");
542                         }
543                         else {
544                                 if (axis) {
545                                         param.push_back(axis);
546                                 }
547                                 else 
548                                         if ( transform )
549                                         {
550                                                 param.push_back("TRANSFORM");  
551                                         }else{ //assumes if axis isn't specified all axises are added
552                                                 param.push_back("X");
553                                                 param.push_back("Y");
554                                                 param.push_back("Z");
555                                         }
556                         }
557                         break;
558                 case COLLADASW::InputSemantic::IN_TANGENT:
559                 case COLLADASW::InputSemantic::OUT_TANGENT:
560                         param.push_back("X");
561                         param.push_back("Y");
562                         break;
563                 default:
564                         break;
565         }
566 }
567
568 void AnimationExporter::get_source_values(BezTriple *bezt, COLLADASW::InputSemantic::Semantics semantic, bool rotation, float *values, int *length)
569 {
570         switch (semantic) {
571                 case COLLADASW::InputSemantic::INPUT:
572                         *length = 1;
573                         values[0] = convert_time(bezt->vec[1][0]);
574                         break;
575                 case COLLADASW::InputSemantic::OUTPUT:
576                         *length = 1;
577                         if (rotation) {
578                                 values[0] = RAD2DEGF(bezt->vec[1][1]);
579                         }
580                         else {
581                                 values[0] = bezt->vec[1][1];
582                         }
583                         break;
584
585                 case COLLADASW::InputSemantic::IN_TANGENT:
586                         *length = 2;
587                         values[0] = convert_time(bezt->vec[0][0]);
588                         if (bezt->ipo != BEZT_IPO_BEZ) {
589                                 // We're in a mixed interpolation scenario, set zero as it's irrelevant but value might contain unused data
590                                 values[0] = 0;  
591                                 values[1] = 0;  
592                         }
593                         else if (rotation) {
594                                 values[1] = RAD2DEGF(bezt->vec[0][1]);
595                         } else {
596                                 values[1] = bezt->vec[0][1];
597                         }
598                         break;
599
600                 case COLLADASW::InputSemantic::OUT_TANGENT:
601                         *length = 2;
602                         values[0] = convert_time(bezt->vec[2][0]);
603                         if (bezt->ipo != BEZT_IPO_BEZ) {
604                                 // We're in a mixed interpolation scenario, set zero as it's irrelevant but value might contain unused data
605                                 values[0] = 0;  
606                                 values[1] = 0;  
607                         }
608                         else if (rotation) {
609                                 values[1] = RAD2DEGF(bezt->vec[2][1]);
610                         } else {
611                                 values[1] = bezt->vec[2][1];
612                         }
613                         break;
614                         break;
615                 default:
616                         *length = 0;
617                         break;
618         }
619 }
620
621 std::string AnimationExporter::create_source_from_fcurve(COLLADASW::InputSemantic::Semantics semantic, FCurve *fcu, const std::string& anim_id, const char *axis_name)
622 {
623         std::string source_id = anim_id + get_semantic_suffix(semantic);
624
625         //bool is_rotation = !strcmp(fcu->rna_path, "rotation");
626         bool is_angle = false;
627
628         if (strstr(fcu->rna_path, "rotation")) is_angle = true;
629
630         COLLADASW::FloatSourceF source(mSW);
631         source.setId(source_id);
632         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
633         source.setAccessorCount(fcu->totvert);
634
635         switch (semantic) {
636                 case COLLADASW::InputSemantic::INPUT:
637                 case COLLADASW::InputSemantic::OUTPUT:
638                         source.setAccessorStride(1);                    
639                         break;
640                 case COLLADASW::InputSemantic::IN_TANGENT:
641                 case COLLADASW::InputSemantic::OUT_TANGENT:
642                         source.setAccessorStride(2);                    
643                         break;
644                 default:
645                         break;
646         }
647
648
649         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
650         add_source_parameters(param, semantic, is_angle, axis_name, false);
651
652         source.prepareToAppendValues();
653
654         for (unsigned int i = 0; i < fcu->totvert; i++) {
655                 float values[3]; // be careful!
656                 int length = 0;
657                 get_source_values(&fcu->bezt[i], semantic, is_angle, values, &length);
658                 for (int j = 0; j < length; j++)
659                         source.appendValues(values[j]);
660         }
661
662         source.finish();
663
664         return source_id;
665 }
666
667 //Currently called only to get OUTPUT source values ( if rotation and hence the axis is also specified )
668 std::string AnimationExporter::create_source_from_array(COLLADASW::InputSemantic::Semantics semantic, float *v, int tot, bool is_rot, const std::string& anim_id, const char *axis_name)
669 {
670         std::string source_id = anim_id + get_semantic_suffix(semantic);
671
672         COLLADASW::FloatSourceF source(mSW);
673         source.setId(source_id);
674         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
675         source.setAccessorCount(tot);
676         source.setAccessorStride(1);
677
678         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
679         add_source_parameters(param, semantic, is_rot, axis_name,  false);
680
681         source.prepareToAppendValues();
682
683         for (int i = 0; i < tot; i++) {
684                 float val = v[i];
685                 ////if (semantic == COLLADASW::InputSemantic::INPUT)
686                 //      val = convert_time(val);
687                 //else
688                 if (is_rot)
689                         val = RAD2DEGF(val);
690                 source.appendValues(val);
691         }
692
693         source.finish();
694
695         return source_id;
696 }
697 // only used for sources with INPUT semantic
698 std::string AnimationExporter::create_source_from_vector(COLLADASW::InputSemantic::Semantics semantic, std::vector<float> &fra, bool is_rot, const std::string& anim_id, const char *axis_name)
699 {
700         std::string source_id = anim_id + get_semantic_suffix(semantic);
701
702         COLLADASW::FloatSourceF source(mSW);
703         source.setId(source_id);
704         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
705         source.setAccessorCount(fra.size());
706         source.setAccessorStride(1);
707
708         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
709         add_source_parameters(param, semantic, is_rot, axis_name, false);
710
711         source.prepareToAppendValues();
712
713         std::vector<float>::iterator it;
714         for (it = fra.begin(); it != fra.end(); it++) {
715                 float val = *it;
716                 //if (semantic == COLLADASW::InputSemantic::INPUT)
717                 val = convert_time(val);
718                 /*else if (is_rot)
719                 val = convert_angle(val);*/
720                 source.appendValues(val);
721         }
722
723         source.finish();
724
725         return source_id;
726 }
727
728 std::string AnimationExporter::create_4x4_source(std::vector<float> &frames , Object * ob_arm, Bone *bone , const std::string& anim_id)
729 {
730         COLLADASW::InputSemantic::Semantics semantic = COLLADASW::InputSemantic::OUTPUT;
731         std::string source_id = anim_id + get_semantic_suffix(semantic);
732
733         COLLADASW::Float4x4Source source(mSW);
734         source.setId(source_id);
735         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
736         source.setAccessorCount(frames.size());
737         source.setAccessorStride(16);
738
739         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
740         add_source_parameters(param, semantic, false, NULL, true);
741
742         source.prepareToAppendValues();
743
744         bPoseChannel *parchan = NULL;
745         bPoseChannel *pchan = NULL;
746         bPose *pose = ob_arm->pose;
747
748         pchan = get_pose_channel(pose, bone->name);
749
750         if (!pchan)
751                 return "";
752
753         parchan = pchan->parent;
754
755         enable_fcurves(ob_arm->adt->action, bone->name);
756
757         std::vector<float>::iterator it;
758         int j = 0;
759         for (it = frames.begin(); it != frames.end(); it++) {
760                 float mat[4][4], ipar[4][4];
761
762                 float ctime = BKE_frame_to_ctime(scene, *it);
763
764                 BKE_animsys_evaluate_animdata(scene , &ob_arm->id, ob_arm->adt, ctime, ADT_RECALC_ANIM);
765                 where_is_pose_bone(scene, ob_arm, pchan, ctime, 1);
766
767                 // compute bone local mat
768                 if (bone->parent) {
769                         invert_m4_m4(ipar, parchan->pose_mat);
770                         mul_m4_m4m4(mat, pchan->pose_mat, ipar);
771                 }
772                 else
773                         copy_m4_m4(mat, pchan->pose_mat);
774                 UnitConverter converter;
775
776                 float outmat[4][4];
777                 converter.mat4_to_dae(outmat,mat);
778
779
780                 source.appendValues(outmat);
781
782
783                 j++;
784         }
785
786         enable_fcurves(ob_arm->adt->action, NULL);
787
788         source.finish();
789
790         return source_id;
791 }
792 // only used for sources with OUTPUT semantic ( locations and scale)
793 std::string AnimationExporter::create_xyz_source(float *v, int tot, const std::string& anim_id)
794 {
795         COLLADASW::InputSemantic::Semantics semantic = COLLADASW::InputSemantic::OUTPUT;
796         std::string source_id = anim_id + get_semantic_suffix(semantic);
797
798         COLLADASW::FloatSourceF source(mSW);
799         source.setId(source_id);
800         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
801         source.setAccessorCount(tot);
802         source.setAccessorStride(3);
803
804         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
805         add_source_parameters(param, semantic, false, NULL, false);
806
807         source.prepareToAppendValues();
808
809         for (int i = 0; i < tot; i++) {
810                 source.appendValues(*v, *(v + 1), *(v + 2));
811                 v += 3;
812         }
813
814         source.finish();
815
816         return source_id;
817 }
818
819 std::string AnimationExporter::create_interpolation_source(FCurve *fcu, const std::string& anim_id, const char *axis_name, bool *has_tangents)
820 {
821         std::string source_id = anim_id + get_semantic_suffix(COLLADASW::InputSemantic::INTERPOLATION);
822
823         COLLADASW::NameSource source(mSW);
824         source.setId(source_id);
825         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
826         source.setAccessorCount(fcu->totvert);
827         source.setAccessorStride(1);
828
829         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
830         param.push_back("INTERPOLATION");
831
832         source.prepareToAppendValues();
833
834         *has_tangents = false;
835
836         for (unsigned int i = 0; i < fcu->totvert; i++) {
837                 if (fcu->bezt[i].ipo==BEZT_IPO_BEZ) {
838                         source.appendValues(BEZIER_NAME);
839                         *has_tangents = true;
840                 } else if (fcu->bezt[i].ipo==BEZT_IPO_CONST) {
841                         source.appendValues(STEP_NAME);
842                 } else { // BEZT_IPO_LIN
843                         source.appendValues(LINEAR_NAME);
844                 }
845         }
846         // unsupported? -- HERMITE, CARDINAL, BSPLINE, NURBS
847
848         source.finish();
849
850         return source_id;
851 }
852
853 std::string AnimationExporter::fake_interpolation_source(int tot, const std::string& anim_id, const char *axis_name)
854 {
855         std::string source_id = anim_id + get_semantic_suffix(COLLADASW::InputSemantic::INTERPOLATION);
856
857         COLLADASW::NameSource source(mSW);
858         source.setId(source_id);
859         source.setArrayId(source_id + ARRAY_ID_SUFFIX);
860         source.setAccessorCount(tot);
861         source.setAccessorStride(1);
862
863         COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
864         param.push_back("INTERPOLATION");
865
866         source.prepareToAppendValues();
867
868         for (int i = 0; i < tot; i++) {
869                 source.appendValues(LINEAR_NAME);
870         }
871
872         source.finish();
873
874         return source_id;
875 }
876
877 std::string AnimationExporter::get_light_param_sid(char *rna_path, int tm_type, const char *axis_name, bool append_axis)
878 {
879         std::string tm_name;
880         // when given rna_path, determine tm_type from it
881         if (rna_path) {
882                 char *name = extract_transform_name(rna_path);
883
884                 if (!strcmp(name, "color"))
885                         tm_type = 1;
886                 else if (!strcmp(name, "spot_size"))
887                         tm_type = 2;
888                 else if (!strcmp(name, "spot_blend"))
889                         tm_type = 3;
890                 else if (!strcmp(name, "distance"))
891                         tm_type = 4;
892                 else
893                         tm_type = -1;
894         }
895
896         switch (tm_type) {
897                 case 1:
898                         tm_name = "color";
899                         break;
900                 case 2:
901                         tm_name = "fall_off_angle";
902                         break;
903                 case 3:
904                         tm_name = "fall_off_exponent";
905                         break;
906                 case 4:
907                         tm_name = "blender/blender_dist";
908                         break;
909
910                 default:
911                         tm_name = "";
912                         break;
913         }
914
915         if (tm_name.size()) {
916                 if (axis_name[0])
917                         return tm_name + "." + std::string(axis_name);
918                 else 
919                         return tm_name;
920         }
921
922         return std::string("");
923 }
924
925 std::string AnimationExporter::get_camera_param_sid(char *rna_path, int tm_type, const char *axis_name, bool append_axis)
926 {
927         std::string tm_name;
928         // when given rna_path, determine tm_type from it
929         if (rna_path) {
930                 char *name = extract_transform_name(rna_path);
931
932                 if (!strcmp(name, "lens"))
933                         tm_type = 0;
934                 else if (!strcmp(name, "ortho_scale"))
935                         tm_type = 1;
936                 else if (!strcmp(name, "clip_end"))
937                         tm_type = 2;
938                 else if (!strcmp(name, "clip_start"))
939                         tm_type = 3;
940
941                 else
942                         tm_type = -1;
943         }
944
945         switch (tm_type) {
946                 case 0:
947                         tm_name = "xfov";
948                         break;
949                 case 1:
950                         tm_name = "xmag";
951                         break;
952                 case 2:
953                         tm_name = "zfar";
954                         break;
955                 case 3:
956                         tm_name = "znear";
957                         break;
958
959                 default:
960                         tm_name = "";
961                         break;
962         }
963
964         if (tm_name.size()) {
965                 if (axis_name[0])
966                         return tm_name + "." + std::string(axis_name);
967                 else 
968                         return tm_name;
969         }
970
971         return std::string("");
972 }
973
974 // Assign sid of the animated parameter or transform 
975 // for rotation, axis name is always appended and the value of append_axis is ignored
976 std::string AnimationExporter::get_transform_sid(char *rna_path, int tm_type, const char *axis_name, bool append_axis)
977 {
978         std::string tm_name;
979         bool is_rotation =false;
980         // when given rna_path, determine tm_type from it
981         if (rna_path) {
982                 char *name = extract_transform_name(rna_path);
983
984                 if (!strcmp(name, "rotation_euler"))
985                         tm_type = 0;
986                 else if (!strcmp(name, "rotation_quaternion"))
987                         tm_type = 1;
988                 else if (!strcmp(name, "scale"))
989                         tm_type = 2;
990                 else if (!strcmp(name, "location"))
991                         tm_type = 3;
992                 else if (!strcmp(name, "specular_hardness"))
993                         tm_type = 4;
994                 else if (!strcmp(name, "specular_color"))
995                         tm_type = 5;
996                 else if (!strcmp(name, "diffuse_color"))
997                         tm_type = 6;
998                 else if (!strcmp(name, "alpha"))
999                         tm_type = 7;
1000                 else if (!strcmp(name, "ior"))
1001                         tm_type = 8;
1002
1003                 else
1004                         tm_type = -1;
1005         }
1006
1007         switch (tm_type) {
1008                 case 0:
1009                 case 1:
1010                         tm_name = "rotation";
1011                         is_rotation = true;
1012                         break;
1013                 case 2:
1014                         tm_name = "scale";
1015                         break;
1016                 case 3:
1017                         tm_name = "location";
1018                         break;
1019                 case 4:
1020                         tm_name = "shininess";
1021                         break;
1022                 case 5:
1023                         tm_name = "specular";
1024                         break;
1025                 case 6:
1026                         tm_name = "diffuse";
1027                         break;  
1028                 case 7:
1029                         tm_name = "transparency";
1030                         break;  
1031                 case 8:
1032                         tm_name = "index_of_refraction";
1033                         break;  
1034
1035                 default:
1036                         tm_name = "";
1037                         break;
1038         }
1039
1040         if (tm_name.size()) {
1041                 if (is_rotation)
1042                         return tm_name + std::string(axis_name) + ".ANGLE";
1043                 else
1044                         if (axis_name[0])
1045                                 return tm_name + "." + std::string(axis_name);
1046                         else 
1047                                 return tm_name;
1048         }
1049
1050         return std::string("");
1051 }
1052
1053 char* AnimationExporter::extract_transform_name(char *rna_path)
1054 {
1055         char *dot = strrchr(rna_path, '.');
1056         return dot ? (dot + 1) : rna_path;
1057 }
1058
1059 //find keyframes of all the objects animations
1060 void AnimationExporter::find_frames(Object *ob, std::vector<float> &fra)
1061 {
1062         FCurve *fcu= (FCurve*)ob->adt->action->curves.first;
1063
1064         for (; fcu; fcu = fcu->next) {
1065
1066                 for (unsigned int i = 0; i < fcu->totvert; i++) {
1067                         float f = fcu->bezt[i].vec[1][0];
1068                         if (std::find(fra.begin(), fra.end(), f) == fra.end())   
1069                                 fra.push_back(f);
1070                 }
1071         }
1072
1073         // keep the keys in ascending order
1074         std::sort(fra.begin(), fra.end());
1075 }
1076
1077
1078
1079 // enable fcurves driving a specific bone, disable all the rest
1080 // if bone_name = NULL enable all fcurves
1081 void AnimationExporter::enable_fcurves(bAction *act, char *bone_name)
1082 {
1083         FCurve *fcu;
1084         char prefix[200];
1085
1086         if (bone_name)
1087                 BLI_snprintf(prefix, sizeof(prefix), "pose.bones[\"%s\"]", bone_name);
1088
1089         for (fcu = (FCurve*)act->curves.first; fcu; fcu = fcu->next) {
1090                 if (bone_name) {
1091                         if (!strncmp(fcu->rna_path, prefix, strlen(prefix)))
1092                                 fcu->flag &= ~FCURVE_DISABLED;
1093                         else
1094                                 fcu->flag |= FCURVE_DISABLED;
1095                 }
1096                 else {
1097                         fcu->flag &= ~FCURVE_DISABLED;
1098                 }
1099         }
1100 }
1101
1102 bool AnimationExporter::hasAnimations(Scene *sce)
1103 {
1104         Base *base= (Base*) sce->base.first;
1105
1106         while(base) {
1107                 Object *ob = base->object;
1108
1109                 FCurve *fcu = 0;
1110                 //Check for object transform animations
1111                 if(ob->adt && ob->adt->action)
1112                         fcu = (FCurve*)ob->adt->action->curves.first;
1113                 //Check for Lamp parameter animations
1114                 else if( (ob->type == OB_LAMP ) && ((Lamp*)ob ->data)->adt && ((Lamp*)ob ->data)->adt->action )
1115                         fcu = (FCurve*)(((Lamp*)ob ->data)->adt->action->curves.first);
1116                 //Check for Camera parameter animations
1117                 else if( (ob->type == OB_CAMERA ) && ((Camera*)ob ->data)->adt && ((Camera*)ob ->data)->adt->action )
1118                         fcu = (FCurve*)(((Camera*)ob ->data)->adt->action->curves.first);
1119
1120                 //Check Material Effect parameter animations.
1121                 for(int a = 0; a < ob->totcol; a++)
1122                 {
1123                         Material *ma = give_current_material(ob, a+1);
1124                         if (!ma) continue;
1125                         if(ma->adt && ma->adt->action)
1126                         {
1127                                 fcu = (FCurve*)ma->adt->action->curves.first;   
1128                         }
1129                 }
1130
1131                 if ( fcu) 
1132                         return true;
1133                 base= base->next;
1134         }
1135         return false;
1136 }
1137
1138 //------------------------------- Not used in the new system.--------------------------------------------------------
1139 void AnimationExporter::find_rotation_frames(Object *ob, std::vector<float> &fra, const char *prefix, int rotmode)
1140 {
1141         if (rotmode > 0)
1142                 find_frames(ob, fra, prefix, "rotation_euler");
1143         else if (rotmode == ROT_MODE_QUAT)
1144                 find_frames(ob, fra, prefix, "rotation_quaternion");
1145         /*else if (rotmode == ROT_MODE_AXISANGLE)
1146         ;*/
1147 }
1148
1149 void AnimationExporter::find_frames(Object *ob, std::vector<float> &fra, const char *prefix, const char *tm_name)
1150 {
1151         FCurve *fcu= (FCurve*)ob->adt->action->curves.first;
1152
1153         for (; fcu; fcu = fcu->next) {
1154                 if (prefix && strncmp(prefix, fcu->rna_path, strlen(prefix)))
1155                         continue;
1156
1157                 char *name = extract_transform_name(fcu->rna_path);
1158                 if (!strcmp(name, tm_name)) {
1159                         for (unsigned int i = 0; i < fcu->totvert; i++) {
1160                                 float f = fcu->bezt[i].vec[1][0];
1161                                 if (std::find(fra.begin(), fra.end(), f) == fra.end())   
1162                                         fra.push_back(f);
1163                         }
1164                 }
1165         }
1166
1167         // keep the keys in ascending order
1168         std::sort(fra.begin(), fra.end());
1169 }
1170
1171 void AnimationExporter::write_bone_animation(Object *ob_arm, Bone *bone)
1172 {
1173         if (!ob_arm->adt)
1174                 return;
1175
1176         //write bone animations for 3 transform types
1177         //i=0 --> rotations
1178         //i=1 --> scale
1179         //i=2 --> location
1180         for (int i = 0; i < 3; i++)
1181                 sample_and_write_bone_animation(ob_arm, bone, i);
1182
1183         for (Bone *child = (Bone*)bone->childbase.first; child; child = child->next)
1184                 write_bone_animation(ob_arm, child);
1185 }
1186
1187 void AnimationExporter::sample_and_write_bone_animation(Object *ob_arm, Bone *bone, int transform_type)
1188 {
1189         bArmature *arm = (bArmature*)ob_arm->data;
1190         int flag = arm->flag;
1191         std::vector<float> fra;
1192         char prefix[256];
1193
1194         BLI_snprintf(prefix, sizeof(prefix), "pose.bones[\"%s\"]", bone->name);
1195
1196         bPoseChannel *pchan = get_pose_channel(ob_arm->pose, bone->name);
1197         if (!pchan)
1198                 return;
1199         //Fill frame array with key frame values framed at @param:transform_type
1200         switch (transform_type) {
1201                 case 0:
1202                         find_rotation_frames(ob_arm, fra, prefix, pchan->rotmode);
1203                         break;
1204                 case 1:
1205                         find_frames(ob_arm, fra, prefix, "scale");
1206                         break;
1207                 case 2:
1208                         find_frames(ob_arm, fra, prefix, "location");
1209                         break;
1210                 default:
1211                         return;
1212         }
1213
1214         // exit rest position
1215         if (flag & ARM_RESTPOS) {
1216                 arm->flag &= ~ARM_RESTPOS;
1217                 where_is_pose(scene, ob_arm);
1218         }
1219         //v array will hold all values which will be exported. 
1220         if (fra.size()) {
1221                 float *values = (float*)MEM_callocN(sizeof(float) * 3 * fra.size(), "temp. anim frames");
1222                 sample_animation(values, fra, transform_type, bone, ob_arm, pchan);
1223
1224                 if (transform_type == 0) {
1225                         // write x, y, z curves separately if it is rotation
1226                         float *axisValues = (float*)MEM_callocN(sizeof(float) * fra.size(), "temp. anim frames");   
1227
1228                         for (int i = 0; i < 3; i++) {
1229                                 for (unsigned int j = 0; j < fra.size(); j++)
1230                                         axisValues[j] = values[j * 3 + i];
1231
1232                                 dae_bone_animation(fra, axisValues, transform_type, i, id_name(ob_arm), bone->name);
1233                         }
1234                         MEM_freeN(axisValues);
1235                 }
1236                 else {
1237                         // write xyz at once if it is location or scale
1238                         dae_bone_animation(fra, values, transform_type, -1, id_name(ob_arm), bone->name);
1239                 }
1240
1241                 MEM_freeN(values);
1242         }
1243
1244         // restore restpos
1245         if (flag & ARM_RESTPOS) 
1246                 arm->flag = flag;
1247         where_is_pose(scene, ob_arm);
1248 }
1249
1250 void AnimationExporter::sample_animation(float *v, std::vector<float> &frames, int type, Bone *bone, Object *ob_arm, bPoseChannel *pchan)
1251 {
1252         bPoseChannel *parchan = NULL;
1253         bPose *pose = ob_arm->pose;
1254
1255         pchan = get_pose_channel(pose, bone->name);
1256
1257         if (!pchan)
1258                 return;
1259
1260         parchan = pchan->parent;
1261
1262         enable_fcurves(ob_arm->adt->action, bone->name);
1263
1264         std::vector<float>::iterator it;
1265         for (it = frames.begin(); it != frames.end(); it++) {
1266                 float mat[4][4], ipar[4][4];
1267
1268                 float ctime = BKE_frame_to_ctime(scene, *it);
1269
1270
1271                 BKE_animsys_evaluate_animdata(scene , &ob_arm->id, ob_arm->adt, ctime, ADT_RECALC_ANIM);
1272                 where_is_pose_bone(scene, ob_arm, pchan, ctime, 1);
1273
1274                 // compute bone local mat
1275                 if (bone->parent) {
1276                         invert_m4_m4(ipar, parchan->pose_mat);
1277                         mul_m4_m4m4(mat, pchan->pose_mat, ipar);
1278                 }
1279                 else
1280                         copy_m4_m4(mat, pchan->pose_mat);
1281
1282                 switch (type) {
1283                         case 0:
1284                                 mat4_to_eul(v, mat);
1285                                 break;
1286                         case 1:
1287                                 mat4_to_size(v, mat);
1288                                 break;
1289                         case 2:
1290                                 copy_v3_v3(v, mat[3]);
1291                                 break;
1292                 }
1293
1294                 v += 3;
1295         }
1296
1297         enable_fcurves(ob_arm->adt->action, NULL);
1298 }