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