svn merge -r 16231:16536 https://svn.blender.org/svnroot/bf-blender/trunk/blender
[blender.git] / source / blender / blenloader / intern / writefile.c
1 /* writefile.c
2  *
3  * .blend file writing
4  *
5  * $Id$
6  *
7  * ***** BEGIN GPL LICENSE BLOCK *****
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License
11  * as published by the Free Software Foundation; either version 2
12  * of the License, or (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): none yet.
29  *
30  * ***** END GPL LICENSE BLOCK *****
31  */
32
33 /*
34 FILEFORMAT: IFF-style structure  (but not IFF compatible!)
35
36 start file:
37         BLENDER_V100    12 bytes  (versie 1.00)
38                                         V = big endian, v = little endian
39                                         _ = 4 byte pointer, - = 8 byte pointer
40
41 datablocks:             also see struct BHead
42         <bh.code>                       4 chars
43         <bh.len>                        int,  len data after BHead
44         <bh.old>                        void,  old pointer
45         <bh.SDNAnr>                     int
46         <bh.nr>                         int, in case of array: amount of structs
47         data
48         ...
49         ...
50
51 Almost all data in Blender are structures. Each struct saved
52 gets a BHead header.  With BHead the struct can be linked again
53 and compared with StructDNA .
54
55 WRITE
56
57 Preferred writing order: (not really a must, but why would you do it random?)
58 Any case: direct data is ALWAYS after the lib block
59
60 (Local file data)
61 - for each LibBlock
62         - write LibBlock
63         - write associated direct data
64 (External file data)
65 - per library
66         - write library block
67         - per LibBlock
68                 - write the ID of LibBlock
69 - write FileGlobal (some global vars)
70 - write SDNA
71 - write USER if filename is ~/.B.blend
72 */
73
74 /* for version 2.2+
75 Important to know is that 'streaming' has been added to files, for Blender Publisher
76 */
77
78
79 #ifdef HAVE_CONFIG_H
80 #include <config.h>
81 #endif
82
83 #include "zlib.h"
84
85 #ifndef WIN32
86 #include <unistd.h>
87 #else
88 #include "winsock2.h"
89 #include "BLI_winstuff.h"
90 #include <io.h>
91 #include <process.h> // for getpid
92 #endif
93
94 #include <math.h>
95 #include <fcntl.h>
96 #include <stdio.h>
97 #include <string.h>
98 #include <stdlib.h>
99
100 #include "nla.h" //  __NLA is defined
101
102 #include "DNA_armature_types.h"
103 #include "DNA_action_types.h"
104 #include "DNA_actuator_types.h"
105 #include "DNA_brush_types.h"
106 #include "DNA_camera_types.h"
107 #include "DNA_cloth_types.h"
108 #include "DNA_color_types.h"
109 #include "DNA_constraint_types.h"
110 #include "DNA_controller_types.h"
111 #include "DNA_curve_types.h"
112 #include "DNA_customdata_types.h"
113 #include "DNA_effect_types.h"
114 #include "DNA_group_types.h"
115 #include "DNA_gpencil_types.h"
116 #include "DNA_image_types.h"
117 #include "DNA_ipo_types.h"
118 #include "DNA_fileglobal_types.h"
119 #include "DNA_key_types.h"
120 #include "DNA_lattice_types.h"
121 #include "DNA_listBase.h" /* for Listbase, the type of samples, ...*/
122 #include "DNA_lamp_types.h"
123 #include "DNA_meta_types.h"
124 #include "DNA_mesh_types.h"
125 #include "DNA_meshdata_types.h"
126 #include "DNA_material_types.h"
127 #include "DNA_modifier_types.h"
128 #include "DNA_nla_types.h"
129 #include "DNA_node_types.h"
130 #include "DNA_object_types.h"
131 #include "DNA_object_force.h"
132 #include "DNA_oops_types.h"
133 #include "DNA_packedFile_types.h"
134 #include "DNA_particle_types.h"
135 #include "DNA_property_types.h"
136 #include "DNA_scene_types.h"
137 #include "DNA_sdna_types.h"
138 #include "DNA_sequence_types.h"
139 #include "DNA_sensor_types.h"
140 #include "DNA_space_types.h"
141 #include "DNA_screen_types.h"
142 #include "DNA_sound_types.h"
143 #include "DNA_texture_types.h"
144 #include "DNA_text_types.h"
145 #include "DNA_view3d_types.h"
146 #include "DNA_vfont_types.h"
147 #include "DNA_userdef_types.h"
148 #include "DNA_world_types.h"
149
150 #include "MEM_guardedalloc.h" // MEM_freeN
151 #include "BLI_blenlib.h"
152 #include "BLI_linklist.h"
153
154 #include "BKE_action.h"
155 #include "BKE_bad_level_calls.h" // build_seqar (from WHILE_SEQ) free_oops error
156 #include "BKE_blender.h"
157 #include "BKE_cloth.h"
158 #include "BKE_curve.h"
159 #include "BKE_customdata.h"
160 #include "BKE_constraint.h"
161 #include "BKE_global.h" // for G
162 #include "BKE_library.h" // for  set_listbasepointers
163 #include "BKE_main.h" // G.main
164 #include "BKE_node.h"
165 #include "BKE_packedFile.h" // for packAll
166 #include "BKE_screen.h" // for waitcursor
167 #include "BKE_scene.h" // for do_seq
168 #include "BKE_sound.h" /* ... and for samples */
169 #include "BKE_utildefines.h" // for defines
170 #include "BKE_modifier.h"
171 #include "BKE_idprop.h"
172 #ifdef WITH_VERSE
173 #include "BKE_verse.h"
174 #include "BIF_verse.h"
175 #endif
176
177 #include "GEN_messaging.h"
178
179 #include "BLO_writefile.h"
180 #include "BLO_readfile.h"
181 #include "BLO_undofile.h"
182
183 #include "readfile.h"
184 #include "genfile.h"
185
186 #include <errno.h>
187
188 /* ********* my write, buffered writing with minimum size chunks ************ */
189
190 #define MYWRITE_BUFFER_SIZE     100000
191 #define MYWRITE_MAX_CHUNK       32768
192
193 typedef struct {
194         struct SDNA *sdna;
195
196         int file;
197         unsigned char *buf;
198         MemFile *compare, *current;
199         
200         int tot, count, error, memsize;
201 } WriteData;
202
203 static WriteData *writedata_new(int file)
204 {
205         extern unsigned char DNAstr[];  /* DNA.c */
206         extern int DNAlen;
207
208         WriteData *wd= MEM_callocN(sizeof(*wd), "writedata");
209
210                 /* XXX, see note about this in readfile.c, remove
211                  * once we have an xp lock - zr
212                  */
213
214         if (wd == NULL) return NULL;
215
216         wd->sdna= dna_sdna_from_data(DNAstr, DNAlen, 0);
217
218         wd->file= file;
219
220         wd->buf= MEM_mallocN(MYWRITE_BUFFER_SIZE, "wd->buf");
221
222         return wd;
223 }
224
225 static void writedata_do_write(WriteData *wd, void *mem, int memlen)
226 {
227         if ((wd == NULL) || wd->error || (mem == NULL) || memlen < 1) return;
228         if (wd->error) return;
229
230         /* memory based save */
231         if(wd->current) {
232                 add_memfilechunk(NULL, wd->current, mem, memlen);
233         }
234         else {
235                 if (write(wd->file, mem, memlen) != memlen)
236                         wd->error= 1;
237                 
238         }
239 }
240
241 static void writedata_free(WriteData *wd)
242 {
243         dna_freestructDNA(wd->sdna);
244
245         MEM_freeN(wd->buf);
246         MEM_freeN(wd);
247 }
248
249 /***/
250
251 int mywfile;
252
253 /**
254  * Low level WRITE(2) wrapper that buffers data
255  * @param adr Pointer to new chunk of data
256  * @param len Length of new chunk of data
257  * @warning Talks to other functions with global parameters
258  */
259  
260 #define MYWRITE_FLUSH           NULL
261
262 static void mywrite( WriteData *wd, void *adr, int len)
263 {
264         if (wd->error) return;
265
266         /* flush helps compression for undo-save */
267         if(adr==MYWRITE_FLUSH) {
268                 if(wd->count) {
269                         writedata_do_write(wd, wd->buf, wd->count);
270                         wd->count= 0;
271                 }
272                 return;
273         }
274
275         wd->tot+= len;
276         
277         /* if we have a single big chunk, write existing data in
278          * buffer and write out big chunk in smaller pieces */
279         if(len>MYWRITE_MAX_CHUNK) {
280                 if(wd->count) {
281                         writedata_do_write(wd, wd->buf, wd->count);
282                         wd->count= 0;
283                 }
284
285                 do {
286                         int writelen= MIN2(len, MYWRITE_MAX_CHUNK);
287                         writedata_do_write(wd, adr, writelen);
288                         adr = (char*)adr + writelen;
289                         len -= writelen;
290                 } while(len > 0);
291
292                 return;
293         }
294
295         /* if data would overflow buffer, write out the buffer */
296         if(len+wd->count>MYWRITE_BUFFER_SIZE-1) {
297                 writedata_do_write(wd, wd->buf, wd->count);
298                 wd->count= 0;
299         }
300
301         /* append data at end of buffer */
302         memcpy(&wd->buf[wd->count], adr, len);
303         wd->count+= len;
304 }
305
306 /**
307  * BeGiN initializer for mywrite
308  * @param file File descriptor
309  * @param write_flags Write parameters
310  * @warning Talks to other functions with global parameters
311  */
312 static WriteData *bgnwrite(int file, MemFile *compare, MemFile *current, int write_flags)
313 {
314         WriteData *wd= writedata_new(file);
315
316         if (wd == NULL) return NULL;
317
318         wd->compare= compare;
319         wd->current= current;
320         /* this inits comparing */
321         add_memfilechunk(compare, NULL, NULL, 0);
322         
323         return wd;
324 }
325
326 /**
327  * END the mywrite wrapper
328  * @return 1 if write failed
329  * @return unknown global variable otherwise
330  * @warning Talks to other functions with global parameters
331  */
332 static int endwrite(WriteData *wd)
333 {
334         int err;
335
336         if (wd->count) {
337                 writedata_do_write(wd, wd->buf, wd->count);
338                 wd->count= 0;
339         }
340         
341         err= wd->error;
342         writedata_free(wd);
343
344         return err;
345 }
346
347 /* ********** WRITE FILE ****************** */
348
349 static void writestruct(WriteData *wd, int filecode, char *structname, int nr, void *adr)
350 {
351         BHead bh;
352         short *sp;
353
354         if(adr==NULL || nr==0) return;
355
356         /* init BHead */
357         bh.code= filecode;
358         bh.old= adr;
359         bh.nr= nr;
360
361         bh.SDNAnr= dna_findstruct_nr(wd->sdna, structname);
362         if(bh.SDNAnr== -1) {
363                 printf("error: can't find SDNA code <%s>\n", structname);
364                 return;
365         }
366         sp= wd->sdna->structs[bh.SDNAnr];
367
368         bh.len= nr*wd->sdna->typelens[sp[0]];
369
370         if(bh.len==0) return;
371
372         mywrite(wd, &bh, sizeof(BHead));
373         mywrite(wd, adr, bh.len);
374 }
375
376 static void writedata(WriteData *wd, int filecode, int len, void *adr)  /* do not use for structs */
377 {
378         BHead bh;
379
380         if(adr==0) return;
381         if(len==0) return;
382
383         len+= 3;
384         len-= ( len % 4);
385
386         /* init BHead */
387         bh.code= filecode;
388         bh.old= adr;
389         bh.nr= 1;
390         bh.SDNAnr= 0;
391         bh.len= len;
392
393         mywrite(wd, &bh, sizeof(BHead));
394         if(len) mywrite(wd, adr, len);
395 }
396
397 /* *************** writing some direct data structs used in more code parts **************** */
398 /*These functions are used by blender's .blend system for file saving/loading.*/
399 void IDP_WriteProperty_OnlyData(IDProperty *prop, void *wd);
400 void IDP_WriteProperty(IDProperty *prop, void *wd);
401
402 void IDP_WriteArray(IDProperty *prop, void *wd)
403 {
404         /*REMEMBER to set totalen to len in the linking code!!*/
405         if (prop->data.pointer) {
406                 writedata(wd, DATA, MEM_allocN_len(prop->data.pointer), prop->data.pointer);
407         }
408 }
409
410 void IDP_WriteString(IDProperty *prop, void *wd)
411 {
412         /*REMEMBER to set totalen to len in the linking code!!*/
413         writedata(wd, DATA, prop->len+1, prop->data.pointer);
414 }
415
416 void IDP_WriteGroup(IDProperty *prop, void *wd)
417 {
418         IDProperty *loop;
419
420         for (loop=prop->data.group.first; loop; loop=loop->next) {
421                 IDP_WriteProperty(loop, wd);
422         }
423 }
424
425 /* Functions to read/write ID Properties */
426 void IDP_WriteProperty_OnlyData(IDProperty *prop, void *wd)
427 {
428         switch (prop->type) {
429                 case IDP_GROUP:
430                         IDP_WriteGroup(prop, wd);
431                         break;
432                 case IDP_STRING:
433                         IDP_WriteString(prop, wd);
434                         break;
435                 case IDP_ARRAY:
436                         IDP_WriteArray(prop, wd);
437                         break;
438         }
439 }
440
441 void IDP_WriteProperty(IDProperty *prop, void *wd)
442 {
443         writestruct(wd, DATA, "IDProperty", 1, prop);
444         IDP_WriteProperty_OnlyData(prop, wd);
445 }
446
447 static void write_curvemapping(WriteData *wd, CurveMapping *cumap)
448 {
449         int a;
450         
451         writestruct(wd, DATA, "CurveMapping", 1, cumap);
452         for(a=0; a<CM_TOT; a++)
453                 writestruct(wd, DATA, "CurveMapPoint", cumap->cm[a].totpoint, cumap->cm[a].curve);
454 }
455
456 /* this is only direct data, tree itself should have been written */
457 static void write_nodetree(WriteData *wd, bNodeTree *ntree)
458 {
459         bNode *node;
460         bNodeSocket *sock;
461         bNodeLink *link;
462         
463         /* for link_list() speed, we write per list */
464         
465         for(node= ntree->nodes.first; node; node= node->next)
466                 writestruct(wd, DATA, "bNode", 1, node);
467
468         for(node= ntree->nodes.first; node; node= node->next) {
469                 if(node->storage && node->type!=NODE_DYNAMIC) {
470                         /* could be handlerized at some point, now only 1 exception still */
471                         if(ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
472                                 write_curvemapping(wd, node->storage);
473                         else if(ntree->type==NTREE_COMPOSIT && (node->type==CMP_NODE_TIME || node->type==CMP_NODE_CURVE_VEC || node->type==CMP_NODE_CURVE_RGB))
474                                 write_curvemapping(wd, node->storage);
475                         else 
476                                 writestruct(wd, DATA, node->typeinfo->storagename, 1, node->storage);
477                 }
478                 for(sock= node->inputs.first; sock; sock= sock->next)
479                         writestruct(wd, DATA, "bNodeSocket", 1, sock);
480                 for(sock= node->outputs.first; sock; sock= sock->next)
481                         writestruct(wd, DATA, "bNodeSocket", 1, sock);
482         }
483         
484         for(link= ntree->links.first; link; link= link->next)
485                 writestruct(wd, DATA, "bNodeLink", 1, link);
486 }
487
488 static void write_scriptlink(WriteData *wd, ScriptLink *slink)
489 {
490         writedata(wd, DATA, sizeof(void *)*slink->totscript, slink->scripts);
491         writedata(wd, DATA, sizeof(short)*slink->totscript, slink->flag);
492 }
493
494 static void write_renderinfo(WriteData *wd)             /* for renderdeamon */
495 {
496         Scene *sce;
497         int data[8];
498
499         sce= G.main->scene.first;
500         while(sce) {
501                 if(sce->id.lib==0  && ( sce==G.scene || (sce->r.scemode & R_BG_RENDER)) ) {
502                         data[0]= sce->r.sfra;
503                         data[1]= sce->r.efra;
504
505                         memset(data+2, 0, sizeof(int)*6);
506                         strncpy((char *)(data+2), sce->id.name+2, 21);
507
508                         writedata(wd, REND, 32, data);
509                 }
510                 sce= sce->id.next;
511         }
512 }
513
514 static void write_userdef(WriteData *wd)
515 {
516         bTheme *btheme;
517
518         writestruct(wd, USER, "UserDef", 1, &U);
519
520         btheme= U.themes.first;
521         while(btheme) {
522                 writestruct(wd, DATA, "bTheme", 1, btheme);
523                 btheme= btheme->next;
524         }
525 }
526
527 static void write_particlesettings(WriteData *wd, ListBase *idbase)
528 {
529         ParticleSettings *part;
530
531         part= idbase->first;
532         while(part) {
533                 if(part->id.us>0 || wd->current) {
534                         /* write LibData */
535                         writestruct(wd, ID_PA, "ParticleSettings", 1, part);
536                         if (part->id.properties) IDP_WriteProperty(part->id.properties, wd);
537                         writestruct(wd, DATA, "PartDeflect", 1, part->pd);
538                         writestruct(wd, DATA, "PartDeflect", 1, part->pd2);
539                 }
540                 part= part->id.next;
541         }
542 }
543 static void write_particlesystems(WriteData *wd, ListBase *particles)
544 {
545         ParticleSystem *psys= particles->first;
546         int a;
547
548         for(; psys; psys=psys->next) {
549                 writestruct(wd, DATA, "ParticleSystem", 1, psys);
550
551                 if(psys->particles) {
552                         writestruct(wd, DATA, "ParticleData", psys->totpart ,psys->particles);
553
554                         if(psys->particles->hair) {
555                                 ParticleData *pa = psys->particles;
556
557                                 for(a=0; a<psys->totpart; a++, pa++)
558                                         writestruct(wd, DATA, "HairKey", pa->totkey, pa->hair);
559                         }
560                 }
561                 if(psys->child) writestruct(wd, DATA, "ChildParticle", psys->totchild ,psys->child);
562                 writestruct(wd, DATA, "SoftBody", 1, psys->soft);
563                 if(psys->soft) writestruct(wd, DATA, "PointCache", 1, psys->soft->pointcache);
564                 writestruct(wd, DATA, "PointCache", 1, psys->pointcache);
565         }
566 }
567
568 static void write_properties(WriteData *wd, ListBase *lb)
569 {
570         bProperty *prop;
571
572         prop= lb->first;
573         while(prop) {
574                 writestruct(wd, DATA, "bProperty", 1, prop);
575
576                 if(prop->poin && prop->poin != &prop->data)
577                         writedata(wd, DATA, MEM_allocN_len(prop->poin), prop->poin);
578
579                 prop= prop->next;
580         }
581 }
582
583 static void write_sensors(WriteData *wd, ListBase *lb)
584 {
585         bSensor *sens;
586
587         sens= lb->first;
588         while(sens) {
589                 writestruct(wd, DATA, "bSensor", 1, sens);
590
591                 writedata(wd, DATA, sizeof(void *)*sens->totlinks, sens->links);
592
593                 switch(sens->type) {
594                 case SENS_NEAR:
595                         writestruct(wd, DATA, "bNearSensor", 1, sens->data);
596                         break;
597                 case SENS_MOUSE:
598                         writestruct(wd, DATA, "bMouseSensor", 1, sens->data);
599                         break;
600                 case SENS_TOUCH:
601                         writestruct(wd, DATA, "bTouchSensor", 1, sens->data);
602                         break;
603                 case SENS_KEYBOARD:
604                         writestruct(wd, DATA, "bKeyboardSensor", 1, sens->data);
605                         break;
606                 case SENS_PROPERTY:
607                         writestruct(wd, DATA, "bPropertySensor", 1, sens->data);
608                         break;
609                 case SENS_ACTUATOR:
610                         writestruct(wd, DATA, "bActuatorSensor", 1, sens->data);
611                         break;
612                 case SENS_DELAY:
613                         writestruct(wd, DATA, "bDelaySensor", 1, sens->data);
614                         break;
615                 case SENS_COLLISION:
616                         writestruct(wd, DATA, "bCollisionSensor", 1, sens->data);
617                         break;
618                 case SENS_RADAR:
619                         writestruct(wd, DATA, "bRadarSensor", 1, sens->data);
620                         break;
621                 case SENS_RANDOM:
622                         writestruct(wd, DATA, "bRandomSensor", 1, sens->data);
623                         break;
624                 case SENS_RAY:
625                         writestruct(wd, DATA, "bRaySensor", 1, sens->data);
626                         break;
627                 case SENS_MESSAGE:
628                         writestruct(wd, DATA, "bMessageSensor", 1, sens->data);
629                         break;
630                 case SENS_JOYSTICK:
631                         writestruct(wd, DATA, "bJoystickSensor", 1, sens->data);
632                         break;
633                 default:
634                         ; /* error: don't know how to write this file */
635                 }
636
637                 sens= sens->next;
638         }
639 }
640
641 static void write_controllers(WriteData *wd, ListBase *lb)
642 {
643         bController *cont;
644
645         cont= lb->first;
646         while(cont) {
647                 writestruct(wd, DATA, "bController", 1, cont);
648
649                 writedata(wd, DATA, sizeof(void *)*cont->totlinks, cont->links);
650
651                 switch(cont->type) {
652                 case CONT_EXPRESSION:
653                         writestruct(wd, DATA, "bExpressionCont", 1, cont->data);
654                         break;
655                 case CONT_PYTHON:
656                         writestruct(wd, DATA, "bPythonCont", 1, cont->data);
657                         break;
658                 default:
659                         ; /* error: don't know how to write this file */
660                 }
661
662                 cont= cont->next;
663         }
664 }
665
666 static void write_actuators(WriteData *wd, ListBase *lb)
667 {
668         bActuator *act;
669
670         act= lb->first;
671         while(act) {
672                 writestruct(wd, DATA, "bActuator", 1, act);
673
674                 switch(act->type) {
675                 case ACT_ACTION:
676                 case ACT_SHAPEACTION:
677                         writestruct(wd, DATA, "bActionActuator", 1, act->data);
678                         break;
679                 case ACT_SOUND:
680                         writestruct(wd, DATA, "bSoundActuator", 1, act->data);
681                         break;
682                 case ACT_CD:
683                         writestruct(wd, DATA, "bCDActuator", 1, act->data);
684                         break;
685                 case ACT_OBJECT:
686                         writestruct(wd, DATA, "bObjectActuator", 1, act->data);
687                         break;
688                 case ACT_IPO:
689                         writestruct(wd, DATA, "bIpoActuator", 1, act->data);
690                         break;
691                 case ACT_PROPERTY:
692                         writestruct(wd, DATA, "bPropertyActuator", 1, act->data);
693                         break;
694                 case ACT_CAMERA:
695                         writestruct(wd, DATA, "bCameraActuator", 1, act->data);
696                         break;
697                 case ACT_CONSTRAINT:
698                         writestruct(wd, DATA, "bConstraintActuator", 1, act->data);
699                         break;
700                 case ACT_EDIT_OBJECT:
701                         writestruct(wd, DATA, "bEditObjectActuator", 1, act->data);
702                         break;
703                 case ACT_SCENE:
704                         writestruct(wd, DATA, "bSceneActuator", 1, act->data);
705                         break;
706                 case ACT_GROUP:
707                         writestruct(wd, DATA, "bGroupActuator", 1, act->data);
708                         break;
709                 case ACT_RANDOM:
710                         writestruct(wd, DATA, "bRandomActuator", 1, act->data);
711                         break;
712                 case ACT_MESSAGE:
713                         writestruct(wd, DATA, "bMessageActuator", 1, act->data);
714                         break;
715                 case ACT_GAME:
716                         writestruct(wd, DATA, "bGameActuator", 1, act->data);
717                         break;
718                 case ACT_VISIBILITY:
719                         writestruct(wd, DATA, "bVisibilityActuator", 1, act->data);
720                         break;
721                 case ACT_2DFILTER:
722                         writestruct(wd, DATA, "bTwoDFilterActuator", 1, act->data);
723                         break;
724                 case ACT_PARENT:
725                         writestruct(wd, DATA, "bParentActuator", 1, act->data);
726                         break;
727                 case ACT_STATE:
728                         writestruct(wd, DATA, "bStateActuator", 1, act->data);
729                         break;
730                 default:
731                         ; /* error: don't know how to write this file */
732                 }
733
734                 act= act->next;
735         }
736 }
737
738 static void write_nlastrips(WriteData *wd, ListBase *nlabase)
739 {
740         bActionStrip *strip;
741         bActionModifier *amod;
742         
743         for (strip=nlabase->first; strip; strip=strip->next)
744                 writestruct(wd, DATA, "bActionStrip", 1, strip);
745         for (strip=nlabase->first; strip; strip=strip->next) {
746                 for(amod= strip->modifiers.first; amod; amod= amod->next)
747                         writestruct(wd, DATA, "bActionModifier", 1, amod);
748         }
749 }
750
751 static void write_constraints(WriteData *wd, ListBase *conlist)
752 {
753         bConstraint *con;
754
755         for (con=conlist->first; con; con=con->next) {
756                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
757                 
758                 /* Write the specific data */
759                 if (cti && con->data) {
760                         /* firstly, just write the plain con->data struct */
761                         writestruct(wd, DATA, cti->structName, 1, con->data);
762                         
763                         /* do any constraint specific stuff */
764                         switch (con->type) {
765                                 case CONSTRAINT_TYPE_PYTHON:
766                                 {
767                                         bPythonConstraint *data = (bPythonConstraint *)con->data;
768                                         bConstraintTarget *ct;
769                                         
770                                         /* write targets */
771                                         for (ct= data->targets.first; ct; ct= ct->next)
772                                                 writestruct(wd, DATA, "bConstraintTarget", 1, ct);
773                                         
774                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
775                                          of library blocks that implement this.*/
776                                         IDP_WriteProperty(data->prop, wd);
777                                 }
778                                 break;
779                         }
780                 }
781                 
782                 /* Write the constraint */
783                 writestruct(wd, DATA, "bConstraint", 1, con);
784         }
785 }
786
787 static void write_pose(WriteData *wd, bPose *pose)
788 {
789         bPoseChannel *chan;
790         bActionGroup *grp;
791
792         /* Write each channel */
793         if (!pose)
794                 return;
795
796         /* Write channels */
797         for (chan=pose->chanbase.first; chan; chan=chan->next) {
798                 write_constraints(wd, &chan->constraints);
799                 
800                 /* prevent crashes with autosave, when a bone duplicated in editmode has not yet been assigned to its posechannel */
801                 if (chan->bone) 
802                         chan->selectflag= chan->bone->flag & (BONE_SELECTED|BONE_ACTIVE); /* gets restored on read, for library armatures */
803                 
804                 writestruct(wd, DATA, "bPoseChannel", 1, chan);
805         }
806         
807         /* Write groups */
808         for (grp=pose->agroups.first; grp; grp=grp->next) 
809                 writestruct(wd, DATA, "bActionGroup", 1, grp);
810
811         /* Write this pose */
812         writestruct(wd, DATA, "bPose", 1, pose);
813 }
814
815 static void write_defgroups(WriteData *wd, ListBase *defbase)
816 {
817         bDeformGroup    *defgroup;
818
819         for (defgroup=defbase->first; defgroup; defgroup=defgroup->next)
820                 writestruct(wd, DATA, "bDeformGroup", 1, defgroup);
821 }
822
823 static void write_constraint_channels(WriteData *wd, ListBase *chanbase)
824 {
825         bConstraintChannel *chan;
826
827         for (chan = chanbase->first; chan; chan=chan->next)
828                 writestruct(wd, DATA, "bConstraintChannel", 1, chan);
829
830 }
831
832 static void write_modifiers(WriteData *wd, ListBase *modbase)
833 {
834         ModifierData *md;
835
836         if (modbase == NULL) return;
837         for (md=modbase->first; md; md= md->next) {
838                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
839                 if (mti == NULL) return;
840                 
841                 writestruct(wd, DATA, mti->structName, 1, md);
842                         
843                 if (md->type==eModifierType_Hook) {
844                         HookModifierData *hmd = (HookModifierData*) md;
845                         
846                         writedata(wd, DATA, sizeof(int)*hmd->totindex, hmd->indexar);
847                 }
848                 else if(md->type==eModifierType_Cloth) {
849                         ClothModifierData *clmd = (ClothModifierData*) md;
850                         
851                         writestruct(wd, DATA, "ClothSimSettings", 1, clmd->sim_parms);
852                         writestruct(wd, DATA, "ClothCollSettings", 1, clmd->coll_parms);
853                         writestruct(wd, DATA, "PointCache", 1, clmd->point_cache);
854                 } 
855                 else if (md->type==eModifierType_Collision) {
856                         
857                         /*
858                         CollisionModifierData *collmd = (CollisionModifierData*) md;
859                         // TODO: CollisionModifier should use pointcache 
860                         // + have proper reset events before enabling this
861                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->x);
862                         writestruct(wd, DATA, "MVert", collmd->numverts, collmd->xnew);
863                         writestruct(wd, DATA, "MFace", collmd->numfaces, collmd->mfaces);
864                         */
865                 }
866                 else if (md->type==eModifierType_MeshDeform) {
867                         MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
868                         int size = mmd->dyngridsize;
869
870                         writedata(wd, DATA, sizeof(float)*mmd->totvert*mmd->totcagevert,
871                                 mmd->bindweights);
872                         writedata(wd, DATA, sizeof(float)*3*mmd->totcagevert,
873                                 mmd->bindcos);
874                         writestruct(wd, DATA, "MDefCell", size*size*size, mmd->dyngrid);
875                         writestruct(wd, DATA, "MDefInfluence", mmd->totinfluence, mmd->dyninfluences);
876                         writedata(wd, DATA, sizeof(int)*mmd->totvert, mmd->dynverts);
877                 }
878         }
879 }
880
881 static void write_objects(WriteData *wd, ListBase *idbase)
882 {
883         Object *ob;
884         
885         ob= idbase->first;
886         while(ob) {
887                 if(ob->id.us>0 || wd->current) {
888                         /* write LibData */
889 #ifdef WITH_VERSE
890                         /* pointer at vnode stored in file have to be NULL */
891                         struct VNode *vnode = (VNode*)ob->vnode;
892                         if(vnode) ob->vnode = NULL;
893 #endif
894                         writestruct(wd, ID_OB, "Object", 1, ob);
895 #ifdef WITH_VERSE
896                         if(vnode) ob->vnode = (void*)vnode;
897 #endif
898
899                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
900                           of library blocks that implement this.*/
901                         if (ob->id.properties) IDP_WriteProperty(ob->id.properties, wd);
902
903                         /* direct data */
904                         writedata(wd, DATA, sizeof(void *)*ob->totcol, ob->mat);
905                         /* write_effects(wd, &ob->effect); */ /* not used anymore */
906                         write_properties(wd, &ob->prop);
907                         write_sensors(wd, &ob->sensors);
908                         write_controllers(wd, &ob->controllers);
909                         write_actuators(wd, &ob->actuators);
910                         write_scriptlink(wd, &ob->scriptlink);
911                         write_pose(wd, ob->pose);
912                         write_defgroups(wd, &ob->defbase);
913                         write_constraints(wd, &ob->constraints);
914                         write_constraint_channels(wd, &ob->constraintChannels);
915                         write_nlastrips(wd, &ob->nlastrips);
916                         
917                         writestruct(wd, DATA, "PartDeflect", 1, ob->pd);
918                         writestruct(wd, DATA, "SoftBody", 1, ob->soft);
919                         if(ob->soft) writestruct(wd, DATA, "PointCache", 1, ob->soft->pointcache);
920                         writestruct(wd, DATA, "FluidsimSettings", 1, ob->fluidsimSettings); // NT
921                         
922                         write_particlesystems(wd, &ob->particlesystem);
923                         write_modifiers(wd, &ob->modifiers);
924                 }
925                 ob= ob->id.next;
926         }
927
928         /* flush helps the compression for undo-save */
929         mywrite(wd, MYWRITE_FLUSH, 0);
930 }
931
932
933 static void write_vfonts(WriteData *wd, ListBase *idbase)
934 {
935         VFont *vf;
936         PackedFile * pf;
937
938         vf= idbase->first;
939         while(vf) {
940                 if(vf->id.us>0 || wd->current) {
941                         /* write LibData */
942                         writestruct(wd, ID_VF, "VFont", 1, vf);
943                         if (vf->id.properties) IDP_WriteProperty(vf->id.properties, wd);
944
945                         /* direct data */
946
947                         if (vf->packedfile) {
948                                 pf = vf->packedfile;
949                                 writestruct(wd, DATA, "PackedFile", 1, pf);
950                                 writedata(wd, DATA, pf->size, pf->data);
951                         }
952                 }
953
954                 vf= vf->id.next;
955         }
956 }
957
958 static void write_ipos(WriteData *wd, ListBase *idbase)
959 {
960         Ipo *ipo;
961         IpoCurve *icu;
962
963         ipo= idbase->first;
964         while(ipo) {
965                 if(ipo->id.us>0 || wd->current) {
966                         /* write LibData */
967                         writestruct(wd, ID_IP, "Ipo", 1, ipo);
968                         if (ipo->id.properties) IDP_WriteProperty(ipo->id.properties, wd);
969
970                         /* direct data */
971                         icu= ipo->curve.first;
972                         while(icu) {
973                                 writestruct(wd, DATA, "IpoCurve", 1, icu);
974                                 icu= icu->next;
975                         }
976
977                         icu= ipo->curve.first;
978                         while(icu) {
979                                 if(icu->bezt)  writestruct(wd, DATA, "BezTriple", icu->totvert, icu->bezt);
980                                 if(icu->bp)  writestruct(wd, DATA, "BPoint", icu->totvert, icu->bp);
981                                 if(icu->driver)  writestruct(wd, DATA, "IpoDriver", 1, icu->driver);
982                                 icu= icu->next;
983                         }
984                 }
985
986                 ipo= ipo->id.next;
987         }
988
989         /* flush helps the compression for undo-save */
990         mywrite(wd, MYWRITE_FLUSH, 0);
991 }
992
993 static void write_keys(WriteData *wd, ListBase *idbase)
994 {
995         Key *key;
996         KeyBlock *kb;
997
998         key= idbase->first;
999         while(key) {
1000                 if(key->id.us>0 || wd->current) {
1001                         /* write LibData */
1002                         writestruct(wd, ID_KE, "Key", 1, key);
1003                         if (key->id.properties) IDP_WriteProperty(key->id.properties, wd);
1004
1005                         /* direct data */
1006                         kb= key->block.first;
1007                         while(kb) {
1008                                 writestruct(wd, DATA, "KeyBlock", 1, kb);
1009                                 if(kb->data) writedata(wd, DATA, kb->totelem*key->elemsize, kb->data);
1010                                 kb= kb->next;
1011                         }
1012                 }
1013
1014                 key= key->id.next;
1015         }
1016         /* flush helps the compression for undo-save */
1017         mywrite(wd, MYWRITE_FLUSH, 0);
1018 }
1019
1020 static void write_cameras(WriteData *wd, ListBase *idbase)
1021 {
1022         Camera *cam;
1023
1024         cam= idbase->first;
1025         while(cam) {
1026                 if(cam->id.us>0 || wd->current) {
1027                         /* write LibData */
1028                         writestruct(wd, ID_CA, "Camera", 1, cam);
1029                         if (cam->id.properties) IDP_WriteProperty(cam->id.properties, wd);
1030
1031                         /* direct data */
1032                         write_scriptlink(wd, &cam->scriptlink);
1033                 }
1034
1035                 cam= cam->id.next;
1036         }
1037 }
1038
1039 static void write_mballs(WriteData *wd, ListBase *idbase)
1040 {
1041         MetaBall *mb;
1042         MetaElem *ml;
1043
1044         mb= idbase->first;
1045         while(mb) {
1046                 if(mb->id.us>0 || wd->current) {
1047                         /* write LibData */
1048                         writestruct(wd, ID_MB, "MetaBall", 1, mb);
1049                         if (mb->id.properties) IDP_WriteProperty(mb->id.properties, wd);
1050
1051                         /* direct data */
1052                         writedata(wd, DATA, sizeof(void *)*mb->totcol, mb->mat);
1053
1054                         ml= mb->elems.first;
1055                         while(ml) {
1056                                 writestruct(wd, DATA, "MetaElem", 1, ml);
1057                                 ml= ml->next;
1058                         }
1059                 }
1060                 mb= mb->id.next;
1061         }
1062 }
1063
1064 int amount_of_chars(char *str)
1065 {
1066         // Since the data is saved as UTF-8 to the cu->str
1067         // The cu->len is not same as the strlen(cu->str)
1068         return strlen(str);
1069 }
1070
1071 static void write_curves(WriteData *wd, ListBase *idbase)
1072 {
1073         Curve *cu;
1074         Nurb *nu;
1075
1076         cu= idbase->first;
1077         while(cu) {
1078                 if(cu->id.us>0 || wd->current) {
1079                         /* write LibData */
1080                         writestruct(wd, ID_CU, "Curve", 1, cu);
1081
1082                         /* direct data */
1083                         writedata(wd, DATA, sizeof(void *)*cu->totcol, cu->mat);
1084                         if (cu->id.properties) IDP_WriteProperty(cu->id.properties, wd);
1085
1086                         if(cu->vfont) {
1087                                 writedata(wd, DATA, amount_of_chars(cu->str)+1, cu->str);
1088                                 writestruct(wd, DATA, "CharInfo", cu->len, cu->strinfo);
1089                                 writestruct(wd, DATA, "TextBox", cu->totbox, cu->tb);                           
1090                         }
1091                         else {
1092                                 /* is also the order of reading */
1093                                 nu= cu->nurb.first;
1094                                 while(nu) {
1095                                         writestruct(wd, DATA, "Nurb", 1, nu);
1096                                         nu= nu->next;
1097                                 }
1098                                 nu= cu->nurb.first;
1099                                 while(nu) {
1100                                         if( (nu->type & 7)==CU_BEZIER)
1101                                                 writestruct(wd, DATA, "BezTriple", nu->pntsu, nu->bezt);
1102                                         else {
1103                                                 writestruct(wd, DATA, "BPoint", nu->pntsu*nu->pntsv, nu->bp);
1104                                                 if(nu->knotsu) writedata(wd, DATA, KNOTSU(nu)*sizeof(float), nu->knotsu);
1105                                                 if(nu->knotsv) writedata(wd, DATA, KNOTSV(nu)*sizeof(float), nu->knotsv);
1106                                         }
1107                                         nu= nu->next;
1108                                 }
1109                         }
1110                 }
1111                 cu= cu->id.next;
1112         }
1113
1114         /* flush helps the compression for undo-save */
1115         mywrite(wd, MYWRITE_FLUSH, 0);
1116 }
1117
1118 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
1119 {
1120         if (dvlist) {
1121                 int     i;
1122                 
1123                 /* Write the dvert list */
1124                 writestruct(wd, DATA, "MDeformVert", count, dvlist);
1125                 
1126                 /* Write deformation data for each dvert */
1127                 for (i=0; i<count; i++) {
1128                         if (dvlist[i].dw)
1129                                 writestruct(wd, DATA, "MDeformWeight", dvlist[i].totweight, dvlist[i].dw);
1130                 }
1131         }
1132 }
1133
1134 static void write_customdata(WriteData *wd, int count, CustomData *data, int partial_type, int partial_count)
1135 {
1136         int i;
1137
1138         writestruct(wd, DATA, "CustomDataLayer", data->maxlayer, data->layers);
1139
1140         for (i=0; i<data->totlayer; i++) {
1141                 CustomDataLayer *layer= &data->layers[i];
1142                 char *structname;
1143                 int structnum, datasize;
1144
1145                 if (layer->type == CD_MDEFORMVERT) {
1146                         /* layer types that allocate own memory need special handling */
1147                         write_dverts(wd, count, layer->data);
1148                 }
1149                 else {
1150                         CustomData_file_write_info(layer->type, &structname, &structnum);
1151                         if (structnum) {
1152                                 /* when using partial visibility, the MEdge and MFace layers
1153                                    are smaller than the original, so their type and count is
1154                                    passed to make this work */
1155                                 if (layer->type != partial_type) datasize= structnum*count;
1156                                 else datasize= structnum*partial_count;
1157
1158                                 writestruct(wd, DATA, structname, datasize, layer->data);
1159                         }
1160                         else
1161                                 printf("error: this CustomDataLayer must not be written to file\n");
1162                 }
1163         }
1164 }
1165
1166 static void write_meshs(WriteData *wd, ListBase *idbase)
1167 {
1168         Mesh *mesh;
1169         MultiresLevel *lvl;
1170
1171         mesh= idbase->first;
1172         while(mesh) {
1173                 if(mesh->id.us>0 || wd->current) {
1174                         /* write LibData */
1175 #ifdef WITH_VERSE
1176                         struct VNode *vnode = (VNode*)mesh->vnode;
1177                         if(vnode) {
1178                                 /* mesh has to be created from verse geometry node*/
1179                                 create_meshdata_from_geom_node(mesh, vnode);
1180                                 /* pointer at verse node can't be stored in file */
1181                                 mesh->vnode = NULL;
1182                         }
1183 #endif
1184
1185                         writestruct(wd, ID_ME, "Mesh", 1, mesh);
1186 #ifdef WITH_VERSE
1187                         if(vnode) mesh->vnode = (void*)vnode;
1188 #endif
1189
1190                         /* direct data */
1191                         if (mesh->id.properties) IDP_WriteProperty(mesh->id.properties, wd);
1192
1193                         writedata(wd, DATA, sizeof(void *)*mesh->totcol, mesh->mat);
1194
1195                         if(mesh->pv) {
1196                                 write_customdata(wd, mesh->pv->totvert, &mesh->vdata, -1, 0);
1197                                 write_customdata(wd, mesh->pv->totedge, &mesh->edata,
1198                                         CD_MEDGE, mesh->totedge);
1199                                 write_customdata(wd, mesh->pv->totface, &mesh->fdata,
1200                                         CD_MFACE, mesh->totface);
1201                         }
1202                         else {
1203                                 write_customdata(wd, mesh->totvert, &mesh->vdata, -1, 0);
1204                                 write_customdata(wd, mesh->totedge, &mesh->edata, -1, 0);
1205                                 write_customdata(wd, mesh->totface, &mesh->fdata, -1, 0);
1206                         }
1207
1208                         /* Multires data */
1209                         writestruct(wd, DATA, "Multires", 1, mesh->mr);
1210                         if(mesh->mr) {
1211                                 lvl= mesh->mr->levels.first;
1212                                 if(lvl) {
1213                                         write_customdata(wd, lvl->totvert, &mesh->mr->vdata, -1, 0);
1214                                         write_customdata(wd, lvl->totface, &mesh->mr->fdata, -1, 0);
1215                                         writedata(wd, DATA, sizeof(short)*lvl->totedge, mesh->mr->edge_flags);
1216                                         writedata(wd, DATA, sizeof(char)*lvl->totedge, mesh->mr->edge_creases);
1217                                 }
1218
1219                                 for(; lvl; lvl= lvl->next) {
1220                                         writestruct(wd, DATA, "MultiresLevel", 1, lvl);
1221                                         writestruct(wd, DATA, "MultiresFace", lvl->totface, lvl->faces);
1222                                         writestruct(wd, DATA, "MultiresEdge", lvl->totedge, lvl->edges);
1223                                         writestruct(wd, DATA, "MultiresColFace", lvl->totface, lvl->colfaces);
1224                                 }
1225
1226                                 lvl= mesh->mr->levels.last;
1227                                 if(lvl)
1228                                         writestruct(wd, DATA, "MVert", lvl->totvert, mesh->mr->verts);
1229                         }
1230
1231                         /* PMV data */
1232                         if(mesh->pv) {
1233                                 writestruct(wd, DATA, "PartialVisibility", 1, mesh->pv);
1234                                 writedata(wd, DATA, sizeof(unsigned int)*mesh->pv->totvert, mesh->pv->vert_map);
1235                                 writedata(wd, DATA, sizeof(int)*mesh->pv->totedge, mesh->pv->edge_map);
1236                                 writestruct(wd, DATA, "MFace", mesh->pv->totface, mesh->pv->old_faces);
1237                                 writestruct(wd, DATA, "MEdge", mesh->pv->totedge, mesh->pv->old_edges);
1238                         }
1239                 }
1240                 mesh= mesh->id.next;
1241         }
1242 }
1243
1244 static void write_lattices(WriteData *wd, ListBase *idbase)
1245 {
1246         Lattice *lt;
1247         
1248         lt= idbase->first;
1249         while(lt) {
1250                 if(lt->id.us>0 || wd->current) {
1251                         /* write LibData */
1252                         writestruct(wd, ID_LT, "Lattice", 1, lt);
1253                         if (lt->id.properties) IDP_WriteProperty(lt->id.properties, wd);
1254
1255                         /* direct data */
1256                         writestruct(wd, DATA, "BPoint", lt->pntsu*lt->pntsv*lt->pntsw, lt->def);
1257                         
1258                         write_dverts(wd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
1259                         
1260                 }
1261                 lt= lt->id.next;
1262         }
1263 }
1264
1265 static void write_previews(WriteData *wd, PreviewImage *prv)
1266 {
1267         if (prv) {
1268                 short w = prv->w[1];
1269                 short h = prv->h[1];
1270                 unsigned int *rect = prv->rect[1];
1271                 /* don't write out large previews if not requested */
1272                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1273                         prv->w[1] = 0;
1274                         prv->h[1] = 0;
1275                         prv->rect[1] = NULL;
1276                 }
1277                 writestruct(wd, DATA, "PreviewImage", 1, prv);
1278                 if (prv->rect[0]) writedata(wd, DATA, prv->w[0]*prv->h[0]*sizeof(unsigned int), prv->rect[0]);
1279                 if (prv->rect[1]) writedata(wd, DATA, prv->w[1]*prv->h[1]*sizeof(unsigned int), prv->rect[1]);
1280
1281                 /* restore preview, we still want to keep it in memory even if not saved to file */
1282                 if (!(U.flag & USER_SAVE_PREVIEWS) ) {
1283                         prv->w[1] = w;
1284                         prv->h[1] = h;
1285                         prv->rect[1] = rect;
1286                 }
1287         }
1288 }
1289
1290 static void write_images(WriteData *wd, ListBase *idbase)
1291 {
1292         Image *ima;
1293         PackedFile * pf;
1294
1295
1296         ima= idbase->first;
1297         while(ima) {
1298                 if(ima->id.us>0 || wd->current) {
1299                         /* write LibData */
1300                         writestruct(wd, ID_IM, "Image", 1, ima);
1301                         if (ima->id.properties) IDP_WriteProperty(ima->id.properties, wd);
1302
1303                         if (ima->packedfile) {
1304                                 pf = ima->packedfile;
1305                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1306                                 writedata(wd, DATA, pf->size, pf->data);
1307                         }
1308
1309                         write_previews(wd, ima->preview);
1310
1311                         }
1312                 ima= ima->id.next;
1313         }
1314         /* flush helps the compression for undo-save */
1315         mywrite(wd, MYWRITE_FLUSH, 0);
1316 }
1317
1318 static void write_textures(WriteData *wd, ListBase *idbase)
1319 {
1320         Tex *tex;
1321
1322         tex= idbase->first;
1323         while(tex) {
1324                 if(tex->id.us>0 || wd->current) {
1325                         /* write LibData */
1326                         writestruct(wd, ID_TE, "Tex", 1, tex);
1327                         if (tex->id.properties) IDP_WriteProperty(tex->id.properties, wd);
1328
1329                         /* direct data */
1330                         if(tex->plugin) writestruct(wd, DATA, "PluginTex", 1, tex->plugin);
1331                         if(tex->coba) writestruct(wd, DATA, "ColorBand", 1, tex->coba);
1332                         if(tex->env) writestruct(wd, DATA, "EnvMap", 1, tex->env);
1333                         
1334                         write_previews(wd, tex->preview);
1335                 }
1336                 tex= tex->id.next;
1337         }
1338
1339         /* flush helps the compression for undo-save */
1340         mywrite(wd, MYWRITE_FLUSH, 0);
1341 }
1342
1343 static void write_materials(WriteData *wd, ListBase *idbase)
1344 {
1345         Material *ma;
1346         int a;
1347
1348         ma= idbase->first;
1349         while(ma) {
1350                 if(ma->id.us>0 || wd->current) {
1351                         /* write LibData */
1352                         writestruct(wd, ID_MA, "Material", 1, ma);
1353                         
1354                         /*Write ID Properties -- and copy this comment EXACTLY for easy finding
1355                           of library blocks that implement this.*/
1356                         /*manually set head group property to IDP_GROUP, just in case it hadn't been
1357                           set yet :) */
1358                         if (ma->id.properties) IDP_WriteProperty(ma->id.properties, wd);
1359
1360                         for(a=0; a<MAX_MTEX; a++) {
1361                                 if(ma->mtex[a]) writestruct(wd, DATA, "MTex", 1, ma->mtex[a]);
1362                         }
1363                         
1364                         if(ma->ramp_col) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_col);
1365                         if(ma->ramp_spec) writestruct(wd, DATA, "ColorBand", 1, ma->ramp_spec);
1366                         
1367                         write_scriptlink(wd, &ma->scriptlink);
1368                         
1369                         /* nodetree is integral part of material, no libdata */
1370                         if(ma->nodetree) {
1371                                 writestruct(wd, DATA, "bNodeTree", 1, ma->nodetree);
1372                                 write_nodetree(wd, ma->nodetree);
1373                         }
1374
1375                         write_previews(wd, ma->preview);                        
1376                 }
1377                 ma= ma->id.next;
1378         }
1379 }
1380
1381 static void write_worlds(WriteData *wd, ListBase *idbase)
1382 {
1383         World *wrld;
1384         int a;
1385
1386         wrld= idbase->first;
1387         while(wrld) {
1388                 if(wrld->id.us>0 || wd->current) {
1389                         /* write LibData */
1390                         writestruct(wd, ID_WO, "World", 1, wrld);
1391                         if (wrld->id.properties) IDP_WriteProperty(wrld->id.properties, wd);
1392
1393                         for(a=0; a<MAX_MTEX; a++) {
1394                                 if(wrld->mtex[a]) writestruct(wd, DATA, "MTex", 1, wrld->mtex[a]);
1395                         }
1396
1397                         write_scriptlink(wd, &wrld->scriptlink);
1398
1399                         write_previews(wd, wrld->preview);
1400
1401                 }
1402                 wrld= wrld->id.next;
1403         }
1404 }
1405
1406 static void write_lamps(WriteData *wd, ListBase *idbase)
1407 {
1408         Lamp *la;
1409         int a;
1410
1411         la= idbase->first;
1412         while(la) {
1413                 if(la->id.us>0 || wd->current) {
1414                         /* write LibData */
1415                         writestruct(wd, ID_LA, "Lamp", 1, la);
1416                         if (la->id.properties) IDP_WriteProperty(la->id.properties, wd);
1417
1418                         /* direct data */
1419                         for(a=0; a<MAX_MTEX; a++) {
1420                                 if(la->mtex[a]) writestruct(wd, DATA, "MTex", 1, la->mtex[a]);
1421                         }
1422
1423                         if(la->curfalloff)
1424                                 write_curvemapping(wd, la->curfalloff); 
1425                         
1426                         write_scriptlink(wd, &la->scriptlink);
1427
1428                         write_previews(wd, la->preview);
1429
1430                 }
1431                 la= la->id.next;
1432         }
1433 }
1434
1435
1436 static void write_scenes(WriteData *wd, ListBase *scebase)
1437 {
1438         Scene *sce;
1439         Base *base;
1440         Editing *ed;
1441         Sequence *seq;
1442         MetaStack *ms;
1443         Strip *strip;
1444         TimeMarker *marker;
1445         TransformOrientation *ts;
1446         SceneRenderLayer *srl;
1447         int a;
1448         
1449         sce= scebase->first;
1450         while(sce) {
1451                 /* write LibData */
1452                 writestruct(wd, ID_SCE, "Scene", 1, sce);
1453                 if (sce->id.properties) IDP_WriteProperty(sce->id.properties, wd);
1454
1455                 /* direct data */
1456                 base= sce->base.first;
1457                 while(base) {
1458                         writestruct(wd, DATA, "Base", 1, base);
1459                         base= base->next;
1460                 }
1461
1462                 writestruct(wd, DATA, "Radio", 1, sce->radio);
1463                 writestruct(wd, DATA, "ToolSettings", 1, sce->toolsettings);
1464
1465                 for(a=0; a<MAX_MTEX; ++a)
1466                         writestruct(wd, DATA, "MTex", 1, sce->sculptdata.mtex[a]);
1467                 if(sce->sculptdata.cumap)
1468                         write_curvemapping(wd, sce->sculptdata.cumap);
1469
1470                 ed= sce->ed;
1471                 if(ed) {
1472                         writestruct(wd, DATA, "Editing", 1, ed);
1473
1474                         /* reset write flags too */
1475                         WHILE_SEQ(&ed->seqbase) {
1476                                 if(seq->strip) seq->strip->done= 0;
1477                                 writestruct(wd, DATA, "Sequence", 1, seq);
1478                         }
1479                         END_SEQ
1480
1481                         WHILE_SEQ(&ed->seqbase) {
1482                                 if(seq->strip && seq->strip->done==0) {
1483                                         /* write strip with 'done' at 0 because readfile */
1484
1485                                         if(seq->plugin) writestruct(wd, DATA, "PluginSeq", 1, seq->plugin);
1486                                         if(seq->effectdata) {
1487                                                 switch(seq->type){
1488                                                 case SEQ_COLOR:
1489                                                         writestruct(wd, DATA, "SolidColorVars", 1, seq->effectdata);
1490                                                         break;
1491                                                 case SEQ_SPEED:
1492                                                         writestruct(wd, DATA, "SpeedControlVars", 1, seq->effectdata);
1493                                                         break;
1494                                                 case SEQ_WIPE:
1495                                                         writestruct(wd, DATA, "WipeVars", 1, seq->effectdata);
1496                                                         break;
1497                                                 case SEQ_GLOW:
1498                                                         writestruct(wd, DATA, "GlowVars", 1, seq->effectdata);
1499                                                         break;
1500                                                 case SEQ_TRANSFORM:
1501                                                         writestruct(wd, DATA, "TransformVars", 1, seq->effectdata);
1502                                                         break;
1503                                                 }
1504                                         }
1505
1506                                         strip= seq->strip;
1507                                         writestruct(wd, DATA, "Strip", 1, strip);
1508                                         if(seq->flag & SEQ_USE_CROP && strip->crop) {
1509                                                 writestruct(wd, DATA, "StripCrop", 1, strip->crop);
1510                                         }
1511                                         if(seq->flag & SEQ_USE_TRANSFORM && strip->transform) {
1512                                                 writestruct(wd, DATA, "StripTransform", 1, strip->transform);
1513                                         }
1514                                         if(seq->flag & SEQ_USE_PROXY && strip->proxy) {
1515                                                 writestruct(wd, DATA, "StripProxy", 1, strip->proxy);
1516                                         }
1517                                         if(seq->flag & SEQ_USE_COLOR_BALANCE && strip->color_balance) {
1518                                                 writestruct(wd, DATA, "StripColorBalance", 1, strip->color_balance);
1519                                         }
1520                                         if(seq->type==SEQ_IMAGE)
1521                                                 writestruct(wd, DATA, "StripElem", MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem), strip->stripdata);
1522                                         else if(seq->type==SEQ_MOVIE || seq->type==SEQ_RAM_SOUND || seq->type == SEQ_HD_SOUND)
1523                                                 writestruct(wd, DATA, "StripElem", 1, strip->stripdata);
1524
1525                                         strip->done= 1;
1526                                 }
1527                         }
1528                         END_SEQ
1529                                 
1530                         /* new; meta stack too, even when its nasty restore code */
1531                         for(ms= ed->metastack.first; ms; ms= ms->next) {
1532                                 writestruct(wd, DATA, "MetaStack", 1, ms);
1533                         }
1534                 }
1535
1536                 write_scriptlink(wd, &sce->scriptlink);
1537
1538                 if (sce->r.avicodecdata) {
1539                         writestruct(wd, DATA, "AviCodecData", 1, sce->r.avicodecdata);
1540                         if (sce->r.avicodecdata->lpFormat) writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
1541                         if (sce->r.avicodecdata->lpParms) writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
1542                 }
1543
1544                 if (sce->r.qtcodecdata) {
1545                         writestruct(wd, DATA, "QuicktimeCodecData", 1, sce->r.qtcodecdata);
1546                         if (sce->r.qtcodecdata->cdParms) writedata(wd, DATA, sce->r.qtcodecdata->cdSize, sce->r.qtcodecdata->cdParms);
1547                 }
1548                 if (sce->r.ffcodecdata.properties) {
1549                         IDP_WriteProperty(sce->r.ffcodecdata.properties, wd);
1550                 }
1551
1552                 /* writing dynamic list of TimeMarkers to the blend file */
1553                 for(marker= sce->markers.first; marker; marker= marker->next)
1554                         writestruct(wd, DATA, "TimeMarker", 1, marker);
1555                 
1556                 /* writing dynamic list of TransformOrientations to the blend file */
1557                 for(ts = sce->transform_spaces.first; ts; ts = ts->next)
1558                         writestruct(wd, DATA, "TransformOrientation", 1, ts);
1559                 
1560                 for(srl= sce->r.layers.first; srl; srl= srl->next)
1561                         writestruct(wd, DATA, "SceneRenderLayer", 1, srl);
1562                 
1563                 if(sce->nodetree) {
1564                         writestruct(wd, DATA, "bNodeTree", 1, sce->nodetree);
1565                         write_nodetree(wd, sce->nodetree);
1566                 }
1567                 
1568                 sce= sce->id.next;
1569         }
1570         /* flush helps the compression for undo-save */
1571         mywrite(wd, MYWRITE_FLUSH, 0);
1572 }
1573
1574 static void write_gpencil(WriteData *wd, bGPdata *gpd)
1575 {
1576         bGPDlayer *gpl;
1577         bGPDframe *gpf;
1578         bGPDstroke *gps;
1579         
1580         /* write gpd data block to file */
1581         writestruct(wd, DATA, "bGPdata", 1, gpd);
1582         
1583         /* write grease-pencil layers to file */
1584         for (gpl= gpd->layers.first; gpl; gpl= gpl->next) {
1585                 writestruct(wd, DATA, "bGPDlayer", 1, gpl);
1586                 
1587                 /* write this layer's frames to file */
1588                 for (gpf= gpl->frames.first; gpf; gpf= gpf->next) {
1589                         writestruct(wd, DATA, "bGPDframe", 1, gpf);
1590                         
1591                         /* write strokes */
1592                         for (gps= gpf->strokes.first; gps; gps= gps->next) {
1593                                 writestruct(wd, DATA, "bGPDstroke", 1, gps);
1594                                 writestruct(wd, DATA, "bGPDspoint", gps->totpoints, gps->points);                               
1595                         }
1596                 }
1597         }
1598 }
1599
1600 static void write_screens(WriteData *wd, ListBase *scrbase)
1601 {
1602         bScreen *sc;
1603         ScrArea *sa;
1604         ScrVert *sv;
1605         ScrEdge *se;
1606
1607         sc= scrbase->first;
1608         while(sc) {
1609                 /* write LibData */
1610                 writestruct(wd, ID_SCR, "Screen", 1, sc);
1611                 if (sc->id.properties) IDP_WriteProperty(sc->id.properties, wd);
1612
1613                 /* direct data */
1614                 sv= sc->vertbase.first;
1615                 while(sv) {
1616                         writestruct(wd, DATA, "ScrVert", 1, sv);
1617                         sv= sv->next;
1618                 }
1619
1620                 se= sc->edgebase.first;
1621                 while(se) {
1622                         writestruct(wd, DATA, "ScrEdge", 1, se);
1623                         se= se->next;
1624                 }
1625
1626                 sa= sc->areabase.first;
1627                 while(sa) {
1628                         SpaceLink *sl;
1629                         Panel *pa;
1630
1631                         writestruct(wd, DATA, "ScrArea", 1, sa);
1632
1633                         pa= sa->panels.first;
1634                         while(pa) {
1635                                 writestruct(wd, DATA, "Panel", 1, pa);
1636                                 pa= pa->next;
1637                         }
1638
1639                         /* space handler scriptlinks */
1640                         write_scriptlink(wd, &sa->scriptlink);
1641
1642                         sl= sa->spacedata.first;
1643                         while(sl) {
1644                                 if(sl->spacetype==SPACE_VIEW3D) {
1645                                         View3D *v3d= (View3D *) sl;
1646                                         writestruct(wd, DATA, "View3D", 1, v3d);
1647                                         if(v3d->bgpic) writestruct(wd, DATA, "BGpic", 1, v3d->bgpic);
1648                                         if(v3d->localvd) writestruct(wd, DATA, "View3D", 1, v3d->localvd);
1649                                         if(v3d->clipbb) writestruct(wd, DATA, "BoundBox", 1, v3d->clipbb);
1650                                         if(v3d->gpd) write_gpencil(wd, v3d->gpd);
1651                                 }
1652                                 else if(sl->spacetype==SPACE_IPO) {
1653                                         writestruct(wd, DATA, "SpaceIpo", 1, sl);
1654                                 }
1655                                 else if(sl->spacetype==SPACE_BUTS) {
1656                                         writestruct(wd, DATA, "SpaceButs", 1, sl);
1657                                 }
1658                                 else if(sl->spacetype==SPACE_FILE) {
1659                                         writestruct(wd, DATA, "SpaceFile", 1, sl);
1660                                 }
1661                                 else if(sl->spacetype==SPACE_SEQ) {
1662                                         SpaceSeq *sseq= (SpaceSeq *)sl;
1663                                         writestruct(wd, DATA, "SpaceSeq", 1, sl);
1664                                         if(sseq->gpd) write_gpencil(wd, sseq->gpd);
1665                                 }
1666                                 else if(sl->spacetype==SPACE_OOPS) {
1667                                         SpaceOops *so= (SpaceOops *)sl;
1668                                         Oops *oops;
1669
1670                                         /* cleanup */
1671                                         oops= so->oops.first;
1672                                         while(oops) {
1673                                                 Oops *oopsn= oops->next;
1674                                                 if(oops->id==0) {
1675                                                         BLI_remlink(&so->oops, oops);
1676                                                         free_oops(oops);
1677                                                 }
1678                                                 oops= oopsn;
1679                                         }
1680
1681                                         /* ater cleanup, because of listbase! */
1682                                         writestruct(wd, DATA, "SpaceOops", 1, so);
1683
1684                                         oops= so->oops.first;
1685                                         while(oops) {
1686                                                 writestruct(wd, DATA, "Oops", 1, oops);
1687                                                 oops= oops->next;
1688                                         }
1689                                         /* outliner */
1690                                         if(so->treestore) {
1691                                                 writestruct(wd, DATA, "TreeStore", 1, so->treestore);
1692                                                 if(so->treestore->data)
1693                                                         writestruct(wd, DATA, "TreeStoreElem", so->treestore->usedelem, so->treestore->data);
1694                                         }
1695                                 }
1696                                 else if(sl->spacetype==SPACE_IMAGE) {
1697                                         SpaceImage *sima= (SpaceImage *)sl;
1698                                         
1699                                         writestruct(wd, DATA, "SpaceImage", 1, sl);
1700                                         if(sima->cumap)
1701                                                 write_curvemapping(wd, sima->cumap);
1702                                         if(sima->gpd) 
1703                                                 write_gpencil(wd, sima->gpd);
1704                                 }
1705                                 else if(sl->spacetype==SPACE_IMASEL) {
1706                                         writestruct(wd, DATA, "SpaceImaSel", 1, sl);
1707                                 }
1708                                 else if(sl->spacetype==SPACE_TEXT) {
1709                                         writestruct(wd, DATA, "SpaceText", 1, sl);
1710                                 }
1711                                 else if(sl->spacetype==SPACE_SCRIPT) {
1712                                         SpaceScript *sc = (SpaceScript*)sl;
1713                                         sc->but_refs = NULL;
1714                                         writestruct(wd, DATA, "SpaceScript", 1, sl);
1715                                 }
1716                                 else if(sl->spacetype==SPACE_ACTION) {
1717                                         writestruct(wd, DATA, "SpaceAction", 1, sl);
1718                                 }
1719                                 else if(sl->spacetype==SPACE_SOUND) {
1720                                         writestruct(wd, DATA, "SpaceSound", 1, sl);
1721                                 }
1722                                 else if(sl->spacetype==SPACE_NLA){
1723                                         writestruct(wd, DATA, "SpaceNla", 1, sl);
1724                                 }
1725                                 else if(sl->spacetype==SPACE_TIME){
1726                                         writestruct(wd, DATA, "SpaceTime", 1, sl);
1727                                 }
1728                                 else if(sl->spacetype==SPACE_NODE){
1729                                         SpaceNode *snode= (SpaceNode *)sl;
1730                                         writestruct(wd, DATA, "SpaceNode", 1, sl);
1731                                         if(snode->gpd) write_gpencil(wd, snode->gpd);
1732                                 }
1733                                 sl= sl->next;
1734                         }
1735
1736                         sa= sa->next;
1737                 }
1738
1739                 sc= sc->id.next;
1740         }
1741 }
1742
1743 static void write_libraries(WriteData *wd, Main *main)
1744 {
1745         ListBase *lbarray[30];
1746         ID *id;
1747         int a, tot, foundone;
1748
1749         for(; main; main= main->next) {
1750
1751                 a=tot= set_listbasepointers(main, lbarray);
1752
1753                 /* test: is lib being used */
1754                 foundone= 0;
1755                 while(tot--) {
1756                         for(id= lbarray[tot]->first; id; id= id->next) {
1757                                 if(id->us>0 && (id->flag & LIB_EXTERN)) {
1758                                         foundone= 1;
1759                                         break;
1760                                 }
1761                         }
1762                         if(foundone) break;
1763                 }
1764
1765                 if(foundone) {
1766                         writestruct(wd, ID_LI, "Library", 1, main->curlib);
1767
1768                         while(a--) {
1769                                 for(id= lbarray[a]->first; id; id= id->next) {
1770                                         if(id->us>0 && (id->flag & LIB_EXTERN)) {
1771                                                 writestruct(wd, ID_ID, "ID", 1, id);
1772                                         }
1773                                 }
1774                         }
1775                 }
1776         }
1777 }
1778
1779 static void write_bone(WriteData *wd, Bone* bone)
1780 {
1781         Bone*   cbone;
1782
1783         // PATCH for upward compatibility after 2.37+ armature recode
1784         bone->size[0]= bone->size[1]= bone->size[2]= 1.0f;
1785                 
1786         // Write this bone
1787         writestruct(wd, DATA, "Bone", 1, bone);
1788         
1789         // Write Children
1790         cbone= bone->childbase.first;
1791         while(cbone) {
1792                 write_bone(wd, cbone);
1793                 cbone= cbone->next;
1794         }
1795 }
1796
1797 static void write_armatures(WriteData *wd, ListBase *idbase)
1798 {
1799         bArmature       *arm;
1800         Bone            *bone;
1801
1802         arm=idbase->first;
1803         while (arm) {
1804                 if (arm->id.us>0 || wd->current) {
1805                         writestruct(wd, ID_AR, "bArmature", 1, arm);
1806                         if (arm->id.properties) IDP_WriteProperty(arm->id.properties, wd);
1807
1808                         /* Direct data */
1809                         bone= arm->bonebase.first;
1810                         while(bone) {
1811                                 write_bone(wd, bone);
1812                                 bone=bone->next;
1813                         }
1814                 }
1815                 arm=arm->id.next;
1816         }
1817
1818         /* flush helps the compression for undo-save */
1819         mywrite(wd, MYWRITE_FLUSH, 0);
1820 }
1821
1822 static void write_actions(WriteData *wd, ListBase *idbase)
1823 {
1824         bAction                 *act;
1825         bActionChannel  *chan;
1826         bActionGroup    *grp;
1827         TimeMarker *marker;
1828         
1829         for(act=idbase->first; act; act= act->id.next) {
1830                 if (act->id.us>0 || wd->current) {
1831                         writestruct(wd, ID_AC, "bAction", 1, act);
1832                         if (act->id.properties) IDP_WriteProperty(act->id.properties, wd);
1833                         
1834                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1835                                 writestruct(wd, DATA, "bActionChannel", 1, chan);
1836                                 write_constraint_channels(wd, &chan->constraintChannels);
1837                         }
1838                         
1839                         for (grp=act->groups.first; grp; grp=grp->next) {
1840                                 writestruct(wd, DATA, "bActionGroup", 1, grp);
1841                         }
1842                         
1843                         for (marker=act->markers.first; marker; marker=marker->next) {
1844                                 writestruct(wd, DATA, "TimeMarker", 1, marker);
1845                         }
1846                 }
1847         }
1848 }
1849
1850 static void write_texts(WriteData *wd, ListBase *idbase)
1851 {
1852         Text *text;
1853         TextLine *tmp;
1854         TextMarker *mrk;
1855
1856         text= idbase->first;
1857         while(text) {
1858                 if ( (text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) text->flags &= ~TXT_ISEXT;
1859
1860                 /* write LibData */
1861                 writestruct(wd, ID_TXT, "Text", 1, text);
1862                 if(text->name) writedata(wd, DATA, strlen(text->name)+1, text->name);
1863                 if (text->id.properties) IDP_WriteProperty(text->id.properties, wd);
1864
1865                 if(!(text->flags & TXT_ISEXT)) {
1866                         /* now write the text data, in two steps for optimization in the readfunction */
1867                         tmp= text->lines.first;
1868                         while (tmp) {
1869                                 writestruct(wd, DATA, "TextLine", 1, tmp);
1870                                 tmp= tmp->next;
1871                         }
1872
1873                         tmp= text->lines.first;
1874                         while (tmp) {
1875                                 writedata(wd, DATA, tmp->len+1, tmp->line);
1876                                 tmp= tmp->next;
1877                         }
1878
1879                         /* write markers */
1880                         mrk= text->markers.first;
1881                         while (mrk) {
1882                                 writestruct(wd, DATA, "TextMarker", 1, mrk);
1883                                 mrk= mrk->next;
1884                         }
1885                 }
1886
1887
1888                 text= text->id.next;
1889         }
1890
1891         /* flush helps the compression for undo-save */
1892         mywrite(wd, MYWRITE_FLUSH, 0);
1893 }
1894
1895 static void write_sounds(WriteData *wd, ListBase *idbase)
1896 {
1897         bSound *sound;
1898         bSample *sample;
1899
1900         PackedFile * pf;
1901
1902         // set all samples to unsaved status
1903
1904         sample = samples->first; // samples is a global defined in sound.c
1905         while (sample) {
1906                 sample->flags |= SAMPLE_NEEDS_SAVE;
1907                 sample = sample->id.next;
1908         }
1909
1910         sound= idbase->first;
1911         while(sound) {
1912                 if(sound->id.us>0 || wd->current) {
1913                         // do we need to save the packedfile as well ?
1914                         sample = sound->sample;
1915                         if (sample) {
1916                                 if (sample->flags & SAMPLE_NEEDS_SAVE) {
1917                                         sound->newpackedfile = sample->packedfile;
1918                                         sample->flags &= ~SAMPLE_NEEDS_SAVE;
1919                                 } else {
1920                                         sound->newpackedfile = NULL;
1921                                 }
1922                         }
1923
1924                         /* write LibData */
1925                         writestruct(wd, ID_SO, "bSound", 1, sound);
1926                         if (sound->id.properties) IDP_WriteProperty(sound->id.properties, wd);
1927
1928                         if (sound->newpackedfile) {
1929                                 pf = sound->newpackedfile;
1930                                 writestruct(wd, DATA, "PackedFile", 1, pf);
1931                                 writedata(wd, DATA, pf->size, pf->data);
1932                         }
1933
1934                         if (sample) {
1935                                 sound->newpackedfile = sample->packedfile;
1936                         }
1937                 }
1938                 sound= sound->id.next;
1939         }
1940
1941         /* flush helps the compression for undo-save */
1942         mywrite(wd, MYWRITE_FLUSH, 0);
1943 }
1944
1945 static void write_groups(WriteData *wd, ListBase *idbase)
1946 {
1947         Group *group;
1948         GroupObject *go;
1949
1950         for(group= idbase->first; group; group= group->id.next) {
1951                 if(group->id.us>0 || wd->current) {
1952                         /* write LibData */
1953                         writestruct(wd, ID_GR, "Group", 1, group);
1954                         if (group->id.properties) IDP_WriteProperty(group->id.properties, wd);
1955
1956                         go= group->gobject.first;
1957                         while(go) {
1958                                 writestruct(wd, DATA, "GroupObject", 1, go);
1959                                 go= go->next;
1960                         }
1961                 }
1962         }
1963 }
1964
1965 static void write_nodetrees(WriteData *wd, ListBase *idbase)
1966 {
1967         bNodeTree *ntree;
1968         
1969         for(ntree=idbase->first; ntree; ntree= ntree->id.next) {
1970                 if (ntree->id.us>0 || wd->current) {
1971                         writestruct(wd, ID_NT, "bNodeTree", 1, ntree);
1972                         write_nodetree(wd, ntree);
1973                         if (ntree->id.properties) IDP_WriteProperty(ntree->id.properties, wd);
1974                 }
1975         }
1976 }
1977
1978 static void write_brushes(WriteData *wd, ListBase *idbase)
1979 {
1980         Brush *brush;
1981         int a;
1982         
1983         for(brush=idbase->first; brush; brush= brush->id.next) {
1984                 if(brush->id.us>0 || wd->current) {
1985                         writestruct(wd, ID_BR, "Brush", 1, brush);
1986                         if (brush->id.properties) IDP_WriteProperty(brush->id.properties, wd);
1987                         for(a=0; a<MAX_MTEX; a++)
1988                                 if(brush->mtex[a])
1989                                         writestruct(wd, DATA, "MTex", 1, brush->mtex[a]);
1990                 }
1991         }
1992 }
1993
1994 static void write_scripts(WriteData *wd, ListBase *idbase)
1995 {
1996         Script *script;
1997         
1998         for(script=idbase->first; script; script= script->id.next) {
1999                 if(script->id.us>0 || wd->current) {
2000                         writestruct(wd, ID_SCRIPT, "Script", 1, script);
2001                         if (script->id.properties) IDP_WriteProperty(script->id.properties, wd);
2002                 }
2003         }
2004 }
2005
2006 static void write_global(WriteData *wd)
2007 {
2008         FileGlobal fg;
2009         char subvstr[8];
2010         
2011         fg.curscreen= G.curscreen;
2012         fg.curscene= G.scene;
2013         fg.displaymode= G.displaymode;
2014         fg.winpos= G.winpos;
2015         fg.fileflags= (G.fileflags & ~G_FILE_NO_UI);    // prevent to save this, is not good convention, and feature with concerns...
2016         fg.globalf= G.f;
2017
2018         sprintf(subvstr, "%4d", BLENDER_SUBVERSION);
2019         memcpy(fg.subvstr, subvstr, 4);
2020         
2021         fg.subversion= BLENDER_SUBVERSION;
2022         fg.minversion= BLENDER_MINVERSION;
2023         fg.minsubversion= BLENDER_MINSUBVERSION;
2024         
2025         writestruct(wd, GLOB, "FileGlobal", 1, &fg);
2026 }
2027
2028 /* if MemFile * there's filesave to memory */
2029 static int write_file_handle(int handle, MemFile *compare, MemFile *current, int write_user_block, int write_flags)
2030 {
2031         BHead bhead;
2032         ListBase mainlist;
2033         char buf[16];
2034         WriteData *wd;
2035
2036         blo_split_main(&mainlist, G.main);
2037
2038         wd= bgnwrite(handle, compare, current, write_flags);
2039         
2040         sprintf(buf, "BLENDER%c%c%.3d", (sizeof(void*)==8)?'-':'_', (G.order==B_ENDIAN)?'V':'v', G.version);
2041         mywrite(wd, buf, 12);
2042
2043         write_renderinfo(wd);
2044         write_global(wd);
2045
2046         if(current==NULL)
2047                 write_screens  (wd, &G.main->screen);   /* no UI save in undo */
2048         write_scenes   (wd, &G.main->scene);
2049         write_curves   (wd, &G.main->curve);
2050         write_mballs   (wd, &G.main->mball);
2051         write_images   (wd, &G.main->image);
2052         write_cameras  (wd, &G.main->camera);
2053         write_lamps    (wd, &G.main->lamp);
2054         write_lattices (wd, &G.main->latt);
2055         write_vfonts   (wd, &G.main->vfont);
2056         write_ipos     (wd, &G.main->ipo);
2057         write_keys     (wd, &G.main->key);
2058         write_worlds   (wd, &G.main->world);
2059         write_texts    (wd, &G.main->text);
2060         write_sounds   (wd, &G.main->sound);
2061         write_groups   (wd, &G.main->group);
2062         write_armatures(wd, &G.main->armature);
2063         write_actions  (wd, &G.main->action);
2064         write_objects  (wd, &G.main->object);
2065         write_materials(wd, &G.main->mat);
2066         write_textures (wd, &G.main->tex);
2067         write_meshs    (wd, &G.main->mesh);
2068         write_particlesettings(wd, &G.main->particle);
2069         write_nodetrees(wd, &G.main->nodetree);
2070         write_brushes  (wd, &G.main->brush);
2071         write_scripts  (wd, &G.main->script);
2072         if(current==NULL)       
2073                 write_libraries(wd,  G.main->next); /* no library save in undo */
2074
2075         if (write_user_block) {
2076                 write_userdef(wd);
2077         }
2078
2079         /* dna as last, because (to be implemented) test for which structs are written */
2080         writedata(wd, DNA1, wd->sdna->datalen, wd->sdna->data);
2081
2082         /* end of file */
2083         memset(&bhead, 0, sizeof(BHead));
2084         bhead.code= ENDB;
2085         mywrite(wd, &bhead, sizeof(BHead));
2086
2087         blo_join_main(&mainlist);
2088         G.main= mainlist.first;
2089
2090         return endwrite(wd);
2091 }
2092
2093 /* return: success (1) */
2094 int BLO_write_file(char *dir, int write_flags, char **error_r)
2095 {
2096         char userfilename[FILE_MAXDIR+FILE_MAXFILE];
2097         char tempname[FILE_MAXDIR+FILE_MAXFILE];
2098         int file, err, write_user_block;
2099
2100         sprintf(tempname, "%s@", dir);
2101
2102         file = open(tempname,O_BINARY+O_WRONLY+O_CREAT+O_TRUNC, 0666);
2103         if(file == -1) {
2104                 *error_r= "Unable to open";
2105                 return 0;
2106         }
2107
2108         BLI_make_file_string(G.sce, userfilename, BLI_gethome(), ".B.blend");
2109
2110         write_user_block= BLI_streq(dir, userfilename);
2111
2112         err= write_file_handle(file, NULL,NULL, write_user_block, write_flags);
2113         close(file);
2114
2115         if(!err) {
2116                 if(write_flags & G_FILE_COMPRESS)
2117                 {       
2118                         // compressed files have the same ending as regular files... only from 2.4!!!
2119                         
2120                         int ret = BLI_gzip(tempname, dir);
2121                         
2122                         if(-1==ret) {
2123                                 *error_r= "Failed opening .gz file";
2124                                 return 0;
2125                         }
2126                         if(-2==ret) {
2127                                 *error_r= "Failed opening .blend file for compression";
2128                                 return 0;
2129                         }
2130                 }
2131                 else
2132                 if(BLI_rename(tempname, dir) != 0) {
2133                         *error_r= "Can't change old file. File saved with @";
2134                         return 0;
2135                 }
2136
2137                 
2138         } else {
2139                 *error_r= strerror(errno);
2140                 remove(tempname);
2141
2142                 return 0;
2143         }
2144
2145         return 1;
2146 }
2147
2148 /* return: success (1) */
2149 int BLO_write_file_mem(MemFile *compare, MemFile *current, int write_flags, char **error_r)
2150 {
2151         int err;
2152
2153         err= write_file_handle(0, compare, current, 0, write_flags);
2154         
2155         if(err==0) return 1;
2156         return 0;
2157 }
2158
2159
2160         /* Runtime writing */
2161
2162 #ifdef WIN32
2163 #define PATHSEPERATOR           "\\"
2164 #else
2165 #define PATHSEPERATOR           "/"
2166 #endif
2167
2168 char *get_install_dir(void) {
2169         extern char bprogname[];
2170         char *tmpname = BLI_strdup(bprogname);
2171         char *cut;
2172
2173 #ifdef __APPLE__
2174         cut = strstr(tmpname, ".app");
2175         if (cut) cut[0] = 0;
2176 #endif
2177
2178         cut = BLI_last_slash(tmpname);
2179
2180         if (cut) {
2181                 cut[0] = 0;
2182                 return tmpname;
2183         } else {
2184                 MEM_freeN(tmpname);
2185                 return NULL;
2186         }
2187 }
2188
2189 static char *get_runtime_path(char *exename) {
2190         char *installpath= get_install_dir();
2191
2192         if (!installpath) {
2193                 return NULL;
2194         } else {
2195                 char *path= MEM_mallocN(strlen(installpath)+strlen(PATHSEPERATOR)+strlen(exename)+1, "runtimepath");
2196
2197                 if (path == NULL) {
2198                         MEM_freeN(installpath);
2199                         return NULL;
2200                 }
2201
2202                 strcpy(path, installpath);
2203                 strcat(path, PATHSEPERATOR);
2204                 strcat(path, exename);
2205
2206                 MEM_freeN(installpath);
2207
2208                 return path;
2209         }
2210 }
2211
2212 #ifdef __APPLE__
2213
2214 static int recursive_copy_runtime(char *outname, char *exename, char **cause_r) 
2215 {
2216         char *cause = NULL, *runtime = get_runtime_path(exename);
2217         char command[2 * (FILE_MAXDIR+FILE_MAXFILE) + 32];
2218         int progfd = -1;
2219
2220         if (!runtime) {
2221                 cause= "Unable to find runtime";
2222                 goto cleanup;
2223         }
2224         //printf("runtimepath %s\n", runtime);
2225                 
2226         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2227         if (progfd==-1) {
2228                 cause= "Unable to find runtime";
2229                 goto cleanup;
2230         }
2231
2232         sprintf(command, "/bin/cp -R \"%s\" \"%s\"", runtime, outname);
2233         //printf("command %s\n", command);
2234         if (system(command) == -1) {
2235                 cause = "Couldn't copy runtime";
2236         }
2237
2238 cleanup:
2239         if (progfd!=-1)
2240                 close(progfd);
2241         if (runtime)
2242                 MEM_freeN(runtime);
2243
2244         if (cause) {
2245                 *cause_r= cause;
2246                 return 0;
2247         } else
2248                 return 1;
2249 }
2250
2251 void BLO_write_runtime(char *file, char *exename) {
2252         char gamename[FILE_MAXDIR+FILE_MAXFILE];
2253         int outfd = -1;
2254         char *cause= NULL;
2255
2256         // remove existing file / bundle
2257         //printf("Delete file %s\n", file);
2258         BLI_delete(file, 0, TRUE);
2259
2260         if (!recursive_copy_runtime(file, exename, &cause))
2261                 goto cleanup;
2262
2263         strcpy(gamename, file);
2264         strcat(gamename, "/Contents/Resources/game.blend");
2265         //printf("gamename %s\n", gamename);
2266         outfd= open(gamename, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2267         if (outfd != -1) {
2268
2269                 write_file_handle(outfd, NULL,NULL, 0, G.fileflags);
2270
2271                 if (write(outfd, " ", 1) != 1) {
2272                         cause= "Unable to write to output file";
2273                         goto cleanup;
2274                 }
2275         } else {
2276                 cause = "Unable to open blenderfile";
2277         }
2278
2279 cleanup:
2280         if (outfd!=-1)
2281                 close(outfd);
2282
2283         if (cause)
2284                 error("Unable to make runtime: %s", cause);
2285 }
2286
2287 #else /* !__APPLE__ */
2288
2289 static int handle_append_runtime(int handle, char *exename, char **cause_r) {
2290         char *cause= NULL, *runtime= get_runtime_path(exename);
2291         unsigned char buf[1024];
2292         int count, progfd= -1;
2293
2294         if (!BLI_exists(runtime)) {
2295                 cause= "Unable to find runtime";
2296                 goto cleanup;
2297         }
2298
2299         progfd= open(runtime, O_BINARY|O_RDONLY, 0);
2300         if (progfd==-1) {
2301                 cause= "Unable to find runtime";
2302                 goto cleanup;
2303         }
2304
2305         while ((count= read(progfd, buf, sizeof(buf)))>0) {
2306                 if (write(handle, buf, count)!=count) {
2307                         cause= "Unable to write to output file";
2308                         goto cleanup;
2309                 }
2310         }
2311
2312 cleanup:
2313         if (progfd!=-1)
2314                 close(progfd);
2315         if (runtime)
2316                 MEM_freeN(runtime);
2317
2318         if (cause) {
2319                 *cause_r= cause;
2320                 return 0;
2321         } else
2322                 return 1;
2323 }
2324
2325 static int handle_write_msb_int(int handle, int i) {
2326         unsigned char buf[4];
2327         buf[0]= (i>>24)&0xFF;
2328         buf[1]= (i>>16)&0xFF;
2329         buf[2]= (i>>8)&0xFF;
2330         buf[3]= (i>>0)&0xFF;
2331
2332         return (write(handle, buf, 4)==4);
2333 }
2334
2335 void BLO_write_runtime(char *file, char *exename) {
2336         int outfd= open(file, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0777);
2337         char *cause= NULL;
2338         int datastart;
2339
2340         if (!outfd) {
2341                 cause= "Unable to open output file";
2342                 goto cleanup;
2343         }
2344         if (!handle_append_runtime(outfd, exename, &cause))
2345                 goto cleanup;
2346
2347         datastart= lseek(outfd, 0, SEEK_CUR);
2348
2349         write_file_handle(outfd, NULL,NULL, 0, G.fileflags);
2350
2351         if (!handle_write_msb_int(outfd, datastart) || (write(outfd, "BRUNTIME", 8)!=8)) {
2352                 cause= "Unable to write to output file";
2353                 goto cleanup;
2354         }
2355
2356 cleanup:
2357         if (outfd!=-1)
2358                 close(outfd);
2359
2360         if (cause)
2361                 error("Unable to make runtime: %s", cause);
2362 }
2363
2364 #endif /* !__APPLE__ */