Fix #32667: Curve softbodies doesn't render animation (cycles)
[blender.git] / source / blender / blenkernel / intern / pointcache.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Campbell Barton <ideasman42@gmail.com>
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/blenkernel/intern/pointcache.c
27  *  \ingroup bke
28  */
29
30
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <sys/stat.h>
35 #include <sys/types.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_ID.h"
40 #include "DNA_cloth_types.h"
41 #include "DNA_dynamicpaint_types.h"
42 #include "DNA_modifier_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_object_force.h"
45 #include "DNA_particle_types.h"
46 #include "DNA_scene_types.h"
47 #include "DNA_smoke_types.h"
48
49 #include "BLI_blenlib.h"
50 #include "BLI_threads.h"
51 #include "BLI_math.h"
52 #include "BLI_utildefines.h"
53
54 #include "PIL_time.h"
55
56 #include "WM_api.h"
57
58 #include "BKE_anim.h"
59 #include "BKE_blender.h"
60 #include "BKE_cloth.h"
61 #include "BKE_depsgraph.h"
62 #include "BKE_dynamicpaint.h"
63 #include "BKE_global.h"
64 #include "BKE_library.h"
65 #include "BKE_main.h"
66 #include "BKE_object.h"
67 #include "BKE_particle.h"
68 #include "BKE_pointcache.h"
69 #include "BKE_scene.h"
70 #include "BKE_smoke.h"
71 #include "BKE_softbody.h"
72
73 #include "BIK_api.h"
74
75 /* both in intern */
76 #ifdef WITH_SMOKE
77 #include "smoke_API.h"
78 #endif
79
80 #ifdef WITH_LZO
81 #include "minilzo.h"
82 #else
83 /* used for non-lzo cases */
84 #define LZO_OUT_LEN(size)     ((size) + (size) / 16 + 64 + 3)
85 #endif
86
87 #ifdef WITH_LZMA
88 #include "LzmaLib.h"
89 #endif
90
91 /* needed for directory lookup */
92 /* untitled blend's need getpid for a unique name */
93 #ifndef WIN32
94 #  include <dirent.h>
95 #  include <unistd.h>
96 #else
97 #  include <process.h>
98 #  include "BLI_winstuff.h"
99 #endif
100
101 #define PTCACHE_DATA_FROM(data, type, from)  \
102         if (data[type]) { \
103                 memcpy(data[type], from, ptcache_data_size[type]); \
104         } (void)0
105
106 #define PTCACHE_DATA_TO(data, type, index, to)  \
107         if (data[type]) { \
108                 memcpy(to, (char *)(data)[type] + ((index) ? (index) * ptcache_data_size[type] : 0), ptcache_data_size[type]); \
109         } (void)0
110
111 /* could be made into a pointcache option */
112 #define DURIAN_POINTCACHE_LIB_OK 1
113
114 static int ptcache_data_size[] = {      
115                 sizeof(unsigned int), // BPHYS_DATA_INDEX
116                 3 * sizeof(float), // BPHYS_DATA_LOCATION
117                 3 * sizeof(float), // BPHYS_DATA_VELOCITY
118                 4 * sizeof(float), // BPHYS_DATA_ROTATION
119                 3 * sizeof(float), // BPHYS_DATA_AVELOCITY / BPHYS_DATA_XCONST
120                 sizeof(float), // BPHYS_DATA_SIZE
121                 3 * sizeof(float), // BPHYS_DATA_TIMES
122                 sizeof(BoidData) // case BPHYS_DATA_BOIDS
123 };
124
125 static int ptcache_extra_datasize[] = {
126         0,
127         sizeof(ParticleSpring)
128 };
129
130 /* forward declerations */
131 static int ptcache_file_compressed_read(PTCacheFile *pf, unsigned char *result, unsigned int len);
132 static int ptcache_file_compressed_write(PTCacheFile *pf, unsigned char *in, unsigned int in_len, unsigned char *out, int mode);
133 static int ptcache_file_write(PTCacheFile *pf, const void *f, unsigned int tot, unsigned int size);
134 static int ptcache_file_read(PTCacheFile *pf, void *f, unsigned int tot, unsigned int size);
135
136 /* Common functions */
137 static int ptcache_basic_header_read(PTCacheFile *pf)
138 {
139         int error=0;
140
141         /* Custom functions should read these basic elements too! */
142         if (!error && !fread(&pf->totpoint, sizeof(unsigned int), 1, pf->fp))
143                 error = 1;
144         
145         if (!error && !fread(&pf->data_types, sizeof(unsigned int), 1, pf->fp))
146                 error = 1;
147
148         return !error;
149 }
150 static int ptcache_basic_header_write(PTCacheFile *pf)
151 {
152         /* Custom functions should write these basic elements too! */
153         if (!fwrite(&pf->totpoint, sizeof(unsigned int), 1, pf->fp))
154                 return 0;
155         
156         if (!fwrite(&pf->data_types, sizeof(unsigned int), 1, pf->fp))
157                 return 0;
158
159         return 1;
160 }
161 /* Softbody functions */
162 static int  ptcache_softbody_write(int index, void *soft_v, void **data, int UNUSED(cfra))
163 {
164         SoftBody *soft= soft_v;
165         BodyPoint *bp = soft->bpoint + index;
166
167         PTCACHE_DATA_FROM(data, BPHYS_DATA_LOCATION, bp->pos);
168         PTCACHE_DATA_FROM(data, BPHYS_DATA_VELOCITY, bp->vec);
169
170         return 1;
171 }
172 static void ptcache_softbody_read(int index, void *soft_v, void **data, float UNUSED(cfra), float *old_data)
173 {
174         SoftBody *soft= soft_v;
175         BodyPoint *bp = soft->bpoint + index;
176
177         if (old_data) {
178                 memcpy(bp->pos, data, 3 * sizeof(float));
179                 memcpy(bp->vec, data + 3, 3 * sizeof(float));
180         }
181         else {
182                 PTCACHE_DATA_TO(data, BPHYS_DATA_LOCATION, 0, bp->pos);
183                 PTCACHE_DATA_TO(data, BPHYS_DATA_VELOCITY, 0, bp->vec);
184         }
185 }
186 static void ptcache_softbody_interpolate(int index, void *soft_v, void **data, float cfra, float cfra1, float cfra2, float *old_data)
187 {
188         SoftBody *soft= soft_v;
189         BodyPoint *bp = soft->bpoint + index;
190         ParticleKey keys[4];
191         float dfra;
192
193         if (cfra1 == cfra2)
194                 return;
195
196         copy_v3_v3(keys[1].co, bp->pos);
197         copy_v3_v3(keys[1].vel, bp->vec);
198
199         if (old_data) {
200                 memcpy(keys[2].co, old_data, 3 * sizeof(float));
201                 memcpy(keys[2].vel, old_data + 3, 3 * sizeof(float));
202         }
203         else
204                 BKE_ptcache_make_particle_key(keys+2, 0, data, cfra2);
205
206         dfra = cfra2 - cfra1;
207
208         mul_v3_fl(keys[1].vel, dfra);
209         mul_v3_fl(keys[2].vel, dfra);
210
211         psys_interpolate_particle(-1, keys, (cfra - cfra1) / dfra, keys, 1);
212
213         mul_v3_fl(keys->vel, 1.0f / dfra);
214
215         copy_v3_v3(bp->pos, keys->co);
216         copy_v3_v3(bp->vec, keys->vel);
217 }
218 static int  ptcache_softbody_totpoint(void *soft_v, int UNUSED(cfra))
219 {
220         SoftBody *soft= soft_v;
221         return soft->totpoint;
222 }
223 /* Particle functions */
224 void BKE_ptcache_make_particle_key(ParticleKey *key, int index, void **data, float time)
225 {
226         PTCACHE_DATA_TO(data, BPHYS_DATA_LOCATION, index, key->co);
227         PTCACHE_DATA_TO(data, BPHYS_DATA_VELOCITY, index, key->vel);
228         
229         /* no rotation info, so make something nice up */
230         if (data[BPHYS_DATA_ROTATION]==NULL) {
231                 vec_to_quat(key->rot, key->vel, OB_NEGX, OB_POSZ);
232         }
233         else {
234                 PTCACHE_DATA_TO(data, BPHYS_DATA_ROTATION, index, key->rot);
235         }
236
237         PTCACHE_DATA_TO(data, BPHYS_DATA_AVELOCITY, index, key->ave);
238         key->time = time;
239 }
240 static int  ptcache_particle_write(int index, void *psys_v, void **data, int cfra)
241 {
242         ParticleSystem *psys= psys_v;
243         ParticleData *pa = psys->particles + index;
244         BoidParticle *boid = (psys->part->phystype == PART_PHYS_BOIDS) ? pa->boid : NULL;
245         float times[3];
246         int step = psys->pointcache->step;
247
248         /* No need to store unborn or died particles outside cache step bounds */
249         if (data[BPHYS_DATA_INDEX] && (cfra < pa->time - step || cfra > pa->dietime + step))
250                 return 0;
251
252         times[0]= pa->time;
253         times[1]= pa->dietime;
254         times[2]= pa->lifetime;
255
256         PTCACHE_DATA_FROM(data, BPHYS_DATA_INDEX, &index);
257         PTCACHE_DATA_FROM(data, BPHYS_DATA_LOCATION, pa->state.co);
258         PTCACHE_DATA_FROM(data, BPHYS_DATA_VELOCITY, pa->state.vel);
259         PTCACHE_DATA_FROM(data, BPHYS_DATA_ROTATION, pa->state.rot);
260         PTCACHE_DATA_FROM(data, BPHYS_DATA_AVELOCITY, pa->state.ave);
261         PTCACHE_DATA_FROM(data, BPHYS_DATA_SIZE, &pa->size);
262         PTCACHE_DATA_FROM(data, BPHYS_DATA_TIMES, times);
263
264         if (boid)
265                 PTCACHE_DATA_FROM(data, BPHYS_DATA_BOIDS, &boid->data);
266
267         /* return flag 1+1=2 for newly born particles to copy exact birth location to previously cached frame */
268         return 1 + (pa->state.time >= pa->time && pa->prev_state.time <= pa->time);
269 }
270 static void ptcache_particle_read(int index, void *psys_v, void **data, float cfra, float *old_data)
271 {
272         ParticleSystem *psys= psys_v;
273         ParticleData *pa;
274         BoidParticle *boid;
275         float timestep = 0.04f*psys->part->timetweak;
276
277         if (index >= psys->totpart)
278                 return;
279
280         pa = psys->particles + index;
281         boid = (psys->part->phystype == PART_PHYS_BOIDS) ? pa->boid : NULL;
282
283         if (cfra > pa->state.time)
284                 memcpy(&pa->prev_state, &pa->state, sizeof(ParticleKey));
285
286         if (old_data) {
287                 /* old format cache */
288                 memcpy(&pa->state, old_data, sizeof(ParticleKey));
289                 return;
290         }
291
292         BKE_ptcache_make_particle_key(&pa->state, 0, data, cfra);
293
294         /* set frames cached before birth to birth time */
295         if (cfra < pa->time)
296                 pa->state.time = pa->time;
297         else if (cfra > pa->dietime)
298                 pa->state.time = pa->dietime;
299
300         if (data[BPHYS_DATA_SIZE])
301                 PTCACHE_DATA_TO(data, BPHYS_DATA_SIZE, 0, &pa->size);
302         
303         if (data[BPHYS_DATA_TIMES]) {
304                 float times[3];
305                 PTCACHE_DATA_TO(data, BPHYS_DATA_TIMES, 0, &times);
306                 pa->time = times[0];
307                 pa->dietime = times[1];
308                 pa->lifetime = times[2];
309         }
310
311         if (boid)
312                 PTCACHE_DATA_TO(data, BPHYS_DATA_BOIDS, 0, &boid->data);
313
314         /* determine velocity from previous location */
315         if (data[BPHYS_DATA_LOCATION] && !data[BPHYS_DATA_VELOCITY]) {
316                 if (cfra > pa->prev_state.time) {
317                         sub_v3_v3v3(pa->state.vel, pa->state.co, pa->prev_state.co);
318                         mul_v3_fl(pa->state.vel, (cfra - pa->prev_state.time) * timestep);
319                 }
320                 else {
321                         sub_v3_v3v3(pa->state.vel, pa->prev_state.co, pa->state.co);
322                         mul_v3_fl(pa->state.vel, (pa->prev_state.time - cfra) * timestep);
323                 }
324         }
325
326         /* default to no rotation */
327         if (data[BPHYS_DATA_LOCATION] && !data[BPHYS_DATA_ROTATION]) {
328                 unit_qt(pa->state.rot);
329         }
330 }
331 static void ptcache_particle_interpolate(int index, void *psys_v, void **data, float cfra, float cfra1, float cfra2, float *old_data)
332 {
333         ParticleSystem *psys= psys_v;
334         ParticleData *pa;
335         ParticleKey keys[4];
336         float dfra, timestep = 0.04f*psys->part->timetweak;
337
338         if (index >= psys->totpart)
339                 return;
340
341         pa = psys->particles + index;
342
343         /* particle wasn't read from first cache so can't interpolate */
344         if ((int)cfra1 < pa->time - psys->pointcache->step || (int)cfra1 > pa->dietime + psys->pointcache->step)
345                 return;
346
347         cfra = MIN2(cfra, pa->dietime);
348         cfra1 = MIN2(cfra1, pa->dietime);
349         cfra2 = MIN2(cfra2, pa->dietime);
350
351         if (cfra1 == cfra2)
352                 return;
353
354         memcpy(keys+1, &pa->state, sizeof(ParticleKey));
355         if (old_data)
356                 memcpy(keys+2, old_data, sizeof(ParticleKey));
357         else
358                 BKE_ptcache_make_particle_key(keys+2, 0, data, cfra2);
359
360         /* determine velocity from previous location */
361         if (data[BPHYS_DATA_LOCATION] && !data[BPHYS_DATA_VELOCITY]) {
362                 if (keys[1].time > keys[2].time) {
363                         sub_v3_v3v3(keys[2].vel, keys[1].co, keys[2].co);
364                         mul_v3_fl(keys[2].vel, (keys[1].time - keys[2].time) * timestep);
365                 }
366                 else {
367                         sub_v3_v3v3(keys[2].vel, keys[2].co, keys[1].co);
368                         mul_v3_fl(keys[2].vel, (keys[2].time - keys[1].time) * timestep);
369                 }
370         }
371
372         /* determine rotation from velocity */
373         if (data[BPHYS_DATA_LOCATION] && !data[BPHYS_DATA_ROTATION]) {
374                 vec_to_quat(keys[2].rot, keys[2].vel, OB_NEGX, OB_POSZ);
375         }
376
377         if (cfra > pa->time)
378                 cfra1 = MAX2(cfra1, pa->time);
379
380         dfra = cfra2 - cfra1;
381
382         mul_v3_fl(keys[1].vel, dfra * timestep);
383         mul_v3_fl(keys[2].vel, dfra * timestep);
384
385         psys_interpolate_particle(-1, keys, (cfra - cfra1) / dfra, &pa->state, 1);
386         interp_qt_qtqt(pa->state.rot, keys[1].rot, keys[2].rot, (cfra - cfra1) / dfra);
387
388         mul_v3_fl(pa->state.vel, 1.f / (dfra * timestep));
389
390         pa->state.time = cfra;
391 }
392
393 static int  ptcache_particle_totpoint(void *psys_v, int UNUSED(cfra))
394 {
395         ParticleSystem *psys = psys_v;
396         return psys->totpart;
397 }
398 static int  ptcache_particle_totwrite(void *psys_v, int cfra)
399 {
400         ParticleSystem *psys = psys_v;
401         ParticleData *pa= psys->particles;
402         int p, step = psys->pointcache->step;
403         int totwrite = 0;
404
405         if (cfra == 0)
406                 return psys->totpart;
407
408         for (p=0; p<psys->totpart; p++, pa++)
409                 totwrite += (cfra >= pa->time - step && cfra <= pa->dietime + step);
410
411         return totwrite;
412 }
413
414 static void ptcache_particle_extra_write(void *psys_v, PTCacheMem *pm, int UNUSED(cfra))
415 {
416         ParticleSystem *psys = psys_v;
417         PTCacheExtra *extra = NULL;
418
419         if (psys->part->phystype == PART_PHYS_FLUID &&
420                 psys->part->fluid && psys->part->fluid->flag & SPH_VISCOELASTIC_SPRINGS &&
421                 psys->tot_fluidsprings && psys->fluid_springs) {
422
423                 extra = MEM_callocN(sizeof(PTCacheExtra), "Point cache: fluid extra data");
424
425                 extra->type = BPHYS_EXTRA_FLUID_SPRINGS;
426                 extra->totdata = psys->tot_fluidsprings;
427
428                 extra->data = MEM_callocN(extra->totdata * ptcache_extra_datasize[extra->type], "Point cache: extra data");
429                 memcpy(extra->data, psys->fluid_springs, extra->totdata * ptcache_extra_datasize[extra->type]);
430
431                 BLI_addtail(&pm->extradata, extra);
432         }
433 }
434
435 static void ptcache_particle_extra_read(void *psys_v, PTCacheMem *pm, float UNUSED(cfra))
436 {
437         ParticleSystem *psys = psys_v;
438         PTCacheExtra *extra = pm->extradata.first;
439
440         for (; extra; extra=extra->next) {
441                 switch (extra->type) {
442                         case BPHYS_EXTRA_FLUID_SPRINGS:
443                         {
444                                 if (psys->fluid_springs)
445                                         MEM_freeN(psys->fluid_springs);
446
447                                 psys->fluid_springs = MEM_dupallocN(extra->data);
448                                 psys->tot_fluidsprings = psys->alloc_fluidsprings = extra->totdata;
449                                 break;
450                         }
451                 }
452         }
453 }
454
455 /* Cloth functions */
456 static int  ptcache_cloth_write(int index, void *cloth_v, void **data, int UNUSED(cfra))
457 {
458         ClothModifierData *clmd= cloth_v;
459         Cloth *cloth= clmd->clothObject;
460         ClothVertex *vert = cloth->verts + index;
461
462         PTCACHE_DATA_FROM(data, BPHYS_DATA_LOCATION, vert->x);
463         PTCACHE_DATA_FROM(data, BPHYS_DATA_VELOCITY, vert->v);
464         PTCACHE_DATA_FROM(data, BPHYS_DATA_XCONST, vert->xconst);
465
466         return 1;
467 }
468 static void ptcache_cloth_read(int index, void *cloth_v, void **data, float UNUSED(cfra), float *old_data)
469 {
470         ClothModifierData *clmd= cloth_v;
471         Cloth *cloth= clmd->clothObject;
472         ClothVertex *vert = cloth->verts + index;
473         
474         if (old_data) {
475                 memcpy(vert->x, data, 3 * sizeof(float));
476                 memcpy(vert->xconst, data + 3, 3 * sizeof(float));
477                 memcpy(vert->v, data + 6, 3 * sizeof(float));
478         }
479         else {
480                 PTCACHE_DATA_TO(data, BPHYS_DATA_LOCATION, 0, vert->x);
481                 PTCACHE_DATA_TO(data, BPHYS_DATA_VELOCITY, 0, vert->v);
482                 PTCACHE_DATA_TO(data, BPHYS_DATA_XCONST, 0, vert->xconst);
483         }
484 }
485 static void ptcache_cloth_interpolate(int index, void *cloth_v, void **data, float cfra, float cfra1, float cfra2, float *old_data)
486 {
487         ClothModifierData *clmd= cloth_v;
488         Cloth *cloth= clmd->clothObject;
489         ClothVertex *vert = cloth->verts + index;
490         ParticleKey keys[4];
491         float dfra;
492
493         if (cfra1 == cfra2)
494                 return;
495
496         copy_v3_v3(keys[1].co, vert->x);
497         copy_v3_v3(keys[1].vel, vert->v);
498
499         if (old_data) {
500                 memcpy(keys[2].co, old_data, 3 * sizeof(float));
501                 memcpy(keys[2].vel, old_data + 6, 3 * sizeof(float));
502         }
503         else
504                 BKE_ptcache_make_particle_key(keys+2, 0, data, cfra2);
505
506         dfra = cfra2 - cfra1;
507
508         mul_v3_fl(keys[1].vel, dfra);
509         mul_v3_fl(keys[2].vel, dfra);
510
511         psys_interpolate_particle(-1, keys, (cfra - cfra1) / dfra, keys, 1);
512
513         mul_v3_fl(keys->vel, 1.0f / dfra);
514
515         copy_v3_v3(vert->x, keys->co);
516         copy_v3_v3(vert->v, keys->vel);
517
518         /* should vert->xconst be interpolated somehow too? - jahka */
519 }
520
521 static int  ptcache_cloth_totpoint(void *cloth_v, int UNUSED(cfra))
522 {
523         ClothModifierData *clmd= cloth_v;
524         return clmd->clothObject ? clmd->clothObject->numverts : 0;
525 }
526
527 #ifdef WITH_SMOKE
528 /* Smoke functions */
529 static int  ptcache_smoke_totpoint(void *smoke_v, int UNUSED(cfra))
530 {
531         SmokeModifierData *smd= (SmokeModifierData *)smoke_v;
532         SmokeDomainSettings *sds = smd->domain;
533         
534         if (sds->fluid) {
535                 return sds->res[0]*sds->res[1]*sds->res[2];
536         }
537         else
538                 return 0;
539 }
540 static int  ptcache_smoke_write(PTCacheFile *pf, void *smoke_v)
541 {       
542         SmokeModifierData *smd= (SmokeModifierData *)smoke_v;
543         SmokeDomainSettings *sds = smd->domain;
544         int ret = 0;
545         
546         if (sds->fluid) {
547                 size_t res = sds->res[0]*sds->res[1]*sds->res[2];
548                 float dt, dx, *dens, *densold, *heat, *heatold, *vx, *vy, *vz, *vxold, *vyold, *vzold;
549                 unsigned char *obstacles;
550                 unsigned int in_len = sizeof(float)*(unsigned int)res;
551                 unsigned char *out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len)*4, "pointcache_lzo_buffer");
552                 //int mode = res >= 1000000 ? 2 : 1;
553                 int mode=1;             // light
554                 if (sds->cache_comp == SM_CACHE_HEAVY) mode=2;  // heavy
555
556                 smoke_export(sds->fluid, &dt, &dx, &dens, &densold, &heat, &heatold, &vx, &vy, &vz, &vxold, &vyold, &vzold, &obstacles);
557
558                 ptcache_file_compressed_write(pf, (unsigned char *)sds->shadow, in_len, out, mode);
559                 ptcache_file_compressed_write(pf, (unsigned char *)dens, in_len, out, mode);
560                 ptcache_file_compressed_write(pf, (unsigned char *)densold, in_len, out, mode); 
561                 ptcache_file_compressed_write(pf, (unsigned char *)heat, in_len, out, mode);
562                 ptcache_file_compressed_write(pf, (unsigned char *)heatold, in_len, out, mode);
563                 ptcache_file_compressed_write(pf, (unsigned char *)vx, in_len, out, mode);
564                 ptcache_file_compressed_write(pf, (unsigned char *)vy, in_len, out, mode);
565                 ptcache_file_compressed_write(pf, (unsigned char *)vz, in_len, out, mode);
566                 ptcache_file_compressed_write(pf, (unsigned char *)vxold, in_len, out, mode);
567                 ptcache_file_compressed_write(pf, (unsigned char *)vyold, in_len, out, mode);
568                 ptcache_file_compressed_write(pf, (unsigned char *)vzold, in_len, out, mode);
569                 ptcache_file_compressed_write(pf, (unsigned char *)obstacles, (unsigned int)res, out, mode);
570                 ptcache_file_write(pf, &dt, 1, sizeof(float));
571                 ptcache_file_write(pf, &dx, 1, sizeof(float));
572
573                 MEM_freeN(out);
574                 
575                 ret = 1;
576         }
577
578         if (sds->wt) {
579                 int res_big_array[3];
580                 int res_big;
581                 int res = sds->res[0]*sds->res[1]*sds->res[2];
582                 float *dens, *densold, *tcu, *tcv, *tcw;
583                 unsigned int in_len = sizeof(float)*(unsigned int)res;
584                 unsigned int in_len_big;
585                 unsigned char *out;
586                 int mode;
587
588                 smoke_turbulence_get_res(sds->wt, res_big_array);
589                 res_big = res_big_array[0]*res_big_array[1]*res_big_array[2];
590                 //mode =  res_big >= 1000000 ? 2 : 1;
591                 mode = 1;       // light
592                 if (sds->cache_high_comp == SM_CACHE_HEAVY) mode=2;     // heavy
593
594                 in_len_big = sizeof(float) * (unsigned int)res_big;
595
596                 smoke_turbulence_export(sds->wt, &dens, &densold, &tcu, &tcv, &tcw);
597
598                 out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len_big), "pointcache_lzo_buffer");
599                 ptcache_file_compressed_write(pf, (unsigned char *)dens, in_len_big, out, mode);
600                 ptcache_file_compressed_write(pf, (unsigned char *)densold, in_len_big, out, mode);     
601                 MEM_freeN(out);
602
603                 out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len), "pointcache_lzo_buffer");
604                 ptcache_file_compressed_write(pf, (unsigned char *)tcu, in_len, out, mode);
605                 ptcache_file_compressed_write(pf, (unsigned char *)tcv, in_len, out, mode);
606                 ptcache_file_compressed_write(pf, (unsigned char *)tcw, in_len, out, mode);
607                 MEM_freeN(out);
608                 
609                 ret = 1;
610         }
611
612         return ret;
613 }
614 static int ptcache_smoke_read(PTCacheFile *pf, void *smoke_v)
615 {
616         SmokeModifierData *smd= (SmokeModifierData *)smoke_v;
617         SmokeDomainSettings *sds = smd->domain;
618         
619         if (sds->fluid) {
620                 size_t res = sds->res[0]*sds->res[1]*sds->res[2];
621                 float dt, dx, *dens, *densold, *heat, *heatold, *vx, *vy, *vz, *vxold, *vyold, *vzold;
622                 unsigned char *obstacles;
623                 unsigned int out_len = (unsigned int)res * sizeof(float);
624                 
625                 smoke_export(sds->fluid, &dt, &dx, &dens, &densold, &heat, &heatold, &vx, &vy, &vz, &vxold, &vyold, &vzold, &obstacles);
626
627                 ptcache_file_compressed_read(pf, (unsigned char *)sds->shadow, out_len);
628                 ptcache_file_compressed_read(pf, (unsigned char*)dens, out_len);
629                 ptcache_file_compressed_read(pf, (unsigned char*)densold, out_len);
630                 ptcache_file_compressed_read(pf, (unsigned char*)heat, out_len);
631                 ptcache_file_compressed_read(pf, (unsigned char*)heatold, out_len);
632                 ptcache_file_compressed_read(pf, (unsigned char*)vx, out_len);
633                 ptcache_file_compressed_read(pf, (unsigned char*)vy, out_len);
634                 ptcache_file_compressed_read(pf, (unsigned char*)vz, out_len);
635                 ptcache_file_compressed_read(pf, (unsigned char*)vxold, out_len);
636                 ptcache_file_compressed_read(pf, (unsigned char*)vyold, out_len);
637                 ptcache_file_compressed_read(pf, (unsigned char*)vzold, out_len);
638                 ptcache_file_compressed_read(pf, (unsigned char*)obstacles, (unsigned int)res);
639                 ptcache_file_read(pf, &dt, 1, sizeof(float));
640                 ptcache_file_read(pf, &dx, 1, sizeof(float));
641
642                 if (pf->data_types & (1<<BPHYS_DATA_SMOKE_HIGH) && sds->wt) {
643                         int res = sds->res[0]*sds->res[1]*sds->res[2];
644                         int res_big, res_big_array[3];
645                         float *dens, *densold, *tcu, *tcv, *tcw;
646                         unsigned int out_len = sizeof(float)*(unsigned int)res;
647                         unsigned int out_len_big;
648
649                         smoke_turbulence_get_res(sds->wt, res_big_array);
650                         res_big = res_big_array[0]*res_big_array[1]*res_big_array[2];
651                         out_len_big = sizeof(float) * (unsigned int)res_big;
652
653                         smoke_turbulence_export(sds->wt, &dens, &densold, &tcu, &tcv, &tcw);
654
655                         ptcache_file_compressed_read(pf, (unsigned char*)dens, out_len_big);
656                         ptcache_file_compressed_read(pf, (unsigned char*)densold, out_len_big);
657
658                         ptcache_file_compressed_read(pf, (unsigned char*)tcu, out_len);
659                         ptcache_file_compressed_read(pf, (unsigned char*)tcv, out_len);
660                         ptcache_file_compressed_read(pf, (unsigned char*)tcw, out_len);
661                 }
662         }
663
664         return 1;
665 }
666 #else // WITH_SMOKE
667 static int  ptcache_smoke_totpoint(void *UNUSED(smoke_v), int UNUSED(cfra)) { return 0; }
668 static int  ptcache_smoke_read(PTCacheFile *UNUSED(pf), void *UNUSED(smoke_v)) { return 0; }
669 static int  ptcache_smoke_write(PTCacheFile *UNUSED(pf), void *UNUSED(smoke_v)) { return 0; }
670 #endif // WITH_SMOKE
671
672 static int ptcache_dynamicpaint_totpoint(void *sd, int UNUSED(cfra))
673 {
674         DynamicPaintSurface *surface = (DynamicPaintSurface*)sd;
675
676         if (!surface->data) return 0;
677         else return surface->data->total_points;
678 }
679
680 #define DPAINT_CACHE_VERSION "1.01"
681
682 static int  ptcache_dynamicpaint_write(PTCacheFile *pf, void *dp_v)
683 {       
684         DynamicPaintSurface *surface = (DynamicPaintSurface*)dp_v;
685         int cache_compress = 1;
686
687         /* version header */
688         ptcache_file_write(pf, DPAINT_CACHE_VERSION, 1, sizeof(char)*4);
689
690         if (surface->format != MOD_DPAINT_SURFACE_F_IMAGESEQ && surface->data) {
691                 int total_points=surface->data->total_points;
692                 unsigned int in_len;
693                 unsigned char *out;
694
695                 /* cache type */
696                 ptcache_file_write(pf, &surface->type, 1, sizeof(int));
697
698                 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
699                         in_len = sizeof(PaintPoint) * total_points;
700                 }
701                 else if (surface->type == MOD_DPAINT_SURFACE_T_DISPLACE ||
702                          surface->type == MOD_DPAINT_SURFACE_T_WEIGHT)
703                 {
704                         in_len = sizeof(float) * total_points;
705                 }
706                 else if (surface->type == MOD_DPAINT_SURFACE_T_WAVE) {
707                         in_len = sizeof(PaintWavePoint) * total_points;
708                 }
709                 else {
710                         return 0;
711                 }
712
713                 out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len), "pointcache_lzo_buffer");
714
715                 ptcache_file_compressed_write(pf, (unsigned char *)surface->data->type_data, in_len, out, cache_compress);
716                 MEM_freeN(out);
717
718         }
719         return 1;
720 }
721 static int ptcache_dynamicpaint_read(PTCacheFile *pf, void *dp_v)
722 {
723         DynamicPaintSurface *surface = (DynamicPaintSurface*)dp_v;
724         char version[4];
725         
726         /* version header */
727         ptcache_file_read(pf, version, 1, sizeof(char)*4);
728         if (strncmp(version, DPAINT_CACHE_VERSION, 4)) {printf("Dynamic Paint: Invalid cache version: %s!\n", version); return 0;}
729
730         if (surface->format != MOD_DPAINT_SURFACE_F_IMAGESEQ && surface->data) {
731                 unsigned int data_len;
732                 int surface_type;
733
734                 /* cache type */
735                 ptcache_file_read(pf, &surface_type, 1, sizeof(int));
736
737                 if (surface_type != surface->type)
738                         return 0;
739
740                 /* read surface data */
741                 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
742                         data_len = sizeof(PaintPoint);
743                 }
744                 else if (surface->type == MOD_DPAINT_SURFACE_T_DISPLACE ||
745                          surface->type == MOD_DPAINT_SURFACE_T_WEIGHT)
746                 {
747                         data_len = sizeof(float);
748                 }
749                 else if (surface->type == MOD_DPAINT_SURFACE_T_WAVE) {
750                         data_len = sizeof(PaintWavePoint);
751                 }
752                 else {
753                         return 0;
754                 }
755
756                 ptcache_file_compressed_read(pf, (unsigned char*)surface->data->type_data, data_len*surface->data->total_points);
757
758         }
759         return 1;
760 }
761
762 /* Creating ID's */
763 void BKE_ptcache_id_from_softbody(PTCacheID *pid, Object *ob, SoftBody *sb)
764 {
765         memset(pid, 0, sizeof(PTCacheID));
766
767         pid->ob= ob;
768         pid->calldata= sb;
769         pid->type= PTCACHE_TYPE_SOFTBODY;
770         pid->cache= sb->pointcache;
771         pid->cache_ptr= &sb->pointcache;
772         pid->ptcaches= &sb->ptcaches;
773         pid->totpoint= pid->totwrite= ptcache_softbody_totpoint;
774
775         pid->write_point                        = ptcache_softbody_write;
776         pid->read_point                         = ptcache_softbody_read;
777         pid->interpolate_point          = ptcache_softbody_interpolate;
778
779         pid->write_stream                       = NULL;
780         pid->read_stream                        = NULL;
781
782         pid->write_extra_data           = NULL;
783         pid->read_extra_data            = NULL;
784         pid->interpolate_extra_data     = NULL;
785
786         pid->write_header                       = ptcache_basic_header_write;
787         pid->read_header                        = ptcache_basic_header_read;
788
789         pid->data_types= (1<<BPHYS_DATA_LOCATION) | (1<<BPHYS_DATA_VELOCITY);
790         pid->info_types= 0;
791
792         pid->stack_index = pid->cache->index;
793
794         pid->default_step = 10;
795         pid->max_step = 20;
796 }
797 void BKE_ptcache_id_from_particles(PTCacheID *pid, Object *ob, ParticleSystem *psys)
798 {
799         memset(pid, 0, sizeof(PTCacheID));
800
801         pid->ob= ob;
802         pid->calldata= psys;
803         pid->type= PTCACHE_TYPE_PARTICLES;
804         pid->stack_index= psys->pointcache->index;
805         pid->cache= psys->pointcache;
806         pid->cache_ptr= &psys->pointcache;
807         pid->ptcaches= &psys->ptcaches;
808
809         if (psys->part->type != PART_HAIR)
810                 pid->flag |= PTCACHE_VEL_PER_SEC;
811
812         pid->totpoint                           = ptcache_particle_totpoint;
813         pid->totwrite                           = ptcache_particle_totwrite;
814
815         pid->write_point                                = ptcache_particle_write;
816         pid->read_point                         = ptcache_particle_read;
817         pid->interpolate_point          = ptcache_particle_interpolate;
818
819         pid->write_stream                       = NULL;
820         pid->read_stream                        = NULL;
821
822         pid->write_extra_data           = NULL;
823         pid->read_extra_data            = NULL;
824         pid->interpolate_extra_data     = NULL;
825
826         pid->write_header                       = ptcache_basic_header_write;
827         pid->read_header                        = ptcache_basic_header_read;
828
829         pid->data_types = (1<<BPHYS_DATA_LOCATION) | (1<<BPHYS_DATA_VELOCITY) | (1<<BPHYS_DATA_INDEX);
830
831         if (psys->part->phystype == PART_PHYS_BOIDS)
832                 pid->data_types|= (1<<BPHYS_DATA_AVELOCITY) | (1<<BPHYS_DATA_ROTATION) | (1<<BPHYS_DATA_BOIDS);
833         else if (psys->part->phystype == PART_PHYS_FLUID && psys->part->fluid && psys->part->fluid->flag & SPH_VISCOELASTIC_SPRINGS) {
834                 pid->write_extra_data = ptcache_particle_extra_write;
835                 pid->read_extra_data = ptcache_particle_extra_read;
836         }
837
838         if (psys->part->flag & PART_ROTATIONS) {
839                 pid->data_types|= (1<<BPHYS_DATA_ROTATION);
840
841                 if (psys->part->rotmode != PART_ROT_VEL  ||
842                     psys->part->avemode == PART_AVE_RAND ||
843                     psys->part->avefac != 0.0f)
844                 {
845                         pid->data_types |= (1 << BPHYS_DATA_AVELOCITY);
846                 }
847         }
848
849         pid->info_types= (1<<BPHYS_DATA_TIMES);
850
851         pid->default_step = 10;
852         pid->max_step = 20;
853 }
854 void BKE_ptcache_id_from_cloth(PTCacheID *pid, Object *ob, ClothModifierData *clmd)
855 {
856         memset(pid, 0, sizeof(PTCacheID));
857
858         pid->ob= ob;
859         pid->calldata= clmd;
860         pid->type= PTCACHE_TYPE_CLOTH;
861         pid->stack_index= clmd->point_cache->index;
862         pid->cache= clmd->point_cache;
863         pid->cache_ptr= &clmd->point_cache;
864         pid->ptcaches= &clmd->ptcaches;
865         pid->totpoint= pid->totwrite= ptcache_cloth_totpoint;
866
867         pid->write_point                        = ptcache_cloth_write;
868         pid->read_point                         = ptcache_cloth_read;
869         pid->interpolate_point          = ptcache_cloth_interpolate;
870
871         pid->write_stream                       = NULL;
872         pid->read_stream                        = NULL;
873
874         pid->write_extra_data           = NULL;
875         pid->read_extra_data            = NULL;
876         pid->interpolate_extra_data     = NULL;
877
878         pid->write_header                       = ptcache_basic_header_write;
879         pid->read_header                        = ptcache_basic_header_read;
880
881         pid->data_types= (1<<BPHYS_DATA_LOCATION) | (1<<BPHYS_DATA_VELOCITY) | (1<<BPHYS_DATA_XCONST);
882         pid->info_types= 0;
883
884         pid->default_step = 1;
885         pid->max_step = 1;
886 }
887 void BKE_ptcache_id_from_smoke(PTCacheID *pid, struct Object *ob, struct SmokeModifierData *smd)
888 {
889         SmokeDomainSettings *sds = smd->domain;
890
891         memset(pid, 0, sizeof(PTCacheID));
892
893         pid->ob= ob;
894         pid->calldata= smd;
895         
896         pid->type= PTCACHE_TYPE_SMOKE_DOMAIN;
897         pid->stack_index= sds->point_cache[0]->index;
898
899         pid->cache= sds->point_cache[0];
900         pid->cache_ptr= &(sds->point_cache[0]);
901         pid->ptcaches= &(sds->ptcaches[0]);
902
903         pid->totpoint= pid->totwrite= ptcache_smoke_totpoint;
904
905         pid->write_point                        = NULL;
906         pid->read_point                         = NULL;
907         pid->interpolate_point          = NULL;
908
909         pid->read_stream                        = ptcache_smoke_read;
910         pid->write_stream                       = ptcache_smoke_write;
911
912         pid->write_extra_data           = NULL;
913         pid->read_extra_data            = NULL;
914         pid->interpolate_extra_data     = NULL;
915
916         pid->write_header                       = ptcache_basic_header_write;
917         pid->read_header                        = ptcache_basic_header_read;
918
919         pid->data_types= 0;
920         pid->info_types= 0;
921
922         if (sds->fluid)
923                 pid->data_types |= (1<<BPHYS_DATA_SMOKE_LOW);
924         if (sds->wt)
925                 pid->data_types |= (1<<BPHYS_DATA_SMOKE_HIGH);
926
927         pid->default_step = 1;
928         pid->max_step = 1;
929 }
930
931 void BKE_ptcache_id_from_dynamicpaint(PTCacheID *pid, Object *ob, DynamicPaintSurface *surface)
932 {
933
934         memset(pid, 0, sizeof(PTCacheID));
935
936         pid->ob= ob;
937         pid->calldata= surface;
938         pid->type= PTCACHE_TYPE_DYNAMICPAINT;
939         pid->cache= surface->pointcache;
940         pid->cache_ptr= &surface->pointcache;
941         pid->ptcaches= &surface->ptcaches;
942         pid->totpoint= pid->totwrite= ptcache_dynamicpaint_totpoint;
943
944         pid->write_point                        = NULL;
945         pid->read_point                         = NULL;
946         pid->interpolate_point          = NULL;
947
948         pid->write_stream                       = ptcache_dynamicpaint_write;
949         pid->read_stream                        = ptcache_dynamicpaint_read;
950
951         pid->write_extra_data           = NULL;
952         pid->read_extra_data            = NULL;
953         pid->interpolate_extra_data     = NULL;
954
955         pid->write_header                       = ptcache_basic_header_write;
956         pid->read_header                        = ptcache_basic_header_read;
957
958         pid->data_types= BPHYS_DATA_DYNAMICPAINT;
959         pid->info_types= 0;
960
961         pid->stack_index = pid->cache->index;
962
963         pid->default_step = 1;
964         pid->max_step = 1;
965 }
966
967 void BKE_ptcache_ids_from_object(ListBase *lb, Object *ob, Scene *scene, int duplis)
968 {
969         PTCacheID *pid;
970         ParticleSystem *psys;
971         ModifierData *md;
972
973         lb->first= lb->last= NULL;
974
975         if (ob->soft) {
976                 pid= MEM_callocN(sizeof(PTCacheID), "PTCacheID");
977                 BKE_ptcache_id_from_softbody(pid, ob, ob->soft);
978                 BLI_addtail(lb, pid);
979         }
980
981         for (psys=ob->particlesystem.first; psys; psys=psys->next) {
982                 if (psys->part==NULL)
983                         continue;
984                 
985                 /* check to make sure point cache is actually used by the particles */
986                 if (ELEM(psys->part->phystype, PART_PHYS_NO, PART_PHYS_KEYED))
987                         continue;
988
989                 /* hair needs to be included in id-list for cache edit mode to work */
990                 /* if (psys->part->type == PART_HAIR && (psys->flag & PSYS_HAIR_DYNAMICS)==0) */
991                 /*      continue; */
992                         
993                 if (psys->part->type == PART_FLUID)
994                         continue;
995
996                 pid= MEM_callocN(sizeof(PTCacheID), "PTCacheID");
997                 BKE_ptcache_id_from_particles(pid, ob, psys);
998                 BLI_addtail(lb, pid);
999         }
1000
1001         for (md=ob->modifiers.first; md; md=md->next) {
1002                 if (md->type == eModifierType_Cloth) {
1003                         pid= MEM_callocN(sizeof(PTCacheID), "PTCacheID");
1004                         BKE_ptcache_id_from_cloth(pid, ob, (ClothModifierData*)md);
1005                         BLI_addtail(lb, pid);
1006                 }
1007                 else if (md->type == eModifierType_Smoke) {
1008                         SmokeModifierData *smd = (SmokeModifierData *)md;
1009                         if (smd->type & MOD_SMOKE_TYPE_DOMAIN) {
1010                                 pid= MEM_callocN(sizeof(PTCacheID), "PTCacheID");
1011                                 BKE_ptcache_id_from_smoke(pid, ob, (SmokeModifierData*)md);
1012                                 BLI_addtail(lb, pid);
1013                         }
1014                 }
1015                 else if (md->type == eModifierType_DynamicPaint) {
1016                         DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)md;
1017                         if (pmd->canvas) {
1018                                 DynamicPaintSurface *surface = pmd->canvas->surfaces.first;
1019
1020                                 for (; surface; surface=surface->next) {
1021                                         pid= MEM_callocN(sizeof(PTCacheID), "PTCacheID");
1022                                         BKE_ptcache_id_from_dynamicpaint(pid, ob, surface);
1023                                         BLI_addtail(lb, pid);
1024                                 }
1025                         }
1026                 }
1027         }
1028
1029         if (scene && (duplis-- > 0) && (ob->transflag & OB_DUPLI)) {
1030                 ListBase *lb_dupli_ob;
1031
1032                 /* don't update the dupli groups, we only wan't their pid's */
1033                 if ((lb_dupli_ob = object_duplilist_ex(scene, ob, FALSE))) {
1034                         DupliObject *dob;
1035                         for (dob= lb_dupli_ob->first; dob; dob= dob->next) {
1036                                 if (dob->ob != ob) { /* avoids recursive loops with dupliframes: bug 22988 */
1037                                         ListBase lb_dupli_pid;
1038                                         BKE_ptcache_ids_from_object(&lb_dupli_pid, dob->ob, scene, duplis);
1039                                         BLI_movelisttolist(lb, &lb_dupli_pid);
1040                                         if (lb_dupli_pid.first)
1041                                                 printf("Adding Dupli\n");
1042                                 }
1043                         }
1044
1045                         free_object_duplilist(lb_dupli_ob);     /* does restore */
1046                 }
1047         }
1048 }
1049
1050 /* File handling */
1051
1052 /* Takes an Object ID and returns a unique name
1053  * - id: object id
1054  * - cfra: frame for the cache, can be negative
1055  * - stack_index: index in the modifier stack. we can have cache for more then one stack_index
1056  */
1057
1058 #define MAX_PTCACHE_PATH FILE_MAX
1059 #define MAX_PTCACHE_FILE ((FILE_MAX)*2)
1060
1061 static int ptcache_path(PTCacheID *pid, char *filename)
1062 {
1063         Library *lib= (pid->ob)? pid->ob->id.lib: NULL;
1064         const char *blendfilename= (lib && (pid->cache->flag & PTCACHE_IGNORE_LIBPATH)==0) ? lib->filepath: G.main->name;
1065         size_t i;
1066
1067         if (pid->cache->flag & PTCACHE_EXTERNAL) {
1068                 strcpy(filename, pid->cache->path);
1069
1070                 if (BLI_path_is_rel(filename)) {
1071                         BLI_path_abs(filename, blendfilename);
1072                 }
1073
1074                 return BLI_add_slash(filename); /* new strlen() */
1075         }
1076         else if (G.relbase_valid || lib) {
1077                 char file[MAX_PTCACHE_PATH]; /* we don't want the dir, only the file */
1078
1079                 BLI_split_file_part(blendfilename, file, sizeof(file));
1080                 i = strlen(file);
1081                 
1082                 /* remove .blend */
1083                 if (i > 6)
1084                         file[i-6] = '\0';
1085                 
1086                 BLI_snprintf(filename, MAX_PTCACHE_PATH, "//"PTCACHE_PATH"%s", file); /* add blend file name to pointcache dir */
1087                 BLI_path_abs(filename, blendfilename);
1088                 return BLI_add_slash(filename); /* new strlen() */
1089         }
1090         
1091         /* use the temp path. this is weak but better then not using point cache at all */
1092         /* temporary directory is assumed to exist and ALWAYS has a trailing slash */
1093         BLI_snprintf(filename, MAX_PTCACHE_PATH, "%s"PTCACHE_PATH"%d", BLI_temporary_dir(), abs(getpid()));
1094         
1095         return BLI_add_slash(filename); /* new strlen() */
1096 }
1097
1098 static int ptcache_filename(PTCacheID *pid, char *filename, int cfra, short do_path, short do_ext)
1099 {
1100         int len=0;
1101         char *idname;
1102         char *newname;
1103         filename[0] = '\0';
1104         newname = filename;
1105         
1106         if (!G.relbase_valid && (pid->cache->flag & PTCACHE_EXTERNAL)==0) return 0; /* save blend file before using disk pointcache */
1107         
1108         /* start with temp dir */
1109         if (do_path) {
1110                 len = ptcache_path(pid, filename);
1111                 newname += len;
1112         }
1113         if (pid->cache->name[0] == '\0' && (pid->cache->flag & PTCACHE_EXTERNAL)==0) {
1114                 idname = (pid->ob->id.name+2);
1115                 /* convert chars to hex so they are always a valid filename */
1116                 while ('\0' != *idname) {
1117                         BLI_snprintf(newname, MAX_PTCACHE_FILE, "%02X", (char)(*idname++));
1118                         newname+=2;
1119                         len += 2;
1120                 }
1121         }
1122         else {
1123                 int temp = (int)strlen(pid->cache->name); 
1124                 strcpy(newname, pid->cache->name); 
1125                 newname+=temp;
1126                 len += temp;
1127         }
1128
1129         if (do_ext) {
1130
1131                 if (pid->cache->index < 0)
1132                         pid->cache->index =  pid->stack_index = BKE_object_insert_ptcache(pid->ob);
1133
1134                 if (pid->cache->flag & PTCACHE_EXTERNAL) {
1135                         if (pid->cache->index >= 0)
1136                                 BLI_snprintf(newname, MAX_PTCACHE_FILE, "_%06d_%02u"PTCACHE_EXT, cfra, pid->stack_index); /* always 6 chars */
1137                         else
1138                                 BLI_snprintf(newname, MAX_PTCACHE_FILE, "_%06d"PTCACHE_EXT, cfra); /* always 6 chars */
1139                 }
1140                 else {
1141                         BLI_snprintf(newname, MAX_PTCACHE_FILE, "_%06d_%02u"PTCACHE_EXT, cfra, pid->stack_index); /* always 6 chars */
1142                 }
1143                 len += 16;
1144         }
1145         
1146         return len; /* make sure the above string is always 16 chars */
1147 }
1148
1149 /* youll need to close yourself after! */
1150 static PTCacheFile *ptcache_file_open(PTCacheID *pid, int mode, int cfra)
1151 {
1152         PTCacheFile *pf;
1153         FILE *fp = NULL;
1154         char filename[(FILE_MAX)*2];
1155
1156 #ifndef DURIAN_POINTCACHE_LIB_OK
1157         /* don't allow writing for linked objects */
1158         if (pid->ob->id.lib && mode == PTCACHE_FILE_WRITE)
1159                 return NULL;
1160 #endif
1161         if (!G.relbase_valid && (pid->cache->flag & PTCACHE_EXTERNAL)==0) return NULL; /* save blend file before using disk pointcache */
1162         
1163         ptcache_filename(pid, filename, cfra, 1, 1);
1164
1165         if (mode==PTCACHE_FILE_READ) {
1166                 if (!BLI_exists(filename)) {
1167                         return NULL;
1168                 }
1169                 fp = BLI_fopen(filename, "rb");
1170         }
1171         else if (mode==PTCACHE_FILE_WRITE) {
1172                 BLI_make_existing_file(filename); /* will create the dir if needs be, same as //textures is created */
1173                 fp = BLI_fopen(filename, "wb");
1174         }
1175         else if (mode==PTCACHE_FILE_UPDATE) {
1176                 BLI_make_existing_file(filename);
1177                 fp = BLI_fopen(filename, "rb+");
1178         }
1179
1180         if (!fp)
1181                 return NULL;
1182
1183         pf= MEM_mallocN(sizeof(PTCacheFile), "PTCacheFile");
1184         pf->fp= fp;
1185         pf->old_format = 0;
1186         pf->frame = cfra;
1187
1188         return pf;
1189 }
1190 static void ptcache_file_close(PTCacheFile *pf)
1191 {
1192         if (pf) {
1193                 fclose(pf->fp);
1194                 MEM_freeN(pf);
1195         }
1196 }
1197
1198 static int ptcache_file_compressed_read(PTCacheFile *pf, unsigned char *result, unsigned int len)
1199 {
1200         int r = 0;
1201         unsigned char compressed = 0;
1202         size_t in_len;
1203 #ifdef WITH_LZO
1204         size_t out_len = len;
1205 #endif
1206         unsigned char *in;
1207         unsigned char *props = MEM_callocN(16*sizeof(char), "tmp");
1208
1209         ptcache_file_read(pf, &compressed, 1, sizeof(unsigned char));
1210         if (compressed) {
1211                 unsigned int size;
1212                 ptcache_file_read(pf, &size, 1, sizeof(unsigned int));
1213                 in_len = (size_t)size;
1214                 if (in_len==0) {
1215                         /* do nothing */
1216                 }
1217                 else {
1218                         in = (unsigned char *)MEM_callocN(sizeof(unsigned char)*in_len, "pointcache_compressed_buffer");
1219                         ptcache_file_read(pf, in, in_len, sizeof(unsigned char));
1220 #ifdef WITH_LZO
1221                         if (compressed == 1)
1222                                 r = lzo1x_decompress_safe(in, (lzo_uint)in_len, result, (lzo_uint *)&out_len, NULL);
1223 #endif
1224 #ifdef WITH_LZMA
1225                         if (compressed == 2) {
1226                                 size_t sizeOfIt;
1227                                 size_t leni = in_len, leno = len;
1228                                 ptcache_file_read(pf, &size, 1, sizeof(unsigned int));
1229                                 sizeOfIt = (size_t)size;
1230                                 ptcache_file_read(pf, props, sizeOfIt, sizeof(unsigned char));
1231                                 r = LzmaUncompress(result, &leno, in, &leni, props, sizeOfIt);
1232                         }
1233 #endif
1234                         MEM_freeN(in);
1235                 }
1236         }
1237         else {
1238                 ptcache_file_read(pf, result, len, sizeof(unsigned char));
1239         }
1240
1241         MEM_freeN(props);
1242
1243         return r;
1244 }
1245 static int ptcache_file_compressed_write(PTCacheFile *pf, unsigned char *in, unsigned int in_len, unsigned char *out, int mode)
1246 {
1247         int r = 0;
1248         unsigned char compressed = 0;
1249         size_t out_len= 0;
1250         unsigned char *props = MEM_callocN(16*sizeof(char), "tmp");
1251         size_t sizeOfIt = 5;
1252
1253         (void)mode; /* unused when building w/o compression */
1254
1255 #ifdef WITH_LZO
1256         out_len= LZO_OUT_LEN(in_len);
1257         if (mode == 1) {
1258                 LZO_HEAP_ALLOC(wrkmem, LZO1X_MEM_COMPRESS);
1259                 
1260                 r = lzo1x_1_compress(in, (lzo_uint)in_len, out, (lzo_uint *)&out_len, wrkmem);  
1261                 if (!(r == LZO_E_OK) || (out_len >= in_len))
1262                         compressed = 0;
1263                 else
1264                         compressed = 1;
1265         }
1266 #endif
1267 #ifdef WITH_LZMA
1268         if (mode == 2) {
1269                 
1270                 r = LzmaCompress(out, &out_len, in, in_len, //assume sizeof(char)==1....
1271                                                 props, &sizeOfIt, 5, 1 << 24, 3, 0, 2, 32, 2);
1272
1273                 if (!(r == SZ_OK) || (out_len >= in_len))
1274                         compressed = 0;
1275                 else
1276                         compressed = 2;
1277         }
1278 #endif
1279         
1280         ptcache_file_write(pf, &compressed, 1, sizeof(unsigned char));
1281         if (compressed) {
1282                 unsigned int size = out_len;
1283                 ptcache_file_write(pf, &size, 1, sizeof(unsigned int));
1284                 ptcache_file_write(pf, out, out_len, sizeof(unsigned char));
1285         }
1286         else
1287                 ptcache_file_write(pf, in, in_len, sizeof(unsigned char));
1288
1289         if (compressed == 2) {
1290                 unsigned int size = sizeOfIt;
1291                 ptcache_file_write(pf, &sizeOfIt, 1, sizeof(unsigned int));
1292                 ptcache_file_write(pf, props, size, sizeof(unsigned char));
1293         }
1294
1295         MEM_freeN(props);
1296
1297         return r;
1298 }
1299 static int ptcache_file_read(PTCacheFile *pf, void *f, unsigned int tot, unsigned int size)
1300 {
1301         return (fread(f, size, tot, pf->fp) == tot);
1302 }
1303 static int ptcache_file_write(PTCacheFile *pf, const void *f, unsigned int tot, unsigned int size)
1304 {
1305         return (fwrite(f, size, tot, pf->fp) == tot);
1306 }
1307 static int ptcache_file_data_read(PTCacheFile *pf)
1308 {
1309         int i;
1310
1311         for (i=0; i<BPHYS_TOT_DATA; i++) {
1312                 if ((pf->data_types & (1<<i)) && !ptcache_file_read(pf, pf->cur[i], 1, ptcache_data_size[i]))
1313                         return 0;
1314         }
1315         
1316         return 1;
1317 }
1318 static int ptcache_file_data_write(PTCacheFile *pf)
1319 {               
1320         int i;
1321
1322         for (i=0; i<BPHYS_TOT_DATA; i++) {
1323                 if ((pf->data_types & (1<<i)) && !ptcache_file_write(pf, pf->cur[i], 1, ptcache_data_size[i]))
1324                         return 0;
1325         }
1326         
1327         return 1;
1328 }
1329 static int ptcache_file_header_begin_read(PTCacheFile *pf)
1330 {
1331         unsigned int typeflag=0;
1332         int error=0;
1333         char bphysics[8];
1334         
1335         pf->data_types = 0;
1336         
1337         if (fread(bphysics, sizeof(char), 8, pf->fp) != 8)
1338                 error = 1;
1339         
1340         if (!error && strncmp(bphysics, "BPHYSICS", 8))
1341                 error = 1;
1342
1343         if (!error && !fread(&typeflag, sizeof(unsigned int), 1, pf->fp))
1344                 error = 1;
1345
1346         pf->type = (typeflag & PTCACHE_TYPEFLAG_TYPEMASK);
1347         pf->flag = (typeflag & PTCACHE_TYPEFLAG_FLAGMASK);
1348         
1349         /* if there was an error set file as it was */
1350         if (error)
1351                 fseek(pf->fp, 0, SEEK_SET);
1352
1353         return !error;
1354 }
1355 static int ptcache_file_header_begin_write(PTCacheFile *pf)
1356 {
1357         const char *bphysics = "BPHYSICS";
1358         unsigned int typeflag = pf->type + pf->flag;
1359         
1360         if (fwrite(bphysics, sizeof(char), 8, pf->fp) != 8)
1361                 return 0;
1362
1363         if (!fwrite(&typeflag, sizeof(unsigned int), 1, pf->fp))
1364                 return 0;
1365         
1366         return 1;
1367 }
1368
1369 /* Data pointer handling */
1370 int BKE_ptcache_data_size(int data_type)
1371 {
1372         return ptcache_data_size[data_type];
1373 }
1374
1375 static void ptcache_file_pointers_init(PTCacheFile *pf)
1376 {
1377         int data_types = pf->data_types;
1378
1379         pf->cur[BPHYS_DATA_INDEX] =             (data_types & (1<<BPHYS_DATA_INDEX))    ?               &pf->data.index : NULL;
1380         pf->cur[BPHYS_DATA_LOCATION] =  (data_types & (1<<BPHYS_DATA_LOCATION)) ?               &pf->data.loc   : NULL;
1381         pf->cur[BPHYS_DATA_VELOCITY] =  (data_types & (1<<BPHYS_DATA_VELOCITY)) ?               &pf->data.vel   : NULL;
1382         pf->cur[BPHYS_DATA_ROTATION] =  (data_types & (1<<BPHYS_DATA_ROTATION)) ?               &pf->data.rot   : NULL;
1383         pf->cur[BPHYS_DATA_AVELOCITY] = (data_types & (1<<BPHYS_DATA_AVELOCITY))?               &pf->data.ave   : NULL;
1384         pf->cur[BPHYS_DATA_SIZE] =              (data_types & (1<<BPHYS_DATA_SIZE))             ?               &pf->data.size  : NULL;
1385         pf->cur[BPHYS_DATA_TIMES] =             (data_types & (1<<BPHYS_DATA_TIMES))    ?               &pf->data.times : NULL;
1386         pf->cur[BPHYS_DATA_BOIDS] =             (data_types & (1<<BPHYS_DATA_BOIDS))    ?               &pf->data.boids : NULL;
1387 }
1388
1389 /* Check to see if point number "index" is in pm, uses binary search for index data. */
1390 int BKE_ptcache_mem_index_find(PTCacheMem *pm, unsigned int index)
1391 {
1392         if (pm->data[BPHYS_DATA_INDEX]) {
1393                 unsigned int *data = pm->data[BPHYS_DATA_INDEX];
1394                 unsigned int mid, low = 0, high = pm->totpoint - 1;
1395
1396                 if (index < *data || index > *(data+high))
1397                         return -1;
1398
1399                 /* check simple case for continuous indexes first */
1400                 if (index-*data < high && data[index-*data] == index)
1401                         return index-*data;
1402
1403                 while (low <= high) {
1404                         mid= (low + high)/2;
1405
1406                         if (data[mid] > index)
1407                                 high = mid - 1;
1408                         else if (data[mid] < index)
1409                                 low = mid + 1;
1410                         else
1411                                 return mid;
1412                 }
1413
1414                 return -1;
1415         }
1416         else {
1417                 return (index < pm->totpoint ? index : -1);
1418         }
1419 }
1420
1421 void BKE_ptcache_mem_pointers_init(PTCacheMem *pm)
1422 {
1423         int data_types = pm->data_types;
1424         int i;
1425
1426         for (i=0; i<BPHYS_TOT_DATA; i++)
1427                 pm->cur[i] = ((data_types & (1<<i)) ? pm->data[i] : NULL);
1428 }
1429
1430 void BKE_ptcache_mem_pointers_incr(PTCacheMem *pm)
1431 {
1432         int i;
1433
1434         for (i=0; i<BPHYS_TOT_DATA; i++) {
1435                 if (pm->cur[i])
1436                         pm->cur[i] = (char*)pm->cur[i] + ptcache_data_size[i];
1437         }
1438 }
1439 int  BKE_ptcache_mem_pointers_seek(int point_index, PTCacheMem *pm)
1440 {
1441         int data_types = pm->data_types;
1442         int i, index = BKE_ptcache_mem_index_find(pm, point_index);
1443
1444         if (index < 0) {
1445                 /* Can't give proper location without reallocation, so don't give any location.
1446                  * Some points will be cached improperly, but this only happens with simulation
1447                  * steps bigger than cache->step, so the cache has to be recalculated anyways
1448                  * at some point.
1449                  */
1450                 return 0;
1451         }
1452
1453         for (i=0; i<BPHYS_TOT_DATA; i++)
1454                 pm->cur[i] = data_types & (1<<i) ? (char*)pm->data[i] + index * ptcache_data_size[i] : NULL;
1455
1456         return 1;
1457 }
1458 static void ptcache_data_alloc(PTCacheMem *pm)
1459 {
1460         int data_types = pm->data_types;
1461         int totpoint = pm->totpoint;
1462         int i;
1463
1464         for (i=0; i<BPHYS_TOT_DATA; i++) {
1465                 if (data_types & (1<<i))
1466                         pm->data[i] = MEM_callocN(totpoint * ptcache_data_size[i], "PTCache Data");
1467         }
1468 }
1469 static void ptcache_data_free(PTCacheMem *pm)
1470 {
1471         void **data = pm->data;
1472         int i;
1473
1474         for (i=0; i<BPHYS_TOT_DATA; i++) {
1475                 if (data[i])
1476                         MEM_freeN(data[i]);
1477         }
1478 }
1479 static void ptcache_data_copy(void *from[], void *to[])
1480 {
1481         int i;
1482         for (i=0; i<BPHYS_TOT_DATA; i++) {
1483         /* note, durian file 03.4b_comp crashes if to[i] is not tested
1484          * its NULL, not sure if this should be fixed elsewhere but for now its needed */
1485                 if (from[i] && to[i])
1486                         memcpy(to[i], from[i], ptcache_data_size[i]);
1487         }
1488 }
1489
1490 static void ptcache_extra_free(PTCacheMem *pm)
1491 {
1492         PTCacheExtra *extra = pm->extradata.first;
1493
1494         if (extra) {
1495                 for (; extra; extra=extra->next) {
1496                         if (extra->data)
1497                                 MEM_freeN(extra->data);
1498                 }
1499
1500                 BLI_freelistN(&pm->extradata);
1501         }
1502 }
1503 static int ptcache_old_elemsize(PTCacheID *pid)
1504 {
1505         if (pid->type==PTCACHE_TYPE_SOFTBODY)
1506                 return 6 * sizeof(float);
1507         else if (pid->type==PTCACHE_TYPE_PARTICLES)
1508                 return sizeof(ParticleKey);
1509         else if (pid->type==PTCACHE_TYPE_CLOTH)
1510                 return 9 * sizeof(float);
1511
1512         return 0;
1513 }
1514
1515 static void ptcache_find_frames_around(PTCacheID *pid, unsigned int frame, int *fra1, int *fra2)
1516 {
1517         if (pid->cache->flag & PTCACHE_DISK_CACHE) {
1518                 int cfra1=frame, cfra2=frame+1;
1519
1520                 while (cfra1 >= pid->cache->startframe && !BKE_ptcache_id_exist(pid, cfra1))
1521                         cfra1--;
1522
1523                 if (cfra1 < pid->cache->startframe)
1524                         cfra1 = 0;
1525
1526                 while (cfra2 <= pid->cache->endframe && !BKE_ptcache_id_exist(pid, cfra2))
1527                         cfra2++;
1528
1529                 if (cfra2 > pid->cache->endframe)
1530                         cfra2 = 0;
1531
1532                 if (cfra1 && !cfra2) {
1533                         *fra1 = 0;
1534                         *fra2 = cfra1;
1535                 }
1536                 else {
1537                         *fra1 = cfra1;
1538                         *fra2 = cfra2;
1539                 }
1540         }
1541         else if (pid->cache->mem_cache.first) {
1542                 PTCacheMem *pm = pid->cache->mem_cache.first;
1543                 PTCacheMem *pm2 = pid->cache->mem_cache.last;
1544
1545                 while (pm->next && pm->next->frame <= frame)
1546                         pm= pm->next;
1547
1548                 if (pm2->frame < frame) {
1549                         pm2 = NULL;
1550                 }
1551                 else {
1552                         while (pm2->prev && pm2->prev->frame > frame) {
1553                                 pm2= pm2->prev;
1554                         }
1555                 }
1556
1557                 if (!pm2) {
1558                         *fra1 = 0;
1559                         *fra2 = pm->frame;
1560                 }
1561                 else {
1562                         *fra1 = pm->frame;
1563                         *fra2 = pm2->frame;
1564                 }
1565         }
1566 }
1567
1568 static PTCacheMem *ptcache_disk_frame_to_mem(PTCacheID *pid, int cfra)
1569 {
1570         PTCacheFile *pf = ptcache_file_open(pid, PTCACHE_FILE_READ, cfra);
1571         PTCacheMem *pm = NULL;
1572         unsigned int i, error = 0;
1573
1574         if (pf == NULL)
1575                 return NULL;
1576
1577         if (!ptcache_file_header_begin_read(pf))
1578                 error = 1;
1579
1580         if (!error && (pf->type != pid->type || !pid->read_header(pf)))
1581                 error = 1;
1582
1583         if (!error) {
1584                 pm = MEM_callocN(sizeof(PTCacheMem), "Pointcache mem");
1585
1586                 pm->totpoint = pf->totpoint;
1587                 pm->data_types = pf->data_types;
1588                 pm->frame = pf->frame;
1589
1590                 ptcache_data_alloc(pm);
1591
1592                 if (pf->flag & PTCACHE_TYPEFLAG_COMPRESS) {
1593                         for (i=0; i<BPHYS_TOT_DATA; i++) {
1594                                 unsigned int out_len = pm->totpoint*ptcache_data_size[i];
1595                                 if (pf->data_types & (1<<i))
1596                                         ptcache_file_compressed_read(pf, (unsigned char*)(pm->data[i]), out_len);
1597                         }
1598                 }
1599                 else {
1600                         BKE_ptcache_mem_pointers_init(pm);
1601                         ptcache_file_pointers_init(pf);
1602
1603                         for (i=0; i<pm->totpoint; i++) {
1604                                 if (!ptcache_file_data_read(pf)) {
1605                                         error = 1;
1606                                         break;
1607                                 }
1608                                 ptcache_data_copy(pf->cur, pm->cur);
1609                                 BKE_ptcache_mem_pointers_incr(pm);
1610                         }
1611                 }
1612         }
1613
1614         if (!error && pf->flag & PTCACHE_TYPEFLAG_EXTRADATA) {
1615                 unsigned int extratype = 0;
1616
1617                 while (ptcache_file_read(pf, &extratype, 1, sizeof(unsigned int))) {
1618                         PTCacheExtra *extra = MEM_callocN(sizeof(PTCacheExtra), "Pointcache extradata");
1619
1620                         extra->type = extratype;
1621
1622                         ptcache_file_read(pf, &extra->totdata, 1, sizeof(unsigned int));
1623
1624                         extra->data = MEM_callocN(extra->totdata * ptcache_extra_datasize[extra->type], "Pointcache extradata->data");
1625
1626                         if (pf->flag & PTCACHE_TYPEFLAG_COMPRESS)
1627                                 ptcache_file_compressed_read(pf, (unsigned char*)(extra->data), extra->totdata*ptcache_extra_datasize[extra->type]);
1628                         else
1629                                 ptcache_file_read(pf, extra->data, extra->totdata, ptcache_extra_datasize[extra->type]);
1630
1631                         BLI_addtail(&pm->extradata, extra);
1632                 }
1633         }
1634
1635         if (error && pm) {
1636                 ptcache_data_free(pm);
1637                 ptcache_extra_free(pm);
1638                 MEM_freeN(pm);
1639                 pm = NULL;
1640         }
1641
1642         ptcache_file_close(pf);
1643
1644         if (error && G.debug & G_DEBUG)
1645                 printf("Error reading from disk cache\n");
1646         
1647         return pm;
1648 }
1649 static int ptcache_mem_frame_to_disk(PTCacheID *pid, PTCacheMem *pm)
1650 {
1651         PTCacheFile *pf = NULL;
1652         unsigned int i, error = 0;
1653         
1654         BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_FRAME, pm->frame);
1655
1656         pf = ptcache_file_open(pid, PTCACHE_FILE_WRITE, pm->frame);
1657
1658         if (pf==NULL) {
1659                 if (G.debug & G_DEBUG)
1660                         printf("Error opening disk cache file for writing\n");
1661                 return 0;
1662         }
1663
1664         pf->data_types = pm->data_types;
1665         pf->totpoint = pm->totpoint;
1666         pf->type = pid->type;
1667         pf->flag = 0;
1668         
1669         if (pm->extradata.first)
1670                 pf->flag |= PTCACHE_TYPEFLAG_EXTRADATA;
1671         
1672         if (pid->cache->compression)
1673                 pf->flag |= PTCACHE_TYPEFLAG_COMPRESS;
1674
1675         if (!ptcache_file_header_begin_write(pf) || !pid->write_header(pf))
1676                 error = 1;
1677
1678         if (!error) {
1679                 if (pid->cache->compression) {
1680                         for (i=0; i<BPHYS_TOT_DATA; i++) {
1681                                 if (pm->data[i]) {
1682                                         unsigned int in_len = pm->totpoint*ptcache_data_size[i];
1683                                         unsigned char *out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len)*4, "pointcache_lzo_buffer");
1684                                         ptcache_file_compressed_write(pf, (unsigned char*)(pm->data[i]), in_len, out, pid->cache->compression);
1685                                         MEM_freeN(out);
1686                                 }
1687                         }
1688                 }
1689                 else {
1690                         BKE_ptcache_mem_pointers_init(pm);
1691                         ptcache_file_pointers_init(pf);
1692
1693                         for (i=0; i<pm->totpoint; i++) {
1694                                 ptcache_data_copy(pm->cur, pf->cur);
1695                                 if (!ptcache_file_data_write(pf)) {
1696                                         error = 1;
1697                                         break;
1698                                 }
1699                                 BKE_ptcache_mem_pointers_incr(pm);
1700                         }
1701                 }
1702         }
1703
1704         if (!error && pm->extradata.first) {
1705                 PTCacheExtra *extra = pm->extradata.first;
1706
1707                 for (; extra; extra=extra->next) {
1708                         if (extra->data == NULL || extra->totdata == 0)
1709                                 continue;
1710
1711                         ptcache_file_write(pf, &extra->type, 1, sizeof(unsigned int));
1712                         ptcache_file_write(pf, &extra->totdata, 1, sizeof(unsigned int));
1713
1714                         if (pid->cache->compression) {
1715                                 unsigned int in_len = extra->totdata * ptcache_extra_datasize[extra->type];
1716                                 unsigned char *out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len)*4, "pointcache_lzo_buffer");
1717                                 ptcache_file_compressed_write(pf, (unsigned char*)(extra->data), in_len, out, pid->cache->compression);
1718                                 MEM_freeN(out);
1719                         }
1720                         else {
1721                                 ptcache_file_write(pf, extra->data, extra->totdata, ptcache_extra_datasize[extra->type]);
1722                         }
1723                 }
1724         }
1725
1726         ptcache_file_close(pf);
1727         
1728         if (error && G.debug & G_DEBUG)
1729                 printf("Error writing to disk cache\n");
1730
1731         return error==0;
1732 }
1733
1734 static int ptcache_read_stream(PTCacheID *pid, int cfra)
1735 {
1736         PTCacheFile *pf = ptcache_file_open(pid, PTCACHE_FILE_READ, cfra);
1737         int error = 0;
1738
1739         if (pid->read_stream == NULL)
1740                 return 0;
1741
1742         if (pf == NULL) {
1743                 if (G.debug & G_DEBUG)
1744                         printf("Error opening disk cache file for reading\n");
1745                 return 0;
1746         }
1747
1748         if (!ptcache_file_header_begin_read(pf))
1749                 error = 1;
1750
1751         if (!error && (pf->type != pid->type || !pid->read_header(pf)))
1752                 error = 1;
1753
1754         if (!error && pf->totpoint != pid->totpoint(pid->calldata, cfra))
1755                 error = 1;
1756
1757         if (!error) {
1758                 ptcache_file_pointers_init(pf);
1759
1760                 // we have stream reading here
1761                 if (!pid->read_stream(pf, pid->calldata))
1762                         error = 1;
1763         }
1764
1765         ptcache_file_close(pf);
1766         
1767         return error == 0;
1768 }
1769 static int ptcache_read(PTCacheID *pid, int cfra)
1770 {
1771         PTCacheMem *pm = NULL;
1772         int i;
1773         int *index = &i;
1774
1775         /* get a memory cache to read from */
1776         if (pid->cache->flag & PTCACHE_DISK_CACHE) {
1777                 pm = ptcache_disk_frame_to_mem(pid, cfra);
1778         }
1779         else {
1780                 pm = pid->cache->mem_cache.first;
1781                 
1782                 while (pm && pm->frame != cfra)
1783                         pm = pm->next;
1784         }
1785
1786         /* read the cache */
1787         if (pm) {
1788                 int totpoint = pm->totpoint;
1789
1790                 if ((pid->data_types & (1<<BPHYS_DATA_INDEX)) == 0)
1791                         totpoint = MIN2(totpoint, pid->totpoint(pid->calldata, cfra));
1792
1793                 BKE_ptcache_mem_pointers_init(pm);
1794
1795                 for (i=0; i<totpoint; i++) {
1796                         if (pm->data_types & (1<<BPHYS_DATA_INDEX))
1797                                 index = pm->cur[BPHYS_DATA_INDEX];
1798
1799                         pid->read_point(*index, pid->calldata, pm->cur, (float)pm->frame, NULL);
1800                 
1801                         BKE_ptcache_mem_pointers_incr(pm);
1802                 }
1803
1804                 if (pid->read_extra_data && pm->extradata.first)
1805                         pid->read_extra_data(pid->calldata, pm, (float)pm->frame);
1806
1807                 /* clean up temporary memory cache */
1808                 if (pid->cache->flag & PTCACHE_DISK_CACHE) {
1809                         ptcache_data_free(pm);
1810                         ptcache_extra_free(pm);
1811                         MEM_freeN(pm);
1812                 }
1813         }
1814
1815         return 1;
1816 }
1817 static int ptcache_interpolate(PTCacheID *pid, float cfra, int cfra1, int cfra2)
1818 {
1819         PTCacheMem *pm = NULL;
1820         int i;
1821         int *index = &i;
1822
1823         /* get a memory cache to read from */
1824         if (pid->cache->flag & PTCACHE_DISK_CACHE) {
1825                 pm = ptcache_disk_frame_to_mem(pid, cfra2);
1826         }
1827         else {
1828                 pm = pid->cache->mem_cache.first;
1829                 
1830                 while (pm && pm->frame != cfra2)
1831                         pm = pm->next;
1832         }
1833
1834         /* read the cache */
1835         if (pm) {
1836                 int totpoint = pm->totpoint;
1837
1838                 if ((pid->data_types & (1<<BPHYS_DATA_INDEX)) == 0)
1839                         totpoint = MIN2(totpoint, pid->totpoint(pid->calldata, (int)cfra));
1840
1841                 BKE_ptcache_mem_pointers_init(pm);
1842
1843                 for (i=0; i<totpoint; i++) {
1844                         if (pm->data_types & (1<<BPHYS_DATA_INDEX))
1845                                 index = pm->cur[BPHYS_DATA_INDEX];
1846
1847                         pid->interpolate_point(*index, pid->calldata, pm->cur, cfra, (float)cfra1, (float)cfra2, NULL);
1848                         BKE_ptcache_mem_pointers_incr(pm);
1849                 }
1850
1851                 if (pid->interpolate_extra_data && pm->extradata.first)
1852                         pid->interpolate_extra_data(pid->calldata, pm, cfra, (float)cfra1, (float)cfra2);
1853
1854                 /* clean up temporary memory cache */
1855                 if (pid->cache->flag & PTCACHE_DISK_CACHE) {
1856                         ptcache_data_free(pm);
1857                         ptcache_extra_free(pm);
1858                         MEM_freeN(pm);
1859                 }
1860         }
1861
1862         return 1;
1863 }
1864 /* reads cache from disk or memory */
1865 /* possible to get old or interpolated result */
1866 int BKE_ptcache_read(PTCacheID *pid, float cfra)
1867 {
1868         int cfrai = (int)floor(cfra), cfra1=0, cfra2=0;
1869         int ret = 0;
1870
1871         /* nothing to read to */
1872         if (pid->totpoint(pid->calldata, cfrai) == 0)
1873                 return 0;
1874
1875         if (pid->cache->flag & PTCACHE_READ_INFO) {
1876                 pid->cache->flag &= ~PTCACHE_READ_INFO;
1877                 ptcache_read(pid, 0);
1878         }
1879
1880         /* first check if we have the actual frame cached */
1881         if (cfra == (float)cfrai && BKE_ptcache_id_exist(pid, cfrai))
1882                 cfra1 = cfrai;
1883
1884         /* no exact cache frame found so try to find cached frames around cfra */
1885         if (cfra1 == 0)
1886                 ptcache_find_frames_around(pid, cfrai, &cfra1, &cfra2);
1887
1888         if (cfra1 == 0 && cfra2 == 0)
1889                 return 0;
1890
1891         /* don't read old cache if already simulated past cached frame */
1892         if (cfra1 == 0 && cfra2 && cfra2 <= pid->cache->simframe)
1893                 return 0;
1894         if (cfra1 && cfra1 == cfra2)
1895                 return 0;
1896
1897         if (cfra1) {
1898                 
1899                 if (pid->read_stream) {
1900                         if (!ptcache_read_stream(pid, cfra1))
1901                                 return 0;
1902                 }
1903                 else if (pid->read_point)
1904                         ptcache_read(pid, cfra1);
1905         }
1906
1907         if (cfra2) {
1908                 
1909                 if (pid->read_stream) {
1910                         if (!ptcache_read_stream(pid, cfra2))
1911                                 return 0;
1912                 }
1913                 else if (pid->read_point) {
1914                         if (cfra1 && cfra2 && pid->interpolate_point)
1915                                 ptcache_interpolate(pid, cfra, cfra1, cfra2);
1916                         else
1917                                 ptcache_read(pid, cfra2);
1918                 }
1919         }
1920
1921         if (cfra1)
1922                 ret = (cfra2 ? PTCACHE_READ_INTERPOLATED : PTCACHE_READ_EXACT);
1923         else if (cfra2) {
1924                 ret = PTCACHE_READ_OLD;
1925                 pid->cache->simframe = cfra2;
1926         }
1927
1928         if ((pid->cache->flag & PTCACHE_QUICK_CACHE)==0) {
1929                 cfrai = (int)cfra;
1930                 /* clear invalid cache frames so that better stuff can be simulated */
1931                 if (pid->cache->flag & PTCACHE_OUTDATED) {
1932                         BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_AFTER, cfrai);
1933                 }
1934                 else if (pid->cache->flag & PTCACHE_FRAMES_SKIPPED) {
1935                         if (cfra <= pid->cache->last_exact)
1936                                 pid->cache->flag &= ~PTCACHE_FRAMES_SKIPPED;
1937
1938                         BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_AFTER, MAX2(cfrai, pid->cache->last_exact));
1939                 }
1940         }
1941
1942         return ret;
1943 }
1944 static int ptcache_write_stream(PTCacheID *pid, int cfra, int totpoint)
1945 {
1946         PTCacheFile *pf = NULL;
1947         int error = 0;
1948         
1949         BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_FRAME, cfra);
1950
1951         pf = ptcache_file_open(pid, PTCACHE_FILE_WRITE, cfra);
1952
1953         if (pf==NULL) {
1954                 if (G.debug & G_DEBUG)
1955                         printf("Error opening disk cache file for writing\n");
1956                 return 0;
1957         }
1958
1959         pf->data_types = pid->data_types;
1960         pf->totpoint = totpoint;
1961         pf->type = pid->type;
1962         pf->flag = 0;
1963
1964         if (!error && (!ptcache_file_header_begin_write(pf) || !pid->write_header(pf)))
1965                 error = 1;
1966
1967         if (!error && pid->write_stream)
1968                 pid->write_stream(pf, pid->calldata);
1969
1970         ptcache_file_close(pf);
1971
1972         if (error && G.debug & G_DEBUG)
1973                 printf("Error writing to disk cache\n");
1974
1975         return error == 0;
1976 }
1977 static int ptcache_write(PTCacheID *pid, int cfra, int overwrite)
1978 {
1979         PointCache *cache = pid->cache;
1980         PTCacheMem *pm=NULL, *pm2=NULL;
1981         int totpoint = pid->totpoint(pid->calldata, cfra);
1982         int i, error = 0;
1983
1984         pm = MEM_callocN(sizeof(PTCacheMem), "Pointcache mem");
1985
1986         pm->totpoint = pid->totwrite(pid->calldata, cfra);
1987         pm->data_types = cfra ? pid->data_types : pid->info_types;
1988
1989         ptcache_data_alloc(pm);
1990         BKE_ptcache_mem_pointers_init(pm);
1991
1992         if (overwrite) {
1993                 if (cache->flag & PTCACHE_DISK_CACHE) {
1994                         int fra = cfra-1;
1995
1996                         while (fra >= cache->startframe && !BKE_ptcache_id_exist(pid, fra))
1997                                 fra--;
1998                         
1999                         pm2 = ptcache_disk_frame_to_mem(pid, fra);
2000                 }
2001                 else
2002                         pm2 = cache->mem_cache.last;
2003         }
2004
2005         if (pid->write_point) {
2006                 for (i=0; i<totpoint; i++) {
2007                         int write = pid->write_point(i, pid->calldata, pm->cur, cfra);
2008                         if (write) {
2009                                 BKE_ptcache_mem_pointers_incr(pm);
2010
2011                                 /* newly born particles have to be copied to previous cached frame */
2012                                 if (overwrite && write == 2 && pm2 && BKE_ptcache_mem_pointers_seek(i, pm2))
2013                                         pid->write_point(i, pid->calldata, pm2->cur, cfra);
2014                         }
2015                 }
2016         }
2017
2018         if (pid->write_extra_data)
2019                 pid->write_extra_data(pid->calldata, pm, cfra);
2020
2021         pm->frame = cfra;
2022
2023         if (cache->flag & PTCACHE_DISK_CACHE) {
2024                 error += !ptcache_mem_frame_to_disk(pid, pm);
2025
2026                 // if (pm) /* pm is always set */
2027                 {
2028                         ptcache_data_free(pm);
2029                         ptcache_extra_free(pm);
2030                         MEM_freeN(pm);
2031                 }
2032
2033                 if (pm2) {
2034                         error += !ptcache_mem_frame_to_disk(pid, pm2);
2035                         ptcache_data_free(pm2);
2036                         ptcache_extra_free(pm2);
2037                         MEM_freeN(pm2);
2038                 }
2039         }
2040         else {
2041                 BLI_addtail(&cache->mem_cache, pm);
2042         }
2043
2044         return error;
2045 }
2046 static int ptcache_write_needed(PTCacheID *pid, int cfra, int *overwrite)
2047 {
2048         PointCache *cache = pid->cache;
2049         int ofra = 0, efra = cache->endframe;
2050
2051         /* allways start from scratch on the first frame */
2052         if (cfra && cfra == cache->startframe) {
2053                 BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, cfra);
2054                 cache->flag &= ~PTCACHE_REDO_NEEDED;
2055                 return 1;
2056         }
2057
2058         if (pid->cache->flag & PTCACHE_DISK_CACHE) {
2059                 if (cfra==0 && cache->startframe > 0)
2060                         return 1;
2061
2062                                 /* find last cached frame */
2063                 while (efra > cache->startframe && !BKE_ptcache_id_exist(pid, efra))
2064                         efra--;
2065
2066                 /* find second last cached frame */
2067                 ofra = efra-1;
2068                 while (ofra > cache->startframe && !BKE_ptcache_id_exist(pid, ofra))
2069                         ofra--;
2070         }
2071         else {
2072                 PTCacheMem *pm = cache->mem_cache.last;
2073                 /* don't write info file in memory */
2074                 if (cfra == 0)
2075                         return 0;
2076
2077                 if (pm == NULL)
2078                         return 1;
2079
2080                 efra = pm->frame;
2081                 ofra = (pm->prev ? pm->prev->frame : efra - cache->step);
2082         }
2083
2084         if (efra >= cache->startframe && cfra > efra) {
2085                 if (ofra >= cache->startframe && efra - ofra < cache->step) {
2086                         /* overwrite previous frame */
2087                         BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_FRAME, efra);
2088                         *overwrite = 1;
2089                 }
2090                 return 1;
2091         }
2092
2093         return 0;
2094 }
2095 /* writes cache to disk or memory */
2096 int BKE_ptcache_write(PTCacheID *pid, unsigned int cfra)
2097 {
2098         PointCache *cache = pid->cache;
2099         int totpoint = pid->totpoint(pid->calldata, cfra);
2100         int overwrite = 0, error = 0;
2101
2102         if (totpoint == 0 || (cfra ? pid->data_types == 0 : pid->info_types == 0))
2103                 return 0;
2104
2105         if (ptcache_write_needed(pid, cfra, &overwrite)==0)
2106                 return 0;
2107
2108         if (pid->write_stream) {
2109                 ptcache_write_stream(pid, cfra, totpoint);
2110         }
2111         else if (pid->write_point) {
2112                 error += ptcache_write(pid, cfra, overwrite);
2113         }
2114
2115         /* Mark frames skipped if more than 1 frame forwards since last non-skipped frame. */
2116         if (cfra - cache->last_exact == 1 || cfra == cache->startframe) {
2117                 cache->last_exact = cfra;
2118                 cache->flag &= ~PTCACHE_FRAMES_SKIPPED;
2119         }
2120         /* Don't mark skipped when writing info file (frame 0) */
2121         else if (cfra)
2122                 cache->flag |= PTCACHE_FRAMES_SKIPPED;
2123
2124         /* Update timeline cache display */
2125         if (cfra && cache->cached_frames)
2126                 cache->cached_frames[cfra-cache->startframe] = 1;
2127
2128         BKE_ptcache_update_info(pid);
2129
2130         return !error;
2131 }
2132 /* youll need to close yourself after!
2133  * mode - PTCACHE_CLEAR_ALL, 
2134  */
2135
2136 /* Clears & resets */
2137 void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra)
2138 {
2139         unsigned int len; /* store the length of the string */
2140         unsigned int sta, end;
2141
2142         /* mode is same as fopen's modes */
2143         DIR *dir; 
2144         struct dirent *de;
2145         char path[MAX_PTCACHE_PATH];
2146         char filename[MAX_PTCACHE_FILE];
2147         char path_full[MAX_PTCACHE_FILE];
2148         char ext[MAX_PTCACHE_PATH];
2149
2150         if (!pid || !pid->cache || pid->cache->flag & PTCACHE_BAKED)
2151                 return;
2152
2153         if (pid->cache->flag & PTCACHE_IGNORE_CLEAR)
2154                 return;
2155
2156         sta = pid->cache->startframe;
2157         end = pid->cache->endframe;
2158
2159 #ifndef DURIAN_POINTCACHE_LIB_OK
2160         /* don't allow clearing for linked objects */
2161         if (pid->ob->id.lib)
2162                 return;
2163 #endif
2164
2165         /*if (!G.relbase_valid) return; *//* save blend file before using pointcache */
2166         
2167         /* clear all files in the temp dir with the prefix of the ID and the ".bphys" suffix */
2168         switch (mode) {
2169         case PTCACHE_CLEAR_ALL:
2170         case PTCACHE_CLEAR_BEFORE:      
2171         case PTCACHE_CLEAR_AFTER:
2172                 if (pid->cache->flag & PTCACHE_DISK_CACHE) {
2173                         ptcache_path(pid, path);
2174                         
2175                         len = ptcache_filename(pid, filename, cfra, 0, 0); /* no path */
2176                         
2177                         dir = opendir(path);
2178                         if (dir==NULL)
2179                                 return;
2180
2181                         BLI_snprintf(ext, sizeof(ext), "_%02u"PTCACHE_EXT, pid->stack_index);
2182                         
2183                         while ((de = readdir(dir)) != NULL) {
2184                                 if (strstr(de->d_name, ext)) { /* do we have the right extension?*/
2185                                         if (strncmp(filename, de->d_name, len ) == 0) { /* do we have the right prefix */
2186                                                 if (mode == PTCACHE_CLEAR_ALL) {
2187                                                         pid->cache->last_exact = MIN2(pid->cache->startframe, 0);
2188                                                         BLI_join_dirfile(path_full, sizeof(path_full), path, de->d_name);
2189                                                         BLI_delete(path_full, 0, 0);
2190                                                 }
2191                                                 else {
2192                                                         /* read the number of the file */
2193                                                         unsigned int frame, len2 = (int)strlen(de->d_name);
2194                                                         char num[7];
2195
2196                                                         if (len2 > 15) { /* could crash if trying to copy a string out of this range*/
2197                                                                 BLI_strncpy(num, de->d_name + (strlen(de->d_name) - 15), sizeof(num));
2198                                                                 frame = atoi(num);
2199                                                                 
2200                                                                 if ((mode == PTCACHE_CLEAR_BEFORE && frame < cfra) ||
2201                                                                     (mode == PTCACHE_CLEAR_AFTER && frame > cfra))
2202                                                                 {
2203                                                                         
2204                                                                         BLI_join_dirfile(path_full, sizeof(path_full), path, de->d_name);
2205                                                                         BLI_delete(path_full, 0, 0);
2206                                                                         if (pid->cache->cached_frames && frame >=sta && frame <= end)
2207                                                                                 pid->cache->cached_frames[frame-sta] = 0;
2208                                                                 }
2209                                                         }
2210                                                 }
2211                                         }
2212                                 }
2213                         }
2214                         closedir(dir);
2215
2216                         if (mode == PTCACHE_CLEAR_ALL && pid->cache->cached_frames)
2217                                 memset(pid->cache->cached_frames, 0, MEM_allocN_len(pid->cache->cached_frames));
2218                 }
2219                 else {
2220                         PTCacheMem *pm= pid->cache->mem_cache.first;
2221                         PTCacheMem *link= NULL;
2222
2223                         if (mode == PTCACHE_CLEAR_ALL) {
2224                                 /*we want startframe if the cache starts before zero*/
2225                                 pid->cache->last_exact = MIN2(pid->cache->startframe, 0);
2226                                 for (; pm; pm=pm->next) {
2227                                         ptcache_data_free(pm);
2228                                         ptcache_extra_free(pm);
2229                                 }
2230                                 BLI_freelistN(&pid->cache->mem_cache);
2231
2232                                 if (pid->cache->cached_frames) 
2233                                         memset(pid->cache->cached_frames, 0, MEM_allocN_len(pid->cache->cached_frames));
2234                         }
2235                         else {
2236                                 while (pm) {
2237                                         if ((mode == PTCACHE_CLEAR_BEFORE && pm->frame < cfra) ||
2238                                             (mode == PTCACHE_CLEAR_AFTER && pm->frame > cfra))
2239                                         {
2240                                                 link = pm;
2241                                                 if (pid->cache->cached_frames && pm->frame >=sta && pm->frame <= end)
2242                                                         pid->cache->cached_frames[pm->frame-sta] = 0;
2243                                                 ptcache_data_free(pm);
2244                                                 ptcache_extra_free(pm);
2245                                                 pm = pm->next;
2246                                                 BLI_freelinkN(&pid->cache->mem_cache, link);
2247                                         }
2248                                         else
2249                                                 pm = pm->next;
2250                                 }
2251                         }
2252                 }
2253                 break;
2254                 
2255         case PTCACHE_CLEAR_FRAME:
2256                 if (pid->cache->flag & PTCACHE_DISK_CACHE) {
2257                         if (BKE_ptcache_id_exist(pid, cfra)) {
2258                                 ptcache_filename(pid, filename, cfra, 1, 1); /* no path */
2259                                 BLI_delete(filename, 0, 0);
2260                         }
2261                 }
2262                 else {
2263                         PTCacheMem *pm = pid->cache->mem_cache.first;
2264
2265                         for (; pm; pm=pm->next) {
2266                                 if (pm->frame == cfra) {
2267                                         ptcache_data_free(pm);
2268                                         ptcache_extra_free(pm);
2269                                         BLI_freelinkN(&pid->cache->mem_cache, pm);
2270                                         break;
2271                                 }
2272                         }
2273                 }
2274                 if (pid->cache->cached_frames && cfra>=sta && cfra<=end)
2275                         pid->cache->cached_frames[cfra-sta] = 0;
2276                 break;
2277         }
2278
2279         BKE_ptcache_update_info(pid);
2280 }
2281 int  BKE_ptcache_id_exist(PTCacheID *pid, int cfra)
2282 {
2283         if (!pid->cache)
2284                 return 0;
2285
2286         if (cfra<pid->cache->startframe || cfra > pid->cache->endframe)
2287                 return 0;
2288
2289         if (pid->cache->cached_frames &&        pid->cache->cached_frames[cfra-pid->cache->startframe]==0)
2290                 return 0;
2291         
2292         if (pid->cache->flag & PTCACHE_DISK_CACHE) {
2293                 char filename[MAX_PTCACHE_FILE];
2294                 
2295                 ptcache_filename(pid, filename, cfra, 1, 1);
2296
2297                 return BLI_exists(filename);
2298         }
2299         else {
2300                 PTCacheMem *pm = pid->cache->mem_cache.first;
2301
2302                 for (; pm; pm=pm->next) {
2303                         if (pm->frame==cfra)
2304                                 return 1;
2305                 }
2306                 return 0;
2307         }
2308 }
2309 void BKE_ptcache_id_time(PTCacheID *pid, Scene *scene, float cfra, int *startframe, int *endframe, float *timescale)
2310 {
2311         /* Object *ob; */ /* UNUSED */
2312         PointCache *cache;
2313         /* float offset; unused for now */
2314         float time, nexttime;
2315
2316         /* TODO: this has to be sorted out once bsystem_time gets redone, */
2317         /*       now caches can handle interpolating etc. too - jahka */
2318
2319         /* time handling for point cache:
2320          * - simulation time is scaled by result of bsystem_time
2321          * - for offsetting time only time offset is taken into account, since
2322          *   that's always the same and can't be animated. a timeoffset which
2323          *   varies over time is not simple to support.
2324          * - field and motion blur offsets are currently ignored, proper solution
2325          *   is probably to interpolate results from two frames for that ..
2326          */
2327
2328         /* ob= pid->ob; */ /* UNUSED */
2329         cache= pid->cache;
2330
2331         if (timescale) {
2332                 time= BKE_scene_frame_get(scene);
2333                 nexttime = BKE_scene_frame_get_from_ctime(scene, CFRA + 1.0f);
2334                 
2335                 *timescale= MAX2(nexttime - time, 0.0f);
2336         }
2337
2338         if (startframe && endframe) {
2339                 *startframe= cache->startframe;
2340                 *endframe= cache->endframe;
2341
2342                 /* TODO: time handling with object offsets and simulated vs. cached
2343                  * particles isn't particularly easy, so for now what you see is what
2344                  * you get. In the future point cache could handle the whole particle
2345                  * system timing. */
2346 #if 0
2347                 if ((ob->partype & PARSLOW)==0) {
2348                         offset= ob->sf;
2349
2350                         *startframe += (int)(offset+0.5f);
2351                         *endframe += (int)(offset+0.5f);
2352                 }
2353 #endif
2354         }
2355
2356         /* verify cached_frames array is up to date */
2357         if (cache->cached_frames) {
2358                 if (MEM_allocN_len(cache->cached_frames) != sizeof(char) * (cache->endframe-cache->startframe+1)) {
2359                         MEM_freeN(cache->cached_frames);
2360                         cache->cached_frames = NULL;
2361                 }       
2362         }
2363
2364         if (cache->cached_frames==NULL && cache->endframe > cache->startframe) {
2365                 unsigned int sta=cache->startframe;
2366                 unsigned int end=cache->endframe;
2367
2368                 cache->cached_frames = MEM_callocN(sizeof(char) * (cache->endframe-cache->startframe+1), "cached frames array");
2369
2370                 if (pid->cache->flag & PTCACHE_DISK_CACHE) {
2371                         /* mode is same as fopen's modes */
2372                         DIR *dir; 
2373                         struct dirent *de;
2374                         char path[MAX_PTCACHE_PATH];
2375                         char filename[MAX_PTCACHE_FILE];
2376                         char ext[MAX_PTCACHE_PATH];
2377                         unsigned int len; /* store the length of the string */
2378
2379                         ptcache_path(pid, path);
2380                         
2381                         len = ptcache_filename(pid, filename, (int)cfra, 0, 0); /* no path */
2382                         
2383                         dir = opendir(path);
2384                         if (dir==NULL)
2385                                 return;
2386
2387                         BLI_snprintf(ext, sizeof(ext), "_%02u"PTCACHE_EXT, pid->stack_index);
2388                         
2389                         while ((de = readdir(dir)) != NULL) {
2390                                 if (strstr(de->d_name, ext)) { /* do we have the right extension?*/
2391                                         if (strncmp(filename, de->d_name, len ) == 0) { /* do we have the right prefix */
2392                                                 /* read the number of the file */
2393                                                 unsigned int frame, len2 = (int)strlen(de->d_name);
2394                                                 char num[7];
2395
2396                                                 if (len2 > 15) { /* could crash if trying to copy a string out of this range*/
2397                                                         BLI_strncpy(num, de->d_name + (strlen(de->d_name) - 15), sizeof(num));
2398                                                         frame = atoi(num);
2399                                                         
2400                                                         if (frame >= sta && frame <= end)
2401                                                                 cache->cached_frames[frame-sta] = 1;
2402                                                 }
2403                                         }
2404                                 }
2405                         }
2406                         closedir(dir);
2407                 }
2408                 else {
2409                         PTCacheMem *pm= pid->cache->mem_cache.first;
2410
2411                         while (pm) {
2412                                 if (pm->frame >= sta && pm->frame <= end)
2413                                         cache->cached_frames[pm->frame-sta] = 1;
2414                                 pm = pm->next;
2415                         }
2416                 }
2417         }
2418 }
2419 int  BKE_ptcache_id_reset(Scene *scene, PTCacheID *pid, int mode)
2420 {
2421         PointCache *cache;
2422         int reset, clear, after;
2423
2424         if (!pid->cache)
2425                 return 0;
2426
2427         cache= pid->cache;
2428         reset= 0;
2429         clear= 0;
2430         after= 0;
2431
2432         if (mode == PTCACHE_RESET_DEPSGRAPH) {
2433                 if (!(cache->flag & PTCACHE_BAKED) && !BKE_ptcache_get_continue_physics()) {
2434                         if (cache->flag & PTCACHE_QUICK_CACHE)
2435                                 clear= 1;
2436
2437                         after= 1;
2438                 }
2439
2440                 cache->flag |= PTCACHE_OUTDATED;
2441         }
2442         else if (mode == PTCACHE_RESET_BAKED) {
2443                 if (!BKE_ptcache_get_continue_physics()) {
2444                         reset= 1;
2445                         clear= 1;
2446                 }
2447                 else
2448                         cache->flag |= PTCACHE_OUTDATED;
2449         }
2450         else if (mode == PTCACHE_RESET_OUTDATED) {
2451                 reset = 1;
2452
2453                 if (cache->flag & PTCACHE_OUTDATED && !(cache->flag & PTCACHE_BAKED)) {
2454                         clear= 1;
2455                         cache->flag &= ~PTCACHE_OUTDATED;
2456                 }
2457         }
2458
2459         if (reset) {
2460                 BKE_ptcache_invalidate(cache);
2461                 cache->flag &= ~PTCACHE_REDO_NEEDED;
2462
2463                 if (pid->type == PTCACHE_TYPE_CLOTH)
2464                         cloth_free_modifier(pid->calldata);
2465                 else if (pid->type == PTCACHE_TYPE_SOFTBODY)
2466                         sbFreeSimulation(pid->calldata);
2467                 else if (pid->type == PTCACHE_TYPE_PARTICLES)
2468                         psys_reset(pid->calldata, PSYS_RESET_DEPSGRAPH);
2469                 else if (pid->type == PTCACHE_TYPE_SMOKE_DOMAIN)
2470                         smokeModifier_reset(pid->calldata);
2471                 else if (pid->type == PTCACHE_TYPE_SMOKE_HIGHRES)
2472                         smokeModifier_reset_turbulence(pid->calldata);
2473                 else if (pid->type == PTCACHE_TYPE_DYNAMICPAINT)
2474                         dynamicPaint_clearSurface((DynamicPaintSurface*)pid->calldata);
2475         }
2476         if (clear)
2477                 BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0);
2478         else if (after)
2479                 BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_AFTER, CFRA);
2480
2481         return (reset || clear || after);
2482 }
2483 int  BKE_ptcache_object_reset(Scene *scene, Object *ob, int mode)
2484 {
2485         PTCacheID pid;
2486         ParticleSystem *psys;
2487         ModifierData *md;
2488         int reset, skip;
2489
2490         reset= 0;
2491         skip= 0;
2492
2493         if (ob->soft) {
2494                 BKE_ptcache_id_from_softbody(&pid, ob, ob->soft);
2495                 reset |= BKE_ptcache_id_reset(scene, &pid, mode);
2496         }
2497
2498         for (psys=ob->particlesystem.first; psys; psys=psys->next) {
2499                 /* children or just redo can be calculated without reseting anything */
2500                 if (psys->recalc & PSYS_RECALC_REDO || psys->recalc & PSYS_RECALC_CHILD)
2501                         skip = 1;
2502                 /* Baked cloth hair has to be checked too, because we don't want to reset */
2503                 /* particles or cloth in that case -jahka */
2504                 else if (psys->clmd) {
2505                         BKE_ptcache_id_from_cloth(&pid, ob, psys->clmd);
2506                         if (mode == PSYS_RESET_ALL || !(psys->part->type == PART_HAIR && (pid.cache->flag & PTCACHE_BAKED))) 
2507                                 reset |= BKE_ptcache_id_reset(scene, &pid, mode);
2508                         else
2509                                 skip = 1;
2510                 }
2511
2512                 if (skip == 0 && psys->part) {
2513                         BKE_ptcache_id_from_particles(&pid, ob, psys);
2514                         reset |= BKE_ptcache_id_reset(scene, &pid, mode);
2515                 }
2516         }
2517
2518         for (md=ob->modifiers.first; md; md=md->next) {
2519                 if (md->type == eModifierType_Cloth) {
2520                         BKE_ptcache_id_from_cloth(&pid, ob, (ClothModifierData*)md);
2521                         reset |= BKE_ptcache_id_reset(scene, &pid, mode);
2522                 }
2523                 if (md->type == eModifierType_Smoke) {
2524                         SmokeModifierData *smd = (SmokeModifierData *)md;
2525                         if (smd->type & MOD_SMOKE_TYPE_DOMAIN) {
2526                                 BKE_ptcache_id_from_smoke(&pid, ob, (SmokeModifierData*)md);
2527                                 reset |= BKE_ptcache_id_reset(scene, &pid, mode);
2528                         }
2529                 }
2530                 if (md->type == eModifierType_DynamicPaint) {
2531                         DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)md;
2532                         if (pmd->canvas) {
2533                                 DynamicPaintSurface *surface = pmd->canvas->surfaces.first;
2534
2535                                 for (; surface; surface=surface->next) {
2536                                         BKE_ptcache_id_from_dynamicpaint(&pid, ob, surface);
2537                                         reset |= BKE_ptcache_id_reset(scene, &pid, mode);
2538                                 }
2539                         }
2540                 }
2541         }
2542
2543         if (ob->type == OB_ARMATURE)
2544                 BIK_clear_cache(ob->pose);
2545
2546         return reset;
2547 }
2548
2549 /* Use this when quitting blender, with unsaved files */
2550 void BKE_ptcache_remove(void)
2551 {
2552         char path[MAX_PTCACHE_PATH];
2553         char path_full[MAX_PTCACHE_PATH];
2554         int rmdir = 1;
2555         
2556         ptcache_path(NULL, path);
2557
2558         if (BLI_exists(path)) {
2559                 /* The pointcache dir exists? - remove all pointcache */
2560
2561                 DIR *dir; 
2562                 struct dirent *de;
2563
2564                 dir = opendir(path);
2565                 if (dir==NULL)
2566                         return;
2567                 
2568                 while ((de = readdir(dir)) != NULL) {
2569                         if ( strcmp(de->d_name, ".")==0 || strcmp(de->d_name, "..")==0) {
2570                                 /* do nothing */
2571                         }
2572                         else if (strstr(de->d_name, PTCACHE_EXT)) { /* do we have the right extension?*/
2573                                 BLI_join_dirfile(path_full, sizeof(path_full), path, de->d_name);
2574                                 BLI_delete(path_full, 0, 0);
2575                         }
2576                         else {
2577                                 rmdir = 0; /* unknown file, don't remove the dir */
2578                         }
2579                 }
2580
2581                 closedir(dir);
2582         }
2583         else {
2584                 rmdir = 0; /* path dosnt exist  */
2585         }
2586         
2587         if (rmdir) {
2588                 BLI_delete(path, 1, 0);
2589         }
2590 }
2591
2592 /* Continuous Interaction */
2593
2594 static int CONTINUE_PHYSICS = 0;
2595
2596 void BKE_ptcache_set_continue_physics(Main *bmain, Scene *scene, int enable)
2597 {
2598         Object *ob;
2599
2600         if (CONTINUE_PHYSICS != enable) {
2601                 CONTINUE_PHYSICS = enable;
2602
2603                 if (CONTINUE_PHYSICS == 0) {
2604                         for (ob=bmain->object.first; ob; ob=ob->id.next)
2605                                 if (BKE_ptcache_object_reset(scene, ob, PTCACHE_RESET_OUTDATED))
2606                                         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2607                 }
2608         }
2609 }
2610
2611 int  BKE_ptcache_get_continue_physics(void)
2612 {
2613         return CONTINUE_PHYSICS;
2614 }
2615
2616 /* Point Cache handling */
2617
2618 PointCache *BKE_ptcache_add(ListBase *ptcaches)
2619 {
2620         PointCache *cache;
2621
2622         cache= MEM_callocN(sizeof(PointCache), "PointCache");
2623         cache->startframe= 1;
2624         cache->endframe= 250;
2625         cache->step= 10;
2626         cache->index = -1;
2627
2628         BLI_addtail(ptcaches, cache);
2629
2630         return cache;
2631 }
2632
2633 void BKE_ptcache_free_mem(ListBase *mem_cache)
2634 {
2635         PTCacheMem *pm = mem_cache->first;
2636
2637         if (pm) {
2638                 for (; pm; pm=pm->next) {
2639                         ptcache_data_free(pm);
2640                         ptcache_extra_free(pm);
2641                 }
2642
2643                 BLI_freelistN(mem_cache);
2644         }
2645 }
2646 void BKE_ptcache_free(PointCache *cache)
2647 {
2648         BKE_ptcache_free_mem(&cache->mem_cache);
2649         if (cache->edit && cache->free_edit)
2650                 cache->free_edit(cache->edit);
2651         if (cache->cached_frames)
2652                 MEM_freeN(cache->cached_frames);
2653         MEM_freeN(cache);
2654 }
2655 void BKE_ptcache_free_list(ListBase *ptcaches)
2656 {
2657         PointCache *cache = ptcaches->first;
2658
2659         while (cache) {
2660                 BLI_remlink(ptcaches, cache);
2661                 BKE_ptcache_free(cache);
2662                 cache = ptcaches->first;
2663         }
2664 }
2665
2666 static PointCache *ptcache_copy(PointCache *cache, int copy_data)
2667 {
2668         PointCache *ncache;
2669
2670         ncache= MEM_dupallocN(cache);
2671
2672         ncache->mem_cache.first = NULL;
2673         ncache->mem_cache.last = NULL;
2674
2675         if (copy_data == FALSE) {
2676                 ncache->mem_cache.first = NULL;
2677                 ncache->mem_cache.last = NULL;
2678                 ncache->cached_frames = NULL;
2679
2680                 ncache->flag= 0;
2681                 ncache->simframe= 0;
2682         }
2683         else {
2684                 PTCacheMem *pm;
2685
2686                 for (pm = cache->mem_cache.first; pm; pm = pm->next) {
2687                         PTCacheMem *pmn = MEM_dupallocN(pm);
2688                         int i;
2689
2690                         for (i = 0; i < BPHYS_TOT_DATA; i++) {
2691                                 if (pmn->data[i])
2692                                         pmn->data[i] = MEM_dupallocN(pm->data[i]);
2693                         }
2694
2695                         BKE_ptcache_mem_pointers_init(pm);
2696
2697                         BLI_addtail(&ncache->mem_cache, pmn);
2698                 }
2699
2700                 if (ncache->cached_frames)
2701                         ncache->cached_frames = MEM_dupallocN(cache->cached_frames);
2702         }
2703
2704         /* hmm, should these be copied over instead? */
2705         ncache->edit = NULL;
2706
2707         return ncache;
2708 }
2709
2710 /* returns first point cache */
2711 PointCache *BKE_ptcache_copy_list(ListBase *ptcaches_new, ListBase *ptcaches_old, int copy_data)
2712 {
2713         PointCache *cache = ptcaches_old->first;
2714
2715         ptcaches_new->first = ptcaches_new->last = NULL;
2716
2717         for (; cache; cache=cache->next)
2718                 BLI_addtail(ptcaches_new, ptcache_copy(cache, copy_data));
2719
2720         return ptcaches_new->first;
2721 }
2722
2723
2724 /* Baking */
2725 void BKE_ptcache_quick_cache_all(Main *bmain, Scene *scene)
2726 {
2727         PTCacheBaker baker;
2728
2729         baker.bake=0;
2730         baker.break_data=NULL;
2731         baker.break_test=NULL;
2732         baker.pid=NULL;
2733         baker.progressbar=NULL;
2734         baker.progressend=NULL;
2735         baker.progresscontext=NULL;
2736         baker.render=0;
2737         baker.anim_init = 0;
2738         baker.main=bmain;
2739         baker.scene=scene;
2740         baker.quick_step=scene->physics_settings.quick_cache_step;
2741
2742         BKE_ptcache_bake(&baker);
2743 }
2744
2745 /* Simulation thread, no need for interlocks as data written in both threads
2746  * are only unitary integers (I/O assumed to be atomic for them) */
2747 typedef struct {
2748         int break_operation;
2749         int thread_ended;
2750         int endframe;
2751         int step;
2752         int *cfra_ptr;
2753         Main *main;
2754         Scene *scene;
2755 } ptcache_bake_data;
2756
2757 static void ptcache_dt_to_str(char *str, double dtime)
2758 {
2759         if (dtime > 60.0) {
2760                 if (dtime > 3600.0)
2761                         sprintf(str, "%ih %im %is", (int)(dtime/3600), ((int)(dtime/60))%60, ((int)dtime) % 60);
2762                 else
2763                         sprintf(str, "%im %is", ((int)(dtime/60))%60, ((int)dtime) % 60);
2764         }
2765         else
2766                 sprintf(str, "%is", ((int)dtime) % 60);
2767 }
2768
2769 static void *ptcache_bake_thread(void *ptr)
2770 {
2771         int use_timer = FALSE, sfra, efra;
2772         double stime, ptime, ctime, fetd;
2773         char run[32], cur[32], etd[32];
2774
2775         ptcache_bake_data *data = (ptcache_bake_data*)ptr;
2776
2777         stime = ptime = PIL_check_seconds_timer();
2778         sfra = *data->cfra_ptr;
2779         efra = data->endframe;
2780
2781         for (; (*data->cfra_ptr <= data->endframe) && !data->break_operation; *data->cfra_ptr+=data->step) {
2782                 BKE_scene_update_for_newframe(data->main, data->scene, data->scene->lay);
2783                 if (G.background) {
2784                         printf("bake: frame %d :: %d\n", (int)*data->cfra_ptr, data->endframe);
2785                 }
2786                 else {
2787                         ctime = PIL_check_seconds_timer();
2788
2789                         fetd = (ctime-ptime)*(efra-*data->cfra_ptr)/data->step;
2790
2791                         if (use_timer || fetd > 60.0) {
2792                                 use_timer = TRUE;
2793
2794                                 ptcache_dt_to_str(cur, ctime-ptime);
2795                                 ptcache_dt_to_str(run, ctime-stime);
2796                                 ptcache_dt_to_str(etd, fetd);
2797
2798                                 printf("Baked for %s, current frame: %i/%i (%.3fs), ETC: %s\r", run, *data->cfra_ptr-sfra+1, efra-sfra+1, ctime-ptime, etd);
2799                         }
2800                         ptime = ctime;
2801                 }
2802         }
2803
2804         if (use_timer) {
2805                 ptcache_dt_to_str(run, PIL_check_seconds_timer()-stime);
2806                 printf("Bake %s %s (%i frames simulated).\n", (data->break_operation ? "canceled after" : "finished in"), run, *data->cfra_ptr-sfra);
2807         }
2808
2809         data->thread_ended = TRUE;
2810         return NULL;
2811 }
2812
2813 /* if bake is not given run simulations to current frame */
2814 void BKE_ptcache_bake(PTCacheBaker* baker)
2815 {
2816         Main *bmain = baker->main;
2817         Scene *scene = baker->scene;
2818         Scene *sce_iter; /* SETLOOPER macro only */
2819         Base *base;
2820         ListBase pidlist;
2821         PTCacheID *pid = baker->pid;
2822         PointCache *cache = NULL;
2823         float frameleno = scene->r.framelen;
2824         int cfrao = CFRA;
2825         int startframe = MAXFRAME;
2826         int bake = baker->bake;
2827         int render = baker->render;
2828         ListBase threads;
2829         ptcache_bake_data thread_data;
2830         int progress, old_progress;
2831         
2832         thread_data.endframe = baker->anim_init ? scene->r.sfra : CFRA;
2833         thread_data.step = baker->quick_step;
2834         thread_data.cfra_ptr = &CFRA;
2835         thread_data.scene = baker->scene;
2836         thread_data.main = baker->main;
2837
2838         G.is_break = FALSE;
2839
2840         /* set caches to baking mode and figure out start frame */
2841         if (pid) {
2842                 /* cache/bake a single object */
2843                 cache = pid->cache;
2844                 if ((cache->flag & PTCACHE_BAKED)==0) {
2845                         if (pid->type==PTCACHE_TYPE_PARTICLES) {
2846                                 ParticleSystem *psys= pid->calldata;
2847
2848                                 /* a bit confusing, could make this work better in the UI */
2849                                 if (psys->part->type == PART_EMITTER)
2850                                         psys_get_pointcache_start_end(scene, pid->calldata, &cache->startframe, &cache->endframe);
2851                         }
2852                         else if (pid->type == PTCACHE_TYPE_SMOKE_HIGHRES) {
2853                                 /* get all pids from the object and search for smoke low res */
2854                                 ListBase pidlist2;
2855                                 PTCacheID *pid2;
2856                                 BKE_ptcache_ids_from_object(&pidlist2, pid->ob, scene, MAX_DUPLI_RECUR);
2857                                 for (pid2=pidlist2.first; pid2; pid2=pid2->next) {
2858                                         if (pid2->type == PTCACHE_TYPE_SMOKE_DOMAIN) {
2859                                                 if (pid2->cache && !(pid2->cache->flag & PTCACHE_BAKED)) {
2860                                                         if (bake || pid2->cache->flag & PTCACHE_REDO_NEEDED)
2861                                                                 BKE_ptcache_id_clear(pid2, PTCACHE_CLEAR_ALL, 0);
2862                                                         if (bake) {
2863                                                                 pid2->cache->flag |= PTCACHE_BAKING;
2864                                                                 pid2->cache->flag &= ~PTCACHE_BAKED;
2865                                                         }
2866                                                 }
2867                                         }
2868                                 }
2869                                 BLI_freelistN(&pidlist2);
2870                         }
2871
2872                         if (bake || cache->flag & PTCACHE_REDO_NEEDED)
2873                                 BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0);
2874
2875                         startframe = MAX2(cache->last_exact, cache->startframe);
2876
2877                         if (bake) {
2878                                 thread_data.endframe = cache->endframe;
2879                                 cache->flag |= PTCACHE_BAKING;
2880                         }
2881                         else {
2882                                 thread_data.endframe = MIN2(thread_data.endframe, cache->endframe);
2883                         }
2884
2885                         cache->flag &= ~PTCACHE_BAKED;
2886                 }
2887         }
2888         else {
2889                 for (SETLOOPER(scene, sce_iter, base)) {
2890                         /* cache/bake everything in the scene */
2891                         BKE_ptcache_ids_from_object(&pidlist, base->object, scene, MAX_DUPLI_RECUR);
2892
2893                         for (pid=pidlist.first; pid; pid=pid->next) {
2894                                 cache = pid->cache;
2895                                 if ((cache->flag & PTCACHE_BAKED)==0) {
2896                                         if (pid->type==PTCACHE_TYPE_PARTICLES) {
2897                                                 ParticleSystem *psys = (ParticleSystem*)pid->calldata;
2898                                                 /* skip hair & keyed particles */
2899                                                 if (psys->part->type == PART_HAIR || psys->part->phystype == PART_PHYS_KEYED)
2900                                                         continue;
2901
2902                                                 psys_get_pointcache_start_end(scene, pid->calldata, &cache->startframe, &cache->endframe);
2903                                         }
2904
2905                                         if ((cache->flag & PTCACHE_REDO_NEEDED || (cache->flag & PTCACHE_SIMULATION_VALID)==0) &&
2906                                             ((cache->flag & PTCACHE_QUICK_CACHE)==0 || render || bake))
2907                                         {
2908                                                 BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0);
2909                                         }
2910
2911                                         startframe = MIN2(startframe, cache->startframe);
2912
2913                                         if (bake || render) {
2914                                                 cache->flag |= PTCACHE_BAKING;
2915
2916                                                 if (bake)
2917                                                         thread_data.endframe = MAX2(thread_data.endframe, cache->endframe);
2918                                         }
2919
2920                                         cache->flag &= ~PTCACHE_BAKED;
2921
2922                                 }
2923                         }
2924                         BLI_freelistN(&pidlist);
2925                 }
2926         }
2927
2928         CFRA = startframe;
2929         scene->r.framelen = 1.0;
2930         thread_data.break_operation = FALSE;
2931         thread_data.thread_ended = FALSE;
2932         old_progress = -1;
2933
2934         WM_cursor_wait(1);
2935         
2936         if (G.background) {
2937                 ptcache_bake_thread((void*)&thread_data);
2938         }
2939         else {
2940                 BLI_init_threads(&threads, ptcache_bake_thread, 1);
2941                 BLI_insert_thread(&threads, (void*)&thread_data);
2942
2943                 while (thread_data.thread_ended == FALSE) {
2944
2945                         if (bake)
2946                                 progress = (int)(100.0f * (float)(CFRA - startframe)/(float)(thread_data.endframe-startframe));
2947                         else
2948                                 progress = CFRA;
2949
2950                         /* NOTE: baking should not redraw whole ui as this slows things down */
2951                         if ((baker->progressbar) && (progress != old_progress)) {
2952                                 baker->progressbar(baker->progresscontext, progress);
2953                                 old_progress = progress;
2954                         }
2955
2956                         /* Delay to lessen CPU load from UI thread */
2957                         PIL_sleep_ms(200);
2958
2959                         /* NOTE: breaking baking should leave calculated frames in cache, not clear it */
2960                         if (blender_test_break() && !thread_data.break_operation) {
2961                                 thread_data.break_operation = TRUE;
2962                                 if (baker->progressend)
2963                                         baker->progressend(baker->progresscontext);
2964                                 WM_cursor_wait(1);
2965                         }
2966                 }
2967
2968         BLI_end_threads(&threads);
2969         }
2970         /* clear baking flag */
2971         if (pid) {
2972                 cache->flag &= ~(PTCACHE_BAKING|PTCACHE_REDO_NEEDED);
2973                 cache->flag |= PTCACHE_SIMULATION_VALID;
2974                 if (bake) {
2975                         cache->flag |= PTCACHE_BAKED;
2976                         /* write info file */
2977                         if (cache->flag & PTCACHE_DISK_CACHE)
2978                                 BKE_ptcache_write(pid, 0);
2979                 }
2980         }
2981         else {
2982                 for (SETLOOPER(scene, sce_iter, base)) {
2983                         BKE_ptcache_ids_from_object(&pidlist, base->object, scene, MAX_DUPLI_RECUR);
2984
2985                         for (pid=pidlist.first; pid; pid=pid->next) {
2986                                 /* skip hair particles */
2987                                 if (pid->type==PTCACHE_TYPE_PARTICLES && ((ParticleSystem*)pid->calldata)->part->type == PART_HAIR)
2988                                         continue;
2989
2990                                 cache = pid->cache;
2991
2992                                 if (thread_data.step > 1)
2993                                         cache->flag &= ~(PTCACHE_BAKING|PTCACHE_OUTDATED);
2994                                 else
2995                                         cache->flag &= ~(PTCACHE_BAKING|PTCACHE_REDO_NEEDED);
2996
2997                                 cache->flag |= PTCACHE_SIMULATION_VALID;
2998
2999                                 if (bake) {
3000                                         cache->flag |= PTCACHE_BAKED;
3001                                         if (cache->flag & PTCACHE_DISK_CACHE)
3002                                                 BKE_ptcache_write(pid, 0);
3003                                 }
3004                         }
3005                         BLI_freelistN(&pidlist);
3006                 }
3007         }
3008
3009         scene->r.framelen = frameleno;
3010         CFRA = cfrao;
3011         
3012         if (bake) /* already on cfra unless baking */
3013                 BKE_scene_update_for_newframe(bmain, scene, scene->lay);
3014
3015         if (thread_data.break_operation)
3016                 WM_cursor_wait(0);
3017         else if (baker->progressend)
3018                 baker->progressend(baker->progresscontext);
3019
3020         WM_cursor_wait(0);
3021
3022         /* TODO: call redraw all windows somehow */
3023 }
3024 /* Helpers */
3025 void BKE_ptcache_disk_to_mem(PTCacheID *pid)
3026 {
3027         PointCache *cache = pid->cache;
3028         PTCacheMem *pm = NULL;
3029         int baked = cache->flag & PTCACHE_BAKED;
3030         int cfra, sfra = cache->startframe, efra = cache->endframe;
3031
3032         /* Remove possible bake flag to allow clear */
3033         cache->flag &= ~PTCACHE_BAKED;
3034
3035         /* PTCACHE_DISK_CACHE flag was cleared already */
3036         BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0);
3037
3038         /* restore possible bake flag */
3039         cache->flag |= baked;
3040
3041         for (cfra=sfra; cfra <= efra; cfra++) {
3042                 pm = ptcache_disk_frame_to_mem(pid, cfra);
3043
3044                 if (pm)
3045                         BLI_addtail(&pid->cache->mem_cache, pm);
3046         }
3047 }
3048 void BKE_ptcache_mem_to_disk(PTCacheID *pid)
3049 {
3050         PointCache *cache = pid->cache;
3051         PTCacheMem *pm = cache->mem_cache.first;
3052         int baked = cache->flag & PTCACHE_BAKED;
3053
3054         /* Remove possible bake flag to allow clear */
3055         cache->flag &= ~PTCACHE_BAKED;
3056
3057         /* PTCACHE_DISK_CACHE flag was set already */
3058         BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0);
3059
3060         /* restore possible bake flag */
3061         cache->flag |= baked;
3062
3063         for (; pm; pm=pm->next) {
3064                 if (ptcache_mem_frame_to_disk(pid, pm)==0) {
3065                         cache->flag &= ~PTCACHE_DISK_CACHE;
3066                         break;
3067                 }
3068         }
3069
3070         /* write info file */
3071         if (cache->flag & PTCACHE_BAKED)
3072                 BKE_ptcache_write(pid, 0);
3073 }
3074 void BKE_ptcache_toggle_disk_cache(PTCacheID *pid)
3075 {
3076         PointCache *cache = pid->cache;
3077         int last_exact = cache->last_exact;
3078
3079         if (!G.relbase_valid) {
3080                 cache->flag &= ~PTCACHE_DISK_CACHE;
3081                 if (G.debug & G_DEBUG)
3082                         printf("File must be saved before using disk cache!\n");
3083                 return;
3084         }
3085
3086         if (cache->cached_frames) {
3087                 MEM_freeN(cache->cached_frames);
3088                 cache->cached_frames=NULL;
3089         }
3090
3091         if (cache->flag & PTCACHE_DISK_CACHE)
3092                 BKE_ptcache_mem_to_disk(pid);
3093         else
3094                 BKE_ptcache_disk_to_mem(pid);
3095
3096         cache->flag ^= PTCACHE_DISK_CACHE;
3097         BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0);
3098         cache->flag ^= PTCACHE_DISK_CACHE;
3099         
3100         cache->last_exact = last_exact;
3101
3102         BKE_ptcache_id_time(pid, NULL, 0.0f, NULL, NULL, NULL);
3103
3104         BKE_ptcache_update_info(pid);
3105 }
3106
3107 void BKE_ptcache_disk_cache_rename(PTCacheID *pid, const char *name_src, const char *name_dst)
3108 {
3109         char old_name[80];
3110         int len; /* store the length of the string */
3111         /* mode is same as fopen's modes */
3112         DIR *dir; 
3113         struct dirent *de;
3114         char path[MAX_PTCACHE_PATH];
3115         char old_filename[MAX_PTCACHE_FILE];
3116         char new_path_full[MAX_PTCACHE_FILE];
3117         char old_path_full[MAX_PTCACHE_FILE];
3118         char ext[MAX_PTCACHE_PATH];
3119
3120         /* save old name */
3121         BLI_strncpy(old_name, pid->cache->name, sizeof(old_name));
3122
3123         /* get "from" filename */
3124         BLI_strncpy(pid->cache->name, name_src, sizeof(pid->cache->name));
3125
3126         len = ptcache_filename(pid, old_filename, 0, 0, 0); /* no path */
3127
3128         ptcache_path(pid, path);
3129         dir = opendir(path);
3130         if (dir==NULL) {
3131                 BLI_strncpy(pid->cache->name, old_name, sizeof(pid->cache->name));
3132                 return;
3133         }
3134
3135         BLI_snprintf(ext, sizeof(ext), "_%02u"PTCACHE_EXT, pid->stack_index);
3136
3137         /* put new name into cache */
3138         BLI_strncpy(pid->cache->name, name_dst, sizeof(pid->cache->name));
3139
3140         while ((de = readdir(dir)) != NULL) {
3141                 if (strstr(de->d_name, ext)) { /* do we have the right extension?*/
3142                         if (strncmp(old_filename, de->d_name, len ) == 0) { /* do we have the right prefix */
3143                                 /* read the number of the file */
3144                                 int frame, len2 = (int)strlen(de->d_name);
3145                                 char num[7];
3146
3147                                 if (len2 > 15) { /* could crash if trying to copy a string out of this range*/
3148                                         BLI_strncpy(num, de->d_name + (strlen(de->d_name) - 15), sizeof(num));
3149                                         frame = atoi(num);
3150
3151                                         BLI_join_dirfile(old_path_full, sizeof(old_path_full), path, de->d_name);
3152                                         ptcache_filename(pid, new_path_full, frame, 1, 1);
3153                                         BLI_rename(old