Welcome to mirror list, hosted at ThFree Co, Russian Federation.

DocumentExporter.cpp « collada « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: cbcb39840189e9a760dbb2107ad46ef3827e2650 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
/**
 * $Id$
 *
 * ***** BEGIN GPL LICENSE BLOCK *****
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * Contributor(s): Chingiz Dyussenov, Arystanbek Dyussenov, Jan Diederich, Tod Liverseed.
 *
 * ***** END GPL LICENSE BLOCK *****
 */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

extern "C" 
{
#include "DNA_scene_types.h"
#include "DNA_object_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_mesh_types.h"
#include "DNA_image_types.h"
#include "DNA_material_types.h"
#include "DNA_texture_types.h"
#include "DNA_anim_types.h"
#include "DNA_action_types.h"
#include "DNA_curve_types.h"
#include "DNA_armature_types.h"
#include "DNA_modifier_types.h"
#include "DNA_userdef_types.h"

#include "BKE_DerivedMesh.h"
#include "BKE_fcurve.h"
#include "BKE_animsys.h"
#include "BLI_path_util.h"
#include "BLI_fileops.h"
#include "ED_keyframing.h"
#ifdef NAN_BUILDINFO
extern char build_rev[];
#endif
}

#include "MEM_guardedalloc.h"

#include "BKE_blender.h" // version info
#include "BKE_scene.h"
#include "BKE_global.h"
#include "BKE_main.h"
#include "BKE_material.h"
#include "BKE_action.h" // pose functions
#include "BKE_armature.h"
#include "BKE_image.h"
#include "BKE_utildefines.h"
#include "BKE_object.h"

#include "BLI_math.h"
#include "BLI_string.h"
#include "BLI_listbase.h"

#include "COLLADASWAsset.h"
#include "COLLADASWLibraryVisualScenes.h"
#include "COLLADASWNode.h"
#include "COLLADASWSource.h"
#include "COLLADASWInstanceGeometry.h"
#include "COLLADASWInputList.h"
#include "COLLADASWPrimitves.h"
#include "COLLADASWVertices.h"
#include "COLLADASWLibraryAnimations.h"
#include "COLLADASWLibraryImages.h"
#include "COLLADASWLibraryEffects.h"
#include "COLLADASWImage.h"
#include "COLLADASWEffectProfile.h"
#include "COLLADASWColorOrTexture.h"
#include "COLLADASWParamTemplate.h"
#include "COLLADASWParamBase.h"
#include "COLLADASWSurfaceInitOption.h"
#include "COLLADASWSampler.h"
#include "COLLADASWScene.h"
#include "COLLADASWTechnique.h"
#include "COLLADASWTexture.h"
#include "COLLADASWLibraryMaterials.h"
#include "COLLADASWBindMaterial.h"
#include "COLLADASWInstanceCamera.h"
#include "COLLADASWInstanceLight.h"
#include "COLLADASWConstants.h"
#include "COLLADASWLibraryControllers.h"
#include "COLLADASWInstanceController.h"
#include "COLLADASWBaseInputElement.h"

#include "collada_internal.h"
#include "DocumentExporter.h"

// can probably go after refactor is complete
#include "InstanceWriter.h"
#include "TransformWriter.h"

#include "ArmatureExporter.h"
#include "CameraExporter.h"
#include "EffectExporter.h"
#include "GeometryExporter.h"
#include "ImageExporter.h"
#include "LightExporter.h"
#include "MaterialExporter.h"

#include <vector>
#include <algorithm> // std::find

char *bc_CustomData_get_layer_name(const struct CustomData *data, int type, int n)
{
	int layer_index = CustomData_get_layer_index(data, type);
	if(layer_index < 0) return NULL;

	return data->layers[layer_index+n].name;
}

char *bc_CustomData_get_active_layer_name(const CustomData *data, int type)
{
	/* get the layer index of the active layer of type */
	int layer_index = CustomData_get_active_layer_index(data, type);
	if(layer_index < 0) return NULL;

	return data->layers[layer_index].name;
}


/*
  Utilities to avoid code duplication.
  Definition can take some time to understand, but they should be useful.
*/


template<class Functor>
void forEachObjectInScene(Scene *sce, Functor &f)
{
	Base *base= (Base*) sce->base.first;
	while(base) {
		Object *ob = base->object;
			
		f(ob);

		base= base->next;
	}
}



class SceneExporter: COLLADASW::LibraryVisualScenes, protected TransformWriter, protected InstanceWriter
{
	ArmatureExporter *arm_exporter;
public:
	SceneExporter(COLLADASW::StreamWriter *sw, ArmatureExporter *arm) : COLLADASW::LibraryVisualScenes(sw),
																		arm_exporter(arm) {}
	
	void exportScene(Scene *sce) {
 		// <library_visual_scenes> <visual_scene>
		std::string id_naming = id_name(sce);
		openVisualScene(translate_id(id_naming), id_naming);

		// write <node>s
		//forEachMeshObjectInScene(sce, *this);
		//forEachCameraObjectInScene(sce, *this);
		//forEachLampObjectInScene(sce, *this);
		exportHierarchy(sce);

		// </visual_scene> </library_visual_scenes>
		closeVisualScene();

		closeLibrary();
	}

	void exportHierarchy(Scene *sce)
	{
		Base *base= (Base*) sce->base.first;
		while(base) {
			Object *ob = base->object;

			if (!ob->parent) {
				switch(ob->type) {
				case OB_MESH:
				case OB_CAMERA:
				case OB_LAMP:
				case OB_EMPTY:
				case OB_ARMATURE:
					// write nodes....
					writeNodes(ob, sce);
					break;
				}
			}

			base= base->next;
		}
	}


	// called for each object
	//void operator()(Object *ob) {
	void writeNodes(Object *ob, Scene *sce)
	{
		COLLADASW::Node node(mSW);
		node.setNodeId(translate_id(id_name(ob)));
		node.setType(COLLADASW::Node::NODE);

		node.start();

		bool is_skinned_mesh = arm_exporter->is_skinned_mesh(ob);

		if (ob->type == OB_MESH && is_skinned_mesh)
			// for skinned mesh we write obmat in <bind_shape_matrix>
			TransformWriter::add_node_transform_identity(node);
		else
			TransformWriter::add_node_transform_ob(node, ob);
		
		// <instance_geometry>
		if (ob->type == OB_MESH) {
			if (is_skinned_mesh) {
				arm_exporter->add_instance_controller(ob);
			}
			else {
				COLLADASW::InstanceGeometry instGeom(mSW);
				instGeom.setUrl(COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, get_geometry_id(ob)));

				InstanceWriter::add_material_bindings(instGeom.getBindMaterial(), ob);
			
				instGeom.add();
			}
		}

		// <instance_controller>
		else if (ob->type == OB_ARMATURE) {
			arm_exporter->add_armature_bones(ob, sce);

			// XXX this looks unstable...
			node.end();
		}
		
		// <instance_camera>
		else if (ob->type == OB_CAMERA) {
			COLLADASW::InstanceCamera instCam(mSW, COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, get_camera_id(ob)));
			instCam.add();
		}
		
		// <instance_light>
		else if (ob->type == OB_LAMP) {
			COLLADASW::InstanceLight instLa(mSW, COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, get_light_id(ob)));
			instLa.add();
		}

		// empty object
		else if (ob->type == OB_EMPTY) {
		}

		// write nodes for child objects
		Base *b = (Base*) sce->base.first;
		while(b) {
			// cob - child object
			Object *cob = b->object;

			if (cob->parent == ob) {
				switch(cob->type) {
				case OB_MESH:
				case OB_CAMERA:
				case OB_LAMP:
				case OB_EMPTY:
				case OB_ARMATURE:
					// write node...
					writeNodes(cob, sce);
					break;
				}
			}

			b = b->next;
		}

		if (ob->type != OB_ARMATURE)
			node.end();
	}
};

// TODO: it would be better to instantiate animations rather than create a new one per object
// COLLADA allows this through multiple <channel>s in <animation>.
// For this to work, we need to know objects that use a certain action.
class AnimationExporter: COLLADASW::LibraryAnimations
{
	Scene *scene;

public:

	AnimationExporter(COLLADASW::StreamWriter *sw): COLLADASW::LibraryAnimations(sw) {}

	void exportAnimations(Scene *sce)
	{
		this->scene = sce;

		openLibrary();
		
		forEachObjectInScene(sce, *this);
		
		closeLibrary();
	}

	// called for each exported object
	void operator() (Object *ob) 
	{
		if (!ob->adt || !ob->adt->action) return;
		
		FCurve *fcu = (FCurve*)ob->adt->action->curves.first;
		
		if (ob->type == OB_ARMATURE) {
			if (!ob->data) return;

			bArmature *arm = (bArmature*)ob->data;
			for (Bone *bone = (Bone*)arm->bonebase.first; bone; bone = bone->next)
				write_bone_animation(ob, bone);
		}
		else {
			while (fcu) {
				// TODO "rotation_quaternion" is also possible for objects (although euler is default)
				if ((!strcmp(fcu->rna_path, "location") || !strcmp(fcu->rna_path, "scale")) ||
					(!strcmp(fcu->rna_path, "rotation_euler") && ob->rotmode == ROT_MODE_EUL))
					dae_animation(fcu, id_name(ob));

				fcu = fcu->next;
			}
		}
	}

protected:

	void dae_animation(FCurve *fcu, std::string ob_name)
	{
		const char *axis_names[] = {"X", "Y", "Z"};
		const char *axis_name = NULL;
		char anim_id[200];
		
		if (fcu->array_index < 3)
			axis_name = axis_names[fcu->array_index];

		BLI_snprintf(anim_id, sizeof(anim_id), "%s_%s_%s", (char*)translate_id(ob_name).c_str(),
					 fcu->rna_path, axis_names[fcu->array_index]);

		// check rna_path is one of: rotation, scale, location

		openAnimation(anim_id, COLLADABU::Utils::EMPTY_STRING);

		// create input source
		std::string input_id = create_source_from_fcurve(Sampler::INPUT, fcu, anim_id, axis_name);

		// create output source
		std::string output_id = create_source_from_fcurve(Sampler::OUTPUT, fcu, anim_id, axis_name);

		// create interpolations source
		std::string interpolation_id = create_interpolation_source(fcu->totvert, anim_id, axis_name);

		std::string sampler_id = std::string(anim_id) + SAMPLER_ID_SUFFIX;
		COLLADASW::LibraryAnimations::Sampler sampler(sampler_id);
		std::string empty;
		sampler.addInput(Sampler::INPUT, COLLADABU::URI(empty, input_id));
		sampler.addInput(Sampler::OUTPUT, COLLADABU::URI(empty, output_id));

		// this input is required
		sampler.addInput(Sampler::INTERPOLATION, COLLADABU::URI(empty, interpolation_id));

		addSampler(sampler);

		std::string target = translate_id(ob_name)
			+ "/" + get_transform_sid(fcu->rna_path, -1, axis_name, true);
		addChannel(COLLADABU::URI(empty, sampler_id), target);

		closeAnimation();
	}

	void write_bone_animation(Object *ob_arm, Bone *bone)
	{
		if (!ob_arm->adt)
			return;

		for (int i = 0; i < 3; i++)
			sample_and_write_bone_animation(ob_arm, bone, i);

		for (Bone *child = (Bone*)bone->childbase.first; child; child = child->next)
			write_bone_animation(ob_arm, child);
	}

	void sample_and_write_bone_animation(Object *ob_arm, Bone *bone, int transform_type)
	{
		bArmature *arm = (bArmature*)ob_arm->data;
		int flag = arm->flag;
		std::vector<float> fra;
		char prefix[256];

		BLI_snprintf(prefix, sizeof(prefix), "pose.bones[\"%s\"]", bone->name);

		bPoseChannel *pchan = get_pose_channel(ob_arm->pose, bone->name);
		if (!pchan)
			return;

		switch (transform_type) {
		case 0:
			find_rotation_frames(ob_arm, fra, prefix, pchan->rotmode);
			break;
		case 1:
			find_frames(ob_arm, fra, prefix, "scale");
			break;
		case 2:
			find_frames(ob_arm, fra, prefix, "location");
			break;
		default:
			return;
		}

		// exit rest position
		if (flag & ARM_RESTPOS) {
			arm->flag &= ~ARM_RESTPOS;
			where_is_pose(scene, ob_arm);
		}

		if (fra.size()) {
			float *v = (float*)MEM_callocN(sizeof(float) * 3 * fra.size(), "temp. anim frames");
			sample_animation(v, fra, transform_type, bone, ob_arm);

			if (transform_type == 0) {
				// write x, y, z curves separately if it is rotation
				float *c = (float*)MEM_callocN(sizeof(float) * fra.size(), "temp. anim frames");
				for (int i = 0; i < 3; i++) {
					for (unsigned int j = 0; j < fra.size(); j++)
						c[j] = v[j * 3 + i];

					dae_bone_animation(fra, c, transform_type, i, id_name(ob_arm), bone->name);
				}
				MEM_freeN(c);
			}
			else {
				// write xyz at once if it is location or scale
				dae_bone_animation(fra, v, transform_type, -1, id_name(ob_arm), bone->name);
			}

			MEM_freeN(v);
		}

		// restore restpos
		if (flag & ARM_RESTPOS) 
			arm->flag = flag;
		where_is_pose(scene, ob_arm);
	}

	void sample_animation(float *v, std::vector<float> &frames, int type, Bone *bone, Object *ob_arm)
	{
		bPoseChannel *pchan, *parchan = NULL;
		bPose *pose = ob_arm->pose;

		pchan = get_pose_channel(pose, bone->name);

		if (!pchan)
			return;

		parchan = pchan->parent;

		enable_fcurves(ob_arm->adt->action, bone->name);

		std::vector<float>::iterator it;
		for (it = frames.begin(); it != frames.end(); it++) {
			float mat[4][4], ipar[4][4];

			float ctime = bsystem_time(scene, ob_arm, *it, 0.0f);

			BKE_animsys_evaluate_animdata(&ob_arm->id, ob_arm->adt, *it, ADT_RECALC_ANIM);
			where_is_pose_bone(scene, ob_arm, pchan, ctime, 1);

			// compute bone local mat
			if (bone->parent) {
				invert_m4_m4(ipar, parchan->pose_mat);
				mul_m4_m4m4(mat, pchan->pose_mat, ipar);
			}
			else
				copy_m4_m4(mat, pchan->pose_mat);

			switch (type) {
			case 0:
				mat4_to_eul(v, mat);
				break;
			case 1:
				mat4_to_size(v, mat);
				break;
			case 2:
				copy_v3_v3(v, mat[3]);
				break;
			}

			v += 3;
		}

		enable_fcurves(ob_arm->adt->action, NULL);
	}

	// dae_bone_animation -> add_bone_animation
	// (blend this into dae_bone_animation)
	void dae_bone_animation(std::vector<float> &fra, float *v, int tm_type, int axis, std::string ob_name, std::string bone_name)
	{
		const char *axis_names[] = {"X", "Y", "Z"};
		const char *axis_name = NULL;
		char anim_id[200];
		bool is_rot = tm_type == 0;
		
		if (!fra.size())
			return;

		char rna_path[200];
		BLI_snprintf(rna_path, sizeof(rna_path), "pose.bones[\"%s\"].%s", bone_name.c_str(),
					 tm_type == 0 ? "rotation_quaternion" : (tm_type == 1 ? "scale" : "location"));

		if (axis > -1)
			axis_name = axis_names[axis];
		
		std::string transform_sid = get_transform_sid(NULL, tm_type, axis_name, false);
		
		BLI_snprintf(anim_id, sizeof(anim_id), "%s_%s_%s", (char*)translate_id(ob_name).c_str(),
					 (char*)translate_id(bone_name).c_str(), (char*)transform_sid.c_str());

		openAnimation(anim_id, COLLADABU::Utils::EMPTY_STRING);

		// create input source
		std::string input_id = create_source_from_vector(Sampler::INPUT, fra, is_rot, anim_id, axis_name);

		// create output source
		std::string output_id;
		if (axis == -1)
			output_id = create_xyz_source(v, fra.size(), anim_id);
		else
			output_id = create_source_from_array(Sampler::OUTPUT, v, fra.size(), is_rot, anim_id, axis_name);

		// create interpolations source
		std::string interpolation_id = create_interpolation_source(fra.size(), anim_id, axis_name);

		std::string sampler_id = std::string(anim_id) + SAMPLER_ID_SUFFIX;
		COLLADASW::LibraryAnimations::Sampler sampler(sampler_id);
		std::string empty;
		sampler.addInput(Sampler::INPUT, COLLADABU::URI(empty, input_id));
		sampler.addInput(Sampler::OUTPUT, COLLADABU::URI(empty, output_id));

		// TODO create in/out tangents source

		// this input is required
		sampler.addInput(Sampler::INTERPOLATION, COLLADABU::URI(empty, interpolation_id));

		addSampler(sampler);

		std::string target = translate_id(ob_name + "_" + bone_name) + "/" + transform_sid;
		addChannel(COLLADABU::URI(empty, sampler_id), target);

		closeAnimation();
	}

	float convert_time(float frame)
	{
		return FRA2TIME(frame);
	}

	float convert_angle(float angle)
	{
		return COLLADABU::Math::Utils::radToDegF(angle);
	}

	std::string get_semantic_suffix(Sampler::Semantic semantic)
	{
		switch(semantic) {
		case Sampler::INPUT:
			return INPUT_SOURCE_ID_SUFFIX;
		case Sampler::OUTPUT:
			return OUTPUT_SOURCE_ID_SUFFIX;
		case Sampler::INTERPOLATION:
			return INTERPOLATION_SOURCE_ID_SUFFIX;
		case Sampler::IN_TANGENT:
			return INTANGENT_SOURCE_ID_SUFFIX;
		case Sampler::OUT_TANGENT:
			return OUTTANGENT_SOURCE_ID_SUFFIX;
		default:
			break;
		}
		return "";
	}

	void add_source_parameters(COLLADASW::SourceBase::ParameterNameList& param,
							   Sampler::Semantic semantic, bool is_rot, const char *axis)
	{
		switch(semantic) {
		case Sampler::INPUT:
			param.push_back("TIME");
			break;
		case Sampler::OUTPUT:
			if (is_rot) {
				param.push_back("ANGLE");
			}
			else {
				if (axis) {
					param.push_back(axis);
				}
				else {
					param.push_back("X");
					param.push_back("Y");
					param.push_back("Z");
				}
			}
			break;
		case Sampler::IN_TANGENT:
		case Sampler::OUT_TANGENT:
			param.push_back("X");
			param.push_back("Y");
			break;
		default:
			break;
		}
	}

	void get_source_values(BezTriple *bezt, Sampler::Semantic semantic, bool rotation, float *values, int *length)
	{
		switch (semantic) {
		case Sampler::INPUT:
			*length = 1;
			values[0] = convert_time(bezt->vec[1][0]);
			break;
		case Sampler::OUTPUT:
			*length = 1;
			if (rotation) {
				values[0] = convert_angle(bezt->vec[1][1]);
			}
			else {
				values[0] = bezt->vec[1][1];
			}
			break;
		case Sampler::IN_TANGENT:
		case Sampler::OUT_TANGENT:
			// XXX
			*length = 2;
			break;
		default:
			*length = 0;
			break;
		}
	}

	std::string create_source_from_fcurve(Sampler::Semantic semantic, FCurve *fcu, const std::string& anim_id, const char *axis_name)
	{
		std::string source_id = anim_id + get_semantic_suffix(semantic);

		//bool is_rotation = !strcmp(fcu->rna_path, "rotation");
		bool is_rotation = false;
		
		if (strstr(fcu->rna_path, "rotation")) is_rotation = true;
		
		COLLADASW::FloatSourceF source(mSW);
		source.setId(source_id);
		source.setArrayId(source_id + ARRAY_ID_SUFFIX);
		source.setAccessorCount(fcu->totvert);
		source.setAccessorStride(1);
		
		COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
		add_source_parameters(param, semantic, is_rotation, axis_name);

		source.prepareToAppendValues();

		for (unsigned int i = 0; i < fcu->totvert; i++) {
			float values[3]; // be careful!
			int length = 0;

			get_source_values(&fcu->bezt[i], semantic, is_rotation, values, &length);
			for (int j = 0; j < length; j++)
				source.appendValues(values[j]);
		}

		source.finish();

		return source_id;
	}

	std::string create_source_from_array(Sampler::Semantic semantic, float *v, int tot, bool is_rot, const std::string& anim_id, const char *axis_name)
	{
		std::string source_id = anim_id + get_semantic_suffix(semantic);

		COLLADASW::FloatSourceF source(mSW);
		source.setId(source_id);
		source.setArrayId(source_id + ARRAY_ID_SUFFIX);
		source.setAccessorCount(tot);
		source.setAccessorStride(1);
		
		COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
		add_source_parameters(param, semantic, is_rot, axis_name);

		source.prepareToAppendValues();

		for (int i = 0; i < tot; i++) {
			float val = v[i];
			if (semantic == Sampler::INPUT)
				val = convert_time(val);
			else if (is_rot)
				val = convert_angle(val);
			source.appendValues(val);
		}

		source.finish();

		return source_id;
	}

	std::string create_source_from_vector(Sampler::Semantic semantic, std::vector<float> &fra, bool is_rot, const std::string& anim_id, const char *axis_name)
	{
		std::string source_id = anim_id + get_semantic_suffix(semantic);

		COLLADASW::FloatSourceF source(mSW);
		source.setId(source_id);
		source.setArrayId(source_id + ARRAY_ID_SUFFIX);
		source.setAccessorCount(fra.size());
		source.setAccessorStride(1);
		
		COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
		add_source_parameters(param, semantic, is_rot, axis_name);

		source.prepareToAppendValues();

		std::vector<float>::iterator it;
		for (it = fra.begin(); it != fra.end(); it++) {
			float val = *it;
			if (semantic == Sampler::INPUT)
				val = convert_time(val);
			else if (is_rot)
				val = convert_angle(val);
			source.appendValues(val);
		}

		source.finish();

		return source_id;
	}

	// only used for sources with OUTPUT semantic
	std::string create_xyz_source(float *v, int tot, const std::string& anim_id)
	{
		Sampler::Semantic semantic = Sampler::OUTPUT;
		std::string source_id = anim_id + get_semantic_suffix(semantic);

		COLLADASW::FloatSourceF source(mSW);
		source.setId(source_id);
		source.setArrayId(source_id + ARRAY_ID_SUFFIX);
		source.setAccessorCount(tot);
		source.setAccessorStride(3);
		
		COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
		add_source_parameters(param, semantic, false, NULL);

		source.prepareToAppendValues();

		for (int i = 0; i < tot; i++) {
			source.appendValues(*v, *(v + 1), *(v + 2));
			v += 3;
		}

		source.finish();

		return source_id;
	}

	std::string create_interpolation_source(int tot, const std::string& anim_id, const char *axis_name)
	{
		std::string source_id = anim_id + get_semantic_suffix(Sampler::INTERPOLATION);

		COLLADASW::NameSource source(mSW);
		source.setId(source_id);
		source.setArrayId(source_id + ARRAY_ID_SUFFIX);
		source.setAccessorCount(tot);
		source.setAccessorStride(1);
		
		COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
		param.push_back("INTERPOLATION");

		source.prepareToAppendValues();

		for (int i = 0; i < tot; i++) {
			source.appendValues(LINEAR_NAME);
		}

		source.finish();

		return source_id;
	}

	// for rotation, axis name is always appended and the value of append_axis is ignored
	std::string get_transform_sid(char *rna_path, int tm_type, const char *axis_name, bool append_axis)
	{
		std::string tm_name;

		// when given rna_path, determine tm_type from it
		if (rna_path) {
			char *name = extract_transform_name(rna_path);

			if (strstr(name, "rotation"))
				tm_type = 0;
			else if (!strcmp(name, "scale"))
				tm_type = 1;
			else if (!strcmp(name, "location"))
				tm_type = 2;
			else
				tm_type = -1;
		}

		switch (tm_type) {
		case 0:
			return std::string("rotation") + std::string(axis_name) + ".ANGLE";
		case 1:
			tm_name = "scale";
			break;
		case 2:
			tm_name = "location";
			break;
		default:
			tm_name = "";
			break;
		}

		if (tm_name.size()) {
			if (append_axis)
				return tm_name + std::string(".") + std::string(axis_name);
			else
				return tm_name;
		}

		return std::string("");
	}

	char *extract_transform_name(char *rna_path)
	{
		char *dot = strrchr(rna_path, '.');
		return dot ? (dot + 1) : rna_path;
	}

	void find_frames(Object *ob, std::vector<float> &fra, const char *prefix, const char *tm_name)
	{
		FCurve *fcu= (FCurve*)ob->adt->action->curves.first;

		for (; fcu; fcu = fcu->next) {
			if (prefix && strncmp(prefix, fcu->rna_path, strlen(prefix)))
				continue;

			char *name = extract_transform_name(fcu->rna_path);
			if (!strcmp(name, tm_name)) {
				for (unsigned int i = 0; i < fcu->totvert; i++) {
					float f = fcu->bezt[i].vec[1][0];
					if (std::find(fra.begin(), fra.end(), f) == fra.end())
						fra.push_back(f);
				}
			}
		}

		// keep the keys in ascending order
		std::sort(fra.begin(), fra.end());
	}

	void find_rotation_frames(Object *ob, std::vector<float> &fra, const char *prefix, int rotmode)
	{
		if (rotmode > 0)
			find_frames(ob, fra, prefix, "rotation_euler");
		else if (rotmode == ROT_MODE_QUAT)
			find_frames(ob, fra, prefix, "rotation_quaternion");
		/*else if (rotmode == ROT_MODE_AXISANGLE)
			;*/
	}

	// enable fcurves driving a specific bone, disable all the rest
	// if bone_name = NULL enable all fcurves
	void enable_fcurves(bAction *act, char *bone_name)
	{
		FCurve *fcu;
		char prefix[200];

		if (bone_name)
			BLI_snprintf(prefix, sizeof(prefix), "pose.bones[\"%s\"]", bone_name);

		for (fcu = (FCurve*)act->curves.first; fcu; fcu = fcu->next) {
			if (bone_name) {
				if (!strncmp(fcu->rna_path, prefix, strlen(prefix)))
					fcu->flag &= ~FCURVE_DISABLED;
				else
					fcu->flag |= FCURVE_DISABLED;
			}
			else {
				fcu->flag &= ~FCURVE_DISABLED;
			}
		}
	}
};

void DocumentExporter::exportCurrentScene(Scene *sce, const char* filename)
{
	clear_global_id_map();
	
	COLLADABU::NativeString native_filename =
		COLLADABU::NativeString(std::string(filename));
	COLLADASW::StreamWriter sw(native_filename);

	// open <Collada>
	sw.startDocument();

	// <asset>
	COLLADASW::Asset asset(&sw);
	// XXX ask blender devs about this?
	asset.setUnit("decimetre", 0.1);
	asset.setUpAxisType(COLLADASW::Asset::Z_UP);
	// TODO: need an Author field in userpref
	if(strlen(U.author) > 0) {
		asset.getContributor().mAuthor = U.author;
	}
	else {
		asset.getContributor().mAuthor = "Blender User";
	}
#ifdef NAN_BUILDINFO
	char version_buf[128];
	sprintf(version_buf, "Blender %d.%02d.%d r%s", BLENDER_VERSION/100, BLENDER_VERSION%100, BLENDER_SUBVERSION, build_rev);
	asset.getContributor().mAuthoringTool = version_buf;
#else
	asset.getContributor().mAuthoringTool = "Blender 2.5x";
#endif
	asset.add();
	
	// <library_cameras>
	CamerasExporter ce(&sw);
	ce.exportCameras(sce);
	
	// <library_lights>
	LightsExporter le(&sw);
	le.exportLights(sce);

	// <library_images>
	ImagesExporter ie(&sw, filename);
	ie.exportImages(sce);
	
	// <library_effects>
	EffectsExporter ee(&sw);
	ee.exportEffects(sce);
	
	// <library_materials>
	MaterialsExporter me(&sw);
	me.exportMaterials(sce);

	// <library_geometries>
	GeometryExporter ge(&sw);
	ge.exportGeom(sce);

	// <library_animations>
	AnimationExporter ae(&sw);
	ae.exportAnimations(sce);

	// <library_controllers>
	ArmatureExporter arm_exporter(&sw);
	arm_exporter.export_controllers(sce);

	// <library_visual_scenes>
	SceneExporter se(&sw, &arm_exporter);
	se.exportScene(sce);
	
	// <scene>
	std::string scene_name(translate_id(id_name(sce)));
	COLLADASW::Scene scene(&sw, COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING,
											   scene_name));
	scene.add();
	
	// close <Collada>
	sw.endDocument();

}

void DocumentExporter::exportScenes(const char* filename)
{
}

/*

NOTES:

* AnimationExporter::sample_animation enables all curves on armature, this is undesirable for a user

 */