Merging r42160 through r42177 from trunk into soc-2011-tomato
[blender.git] / source / blender / blenloader / intern / writefile.c
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  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  *
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/blenloader/intern/writefile.c
28  *  \ingroup blenloader
29  */
30
31
32 /*
33 FILEFORMAT: IFF-style structure  (but not IFF compatible!)
34
35 start file:
36         BLENDER_V100    12 bytes  (versie 1.00)
37                                         V = big endian, v = little endian
38                                         _ = 4 byte pointer, - = 8 byte pointer
39
40 datablocks:             also see struct BHead
41         <bh.code>                       4 chars
42         <bh.len>                        int,  len data after BHead
43         <bh.old>                        void,  old pointer
44         <bh.SDNAnr>                     int
45         <bh.nr>                         int, in case of array: amount of structs
46         data
47         ...
48         ...
49
50 Almost all data in Blender are structures. Each struct saved
51 gets a BHead header.  With BHead the struct can be linked again
52 and compared with StructDNA .
53
54 WRITE
55
56 Preferred writing order: (not really a must, but why would you do it random?)
57 Any case: direct data is ALWAYS after the lib block
58
59 (Local file data)
60 - for each LibBlock
61         - write LibBlock
62         - write associated direct data
63 (External file data)
64 - per library
65         - write library block
66         - per LibBlock
67                 - write the ID of LibBlock
68 - write TEST (128x128, blend file preview, optional)
69 - write FileGlobal (some global vars)
70 - write SDNA
71 - write USER if filename is ~/X.XX/config/startup.blend
72 */
73
74
75 #include <math.h>
76 #include <fcntl.h>
77 #include <stdio.h>
78 #include <string.h>
79 #include <stdlib.h>
80
81 #include "zlib.h"
82
83 #ifndef WIN32
84 #include <unistd.h>
85 #else
86 #include "winsock2.h"
87 #include <io.h>
88 #include <process.h> // for getpid
89 #include "BLI_winstuff.h"
90 #endif
91
92 #include "DNA_anim_types.h"
93 #include "DNA_armature_types.h"
94 #include "DNA_actuator_types.h"
95 #include "DNA_brush_types.h"
96 #include "DNA_camera_types.h"
97 #include "DNA_cloth_types.h"
98 #include "DNA_constraint_types.h"
99 #include "DNA_controller_types.h"
100 #include "DNA_dynamicpaint_types.h"
101 #include "DNA_genfile.h"
102 #include "DNA_group_types.h"
103 #include "DNA_gpencil_types.h"
104 #include "DNA_fileglobal_types.h"
105 #include "DNA_key_types.h"
106 #include "DNA_lattice_types.h"
107 #include "DNA_lamp_types.h"
108 #include "DNA_meta_types.h"
109 #include "DNA_mesh_types.h"
110 #include "DNA_meshdata_types.h"
111 #include "DNA_material_types.h"
112 #include "DNA_node_types.h"
113 #include "DNA_object_types.h"
114 #include "DNA_object_force.h"
115 #include "DNA_packedFile_types.h"
116 #include "DNA_particle_types.h"
117 #include "DNA_property_types.h"
118 #include "DNA_scene_types.h"
119 #include "DNA_sdna_types.h"
120 #include "DNA_sequence_types.h"
121 #include "DNA_sensor_types.h"
122 #include "DNA_smoke_types.h"
123 #include "DNA_space_types.h"
124 #include "DNA_screen_types.h"
125 #include "DNA_speaker_types.h"
126 #include "DNA_sound_types.h"
127 #include "DNA_text_types.h"
128 #include "DNA_view3d_types.h"
129 #include "DNA_vfont_types.h"
130 #include "DNA_world_types.h"
131 #include "DNA_windowmanager_types.h"
132 #include "DNA_movieclip_types.h"
133
134 #include "MEM_guardedalloc.h" // MEM_freeN
135 #include "BLI_blenlib.h"
136 #include "BLI_linklist.h"
137 #include "BLI_bpath.h"
138 #include "BLI_math.h"
139 #include "BLI_utildefines.h"
140
141 #include "BKE_action.h"
142 #include "BKE_blender.h"
143 #include "BKE_curve.h"
144 #include "BKE_constraint.h"
145 #include "BKE_global.h" // for G
146 #include "BKE_library.h" // for  set_listbasepointers
147 #include "BKE_main.h"
148 #include "BKE_node.h"
149 #include "BKE_report.h"
150 #include "BKE_sequencer.h"
151 #include "BKE_utildefines.h"
152 #include "BKE_modifier.h"
153 #include "BKE_fcurve.h"
154 #include "BKE_pointcache.h"
155
156 #include "BLO_writefile.h"
157 #include "BLO_readfile.h"
158 #include "BLO_undofile.h"
159
160 #include "readfile.h"
161
162 #include <errno.h>
163
164 /* ********* my write, buffered writing with minimum size chunks ************ */
165
166 #define MYWRITE_BUFFER_SIZE     100000
167 #define MYWRITE_MAX_CHUNK       32768
168
169 typedef struct {
170         struct SDNA *sdna;
171
172         int file;
173         unsigned char *buf;
174         MemFile *compare, *current;
175         
176         int tot, count, error, memsize;
177 } WriteData;
178
179 static WriteData *writedata_new(int file)
180 {
181         WriteData *wd= MEM_callocN(sizeof(*wd), "writedata");
182
183                 /* XXX, see note about this in readfile.c, remove
184                  * once we have an xp lock - zr
185                  */
186
187         if (wd == NULL) return NULL;
188
189         wd->sdna= DNA_sdna_from_data(DNAstr, DNAlen, 0);
190
191         wd->file= file;
192
193         wd->buf= MEM_mallocN(MYWRITE_BUFFER_SIZE, "wd->buf");
194
195         return wd;
196 }
197
198 static void writedata_do_write(WriteData *wd, void *mem, int memlen)
199 {
200         if ((wd == NULL) || wd->error || (mem == NULL) || memlen < 1) return;
201         if (wd->error) return;
202
203         /* memory based save */
204         if(wd->current) {
205                 add_memfilechunk(NULL, wd->current, mem, memlen);
206         }
207         else {
208                 if (write(wd->file, mem, memlen) != memlen)
209                         wd->error= 1;
210                 
211         }
212 }
213
214 static void writedata_free(WriteData *wd)
215 {
216         DNA_sdna_free(wd->sdna);
217
218         MEM_freeN(wd->buf);
219         MEM_freeN(wd);
220 }
221
222 /***/
223
224 /**
225  * Low level WRITE(2) wrapper that buffers data
226  * @param adr Pointer to new chunk of data
227  * @param len Length of new chunk of data
228  * @warning Talks to other functions with global parameters
229  */
230  
231 #define MYWRITE_FLUSH           NULL
232
233 static void mywrite( WriteData *wd, void *adr, int len)
234 {
235         if (wd->error) return;
236
237         /* flush helps compression for undo-save */
238         if(adr==MYWRITE_FLUSH) {
239                 if(wd->count) {
240                         writedata_do_write(wd, wd->buf, wd->count);
241                         wd->count= 0;
242                 }
243                 return;
244         }
245
246         wd->tot+= len;
247         
248         /* if we have a single big chunk, write existing data in
249          * buffer and write out big chunk in smaller pieces */
250         if(len>MYWRITE_MAX_CHUNK) {
251                 if(wd->count) {
252                         writedata_do_write(wd, wd->buf, wd->count);
253                         wd->count= 0;
254                 }
255
256                 do {
257                         int writelen= MIN2(len, MYWRITE_MAX_CHUNK);
258                         writedata_do_write(wd, adr, writelen);
259                         adr = (char*)adr + writelen;
260                         len -= writelen;
261                 } while(len > 0);
262
263                 return;
264         }
265
266         /* if data would overflow buffer, write out the buffer */
267         if(len+wd->count>MYWRITE_BUFFER_SIZE-1) {
268                 writedata_do_write(wd, wd->buf, wd->count);
269                 wd->count= 0;
270         }
271
272         /* append data at end of buffer */
273         memcpy(&wd->buf[wd->count], adr, len);
274         wd->count+= len;
275 }
276
277 /**
278  * BeGiN initializer for mywrite
279  * @param file File descriptor
280  * @param write_flags Write parameters
281  * @warning Talks to other functions with global parameters
282  */
283 static WriteData *bgnwrite(int file, MemFile *compare, MemFile *current)
284 {
285         WriteData *wd= writedata_new(file);
286
287         if (wd == NULL) return NULL;
288
289         wd->compare= compare;
290         wd->current= current;
291         /* this inits comparing */
292         add_memfilechunk(compare, NULL, NULL, 0);
293         
294         return wd;
295 }
296
297 /**
298  * END the mywrite wrapper
299  * @return 1 if write failed
300  * @return unknown global variable otherwise
301  * @warning Talks to other functions with global parameters
302  */
303 static int endwrite(WriteData *wd)
304 {
305         int err;
306
307         if (wd->count) {
308                 writedata_do_write(wd, wd->buf, wd->count);
309                 wd->count= 0;
310         }
311         
312         err= wd->error;
313         writedata_free(wd);
314
315         return err;
316 }
317
318 /* ********** WRITE FILE ****************** */
319
320 static void writestruct(WriteData *wd, int filecode, const char *structname, int nr, void *adr)
321 {
322         BHead bh;
323         short *sp;
324
325         if(adr==NULL || nr==0) return;
326
327         /* init BHead */
328         bh.code= filecode;
329         bh.old= adr;
330         bh.nr= nr;
331
332         bh.SDNAnr= DNA_struct_find_nr(wd->sdna, structname);
333         if(bh.SDNAnr== -1) {
334                 printf("error: can't find SDNA code <%s>\n", structname);
335                 return;
336         }
337         sp= wd->sdna->structs[bh.SDNAnr];
338
339         bh.len= nr*wd->sdna->typelens[sp[0]];
340
341         if(bh.len==0) return;
342
343         mywrite(wd, &bh, sizeof(BHead));
344         mywrite(wd, adr, bh.len);
345 }
346
347 static void writedata(WriteData *wd, int filecode, int len, void *adr)  /* do not use for structs */
348 {
349         BHead bh;
350
351         if(adr==NULL) return;
352         if(len==0) return;
353
354         len+= 3;
355         len-= ( len % 4);
356
357         /* init BHead */
358         bh.code= filecode;
359         bh.old= adr;
360         bh.nr= 1;
361         bh.SDNAnr= 0;
362         bh.len= len;
363
364         mywrite(wd, &bh, sizeof(BHead));
365         if(len) mywrite(wd, adr, len);
366 }
367
368 /* *************** writing some direct data structs used in more code parts **************** */
369 /*These functions are used by blender's .blend system for file saving/loading.*/
370 void IDP_WriteProperty_OnlyData(IDProperty *prop, void *wd);
371 void IDP_WriteProperty(IDProperty *prop, void *wd);
372
373 static void IDP_WriteArray(IDProperty *prop, void *wd)
374 {
375         /*REMEMBER to set totalen to len in the linking code!!*/
376         if (prop->data.pointer) {
377                 writedata(wd, DATA, MEM_allocN_len(prop->data.pointer), prop->data.pointer);
378
379                 if(prop->subtype == IDP_GROUP) {
380                         IDProperty **array= prop->data.pointer;
381                         int a;
382
383                         for(a=0; a<prop->len; a++)
384                                 IDP_WriteProperty(array[a], wd);
385                 }
386         }
387 }
388
389 static void IDP_WriteIDPArray(IDProperty *prop, void *wd)
390 {
391         /*REMEMBER to set totalen to len in the linking code!!*/
392         if (prop->data.pointer) {
393                 IDProperty *array = prop->data.pointer;
394                 int a;
395
396                 writestruct(wd, DATA, "IDProperty", prop->len, array);
397
398                 for(a=0; a<prop->len; a++)
399                         IDP_WriteProperty_OnlyData(&array[a], wd);
400         }
401 }
402
403 static void IDP_WriteString(IDProperty *prop, void *wd)
404 {
405         /*REMEMBER to set totalen to len in the linking code!!*/
406         writedata(wd, DATA, prop->len+1, prop->data.pointer);
407 }
408
409 static void IDP_WriteGroup(IDProperty *prop, void *wd)
410 {
411         IDProperty *loop;
412
413         for (loop=prop->data.group.first; loop; loop=loop->next) {
414                 IDP_WriteProperty(loop, wd);
415         }
416 }
417
418 /* Functions to read/write ID Properties */
419 void IDP_WriteProperty_OnlyData(IDProperty *prop, void *wd)
420 {
421         switch (prop->type) {
422                 case IDP_GROUP:
423                         IDP_WriteGroup(prop, wd);
424                         break;
425                 case IDP_STRING:
426                         IDP_WriteString(prop, wd);
427                         break;
428                 case IDP_ARRAY:
429                         IDP_WriteArray(prop, wd);
430                         break;
431                 case IDP_IDPARRAY:
432                         IDP_WriteIDPArray(prop, wd);
433                         break;
434         }
435 }
436
437 void IDP_WriteProperty(IDProperty *prop, void *wd)
438 {
439         writestruct(wd, DATA, "IDProperty", 1, prop);
440         IDP_WriteProperty_OnlyData(prop, wd);
441 }
442
443 static void write_fmodifiers(WriteData *wd, ListBase *fmodifiers)
444 {
445         FModifier *fcm;
446         
447         /* Modifiers */
448         for (fcm= fmodifiers->first; fcm; fcm= fcm->next) {
449                 FModifierTypeInfo *fmi= fmodifier_get_typeinfo(fcm);
450                 
451                 /* Write the specific data */
452                 if (fmi && fcm->data) {
453                         /* firstly, just write the plain fmi->data struct */
454                         writestruct(wd, DATA, fmi->structName, 1, fcm->data);
455                         
456                         /* do any modifier specific stuff */
457                         switch (fcm->type) {
458                                 case FMODIFIER_TYPE_GENERATOR:
459                                 {
460                                         FMod_Generator *data= (FMod_Generator *)fcm->data;
461                                         
462                                         /* write coefficients array */
463                                         if (data->coefficients)
464                                                 writedata(wd, DATA, sizeof(float)*(data->arraysize), data->coefficients);
465                                 }
466                                         break;
467                                 case FMODIFIER_TYPE_ENVELOPE:
468                                 {
469                                         FMod_Envelope *data= (FMod_Envelope *)fcm->data;
470                                         
471                                         /* write envelope data */
472                                         if (data->data)
473                                                 writestruct(wd, DATA, "FCM_EnvelopeData", data->totvert, data->data);
474                                 }
475                                         break;
476                                 case FMODIFIER_TYPE_PYTHON:
477                                 {
478                                         FMod_Python *data = (FMod_Python *)fcm->data;
479                                         
480                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
481                                          of library blocks that implement this.*/
482                                         IDP_WriteProperty(data->prop, wd);
483                                 }
484                                         break;
485                         }
486                 }
487                 
488                 /* Write the modifier */
489                 writestruct(wd, DATA, "FModifier", 1, fcm);
490         }
491 }
492
493 static void write_fcurves(WriteData *wd, ListBase *fcurves)
494 {
495         FCurve *fcu;
496         
497         for (fcu=fcurves->first; fcu; fcu=fcu->next) {
498                 /* F-Curve */
499                 writestruct(wd, DATA, "FCurve", 1, fcu);
500                 
501                 /* curve data */
502                 if (fcu->bezt)          
503                         writestruct(wd, DATA, "BezTriple", fcu->totvert, fcu->bezt);
504                 if (fcu->fpt)
505                         writestruct(wd, DATA, "FPoint", fcu->totvert, fcu->fpt);
506                         
507                 if (fcu->rna_path)
508                         writedata(wd, DATA, strlen(fcu->rna_path)+1, fcu->rna_path);
509                 
510                 /* driver data */
511                 if (fcu->driver) {
512                         ChannelDriver *driver= fcu->driver;
513                         DriverVar *dvar;
514                         
515                         writestruct(wd, DATA, "ChannelDriver", 1, driver);
516                         
517                         /* variables */
518                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
519                                 writestruct(wd, DATA, "DriverVar", 1, dvar);
520                                 
521                                 DRIVER_TARGETS_USED_LOOPER(dvar)
522                                 {
523                                         if (dtar->rna_path)
524                                                 writedata(wd, DATA, strlen(dtar->rna_path)+1, dtar->rna_path);
525                                 }
526                                 DRIVER_TARGETS_LOOPER_END
527                         }
528                 }
529                 
530                 /* write F-Modifiers */
531                 write_fmodifiers(wd, &fcu->modifiers);
532         }
533 }
534
535 static void write_actions(WriteData *wd, ListBase *idbase)
536 {
537         bAction *act;
538         bActionGroup *grp;
539         TimeMarker *marker;
540         
541         for(act=idbase->first; act; act= act->id.next) {
542                 if (act->id.us>0 || wd->current) {
543                         writestruct(wd, ID_AC, "bAction", 1, act);
544                         if (act->id.properties) IDP_WriteProperty(act->id.properties, wd);
545                         
546                         write_fcurves(wd, &act->curves);
547                         
548                         for (grp=act->groups.first; grp; grp=grp->next) {
549                                 writestruct(wd, DATA, "bActionGroup", 1, grp);
550                         }
551                         
552                         for (marker=act->markers.first; marker; marker=marker->next) {
553                                 writestruct(wd, DATA, "TimeMarker", 1, marker);
554                         }
555                 }
556         }
557         
558         /* flush helps the compression for undo-save */
559         mywrite(wd, MYWRITE_FLUSH, 0);
560 }
561
562 static void write_keyingsets(WriteData *wd, ListBase *list)
563 {
564         KeyingSet *ks;
565         KS_Path *ksp;
566         
567         for (ks= list->first; ks; ks= ks->next) {
568                 /* KeyingSet */
569                 writestruct(wd, DATA, "KeyingSet", 1, ks);
570                 
571                 /* Paths */
572                 for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
573                         /* Path */
574                         writestruct(wd, DATA, "KS_Path", 1, ksp);
575                         
576                         if (ksp->rna_path)
577                                 writedata(wd, DATA, strlen(ksp->rna_path)+1, ksp->rna_path);
578                 }
579         }
580 }
581
582 static void write_nlastrips(WriteData *wd, ListBase *strips)
583 {
584         NlaStrip *strip;
585         
586         for (strip= strips->first; strip; strip= strip->next) {
587                 /* write the strip first */
588                 writestruct(wd, DATA, "NlaStrip", 1, strip);
589                 
590                 /* write the strip's F-Curves and modifiers */
591                 write_fcurves(wd, &strip->fcurves);
592                 write_fmodifiers(wd, &strip->modifiers);
593                 
594                 /* write the strip's children */
595                 write_nlastrips(wd, &strip->strips);
596         }
597 }
598
599 static void write_nladata(WriteData *wd, ListBase *nlabase)
600 {
601         NlaTrack *nlt;
602         
603         /* write all the tracks */
604         for (nlt= nlabase->first; nlt; nlt= nlt->next) {
605                 /* write the track first */
606                 writestruct(wd, DATA, "NlaTrack", 1, nlt);
607                 
608                 /* write the track's strips */
609                 write_nlastrips(wd, &nlt->strips);
610         }
611 }
612
613 static void write_animdata(WriteData *wd, AnimData *adt)
614 {
615         AnimOverride *aor;
616         
617         /* firstly, just write the AnimData block */
618         writestruct(wd, DATA, "AnimData", 1, adt);
619         
620         /* write drivers */
621         write_fcurves(wd, &adt->drivers);
622         
623         /* write overrides */
624         // FIXME: are these needed?
625         for (aor= adt->overrides.first; aor; aor= aor->next) {
626                 /* overrides consist of base data + rna_path */
627                 writestruct(wd, DATA, "AnimOverride", 1, aor);
628                 writedata(wd, DATA, strlen(aor->rna_path)+1, aor->rna_path);
629         }
630         
631         // TODO write the remaps (if they are needed)
632         
633         /* write NLA data */
634         write_nladata(wd, &adt->nla_tracks);
635 }
636
637 static void write_curvemapping(WriteData *wd, CurveMapping *cumap)
638 {
639         int a;
640         
641         writestruct(wd, DATA, "CurveMapping", 1, cumap);
642         for(a=0; a<CM_TOT; a++)
643                 writestruct(wd, DATA, "CurveMapPoint", cumap->cm[a].totpoint, cumap->cm[a].curve);
644 }
645
646 static void write_node_socket(WriteData *wd, bNodeSocket *sock)
647 {
648         bNodeSocketType *stype= ntreeGetSocketType(sock->type);
649
650         /* forward compatibility code, so older blenders still open */
651         sock->stack_type = 1;
652
653         if(sock->default_value) {
654                 bNodeSocketValueFloat *valfloat;
655                 bNodeSocketValueVector *valvector;
656                 bNodeSocketValueRGBA *valrgba;
657                 
658                 switch (sock->type) {
659                 case SOCK_FLOAT:
660                         valfloat = sock->default_value;
661                         sock->ns.vec[0] = valfloat->value;
662                         sock->ns.min = valfloat->min;
663                         sock->ns.max = valfloat->max;
664                         break;
665                 case SOCK_VECTOR:
666                         valvector = sock->default_value;
667                         copy_v3_v3(sock->ns.vec, valvector->value);
668                         sock->ns.min = valvector->min;
669                         sock->ns.max = valvector->max;
670                         break;
671                 case SOCK_RGBA:
672                         valrgba = sock->default_value;
673                         copy_v4_v4(sock->ns.vec, valrgba->value);
674                         sock->ns.min = 0.0f;
675                         sock->ns.max = 1.0f;
676                         break;
677                 }
678         }
679
680         /* actual socket writing */
681         writestruct(wd, DATA, "bNodeSocket", 1, sock);
682         if (sock->default_value)
683                 writestruct(wd, DATA, stype->value_structname, 1, sock->default_value);
684 }
685
686 /* this is only direct data, tree itself should have been written */
687 static void write_nodetree(WriteData *wd, bNodeTree *ntree)
688 {
689         bNode *node;
690         bNodeSocket *sock;
691         bNodeLink *link;
692         
693         /* for link_list() speed, we write per list */
694         
695         if(ntree->adt) write_animdata(wd, ntree->adt);
696         
697         for(node= ntree->nodes.first; node; node= node->next)
698                 writestruct(wd, DATA, "bNode", 1, node);
699
700         for(node= ntree->nodes.first; node; node= node->next) {
701                 for(sock= node->inputs.first; sock; sock= sock->next)
702                         write_node_socket(wd, sock);
703                 for(sock= node->outputs.first; sock; sock= sock->next)
704                         write_node_socket(wd, sock);
705
706                 
707                 if(node->storage && node->type!=NODE_DYNAMIC) {
708                         /* could be handlerized at some point, now only 1 exception still */
709                         if(ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
710                                 write_curvemapping(wd, node->storage);
711                         else if(ntree->type==NTREE_COMPOSIT && ELEM4(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB, CMP_NODE_HUECORRECT))
712                                 write_curvemapping(wd, node->storage);
713                         else if(ntree->type==NTREE_TEXTURE && (node->type==TEX_NODE_CURVE_RGB || node->type==TEX_NODE_CURVE_TIME) )
714                                 write_curvemapping(wd, node->storage);
715                         else if(ntree->type==NTREE_COMPOSIT && node->type==CMP_NODE_MOVIEDISTORTION)
716                                 /* pass */ ;
717                         else
718                                 writestruct(wd, DATA, node->typeinfo->storagename, 1, node->storage);
719                 }
720         }
721         
722         for(link= ntree->links.first; link; link= link->next)
723                 writestruct(wd, DATA, "bNodeLink", 1, link);
724         
725         /* external sockets */
726         for(sock= ntree->inputs.first; sock; sock= sock->next)
727                 write_node_socket(wd, sock);
728         for(sock= ntree->outputs.first; sock; sock= sock->next)
729                 write_node_socket(wd, sock);
730 }
731
732 static void current_screen_compat(Main *mainvar, bScreen **screen)
733 {
734         wmWindowManager *wm;
735         wmWindow *window;
736
737         /* find a global current screen in the first open window, to have
738          * a reasonable default for reading in older versions */
739         wm= mainvar->wm.first;
740         window= (wm)? wm->windows.first: NULL;
741         *screen= (window)? window->screen: NULL;
742 }
743
744 static void write_renderinfo(WriteData *wd, Main *mainvar)              /* for renderdeamon */
745 {
746         bScreen *curscreen;
747         Scene *sce;
748         int data[8];
749
750         /* XXX in future, handle multiple windows with multiple screnes? */
751         current_screen_compat(mainvar, &curscreen);
752
753         for(sce= mainvar->scene.first; sce; sce= sce->id.next) {
754                 if(sce->id.lib==NULL  && ( sce==curscreen->scene || (sce->r.scemode & R_BG_RENDER)) ) {
755                         data[0]= sce->r.sfra;
756                         data[1]= sce->r.efra;
757
758                         memset(data+2, 0, sizeof(int)*6);
759                         BLI_strncpy((char *)(data+2), sce->id.name+2, sizeof(sce->id.name)-2);
760
761                         writedata(wd, REND, 32, data);
762                 }
763         }
764 }
765
766 static void write_keymapitem(WriteData *wd, wmKeyMapItem *kmi)
767 {
768         writestruct(wd, DATA, "wmKeyMapItem", 1, kmi);
769         if(kmi->properties)
770                 IDP_WriteProperty(kmi->properties, wd);
771 }
772
773 static void write_userdef(WriteData *wd)
774 {
775         bTheme *btheme;
776         wmKeyMap *keymap;
777         wmKeyMapItem *kmi;
778         wmKeyMapDiffItem *kmdi;
779         bAddon *bext;
780         uiStyle *style;
781         
782         writestruct(wd, USER, "UserDef", 1, &U);
783
784         for(btheme= U.themes.first; btheme; btheme=btheme->next)
785                 writestruct(wd, DATA, "bTheme", 1, btheme);
786
787         for(keymap= U.user_keymaps.first; keymap; keymap=keymap->next) {
788                 writestruct(wd, DATA, "wmKeyMap", 1, keymap);
789
790                 for(kmdi=keymap->diff_items.first; kmdi; kmdi=kmdi->next) {
791                         writestruct(wd, DATA, "wmKeyMapDiffItem", 1, kmdi);
792                         if(kmdi->remove_item)
793                                 write_keymapitem(wd, kmdi->remove_item);
794                         if(kmdi->add_item)
795                                 write_keymapitem(wd, kmdi->add_item);
796                 }
797
798                 for(kmi=keymap->items.first; kmi; kmi=kmi->next)
799                         write_keymapitem(wd, kmi);
800         }
801
802         for(bext= U.addons.first; bext; bext=bext->next)
803                 writestruct(wd, DATA, "bAddon", 1, bext);
804         
805         for(style= U.uistyles.first; style; style= style->next) {
806                 writestruct(wd, DATA, "uiStyle", 1, style);
807         }
808 }
809
810 static void write_boid_state(WriteData *wd, BoidState *state)
811 {
812         BoidRule *rule = state->rules.first;
813         //BoidCondition *cond = state->conditions.first;
814
815         writestruct(wd, DATA, "BoidState", 1, state);
816
817         for(; rule; rule=rule->next) {
818                 switch(rule->type) {
819                         case eBoidRuleType_Goal:
820                         case eBoidRuleType_Avoid:
821                                 writestruct(wd, DATA, "BoidRuleGoalAvoid", 1, rule);
822                                 break;
823                         case eBoidRuleType_AvoidCollision:
824                                 writestruct(wd, DATA, "BoidRuleAvoidCollision", 1, rule);
825                                 break;
826                         case eBoidRuleType_FollowLeader:
827                                 writestruct(wd, DATA, "BoidRuleFollowLeader", 1, rule);
828                                 break;
829                         case eBoidRuleType_AverageSpeed:
830                                 writestruct(wd, DATA, "BoidRuleAverageSpeed", 1, rule);
831                                 break;
832                         case eBoidRuleType_Fight:
833                                 writestruct(wd, DATA, "BoidRuleFight", 1, rule);
834                                 break;
835                         default:
836                                 writestruct(wd, DATA, "BoidRule", 1, rule);
837                                 break;
838                 }
839         }
840         //for(; cond; cond=cond->next)
841         //      writestruct(wd, DATA, "BoidCondition", 1, cond);
842 }
843
844 /* update this also to readfile.c */
845 static const char *ptcache_data_struct[] = {
846         "", // BPHYS_DATA_INDEX
847         "", // BPHYS_DATA_LOCATION
848         "", // BPHYS_DATA_VELOCITY
849         "", // BPHYS_DATA_ROTATION
850         "", // BPHYS_DATA_AVELOCITY / BPHYS_DATA_XCONST */
851         "", // BPHYS_DATA_SIZE:
852         "", // BPHYS_DATA_TIMES:        
853         "BoidData" // case BPHYS_DATA_BOIDS:
854 };
855 static const char *ptcache_extra_struct[] = {
856         "",
857         "ParticleSpring"
858 };
859 static void write_pointcaches(WriteData *wd, ListBase *ptcaches)
860 {
861         PointCache *cache = ptcaches->first;
862         int i;
863
864         for(; cache; cache=cache->next) {
865                 writestruct(wd, DATA, "PointCache", 1, cache);
866
867                 if((cache->flag & PTCACHE_DISK_CACHE)==0) {
868                         PTCacheMem *pm = cache->mem_cache.first;
869
870                         for(; pm; pm=pm->next) {
871                                 PTCacheExtra *extra = pm->extradata.first;
872
873                                 writestruct(wd, DATA, "PTCacheMem", 1, pm);
874                                 
875                                 for(i=0; i<BPHYS_TOT_DATA; i++) {
876                                         if(pm->data[i] && pm->data_types & (1<<i)) {
877                                                 if(ptcache_data_struct[i][0]=='\0')
878                                                         writedata(wd, DATA, MEM_allocN_len(pm->data[i]), pm->data[i]);
879                                                 else
880                                                         writestruct(wd, DATA, ptcache_data_struct[i], pm->totpoint, pm->data[i]);
881                                         }
882                                 }
883
884                                 for(; extra; extra=extra->next) {
885                                         if(ptcache_extra_struct[extra->type][0]=='\0')
886                                                 continue;
887                                         writestruct(wd, DATA, "PTCacheExtra", 1, extra);
888                                         writestruct(wd, DATA, ptcache_extra_struct[extra->type], extra->totdata, extra->data);
889                                 }
890                         }
891                 }
892         }
893 }
894 static void write_particlesettings(WriteData *wd, ListBase *idbase)
895 {
896         ParticleSettings *part;
897         ParticleDupliWeight *dw;
898         GroupObject *go;
899         int a;
900
901         part= idbase->first;
902         while(part) {
903                 if(part->id.us>0 || wd->current) {
904                         /* write LibData */
905                         writestruct(wd, ID_PA, "ParticleSettings", 1, part);
906                         if (part->id.properties) IDP_WriteProperty(part->id.properties, wd);
907                         if (part->adt) write_animdata(wd, part->adt);
908                         writestruct(wd, DATA, "PartDeflect", 1, part->pd);
909                         writestruct(wd, DATA, "PartDeflect", 1, part->pd2);
910                         writestruct(wd, DATA, "EffectorWeights", 1, part->effector_weights);
911
912                         dw = part->dupliweights.first;
913                         for(; dw; dw=dw->next) {
914                                 /* update indices */
915                                 dw->index = 0;
916                                 if(part->dup_group) { /* can be NULL if lining fails or set to None */
917                                         go = part->dup_group->gobject.first;
918                                         while(go && go->ob != dw->ob) {
919                                                 go=go->next;
920                                                 dw->index++;
921                                         }
922                                 }
923                                 writestruct(wd, DATA, "ParticleDupliWeight", 1, dw);
924                         }
925
926                         if(part->boids && part->phystype == PART_PHYS_BOIDS) {
927                                 BoidState *state = part->boids->states.first;
928
929                                 writestruct(wd, DATA, "BoidSettings", 1, part->boids);
930
931                                 for(; state; state=state->next)
932                                         write_boid_state(wd, state);
933                         }
934                         if(part->fluid && part->phystype == PART_PHYS_FLUID){
935                                 writestruct(wd, DATA, "SPHFluidSettings", 1, part->fluid); 
936                         }
937
938                         for(a=0; a<MAX_MTEX; a++) {
939                                 if(part->mtex[a]) writestruct(wd, DATA, "MTex", 1, part->mtex[a]);
940                         }
941                 }
942                 part= part->id.next;
943         }
944 }
945 static void write_particlesystems(WriteData *wd, ListBase *particles)
946 {
947         ParticleSystem *psys= particles->first;
948         ParticleTarget *pt;
949         int a;
950
951         for(; psys; psys=psys->next) {
952                 writestruct(wd, DATA, "ParticleSystem", 1, psys);
953
954                 if(psys->particles) {
955                         writestruct(wd, DATA, "ParticleData", psys->totpart ,psys->particles);
956
957                         if(psys->particles->hair) {
958                                 ParticleData *pa = psys->particles;
959
960                                 for(a=0; a<psys->totpart; a++, pa++)
961                                         writestruct(wd, DATA, "HairKey", pa->totkey, pa->hair);
962                         }
963
964                         if(psys->particles->boid && psys->part->phystype == PART_PHYS_BOIDS)
965                                 writestruct(wd, DATA, "BoidParticle", psys->totpart, psys->particles->boid);
966
967                         if(psys->part->fluid && psys->part->phystype == PART_PHYS_FLUID && (psys->part->fluid->flag & SPH_VISCOELASTIC_SPRINGS))
968                                 writestruct(wd, DATA, "ParticleSpring", psys->tot_fluidsprings, psys->fluid_springs);
969                 }
970                 pt = psys->targets.first;
971                 for(; pt; pt=pt->next)
972                         writestruct(wd, DATA, "ParticleTarget", 1, pt);
973
974                 if(psys->child) writestruct(wd, DATA, "ChildParticle", psys->totchild ,psys->child);
975
976                 if(psys->clmd) {
977                         writestruct(wd, DATA, "ClothModifierData", 1, psys->clmd);
978                         writestruct(wd, DATA, "ClothSimSettings", 1, psys->clmd->sim_parms);
979                         writestruct(wd, DATA, "ClothCollSettings", 1, psys->clmd->coll_parms);
980                 }
981
982                 write_pointcaches(wd, &psys->ptcaches);
983         }
984 }
985
986 static void write_properties(WriteData *wd, ListBase *lb)
987 {
988         bProperty *prop;
989
990         prop= lb->first;
991         while(prop) {
992                 writestruct(wd, DATA, "bProperty", 1, prop);
993
994                 if(prop->poin && prop->poin != &prop->data)
995                         writedata(wd, DATA, MEM_allocN_len(prop->poin), prop->poin);
996
997                 prop= prop->next;
998         }
999 }
1000
1001 static void write_sensors(WriteData *wd, ListBase *lb)
1002 {
1003         bSensor *sens;
1004
1005         sens= lb->first;
1006         while(sens) {
1007                 writestruct(wd, DATA, "bSensor", 1, sens);
1008
1009                 writedata(wd, DATA, sizeof(void *)*sens->totlinks, sens->links);
1010
1011                 switch(sens->type) {
1012                 case SENS_NEAR:
1013                         writestruct(wd, DATA, "bNearSensor", 1, sens->data);
1014                         break;
1015                 case SENS_MOUSE:
1016                         writestruct(wd, DATA, "bMouseSensor", 1, sens->data);
1017                         break;
1018                 case SENS_TOUCH:
1019                         writestruct(wd, DATA, "bTouchSensor", 1, sens->data);
1020                         break;
1021                 case SENS_KEYBOARD:
1022                         writestruct(wd, DATA, "bKeyboardSensor", 1, sens->data);
1023                         break;
1024                 case SENS_PROPERTY:
1025                         writestruct(wd, DATA, "bPropertySensor", 1, sens->data);
1026                         break;
1027                 case SENS_ARMATURE:
1028                         writestruct(wd, DATA, "bArmatureSensor", 1, sens->data);
1029                         break;
1030                 case SENS_ACTUATOR:
1031                         writestruct(wd, DATA, "bActuatorSensor", 1, sens->data);
1032                         break;
1033                 case SENS_DELAY:
1034                         writestruct(wd, DATA, "bDelaySensor", 1, sens->data);
1035                         break;
1036                 case SENS_COLLISION:
1037                         writestruct(wd, DATA, "bCollisionSensor", 1, sens->data);
1038                         break;
1039                 case SENS_RADAR:
1040                         writestruct(wd, DATA, "bRadarSensor", 1, sens->data);
1041                         break;
1042                 case SENS_RANDOM:
1043                         writestruct(wd, DATA, "bRandomSensor", 1, sens->data);
1044                         break;
1045                 case SENS_RAY:
1046                         writestruct(wd, DATA, "bRaySensor", 1, sens->data);
1047                         break;
1048                 case SENS_MESSAGE:
1049                         writestruct(wd, DATA, "bMessageSensor", 1, sens->data);
1050                         break;
1051                 case SENS_JOYSTICK:
1052                         writestruct(wd, DATA, "bJoystickSensor", 1, sens->data);
1053                         break;
1054                 default:
1055                         ; /* error: don't know how to write this file */
1056                 }
1057
1058                 sens= sens->next;
1059         }
1060 }
1061
1062 static void write_controllers(WriteData *wd, ListBase *lb)
1063 {
1064         bController *cont;
1065
1066         cont= lb->first;
1067         while(cont) {
1068                 writestruct(wd, DATA, "bController", 1, cont);
1069
1070                 writedata(wd, DATA, sizeof(void *)*cont->totlinks, cont->links);
1071
1072                 switch(cont->type) {
1073                 case CONT_EXPRESSION:
1074                         writestruct(wd, DATA, "bExpressionCont", 1, cont->data);
1075                         break;
1076                 case CONT_PYTHON:
1077                         writestruct(wd, DATA, "bPythonCont", 1, cont->data);
1078                         break;
1079                 default:
1080                         ; /* error: don't know how to write this file */
1081                 }
1082
1083                 cont= cont->next;
1084         }
1085 }
1086
1087 static void write_actuators(WriteData *wd, ListBase *lb)
1088 {
1089         bActuator *act;
1090
1091         act= lb->first;
1092         while(act) {
1093                 writestruct(wd, DATA, "bActuator", 1, act);
1094
1095                 switch(act->type) {
1096                 case ACT_ACTION:
1097                 case ACT_SHAPEACTION:
1098                         writestruct(wd, DATA, "bActionActuator", 1, act->data);
1099                         break;
1100                 case ACT_SOUND:
1101                         writestruct(wd, DATA, "bSoundActuator", 1, act->data);
1102                         break;
1103                 case ACT_OBJECT:
1104                         writestruct(wd, DATA, "bObjectActuator", 1, act->data);
1105                         break;
1106                 case ACT_IPO:
1107                         writestruct(wd, DATA, "bIpoActuator", 1, act->data);
1108                         break;
1109                 case ACT_PROPERTY:
1110                         writestruct(wd, DATA, "bPropertyActuator", 1, act->data);
1111                         break;
1112                 case ACT_CAMERA:
1113                         writestruct(wd, DATA, "bCameraActuator", 1, act->data);
1114                         break;
1115                 case ACT_CONSTRAINT:
1116                         writestruct(wd, DATA, "bConstraintActuator", 1, act->data);
1117                         break;
1118                 case ACT_EDIT_OBJECT:
1119                         writestruct(wd, DATA, "bEditObjectActuator", 1, act->data);
1120                         break;
1121                 case ACT_SCENE:
1122                         writestruct(wd, DATA, "bSceneActuator", 1, act->data);
1123                         break;
1124                 case ACT_GROUP:
1125                         writestruct(wd, DATA, "bGroupActuator", 1, act->data);
1126                         break;
1127                 case ACT_RANDOM:
1128                         writestruct(wd, DATA, "bRandomActuator", 1, act->data);
1129                         break;
1130                 case ACT_MESSAGE:
1131                         writestruct(wd, DATA, "bMessageActuator", 1, act->data);
1132                         break;
1133                 case ACT_GAME:
1134                         writestruct(wd, DATA, "bGameActuator", 1, act->data);
1135                         break;
1136                 case ACT_VISIBILITY:
1137                         writestruct(wd, DATA, "bVisibilityActuator", 1, act->data);
1138                         break;
1139                 case ACT_2DFILTER:
1140                         writestruct(wd, DATA, "bTwoDFilterActuator", 1, act->data);
1141                         break;
1142                 case ACT_PARENT:
1143                         writestruct(wd, DATA, "bParentActuator", 1, act->data);
1144                         break;
1145                 case ACT_STATE:
1146                         writestruct(wd, DATA, "bStateActuator", 1, act->data);
1147                         break;
1148                 case ACT_ARMATURE:
1149                         writestruct(wd, DATA, "bArmatureActuator", 1, act->data);
1150                         break;
1151                 case ACT_STEERING:
1152                         writestruct(wd, DATA, "bSteeringActuator", 1, act->data);
1153                         break;
1154                 default:
1155                         ; /* error: don't know how to write this file */
1156                 }
1157
1158                 act= act->next;
1159         }
1160 }
1161
1162 static void write_motionpath(WriteData *wd, bMotionPath *mpath)
1163 {
1164         /* sanity checks */
1165         if (mpath == NULL)
1166                 return;
1167         
1168         /* firstly, just write the motionpath struct */
1169         writestruct(wd, DATA, "bMotionPath", 1, mpath);
1170         
1171         /* now write the array of data */
1172         writestruct(wd, DATA, "bMotionPathVert", mpath->length, mpath->points);
1173 }
1174
1175 static void write_constraints(WriteData *wd, ListBase *conlist)
1176 {
1177         bConstraint *con;
1178
1179         for (con=conlist->first; con; con=con->next) {
1180                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1181                 
1182                 /* Write the specific data */
1183                 if (cti && con->data) {
1184                         /* firstly, just write the plain con->data struct */
1185                         writestruct(wd, DATA, cti->structName, 1, con->data);
1186                         
1187                         /* do any constraint specific stuff */
1188                         switch (con->type) {
1189                                 case CONSTRAINT_TYPE_PYTHON:
1190                                 {
1191                                         bPythonConstraint *data = (bPythonConstraint *)con->data;
1192                                         bConstraintTarget *ct;
1193                                         
1194                                         /* write targets */
1195                                         for (ct= data->targets.first; ct; ct= ct->next)
1196                                                 writestruct(wd, DATA, "bConstraintTarget", 1, ct);
1197                                         
1198                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1199                                          of library blocks that implement this.*/
1200                                         IDP_WriteProperty(data->prop, wd);
1201                                 }
1202                                         break;
1203                                 case CONSTRAINT_TYPE_SPLINEIK: 
1204                                 {
1205                                         bSplineIKConstraint *data= (bSplineIKConstraint*)con->data;
1206                                         
1207                                         /* write points array */
1208                                         writedata(wd, DATA, sizeof(float)*(data->numpoints), data->points);
1209                                 }
1210                                         break;
1211                         }
1212                 }
1213                 
1214                 /* Write the constraint */
1215                 writestruct(wd, DATA, "bConstraint", 1, con);
1216         }
1217 }
1218
1219 static void write_pose(WriteData *wd, bPose *pose)
1220 {
1221         bPoseChannel *chan;
1222         bActionGroup *grp;
1223
1224         /* Write each channel */
1225         if (!pose)
1226                 return;
1227
1228         /* Write channels */
1229         for (chan=pose->chanbase.first; chan; chan=chan->next) {
1230                 /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1231                  of library blocks that implement this.*/
1232                 if (chan->prop)
1233                         IDP_WriteProperty(chan->prop, wd);
1234                 
1235                 write_constraints(wd, &chan->constraints);
1236                 
1237                 write_motionpath(wd, chan->mpath);
1238                 
1239                 /* prevent crashes with autosave, when a bone duplicated in editmode has not yet been assigned to its posechannel */
1240                 if (chan->bone) 
1241                         chan->selectflag= chan->bone->flag & BONE_SELECTED; /* gets restored on read, for library armatures */
1242                 
1243                 writestruct(wd, DATA, "bPoseChannel", 1, chan);
1244         }
1245         
1246         /* Write groups */
1247         for (grp=pose->agroups.first; grp; grp=grp->next) 
1248                 writestruct(wd, DATA, "bActionGroup", 1, grp);
1249
1250         /* write IK param */
1251         if (pose->ikparam) {
1252                 char *structname = (char *)get_ikparam_name(pose);
1253                 if (structname)
1254                         writestruct(wd, DATA, structname, 1, pose->ikparam);
1255         }
1256
1257         /* Write this pose */
1258         writestruct(wd, DATA, "bPose", 1, pose);
1259
1260 }
1261
1262 static void write_defgroups(WriteData *wd, ListBase *defbase)
1263 {
1264         bDeformGroup    *defgroup;
1265
1266         for (defgroup=defbase->first; defgroup; defgroup=defgroup->next)
1267                 writestruct(wd, DATA, "bDeformGroup", 1, defgroup);
1268 }
1269
1270 static void write_modifiers(WriteData *wd, ListBase *modbase)
1271 {
1272         ModifierData *md;
1273
1274         if (modbase == NULL) return;
1275         for (md=modbase->first; md; md= md->next) {
1276                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1277                 if (mti == NULL) return;
1278                 
1279                 writestruct(wd, DATA, mti->structName, 1, md);
1280                         
1281                 if (md->type==eModifierType_Hook) {
1282                         HookModifierData *hmd = (HookModifierData*) md;
1283                         
1284                         writedata(wd, DATA, sizeof(int)*hmd->totindex, hmd->indexar);
1285                 }
1286                 else if(md->type==eModifierType_Cloth) {
1287                         ClothModifierData *clmd = (ClothModifierData*) md;
1288                         
1289                         writestruct(wd, DATA, "ClothSimSettings", 1, clmd->sim_parms);
1290                         writestruct(wd, DATA, "ClothCollSettings", 1, clmd->coll_parms);
1291                         writestruct(wd, DATA, "EffectorWeights", 1, clmd->sim_parms->effector_weights);
1292                         write_pointcaches(wd, &clmd->ptcaches);
1293                 } 
1294                 else if(md->type==eModifierType_Smoke) {
1295                         SmokeModifierData *smd = (SmokeModifierData*) md;
1296                         
1297                         if(smd->type & MOD_SMOKE_TYPE_DOMAIN)
1298                         {
1299                                 if(smd->domain)
1300                                 {
1301                                         write_pointcaches(wd, &(smd->domain->ptcaches[0]));
1302
1303                                         /* create fake pointcache so that old blender versions can read it */
1304                                         smd->domain->point_cache[1] = BKE_ptcache_add(&smd->domain->ptcaches[1]);
1305                                         smd->domain->point_cache[1]->flag |= PTCACHE_DISK_CACHE|PTCACHE_FAKE_SMOKE;
1306                                         smd->domain->point_cache[1]->step = 1;
1307
1308                                         write_pointcaches(wd, &(smd->domain->ptcaches[1]));
1309                                 }
1310                                 
1311                                 writestruct(wd, DATA, "SmokeDomainSettings", 1, smd->domain);
1312
1313                                 if(smd->domain) {
1314                                         /* cleanup the fake pointcache */
1315                                         BKE_ptcache_free_list(&smd->domain->ptcaches[1]);
1316                                         smd->domain->point_cache[1] = NULL;
1317                                         
1318                                         writestruct(wd, DATA, "EffectorWeights", 1, smd->domain->effector_weights);
1319                                 }
1320                         }
1321                         else if(smd->type & MOD_SMOKE_TYPE_FLOW)
1322                                 writestruct(wd, DATA, "SmokeFlowSettings", 1, smd->flow);
1323                         else if(smd->type & MOD_SMOKE_TYPE_COLL)
1324                                 writestruct(wd, DATA, "SmokeCollSettings", 1, smd->coll);
1325                 } 
1326                 else if(md->type==eModifierType_Fluidsim) {
1327                         FluidsimModifierData *fluidmd = (FluidsimModifierData*) md;
1328                         
1329                         writestruct(wd, DATA, "FluidsimSettings", 1, fluidmd->fss);
1330                 }
1331                 else if(md->type==eModifierType_DynamicPaint) {
1332                         DynamicPaintModifierData *pmd = (DynamicPaintModifierData*) md;
1333                         
1334                         if(pmd->canvas)
1335                         {
1336                                 DynamicPaintSurface *surface;
1337                                 writestruct(wd, DATA, "DynamicPaintCanvasSettings", 1, pmd->canvas);
1338                                 
1339                                 /* write surfaces */
1340                                 for (surface=pmd->canvas->surfaces.first; surface; surface=surface->next)
1341                                         writestruct(wd, DATA, "DynamicPaintSurface", 1, surface);
1342                                 /* write caches and effector weights */
1343                                 for (surface=pmd->canvas->surfaces.first; surface; surface=surface->next) {
1344                                         write_pointcaches(wd, &(surface->ptcaches));
1345
1346                                         writestruct(wd, DATA, "EffectorWeights", 1, surface->effector_weights);
1347                                 }
1348                         }
1349                         if(pmd->brush)
1350                         {
1351                                 writestruct(wd, DATA, "DynamicPaintBrushSettings", 1, pmd->brush);
1352                                 writestruct(wd, DATA, "ColorBand", 1, pmd->brush->paint_ramp);
1353                                 writestruct(wd, DATA, "ColorBand", 1, pmd->brush->vel_ramp);
1354                         }
1355                 } 
1356                 else if (md->type==eModifierType_Collision) {
1357                         
1358                         /*
1359                         CollisionModifierData *collmd = (CollisionModifierData*) md;
1360                         // TODO: CollisionModifier should use pointcache 
1361                         // + have proper reset events before enabling this
1362                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->x);
1363                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->xnew);
1364                         writestruct(wd, DATA, "MFace", collmd->numfaces, collmd->mfaces);
1365                         */
1366                 }
1367                 else if (md->type==eModifierType_MeshDeform) {
1368                         MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
1369                         int size = mmd->dyngridsize;
1370
1371                         writestruct(wd, DATA, "MDefInfluence", mmd->totinfluence, mmd->bindinfluences);
1372                         writedata(wd, DATA, sizeof(int)*(mmd->totvert+1), mmd->bindoffsets);
1373                         writedata(wd, DATA, sizeof(float)*3*mmd->totcagevert,
1374                                 mmd->bindcagecos);
1375                         writestruct(wd, DATA, "MDefCell", size*size*size, mmd->dyngrid);
1376                         writestruct(wd, DATA, "MDefInfluence", mmd->totinfluence, mmd->dyninfluences);
1377                         writedata(wd, DATA, sizeof(int)*mmd->totvert, mmd->dynverts);
1378                 }
1379                 else if (md->type==eModifierType_Warp) {
1380                         WarpModifierData *tmd = (WarpModifierData*) md;
1381                         if(tmd->curfalloff) {
1382                                 write_curvemapping(wd, tmd->curfalloff);
1383                         }
1384                 }
1385                 else if (md->type==eModifierType_WeightVGEdit) {
1386                         WeightVGEditModifierData *wmd = (WeightVGEditModifierData*) md;
1387
1388                         if (wmd->cmap_curve)
1389                                 write_curvemapping(wd, wmd->cmap_curve);
1390                 }
1391         }
1392 }
1393
1394 static void write_objects(WriteData *wd, ListBase *idbase)
1395 {
1396         Object *ob;
1397         
1398         ob= idbase->first;
1399         while(ob) {
1400                 if(ob->id.us>0 || wd->current) {
1401                         /* write LibData */
1402                         writestruct(wd, ID_OB, "Object", 1, ob);
1403                         
1404                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1405                           of library blocks that implement this.*/
1406                         if (ob->id.properties) IDP_WriteProperty(ob->id.properties, wd);
1407                         
1408                         if (ob->adt) write_animdata(wd, ob->adt);
1409                         
1410                         /* direct data */
1411                         writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
1412                         writedata(wd, DATA, sizeof(char)*ob->totcol, ob->matbits);
1413                         /* write_effects(wd, &ob->effect); */ /* not used anymore */
1414                         write_properties(wd, &ob->prop);
1415                         write_sensors(wd, &ob->sensors);
1416                         write_controllers(wd, &ob->controllers);
1417                         write_actuators(wd, &ob->actuators);
1418
1419                         if (ob->type == OB_ARMATURE) {
1420                                 bArmature *arm = ob->data;
1421                                 if (arm && ob->pose && arm->act_bone) {
1422                                         BLI_strncpy(ob->pose->proxy_act_bone, arm->act_bone->name, sizeof(ob->pose->proxy_act_bone));
1423                                 }
1424                         }
1425
1426                         write_pose(wd, ob->pose);
1427                         write_defgroups(wd, &ob->defbase);
1428                         write_constraints(wd, &ob->constraints);
1429                         write_motionpath(wd, ob->mpath);
1430                         
1431                         writestruct(wd, DATA, "PartDeflect", 1, ob->pd);
1432                         writestruct(wd, DATA, "SoftBody", 1, ob->soft);
1433                         if(ob->soft) {
1434                                 write_pointcaches(wd, &ob->soft->ptcaches);
1435                                 writestruct(wd, DATA, "EffectorWeights", 1, ob->soft->effector_weights);
1436                         }
1437                         writestruct(wd, DATA, "BulletSoftBody", 1, ob->bsoft);
1438                         
1439                         write_particlesystems(wd, &ob->particlesystem);
1440                         write_modifiers(wd, &ob->modifiers);
1441                 }
1442                 ob= ob->id.next;
1443         }
1444
1445         /* flush helps the compression for undo-save */
1446         mywrite(wd, MYWRITE_FLUSH, 0);
1447 }
1448
1449
1450 static void write_vfonts(WriteData *wd, ListBase *idbase)
1451 {
1452         VFont *vf;
1453         PackedFile * pf;
1454
1455         vf= idbase->first;
1456         while(vf) {
1457                 if(vf->id.us>0 || wd->current) {
1458                         /* write LibData */
1459                         writestruct(wd, ID_VF, "VFont", 1, vf);
1460                         if (vf->id.properties) IDP_WriteProperty(vf->id.properties, wd);
1461
1462                         /* direct data */
1463
1464                         if (vf->packedfile) {
1465                                 pf = vf->packedfile;
1466                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1467                                 writedata(wd, DATA, pf->size, pf->data);
1468                         }
1469                 }
1470
1471                 vf= vf->id.next;
1472         }
1473 }
1474
1475
1476 static void write_keys(WriteData *wd, ListBase *idbase)
1477 {
1478         Key *key;
1479         KeyBlock *kb;
1480
1481         key= idbase->first;
1482         while(key) {
1483                 if(key->id.us>0 || wd->current) {
1484                         /* write LibData */
1485                         writestruct(wd, ID_KE, "Key", 1, key);
1486                         if (key->id.properties) IDP_WriteProperty(key->id.properties, wd);
1487                         
1488                         if (key->adt) write_animdata(wd, key->adt);
1489                         
1490                         /* direct data */
1491                         kb= key->block.first;
1492                         while(kb) {
1493                                 writestruct(wd, DATA, "KeyBlock", 1, kb);
1494                                 if(kb->data) writedata(wd, DATA, kb->totelem*key->elemsize, kb->data);
1495                                 kb= kb->next;
1496                         }
1497                 }
1498
1499                 key= key->id.next;
1500         }
1501         /* flush helps the compression for undo-save */
1502         mywrite(wd, MYWRITE_FLUSH, 0);
1503 }
1504
1505 static void write_cameras(WriteData *wd, ListBase *idbase)
1506 {
1507         Camera *cam;
1508
1509         cam= idbase->first;
1510         while(cam) {
1511                 if(cam->id.us>0 || wd->current) {
1512                         /* write LibData */
1513                         writestruct(wd, ID_CA, "Camera", 1, cam);
1514                         if (cam->id.properties) IDP_WriteProperty(cam->id.properties, wd);
1515                         
1516                         if (cam->adt) write_animdata(wd, cam->adt);
1517                 }
1518
1519                 cam= cam->id.next;
1520         }
1521 }
1522
1523 static void write_mballs(WriteData *wd, ListBase *idbase)
1524 {
1525         MetaBall *mb;
1526         MetaElem *ml;
1527
1528         mb= idbase->first;
1529         while(mb) {
1530                 if(mb->id.us>0 || wd->current) {
1531                         /* write LibData */
1532                         writestruct(wd, ID_MB, "MetaBall", 1, mb);
1533                         if (mb->id.properties) IDP_WriteProperty(mb->id.properties, wd);
1534
1535                         /* direct data */
1536                         writedata(wd, DATA, sizeof(void *)*mb->totcol, mb->mat);
1537                         if (mb->adt) write_animdata(wd, mb->adt);
1538
1539                         ml= mb->elems.first;
1540                         while(ml) {
1541                                 writestruct(wd, DATA, "MetaElem", 1, ml);
1542                                 ml= ml->next;
1543                         }
1544                 }
1545                 mb= mb->id.next;
1546         }
1547 }
1548
1549 static int amount_of_chars(char *str)
1550 {
1551         // Since the data is saved as UTF-8 to the cu->str
1552         // The cu->len is not same as the strlen(cu->str)
1553         return strlen(str);
1554 }
1555
1556 static void write_curves(WriteData *wd, ListBase *idbase)
1557 {
1558         Curve *cu;
1559         Nurb *nu;
1560
1561         cu= idbase->first;
1562         while(cu) {
1563                 if(cu->id.us>0 || wd->current) {
1564                         /* write LibData */
1565                         writestruct(wd, ID_CU, "Curve", 1, cu);
1566                         
1567                         /* direct data */
1568                         writedata(wd, DATA, sizeof(void *)*cu->totcol, cu->mat);
1569                         if (cu->id.properties) IDP_WriteProperty(cu->id.properties, wd);
1570                         if (cu->adt) write_animdata(wd, cu->adt);
1571                         
1572                         if(cu->vfont) {
1573                                 writedata(wd, DATA, amount_of_chars(cu->str)+1, cu->str);
1574                                 writestruct(wd, DATA, "CharInfo", cu->len+1, cu->strinfo);
1575                                 writestruct(wd, DATA, "TextBox", cu->totbox, cu->tb);                           
1576                         }
1577                         else {
1578                                 /* is also the order of reading */
1579                                 nu= cu->nurb.first;
1580                                 while(nu) {
1581                                         writestruct(wd, DATA, "Nurb", 1, nu);
1582                                         nu= nu->next;
1583                                 }
1584                                 nu= cu->nurb.first;
1585                                 while(nu) {
1586                                         if(nu->type == CU_BEZIER)
1587                                                 writestruct(wd, DATA, "BezTriple", nu->pntsu, nu->bezt);
1588                                         else {
1589                                                 writestruct(wd, DATA, "BPoint", nu->pntsu*nu->pntsv, nu->bp);
1590                                                 if(nu->knotsu) writedata(wd, DATA, KNOTSU(nu)*sizeof(float), nu->knotsu);
1591                                                 if(nu->knotsv) writedata(wd, DATA, KNOTSV(nu)*sizeof(float), nu->knotsv);
1592                                         }
1593                                         nu= nu->next;
1594                                 }
1595                         }
1596                 }
1597                 cu= cu->id.next;
1598         }
1599
1600         /* flush helps the compression for undo-save */
1601         mywrite(wd, MYWRITE_FLUSH, 0);
1602 }
1603
1604 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
1605 {
1606         if (dvlist) {
1607                 int i;
1608                 
1609                 /* Write the dvert list */
1610                 writestruct(wd, DATA, "MDeformVert", count, dvlist);
1611                 
1612                 /* Write deformation data for each dvert */
1613                 for (i=0; i<count; i++) {
1614                         if (dvlist[i].dw)
1615                                 writestruct(wd, DATA, "MDeformWeight", dvlist[i].totweight, dvlist[i].dw);
1616                 }
1617         }
1618 }
1619
1620 static void write_mdisps(WriteData *wd, int count, MDisps *mdlist, int external)
1621 {
1622         if(mdlist) {
1623                 int i;
1624                 
1625                 writestruct(wd, DATA, "MDisps", count, mdlist);
1626                 if(!external) {
1627                         for(i = 0; i < count; ++i) {
1628                                 if(mdlist[i].disps)
1629                                         writedata(wd, DATA, sizeof(float)*3*mdlist[i].totdisp, mdlist[i].disps);
1630                         }
1631                 }
1632         }
1633 }
1634
1635 static void write_customdata(WriteData *wd, ID *id, int count, CustomData *data, int partial_type, int partial_count)
1636 {
1637         int i;
1638
1639         /* write external customdata (not for undo) */
1640         if(data->external && !wd->current)
1641                 CustomData_external_write(data, id, CD_MASK_MESH, count, 0);
1642
1643         writestruct(wd, DATA, "CustomDataLayer", data->maxlayer, data->layers);
1644
1645         for (i=0; i<data->totlayer; i++) {
1646                 CustomDataLayer *layer= &data->layers[i];
1647                 const char *structname;
1648                 int structnum, datasize;
1649
1650                 if (layer->type == CD_MDEFORMVERT) {
1651                         /* layer types that allocate own memory need special handling */
1652                         write_dverts(wd, count, layer->data);
1653                 }
1654                 else if (layer->type == CD_MDISPS) {
1655                         write_mdisps(wd, count, layer->data, layer->flag & CD_FLAG_EXTERNAL);
1656                 }
1657                 else {
1658                         CustomData_file_write_info(layer->type, &structname, &structnum);
1659                         if (structnum) {
1660                                 /* when using partial visibility, the MEdge and MFace layers
1661                                    are smaller than the original, so their type and count is
1662                                    passed to make this work */
1663                                 if (layer->type != partial_type) datasize= structnum*count;
1664                                 else datasize= structnum*partial_count;
1665
1666                                 writestruct(wd, DATA, structname, datasize, layer->data);
1667                         }
1668                         else
1669                                 printf("%s error: layer '%s':%d - can't be written to file\n",
1670                                        __func__, structname, layer->type);
1671                 }
1672         }
1673
1674         if(data->external)
1675                 writestruct(wd, DATA, "CustomDataExternal", 1, data->external);
1676 }
1677
1678 static void write_meshs(WriteData *wd, ListBase *idbase)
1679 {
1680         Mesh *mesh;
1681
1682         mesh= idbase->first;
1683         while(mesh) {
1684                 if(mesh->id.us>0 || wd->current) {
1685                         /* write LibData */
1686                         writestruct(wd, ID_ME, "Mesh", 1, mesh);
1687
1688                         /* direct data */
1689                         if (mesh->id.properties) IDP_WriteProperty(mesh->id.properties, wd);
1690                         if (mesh->adt) write_animdata(wd, mesh->adt);
1691
1692                         writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
1693
1694                         if(mesh->pv) {
1695                                 write_customdata(wd, &mesh->id, mesh->pv->totvert, &mesh->vdata, -1, 0);
1696                                 write_customdata(wd, &mesh->id, mesh->pv->totedge, &mesh->edata,
1697                                         CD_MEDGE, mesh->totedge);
1698                                 write_customdata(wd, &mesh->id, mesh->pv->totface, &mesh->fdata,
1699                                         CD_MFACE, mesh->totface);
1700                         }
1701                         else {
1702                                 write_customdata(wd, &mesh->id, mesh->totvert, &mesh->vdata, -1, 0);
1703                                 write_customdata(wd, &mesh->id, mesh->totedge, &mesh->edata, -1, 0);
1704                                 write_customdata(wd, &mesh->id, mesh->totface, &mesh->fdata, -1, 0);
1705                         }
1706
1707                         /* PMV data */
1708                         if(mesh->pv) {
1709                                 writestruct(wd, DATA, "PartialVisibility", 1, mesh->pv);
1710                                 writedata(wd, DATA, sizeof(unsigned int)*mesh->pv->totvert, mesh->pv->vert_map);
1711                                 writedata(wd, DATA, sizeof(int)*mesh->pv->totedge, mesh->pv->edge_map);
1712                                 writestruct(wd, DATA, "MFace", mesh->pv->totface, mesh->pv->old_faces);
1713                                 writestruct(wd, DATA, "MEdge", mesh->pv->totedge, mesh->pv->old_edges);
1714                         }
1715                 }
1716                 mesh= mesh->id.next;
1717         }
1718 }
1719
1720 static void write_lattices(WriteData *wd, ListBase *idbase)
1721 {
1722         Lattice *lt;
1723         
1724         lt= idbase->first;
1725         while(lt) {
1726                 if(lt->id.us>0 || wd->current) {
1727                         /* write LibData */
1728                         writestruct(wd, ID_LT, "Lattice", 1, lt);
1729                         if (lt->id.properties) IDP_WriteProperty(lt->id.properties, wd);
1730                         
1731                         /* write animdata */
1732                         if (lt->adt) write_animdata(wd, lt->adt);
1733                         
1734                         /* direct data */
1735                         writestruct(wd, DATA, "BPoint", lt->pntsu*lt->pntsv*lt->pntsw, lt->def);
1736                         
1737                         write_dverts(wd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
1738                         
1739                 }
1740                 lt= lt->id.next;
1741         }
1742 }
1743
1744 static void write_previews(WriteData *wd, PreviewImage *prv)
1745 {
1746         if (prv) {
1747                 short w = prv->w[1];
1748                 short h = prv->h[1];
1749                 unsigned int *rect = prv->rect[1];
1750                 /* don't write out large previews if not requested */
1751                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1752                         prv->w[1] = 0;
1753                         prv->h[1] = 0;
1754                         prv->rect[1] = NULL;
1755                 }
1756                 writestruct(wd, DATA, "PreviewImage", 1, prv);
1757                 if (prv->rect[0]) writedata(wd, DATA, prv->w[0]*prv->h[0]*sizeof(unsigned int), prv->rect[0]);
1758                 if (prv->rect[1]) writedata(wd, DATA, prv->w[1]*prv->h[1]*sizeof(unsigned int), prv->rect[1]);
1759
1760                 /* restore preview, we still want to keep it in memory even if not saved to file */
1761                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1762                         prv->w[1] = w;
1763                         prv->h[1] = h;
1764                         prv->rect[1] = rect;
1765                 }
1766         }
1767 }
1768
1769 static void write_images(WriteData *wd, ListBase *idbase)
1770 {
1771         Image *ima;
1772         PackedFile * pf;
1773
1774
1775         ima= idbase->first;
1776         while(ima) {
1777                 if(ima->id.us>0 || wd->current) {
1778                         /* write LibData */
1779                         writestruct(wd, ID_IM, "Image", 1, ima);
1780                         if (ima->id.properties) IDP_WriteProperty(ima->id.properties, wd);
1781
1782                         if (ima->packedfile) {
1783                                 pf = ima->packedfile;
1784                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1785                                 writedata(wd, DATA, pf->size, pf->data);
1786                         }
1787
1788                         write_previews(wd, ima->preview);
1789                 }
1790                 ima= ima->id.next;
1791         }
1792         /* flush helps the compression for undo-save */
1793         mywrite(wd, MYWRITE_FLUSH, 0);
1794 }
1795
1796 static void write_textures(WriteData *wd, ListBase *idbase)
1797 {
1798         Tex *tex;
1799
1800         tex= idbase->first;
1801         while(tex) {
1802                 if(tex->id.us>0 || wd->current) {
1803                         /* write LibData */
1804                         writestruct(wd, ID_TE, "Tex", 1, tex);
1805                         if (tex->id.properties) IDP_WriteProperty(tex->id.properties, wd);
1806
1807                         if (tex->adt) write_animdata(wd, tex->adt);
1808
1809                         /* direct data */
1810                         if(tex->type == TEX_PLUGIN && tex->plugin) writestruct(wd, DATA, "PluginTex", 1, tex->plugin);
1811                         if(tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
1812                         if(tex->type == TEX_ENVMAP && tex->env) writestruct(wd, DATA, "EnvMap", 1, tex->env);
1813                         if(tex->type == TEX_POINTDENSITY && tex->pd) {
1814                                 writestruct(wd, DATA, "PointDensity", 1, tex->pd);
1815                                 if(tex->pd->coba) writestruct(wd, DATA, "ColorBand", 1, tex->pd->coba);
1816                                 if(tex->pd->falloff_curve) write_curvemapping(wd, tex->pd->falloff_curve);
1817                         }
1818                         if(tex->type == TEX_VOXELDATA) writestruct(wd, DATA, "VoxelData", 1, tex->vd);
1819                         if(tex->type == TEX_OCEAN && tex->ot) writestruct(wd, DATA, "OceanTex", 1, tex->ot);
1820                         
1821                         /* nodetree is integral part of texture, no libdata */
1822                         if(tex->nodetree) {
1823                                 writestruct(wd, DATA, "bNodeTree", 1, tex->nodetree);
1824                                 write_nodetree(wd, tex->nodetree);
1825                         }
1826                         
1827                         write_previews(wd, tex->preview);
1828                 }
1829                 tex= tex->id.next;
1830         }
1831
1832         /* flush helps the compression for undo-save */
1833         mywrite(wd, MYWRITE_FLUSH, 0);
1834 }
1835
1836 static void write_materials(WriteData *wd, ListBase *idbase)
1837 {
1838         Material *ma;
1839         int a;
1840
1841         ma= idbase->first;
1842         while(ma) {
1843                 if(ma->id.us>0 || wd->current) {
1844                         /* write LibData */
1845                         writestruct(wd, ID_MA, "Material", 1, ma);
1846                         
1847                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1848                           of library blocks that implement this.*/
1849                         /*manually set head group property to IDP_GROUP, just in case it hadn't been
1850                           set yet :) */
1851                         if (ma->id.properties) IDP_WriteProperty(ma->id.properties, wd);
1852                         
1853                         if (ma->adt) write_animdata(wd, ma->adt);
1854
1855                         for(a=0; a<MAX_MTEX; a++) {
1856                                 if(ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
1857                         }
1858                         
1859                         if(ma->ramp_col) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_col);
1860                         if(ma->ramp_spec) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_spec);
1861                         
1862                         /* nodetree is integral part of material, no libdata */
1863                         if(ma->nodetree) {
1864                                 writestruct(wd, DATA, "bNodeTree", 1, ma->nodetree);
1865                                 write_nodetree(wd, ma->nodetree);
1866                         }
1867
1868                         write_previews(wd, ma->preview);                        
1869                 }
1870                 ma= ma->id.next;
1871         }
1872 }
1873
1874 static void write_worlds(WriteData *wd, ListBase *idbase)
1875 {
1876         World *wrld;
1877         int a;
1878
1879         wrld= idbase->first;
1880         while(wrld) {
1881                 if(wrld->id.us>0 || wd->current) {
1882                         /* write LibData */
1883                         writestruct(wd, ID_WO, "World", 1, wrld);
1884                         if (wrld->id.properties) IDP_WriteProperty(wrld->id.properties, wd);
1885                         
1886                         if (wrld->adt) write_animdata(wd, wrld->adt);
1887                         
1888                         for(a=0; a<MAX_MTEX; a++) {
1889                                 if(wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
1890                         }
1891
1892                         /* nodetree is integral part of lamps, no libdata */
1893                         if(wrld->nodetree) {
1894                                 writestruct(wd, DATA, "bNodeTree", 1, wrld->nodetree);
1895                                 write_nodetree(wd, wrld->nodetree);
1896                         }
1897                         
1898                         write_previews(wd, wrld->preview);
1899                 }
1900                 wrld= wrld->id.next;
1901         }
1902 }
1903
1904 static void write_lamps(WriteData *wd, ListBase *idbase)
1905 {
1906         Lamp *la;
1907         int a;
1908
1909         la= idbase->first;
1910         while(la) {
1911                 if(la->id.us>0 || wd->current) {
1912                         /* write LibData */
1913                         writestruct(wd, ID_LA, "Lamp", 1, la);
1914                         if (la->id.properties) IDP_WriteProperty(la->id.properties, wd);
1915                         
1916                         if (la->adt) write_animdata(wd, la->adt);
1917                         
1918                         /* direct data */
1919                         for(a=0; a<MAX_MTEX; a++) {
1920                                 if(la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
1921                         }
1922                         
1923                         if(la->curfalloff)
1924                                 write_curvemapping(wd, la->curfalloff); 
1925                         
1926                         /* nodetree is integral part of lamps, no libdata */
1927                         if(la->nodetree) {
1928                                 writestruct(wd, DATA, "bNodeTree", 1, la->nodetree);
1929                                 write_nodetree(wd, la->nodetree);
1930                         }
1931
1932                         write_previews(wd, la->preview);
1933                         
1934                 }
1935                 la= la->id.next;
1936         }
1937 }
1938
1939
1940 static void write_scenes(WriteData *wd, ListBase *scebase)
1941 {
1942         Scene *sce;
1943         Base *base;
1944         Editing *ed;
1945         Sequence *seq;
1946         MetaStack *ms;
1947         Strip *strip;
1948         TimeMarker *marker;
1949         TransformOrientation *ts;
1950         SceneRenderLayer *srl;
1951         ToolSettings *tos;
1952         
1953         sce= scebase->first;
1954         while(sce) {
1955                 /* write LibData */
1956                 writestruct(wd, ID_SCE, "Scene", 1, sce);
1957                 if (sce->id.properties) IDP_WriteProperty(sce->id.properties, wd);
1958                 
1959                 if (sce->adt) write_animdata(wd, sce->adt);
1960                 write_keyingsets(wd, &sce->keyingsets);
1961                 
1962                 /* direct data */
1963                 base= sce->base.first;
1964                 while(base) {
1965                         writestruct(wd, DATA, "Base", 1, base);
1966                         base= base->next;
1967                 }
1968                 
1969                 tos = sce->toolsettings;
1970                 writestruct(wd, DATA, "ToolSettings", 1, tos);
1971                 if(tos->vpaint) {
1972                         writestruct(wd, DATA, "VPaint", 1, tos->vpaint);
1973                 }
1974                 if(tos->wpaint) {
1975                         writestruct(wd, DATA, "VPaint", 1, tos->wpaint);
1976                 }
1977                 if(tos->sculpt) {
1978                         writestruct(wd, DATA, "Sculpt", 1, tos->sculpt);
1979                 }
1980
1981                 // write_paint(wd, &tos->imapaint.paint);
1982
1983                 ed= sce->ed;
1984                 if(ed) {
1985                         writestruct(wd, DATA, "Editing", 1, ed);
1986                         
1987                         /* reset write flags too */
1988                         
1989                         SEQ_BEGIN(ed, seq) {
1990                                 if(seq->strip) seq->strip->done= 0;
1991                                 writestruct(wd, DATA, "Sequence", 1, seq);
1992                         }
1993                         SEQ_END
1994                         
1995                         SEQ_BEGIN(ed, seq) {
1996                                 if(seq->strip && seq->strip->done==0) {
1997                                         /* write strip with 'done' at 0 because readfile */
1998                                         
1999                                         if(seq->plugin) writestruct(wd, DATA, "PluginSeq", 1, seq->plugin);
2000                                         if(seq->effectdata) {
2001                                                 switch(seq->type){
2002                                                 case SEQ_COLOR:
2003                                                         writestruct(wd, DATA, "SolidColorVars", 1, seq->effectdata);
2004                                                         break;
2005                                                 case SEQ_SPEED:
2006                                                         writestruct(wd, DATA, "SpeedControlVars", 1, seq->effectdata);
2007                                                         break;
2008                                                 case SEQ_WIPE:
2009                                                         writestruct(wd, DATA, "WipeVars", 1, seq->effectdata);
2010                                                         break;
2011                                                 case SEQ_GLOW:
2012                                                         writestruct(wd, DATA, "GlowVars", 1, seq->effectdata);
2013                                                         break;
2014                                                 case SEQ_TRANSFORM:
2015                                                         writestruct(wd, DATA, "TransformVars", 1, seq->effectdata);
2016                                                         break;
2017                                                 }
2018                                         }
2019                                         
2020                                         strip= seq->strip;
2021                                         writestruct(wd, DATA, "Strip", 1, strip);
2022                                         if(seq->flag & SEQ_USE_CROP && strip->crop) {
2023                                                 writestruct(wd, DATA, "StripCrop", 1, strip->crop);
2024                                         }
2025                                         if(seq->flag & SEQ_USE_TRANSFORM && strip->transform) {
2026                                                 writestruct(wd, DATA, "StripTransform", 1, strip->transform);
2027                                         }
2028                                         if(seq->flag & SEQ_USE_PROXY && strip->proxy) {
2029                                                 writestruct(wd, DATA, "StripProxy", 1, strip->proxy);
2030                                         }
2031                                         if(seq->flag & SEQ_USE_COLOR_BALANCE && strip->color_balance) {
2032                                                 writestruct(wd, DATA, "StripColorBalance", 1, strip->color_balance);
2033                                         }
2034                                         if(seq->type==SEQ_IMAGE)
2035                                                 writestruct(wd, DATA, "StripElem", MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem), strip->stripdata);
2036                                         else if(seq->type==SEQ_MOVIE || seq->type==SEQ_RAM_SOUND || seq->type == SEQ_HD_SOUND)
2037                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
2038                                         
2039                                         strip->done= 1;
2040                                 }
2041                         }
2042                         SEQ_END
2043                                 
2044                         /* new; meta stack too, even when its nasty restore code */
2045                         for(ms= ed->metastack.first; ms; ms= ms->next) {
2046                                 writestruct(wd, DATA, "MetaStack", 1, ms);
2047                         }
2048                 }
2049                 
2050                 if (sce->r.avicodecdata) {
2051                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
2052                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
2053                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
2054                 }
2055
2056                 if (sce->r.qtcodecdata) {
2057                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
2058                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
2059                 }
2060                 if (sce->r.ffcodecdata.properties) {
2061                         IDP_WriteProperty(sce->r.ffcodecdata.properties, wd);
2062                 }
2063
2064                 /* writing dynamic list of TimeMarkers to the blend file */
2065                 for(marker= sce->markers.first; marker; marker= marker->next)
2066                         writestruct(wd, DATA, "TimeMarker", 1, marker);
2067                 
2068                 /* writing dynamic list of TransformOrientations to the blend file */
2069                 for(ts = sce->transform_spaces.first; ts; ts = ts->next)
2070                         writestruct(wd, DATA, "TransformOrientation", 1, ts);
2071                 
2072                 for(srl= sce->r.layers.first; srl; srl= srl->next)
2073                         writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
2074                 
2075                 if(sce->nodetree) {
2076                         writestruct(wd, DATA, "bNodeTree", 1, sce->nodetree);
2077                         write_nodetree(wd, sce->nodetree);
2078                 }
2079                 
2080                 sce= sce->id.next;
2081         }
2082         /* flush helps the compression for undo-save */
2083         mywrite(wd, MYWRITE_FLUSH, 0);
2084 }
2085
2086 static void write_gpencils(WriteData *wd, ListBase *lb)
2087 {
2088         bGPdata *gpd;
2089         bGPDlayer *gpl;
2090         bGPDframe *gpf;
2091         bGPDstroke *gps;
2092         
2093         for (gpd= lb->first; gpd; gpd= gpd->id.next) {
2094                 if (gpd->id.us>0 || wd->current) {
2095                         /* write gpd data block to file */
2096                         writestruct(wd, ID_GD, "bGPdata", 1, gpd);
2097                         
2098                         /* write grease-pencil layers to file */
2099                         for (gpl= gpd->layers.first; gpl; gpl= gpl->next) {
2100                                 writestruct(wd, DATA, "bGPDlayer", 1, gpl);
2101                                 
2102                                 /* write this layer's frames to file */
2103                                 for (gpf= gpl->frames.first; gpf; gpf= gpf->next) {
2104                                         writestruct(wd, DATA, "bGPDframe", 1, gpf);
2105                                         
2106                                         /* write strokes */
2107                                         for (gps= gpf->strokes.first; gps; gps= gps->next) {
2108                                                 writestruct(wd, DATA, "bGPDstroke", 1, gps);
2109                                                 writestruct(wd, DATA, "bGPDspoint", gps->totpoints, gps->points);                               
2110                                         }
2111                                 }
2112                         }
2113                 }
2114         }
2115 }
2116
2117 static void write_windowmanagers(WriteData *wd, ListBase *lb)
2118 {
2119         wmWindowManager *wm;
2120         wmWindow *win;
2121         
2122         for(wm= lb->first; wm; wm= wm->id.next) {
2123                 writestruct(wd, ID_WM, "wmWindowManager", 1, wm);
2124                 
2125                 for(win= wm->windows.first; win; win= win->next)
2126                         writestruct(wd, DATA, "wmWindow", 1, win);
2127         }
2128 }
2129
2130 static void write_region(WriteData *wd, ARegion *ar, int spacetype)
2131 {       
2132         writestruct(wd, DATA, "ARegion", 1, ar);
2133         
2134         if(ar->regiondata) {
2135                 switch(spacetype) {
2136                         case SPACE_VIEW3D:
2137                                 if(ar->regiontype==RGN_TYPE_WINDOW) {
2138                                         RegionView3D *rv3d= ar->regiondata;
2139                                         writestruct(wd, DATA, "RegionView3D", 1, rv3d);
2140                                         
2141                                         if(rv3d->localvd)
2142                                                 writestruct(wd, DATA, "RegionView3D", 1, rv3d->localvd);
2143                                         if(rv3d->clipbb) 
2144                                                 writestruct(wd, DATA, "BoundBox", 1, rv3d->clipbb);
2145
2146                                 }
2147                                 else
2148                                         printf("regiondata write missing!\n");
2149                                 break;
2150                         default:
2151                                 printf("regiondata write missing!\n");
2152                 }
2153         }
2154 }
2155
2156 static void write_screens(WriteData *wd, ListBase *scrbase)
2157 {
2158         bScreen *sc;
2159         ScrArea *sa;
2160         ScrVert *sv;
2161         ScrEdge *se;
2162
2163         sc= scrbase->first;
2164         while(sc) {
2165                 
2166                 /* write LibData */
2167                 /* in 2.50+ files, the file identifier for screens is patched, forward compatibility */
2168                 writestruct(wd, ID_SCRN, "Screen", 1, sc);
2169                 if (sc->id.properties) 
2170                         IDP_WriteProperty(sc->id.properties, wd);
2171                 
2172                 /* direct data */
2173                 for(sv= sc->vertbase.first; sv; sv= sv->next)
2174                         writestruct(wd, DATA, "ScrVert", 1, sv);
2175                 
2176                 for(se= sc->edgebase.first; se; se= se->next) 
2177                         writestruct(wd, DATA, "ScrEdge", 1, se);
2178                 
2179                 for(sa= sc->areabase.first; sa; sa= sa->next) {
2180                         SpaceLink *sl;
2181                         Panel *pa;
2182                         ARegion *ar;
2183                         
2184                         writestruct(wd, DATA, "ScrArea", 1, sa);
2185                         
2186                         for(ar= sa->regionbase.first; ar; ar= ar->next) {
2187                                 write_region(wd, ar, sa->spacetype);
2188                                 
2189                                 for(pa= ar->panels.first; pa; pa= pa->next)
2190                                         writestruct(wd, DATA, "Panel", 1, pa);
2191                         }
2192                         
2193                         sl= sa->spacedata.first;
2194                         while(sl) {
2195                                 for(ar= sl->regionbase.first; ar; ar= ar->next)
2196                                         write_region(wd, ar, sl->spacetype);
2197                                 
2198                                 if(sl->spacetype==SPACE_VIEW3D) {
2199                                         View3D *v3d= (View3D *) sl;
2200                                         BGpic *bgpic;
2201                                         writestruct(wd, DATA, "View3D", 1, v3d);
2202                                         for (bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next)
2203                                                 writestruct(wd, DATA, "BGpic", 1, bgpic);
2204                                         if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
2205                                 }
2206                                 else if(sl->spacetype==SPACE_IPO) {
2207                                         SpaceIpo *sipo= (SpaceIpo *)sl;
2208                                         ListBase tmpGhosts = sipo->ghostCurves;
2209                                         
2210                                         /* temporarily disable ghost curves when saving */
2211                                         sipo->ghostCurves.first= sipo->ghostCurves.last= NULL;
2212                                         
2213                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
2214                                         if(sipo->ads) writestruct(wd, DATA, "bDopeSheet", 1, sipo->ads);
2215                                         
2216                                         /* reenable ghost curves */
2217                                         sipo->ghostCurves= tmpGhosts;
2218                                 }
2219                                 else if(sl->spacetype==SPACE_BUTS) {
2220                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
2221                                 }
2222                                 else if(sl->spacetype==SPACE_FILE) {
2223                                         SpaceFile *sfile= (SpaceFile *)sl;
2224
2225                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
2226                                         if(sfile->params)
2227                                                 writestruct(wd, DATA, "FileSelectParams", 1, sfile->params);
2228                                 }
2229                                 else if(sl->spacetype==SPACE_SEQ) {
2230                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
2231                                 }
2232                                 else if(sl->spacetype==SPACE_OUTLINER) {
2233                                         SpaceOops *so= (SpaceOops *)sl;
2234                                         
2235                                         writestruct(wd, DATA, "SpaceOops", 1, so);
2236
2237                                         /* outliner */
2238                                         if(so->treestore) {
2239                                                 writestruct(wd, DATA, "TreeStore", 1, so->treestore);
2240                                                 if(so->treestore->data)
2241                                                         writestruct(wd, DATA, "TreeStoreElem", so->treestore->usedelem, so->treestore->data);
2242                                         }
2243                                 }
2244                                 else if(sl->spacetype==SPACE_IMAGE) {
2245                                         SpaceImage *sima= (SpaceImage *)sl;
2246                                         
2247                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
2248                                         if(sima->cumap)
2249                                                 write_curvemapping(wd, sima->cumap);
2250                                 }
2251                                 else if(sl->spacetype==SPACE_TEXT) {
2252                                         writestruct(wd, DATA, "SpaceText", 1, sl);
2253                                 }
2254                                 else if(sl->spacetype==SPACE_SCRIPT) {
2255                                         SpaceScript *scr = (SpaceScript*)sl;
2256                                         scr->but_refs = NULL;
2257                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
2258                                 }
2259                                 else if(sl->spacetype==SPACE_ACTION) {
2260                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
2261                                 }
2262                                 else if(sl->spacetype==SPACE_NLA){
2263                                         SpaceNla *snla= (SpaceNla *)sl;
2264                                         
2265                                         writestruct(wd, DATA, "SpaceNla", 1, snla);
2266                                         if(snla->ads) writestruct(wd, DATA, "bDopeSheet", 1, snla->ads);
2267                                 }
2268                                 else if(sl->spacetype==SPACE_TIME){
2269                                         writestruct(wd, DATA, "SpaceTime", 1, sl);
2270                                 }
2271                                 else if(sl->spacetype==SPACE_NODE){
2272                                         writestruct(wd, DATA, "SpaceNode", 1, sl);
2273                                 }
2274                                 else if(sl->spacetype==SPACE_LOGIC){
2275                                         writestruct(wd, DATA, "SpaceLogic", 1, sl);
2276                                 }
2277                                 else if(sl->spacetype==SPACE_CONSOLE) {
2278                                         SpaceConsole *con = (SpaceConsole*)sl;
2279                                         ConsoleLine *cl;
2280
2281                                         for (cl=con->history.first; cl; cl=cl->next) {
2282                                                 /* 'len_alloc' is invalid on write, set from 'len' on read */
2283                                                 writestruct(wd, DATA, "ConsoleLine", 1, cl);
2284                                                 writedata(wd, DATA, cl->len+1, cl->line);
2285                                         }
2286                                         writestruct(wd, DATA, "SpaceConsole", 1, sl);
2287
2288                                 }
2289                                 else if(sl->spacetype==SPACE_USERPREF) {
2290                                         writestruct(wd, DATA, "SpaceUserPref", 1, sl);
2291                                 }
2292                                 else if(sl->spacetype==SPACE_CLIP) {
2293                                         writestruct(wd, DATA, "SpaceClip", 1, sl);
2294                                 }
2295
2296                                 sl= sl->next;
2297                         }
2298                 }
2299
2300                 sc= sc->id.next;
2301         }
2302 }
2303
2304 static void write_libraries(WriteData *wd, Main *main)
2305 {
2306         ListBase *lbarray[MAX_LIBARRAY];
2307         ID *id;
2308         int a, tot, foundone;
2309
2310         for(; main; main= main->next) {
2311
2312                 a=tot= set_listbasepointers(main, lbarray);
2313
2314                 /* test: is lib being used */
2315                 foundone= 0;
2316                 while(tot--) {
2317                         for(id= lbarray[tot]->first; id; id= id->next) {
2318                                 if(id->us>0 && (id->flag & LIB_EXTERN)) {
2319                                         foundone= 1;
2320                                         break;
2321                                 }
2322                         }
2323                         if(foundone) break;
2324                 }
2325
2326                 if(foundone) {
2327                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
2328
2329                         while(a--) {
2330                                 for(id= lbarray[a]->first; id; id= id->next) {
2331                                         if(id->us>0 && (id->flag & LIB_EXTERN)) {
2332                                                 writestruct(wd, ID_ID, "ID", 1, id);
2333                                         }
2334                                 }
2335                         }
2336                 }
2337         }
2338 }
2339
2340 static void write_bone(WriteData *wd, Bone* bone)
2341 {
2342         Bone*   cbone;
2343
2344         // PATCH for upward compatibility after 2.37+ armature recode
2345         bone->size[0]= bone->size[1]= bone->size[2]= 1.0f;
2346                 
2347         // Write this bone
2348         writestruct(wd, DATA, "Bone", 1, bone);
2349
2350         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
2351          of library blocks that implement this.*/
2352         if (bone->prop)
2353                 IDP_WriteProperty(bone->prop, wd);
2354         
2355         // Write Children
2356         cbone= bone->childbase.first;
2357         while(cbone) {
2358                 write_bone(wd, cbone);
2359                 cbone= cbone->next;
2360         }
2361 }
2362
2363 static void write_armatures(WriteData *wd, ListBase *idbase)
2364 {
2365         bArmature       *arm;
2366         Bone            *bone;
2367
2368         arm=idbase->first;
2369         while (arm) {
2370                 if (arm->id.us>0 || wd->current) {
2371                         writestruct(wd, ID_AR, "bArmature", 1, arm);
2372                         if (arm->id.properties) IDP_WriteProperty(arm->id.properties, wd);
2373
2374                         if (arm->adt) write_animdata(wd, arm->adt);
2375
2376                         /* Direct data */
2377                         bone= arm->bonebase.first;
2378                         while(bone) {
2379                                 write_bone(wd, bone);
2380                                 bone=bone->next;
2381                         }
2382                 }
2383                 arm=arm->id.next;
2384         }
2385
2386         /* flush helps the compression for undo-save */
2387         mywrite(wd, MYWRITE_FLUSH, 0);
2388 }
2389
2390 static void write_texts(WriteData *wd, ListBase *idbase)
2391 {
2392         Text *text;
2393         TextLine *tmp;
2394         TextMarker *mrk;
2395
2396         text= idbase->first;
2397         while(text) {
2398                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
2399
2400                 /* write LibData */
2401                 writestruct(wd, ID_TXT, "Text", 1, text);
2402                 if(text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
2403                 if (text->id.properties) IDP_WriteProperty(text->id.properties, wd);
2404
2405                 if(!(text->flags & TXT_ISEXT)) {
2406                         /* now write the text data, in two steps for optimization in the readfunction */
2407                         tmp= text->lines.first;
2408                         while (tmp) {
2409                                 writestruct(wd, DATA, "TextLine", 1, tmp);
2410                                 tmp= tmp->next;
2411                         }
2412
2413                         tmp= text->lines.first;
2414                         while (tmp) {
2415                                 writedata(wd, DATA, tmp->len+1, tmp->line);
2416                                 tmp= tmp->next;
2417                         }
2418
2419                         /* write markers */
2420                         mrk= text->markers.first;
2421                         while (mrk) {
2422                                 writestruct(wd, DATA, "TextMarker", 1, mrk);
2423                                 mrk= mrk->next;
2424                         }
2425                 }
2426
2427
2428                 text= text->id.next;
2429         }
2430
2431         /* flush helps the compression for undo-save */
2432         mywrite(wd, MYWRITE_FLUSH, 0);
2433 }
2434
2435 static void write_speakers(WriteData *wd, ListBase *idbase)
2436 {
2437         Speaker *spk;
2438
2439         spk= idbase->first;
2440         while(spk) {
2441                 if(spk->id.us>0 || wd->current) {
2442                         /* write LibData */
2443                         writestruct(wd, ID_SPK, "Speaker", 1, spk);
2444                         if (spk->id.properties) IDP_WriteProperty(spk->id.properties, wd);
2445
2446                         if (spk->adt) write_animdata(wd, spk->adt);
2447                 }
2448                 spk= spk->id.next;
2449         }
2450 }
2451
2452 static void write_sounds(WriteData *wd, ListBase *idbase)
2453 {
2454         bSound *sound;
2455
2456         PackedFile * pf;
2457
2458         sound= idbase->first;
2459         while(sound) {
2460                 if(sound->id.us>0 || wd->current) {
2461                         /* write LibData */
2462                         writestruct(wd, ID_SO, "bSound", 1, sound);
2463                         if (sound->id.properties) IDP_WriteProperty(sound->id.properties, wd);
2464
2465                         if (sound->packedfile) {
2466                                 pf = sound->packedfile;
2467                                 writestruct(wd, DATA, "PackedFile", 1, pf);
2468                                 writedata(wd, DATA, pf->size, pf->data);
2469                         }
2470                 }
2471                 sound= sound->id.next;
2472         }
2473
2474         /* flush helps the compression for undo-save */
2475         mywrite(wd, MYWRITE_FLUSH, 0);
2476 }
2477
2478 static void write_groups(WriteData *wd, ListBase *idbase)
2479 {
2480         Group *group;
2481         GroupObject *go;
2482
2483         for(group= idbase->first; group; group= group->id.next) {
2484                 if(group->id.us>0 || wd->current) {
2485                         /* write LibData */
2486                         writestruct(wd, ID_GR, "Group", 1, group);
2487                         if (group->id.properties) IDP_WriteProperty(group->id.properties, wd);
2488
2489                         go= group->gobject.first;
2490                         while(go) {
2491                                 writestruct(wd, DATA, "GroupObject", 1, go);
2492                                 go= go->next;
2493                         }
2494                 }
2495         }
2496 }
2497
2498 static void write_nodetrees(WriteData *wd, ListBase *idbase)
2499 {
2500         bNodeTree *ntree;
2501         
2502         for(ntree=idbase->first; ntree; ntree= ntree->id.next) {
2503                 if (ntree->id.us>0 || wd->current) {
2504                         writestruct(wd, ID_NT, "bNodeTree", 1, ntree);
2505                         write_nodetree(wd, ntree);
2506                         
2507                         if (ntree->id.properties) IDP_WriteProperty(ntree->id.properties, wd);
2508                         
2509                         if (ntree->adt) write_animdata(wd, ntree->adt);
2510                 }
2511         }
2512 }
2513
2514 static void write_brushes(WriteData *wd, ListBase *idbase)
2515 {
2516         Brush *brush;
2517         
2518         for(brush=idbase->first; brush; brush= brush->id.next) {
2519                 if(brush->id.us>0 || wd->current) {
2520                         writestruct(wd, ID_BR, "Brush", 1, brush);
2521                         if (brush->id.properties) IDP_WriteProperty(brush->id.properties, wd);
2522                         
2523                         writestruct(wd, DATA, "MTex", 1, &brush->mtex);
2524                         
2525                         if(brush->curve)
2526                                 write_curvemapping(wd, brush->curve);
2527                 }
2528         }
2529 }
2530
2531 static void write_scripts(WriteData *wd, ListBase *idbase)
2532 {
2533         Script *script;
2534         
2535         for(script=idbase->first; script; script= script->id.next) {
2536                 if(script->id.us>0 || wd->current) {
2537                         writestruct(wd, ID_SCRIPT, "Script", 1, script);
2538                         if (script->id.properties) IDP_WriteProperty(script->id.properties, wd);
2539                 }
2540         }
2541 }
2542
2543 static void write_movieclips(WriteData *wd, ListBase *idbase)
2544 {
2545         MovieClip *clip;
2546
2547         clip= idbase->first;
2548         while(clip) {
2549                 if(clip->id.us>0 || wd->current) {
2550                         MovieTracking *tracking= &clip->tracking;
2551                         MovieTrackingTrack *track;
2552                         writestruct(wd, ID_MC, "MovieClip", 1, clip);
2553
2554                         if(tracking->reconstruction.camnr)
2555                                 writestruct(wd, DATA, "MovieReconstructedCamera", tracking->reconstruction.camnr, tracking->reconstruction.cameras);
2556
2557                         track= tracking->tracks.first;
2558                         while(track) {
2559                                 writestruct(wd, DATA, "MovieTrackingTrack", 1, track);
2560
2561                                 if(track->markers)
2562                                         writestruct(wd, DATA, "MovieTrackingMarker", track->markersnr, track->markers);
2563
2564                                 track= track->next;
2565                         }
2566                 }
2567
2568                 clip= clip->id.next;
2569         }
2570
2571         /* flush helps the compression for undo-save */
2572         mywrite(wd, MYWRITE_FLUSH, 0);
2573 }
2574
2575 /* context is usually defined by WM, two cases where no WM is available:
2576  * - for forward compatibility, curscreen has to be saved
2577  * - for undofile, curscene needs to be saved */
2578 static void write_global(WriteData *wd, int fileflags, Main *mainvar)
2579 {
2580         FileGlobal fg;
2581         bScreen *screen;
2582         char subvstr[8];
2583         
2584         /* prevent mem checkers from complaining */
2585         fg.pads= fg.pad= 0;
2586         memset(fg.filename, 0, sizeof(fg.filename));
2587
2588         current_screen_compat(mainvar, &screen);
2589
2590         /* XXX still remap G */
2591         fg.curscreen= screen;
2592         fg.curscene= screen->scene;
2593         fg.displaymode= G.displaymode;
2594         fg.winpos= G.winpos;
2595         fg.fileflags= (fileflags & ~(G_FILE_NO_UI|G_FILE_RELATIVE_REMAP));      // prevent to save this, is not good convention, and feature with concerns...
2596         fg.globalf= G.f;
2597         BLI_strncpy(fg.filename, mainvar->name, sizeof(fg.filename));
2598
2599         sprintf(subvstr, "%4d", BLENDER_SUBVERSION);
2600         memcpy(fg.subvstr, subvstr, 4);
2601         
2602         fg.subversion= BLENDER_SUBVERSION;
2603         fg.minversion= BLENDER_MINVERSION;
2604         fg.minsubversion= BLENDER_MINSUBVERSION;
2605 #ifdef WITH_BUILDINFO
2606         {
2607                 extern char build_rev[];
2608                 fg.revision= atoi(build_rev);
2609         }
2610 #else
2611         fg.revision= 0;
2612 #endif
2613         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
2614 }
2615
2616 /* preview image, first 2 values are width and height
2617  * second are an RGBA image (unsigned char)
2618  * note, this uses 'TEST' since new types will segfault on file load for older blender versions.
2619  */
2620 static void write_thumb(WriteData *wd, int *img)
2621 {
2622         if(img)
2623                 writedata(wd, TEST, (2 + img[0] * img[1]) * sizeof(int), img);
2624 }
2625
2626 /* if MemFile * there's filesave to memory */
2627 static int write_file_handle(Main *mainvar, int handle, MemFile *compare, MemFile *current, 
2628                                                          int write_user_block, int write_flags, int *thumb)
2629 {
2630         BHead bhead;
2631         ListBase mainlist;
2632         char buf[16];
2633         WriteData *wd;
2634
2635         blo_split_main(&mainlist, mainvar);
2636
2637         wd= bgnwrite(handle, compare, current);
2638         
2639         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (ENDIAN_ORDER==B_ENDIAN)?'V':'v', BLENDER_VERSION);
2640         mywrite(wd, buf, 12);
2641
2642         write_renderinfo(wd, mainvar);
2643         write_thumb(wd, thumb);
2644         write_global(wd, write_flags, mainvar);
2645
2646         /* no UI save in undo */
2647         if(current==NULL) {
2648                 write_windowmanagers(wd, &mainvar->wm);
2649                 write_screens  (wd, &mainvar->screen);
2650         }
2651         write_movieclips (wd, &mainvar->movieclip);
2652         write_scenes   (wd, &mainvar->scene);
2653         write_curves   (wd, &mainvar->curve);
2654         write_mballs   (wd, &mainvar->mball);
2655         write_images   (wd, &mainvar->image);
2656         write_cameras  (wd, &mainvar->camera);
2657         write_lamps    (wd, &mainvar->lamp);
2658         write_lattices (wd, &mainvar->latt);
2659         write_vfonts   (wd, &mainvar->vfont);
2660         write_keys     (wd, &mainvar->key);
2661         write_worlds   (wd, &mainvar->world);
2662         write_texts    (wd, &mainvar->text);
2663         write_speakers (wd, &mainvar->speaker);
2664         write_sounds   (wd, &mainvar->sound);
2665         write_groups   (wd, &mainvar->group);
2666         write_armatures(wd, &mainvar->armature);
2667         write_actions  (wd, &mainvar->action);
2668         write_objects  (wd, &mainvar->object);
2669         write_materials(wd, &mainvar->mat);
2670         write_textures (wd, &mainvar->tex);
2671         write_meshs    (wd, &mainvar->mesh);
2672         write_particlesettings(wd, &mainvar->particle);
2673         write_nodetrees(wd, &mainvar->nodetree);
2674         write_brushes  (wd, &mainvar->brush);
2675         write_scripts  (wd, &mainvar->script);
2676         write_gpencils (wd, &mainvar->gpencil);
2677         write_libraries(wd,  mainvar->next);
2678
2679         if (write_user_block) {
2680                 write_userdef(wd);
2681         }
2682                                                         
2683         /* dna as last, because (to be implemented) test for which structs are written */
2684         writedata(wd, DNA1, wd->sdna->datalen, wd->sdna->data);
2685
2686         /* end of file */
2687         memset(&bhead, 0, sizeof(BHead));
2688         bhead.code= ENDB;
2689         mywrite(wd, &bhead, sizeof(BHead));
2690
2691         blo_join_main(&mainlist);
2692
2693         return endwrite(wd);
2694 }
2695
2696 /* do reverse file history: .blend1 -> .blend2, .blend -> .blend1 */
2697 /* return: success(0), failure(1) */
2698 static int do_history(const char *name, ReportList *reports)
2699 {
2700         char tempname1[FILE_MAX], tempname2[FILE_MAX];
2701         int hisnr= U.versions;
2702         
2703         if(U.versions==0) return 0;
2704         if(strlen(name)<2) {
2705                 BKE_report(reports, RPT_ERROR, "Unable to make version backup: filename too short");
2706                 return 1;
2707         }
2708                 
2709         while(hisnr > 1) {
2710                 BLI_snprintf(tempname1, sizeof(tempname1), "%s%d", name, hisnr-1);
2711                 BLI_snprintf(tempname2, sizeof(tempname2), "%s%d", name, hisnr);
2712         
2713                 if(BLI_rename(tempname1, tempname2)) {
2714                         BKE_report(reports, RPT_ERROR, "Unable to make version backup");
2715                         return 1;
2716                 }       
2717                 hisnr--;
2718         }
2719
2720         /* is needed when hisnr==1 */
2721         BLI_snprintf(tempname1, sizeof(tempname1), "%s%d", name, hisnr);
2722
2723         if(BLI_rename(name, tempname1)) {
2724                 BKE_report(reports, RPT_ERROR, "Unable to make version backup");
2725                 return 1;
2726         }
2727
2728         return 0;
2729 }
2730
2731 /* return: success (1) */
2732 int BLO_write_file(Main *mainvar, const char *filepath, int write_flags, ReportList *reports, int *thumb)
2733 {
2734         char userfilename[FILE_MAX];
2735         char tempname[FILE_MAX+1];
2736         int file, err, write_user_block;
2737
2738         /* open temporary file, so we preserve the original in case we crash */
2739         BLI_snprintf(tempname, sizeof(tempname), "%s@", filepath);
2740
2741         file = open(tempname,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
2742         if(file == -1) {
2743                 BKE_reportf(reports, RPT_ERROR, "Can't open file %s for writing: %s.", tempname, strerror(errno));
2744                 return 0;
2745         }
2746
2747         /* remapping of relative paths to new file location */
2748         if(write_flags & G_FILE_RELATIVE_REMAP) {
2749                 char dir1[FILE_MAX];
2750                 char dir2[FILE_MAX];
2751                 BLI_split_dir_part(filepath, dir1, sizeof(dir1));
2752                 BLI_split_dir_part(mainvar->name, dir2, sizeof(dir2));
2753
2754                 /* just incase there is some subtle difference */
2755                 BLI_cleanup_dir(mainvar->name, dir1);
2756                 BLI_cleanup_dir(mainvar->name, dir2);
2757
2758                 if(BLI_path_cmp(dir1, dir2)==0) {
2759                         write_flags &= ~G_FILE_RELATIVE_REMAP;
2760                 }
2761                 else {
2762                         if(G.relbase_valid) {
2763                                 /* blend may not have been saved before. Tn this case
2764                                  * we should not have any relative paths, but if there
2765                                  * is somehow, an invalid or empty G.main->name it will
2766                                  * print an error, dont try make the absolute in this case. */
2767                                 makeFilesAbsolute(mainvar, G.main->name, NULL);
2768                         }
2769                 }
2770         }
2771
2772         BLI_make_file_string(G.main->name, userfilename, BLI_get_folder_create(BLENDER_USER_CONFIG, NULL), BLENDER_STARTUP_FILE);
2773         write_user_block= (BLI_path_cmp(filepath, userfilename) == 0);
2774
2775         if(write_flags & G_FILE_RELATIVE_REMAP)
2776                 makeFilesRelative(mainvar, filepath, NULL); /* note, making relative to something OTHER then G.main->name */
2777
2778         /* actual file writing */
2779         err= write_file_handle(mainvar, file, NULL,NULL, write_user_block, write_flags, thumb);
2780         close(file);
2781
2782         if (err) {
2783                 BKE_report(reports, RPT_ERROR, strerror(errno));
2784                 remove(tempname);
2785
2786                 return 0;
2787         }
2788
2789         /* file save to temporary file was successful */
2790         /* now do reverse file history (move .blend1 -> .blend2, .blend -> .blend1) */
2791         if (write_flags & G_FILE_HISTORY) { 
2792                 int err_hist = do_history(filepath, reports);
2793                 if (err_hist) {
2794                         BKE_report(reports, RPT_ERROR, "Version backup failed. File saved with @");
2795                         return 0;
2796                 }
2797         }
2798
2799         if(write_flags & G_FILE_COMPRESS) {
2800                 /* compressed files have the same ending as regular files... only from 2.4!!! */
2801                 char gzname[FILE_MAX+4];
2802                 int ret;
2803
2804                 /* first write compressed to separate @.gz */
2805                 BLI_snprintf(gzname, sizeof(gzname), "%s@.gz", filepath);
2806                 ret = BLI_file_gzip(tempname, gzname);
2807                 
2808                 if(0==ret) {
2809                         /* now rename to real file name, and delete temp @ file too */
2810                         if(BLI_rename(gzname, filepath) != 0) {
2811                                 BKE_report(reports, RPT_ERROR, "Can't change old file. File saved with @.");
2812                                 return 0;
2813                         }
2814
2815                         BLI_delete(tempname, 0, 0);
2816                 }
2817                 else if(-1==ret) {
2818                         BKE_report(reports, RPT_ERROR, "Failed opening .gz file.");
2819                         return 0;
2820                 }
2821                 else if(-2==ret) {
2822                         BKE_report(reports, RPT_ERROR, "Failed opening .blend file for compression.");
2823                         return 0;
2824                 }
2825         }
2826         else if(BLI_rename(tempname, filepath) != 0) {
2827                 BKE_report(reports, RPT_ERROR, "Can't change old file. File saved with @");
2828                 return 0;
2829         }
2830
2831         return 1;
2832 }
2833
2834 /* return: success (1) */
2835 int BLO_write_file_mem(Main *mainvar, MemFile *compare, MemFile *current, int write_flags)
2836 {
2837         int err;
2838
2839         err= write_file_handle(mainvar, 0, compare, current, 0, write_flags, NULL);
2840         
2841         if(err==0) return 1;
2842         return 0;
2843 }