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