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