Patch #34204: [Render Animation] Fails with "Error: Specified sample_fmt is not suppo...
[blender.git] / source / blender / blenkernel / intern / particle.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) 2007 by Janne Karhu.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/particle.c
29  *  \ingroup bke
30  */
31
32
33 #include <stdlib.h>
34 #include <math.h>
35 #include <string.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_curve_types.h"
40 #include "DNA_group_types.h"
41 #include "DNA_key_types.h"
42 #include "DNA_material_types.h"
43 #include "DNA_mesh_types.h"
44 #include "DNA_meshdata_types.h"
45 #include "DNA_particle_types.h"
46 #include "DNA_smoke_types.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_dynamicpaint_types.h"
49
50 #include "BLI_blenlib.h"
51 #include "BLI_noise.h"
52 #include "BLI_math.h"
53 #include "BLI_utildefines.h"
54 #include "BLI_kdtree.h"
55 #include "BLI_rand.h"
56 #include "BLI_threads.h"
57 #include "BLI_linklist.h"
58
59 #include "BKE_anim.h"
60 #include "BKE_animsys.h"
61
62 #include "BKE_boids.h"
63 #include "BKE_cloth.h"
64 #include "BKE_effect.h"
65 #include "BKE_global.h"
66 #include "BKE_group.h"
67 #include "BKE_main.h"
68 #include "BKE_lattice.h"
69
70 #include "BKE_displist.h"
71 #include "BKE_particle.h"
72 #include "BKE_object.h"
73 #include "BKE_material.h"
74 #include "BKE_key.h"
75 #include "BKE_library.h"
76 #include "BKE_depsgraph.h"
77 #include "BKE_modifier.h"
78 #include "BKE_mesh.h"
79 #include "BKE_cdderivedmesh.h"
80 #include "BKE_pointcache.h"
81 #include "BKE_scene.h"
82 #include "BKE_deform.h"
83
84 #include "RE_render_ext.h"
85
86 static void get_child_modifier_parameters(ParticleSettings *part, ParticleThreadContext *ctx,
87                                           ChildParticle *cpa, short cpa_from, int cpa_num, float *cpa_fuv, float *orco, ParticleTexture *ptex);
88 static void do_child_modifiers(ParticleSimulationData *sim,
89                                ParticleTexture *ptex, ParticleKey *par, float *par_rot, ChildParticle *cpa,
90                                float *orco, float mat[4][4], ParticleKey *state, float t);
91
92 /* few helpers for countall etc. */
93 int count_particles(ParticleSystem *psys)
94 {
95         ParticleSettings *part = psys->part;
96         PARTICLE_P;
97         int tot = 0;
98
99         LOOP_SHOWN_PARTICLES {
100                 if (pa->alive == PARS_UNBORN && (part->flag & PART_UNBORN) == 0) {}
101                 else if (pa->alive == PARS_DEAD && (part->flag & PART_DIED) == 0) {}
102                 else tot++;
103         }
104         return tot;
105 }
106 int count_particles_mod(ParticleSystem *psys, int totgr, int cur)
107 {
108         ParticleSettings *part = psys->part;
109         PARTICLE_P;
110         int tot = 0;
111
112         LOOP_SHOWN_PARTICLES {
113                 if (pa->alive == PARS_UNBORN && (part->flag & PART_UNBORN) == 0) {}
114                 else if (pa->alive == PARS_DEAD && (part->flag & PART_DIED) == 0) {}
115                 else if (p % totgr == cur) tot++;
116         }
117         return tot;
118 }
119 /* we allocate path cache memory in chunks instead of a big contiguous
120  * chunk, windows' memory allocater fails to find big blocks of memory often */
121
122 #define PATH_CACHE_BUF_SIZE 1024
123
124 static ParticleCacheKey **psys_alloc_path_cache_buffers(ListBase *bufs, int tot, int steps)
125 {
126         LinkData *buf;
127         ParticleCacheKey **cache;
128         int i, totkey, totbufkey;
129
130         tot = MAX2(tot, 1);
131         totkey = 0;
132         cache = MEM_callocN(tot * sizeof(void *), "PathCacheArray");
133
134         while (totkey < tot) {
135                 totbufkey = MIN2(tot - totkey, PATH_CACHE_BUF_SIZE);
136                 buf = MEM_callocN(sizeof(LinkData), "PathCacheLinkData");
137                 buf->data = MEM_callocN(sizeof(ParticleCacheKey) * totbufkey * steps, "ParticleCacheKey");
138
139                 for (i = 0; i < totbufkey; i++)
140                         cache[totkey + i] = ((ParticleCacheKey *)buf->data) + i * steps;
141
142                 totkey += totbufkey;
143                 BLI_addtail(bufs, buf);
144         }
145
146         return cache;
147 }
148
149 static void psys_free_path_cache_buffers(ParticleCacheKey **cache, ListBase *bufs)
150 {
151         LinkData *buf;
152
153         if (cache)
154                 MEM_freeN(cache);
155
156         for (buf = bufs->first; buf; buf = buf->next)
157                 MEM_freeN(buf->data);
158         BLI_freelistN(bufs);
159 }
160
161 /************************************************/
162 /*                      Getting stuff                                           */
163 /************************************************/
164 /* get object's active particle system safely */
165 ParticleSystem *psys_get_current(Object *ob)
166 {
167         ParticleSystem *psys;
168         if (ob == NULL) return NULL;
169
170         for (psys = ob->particlesystem.first; psys; psys = psys->next) {
171                 if (psys->flag & PSYS_CURRENT)
172                         return psys;
173         }
174         
175         return NULL;
176 }
177 short psys_get_current_num(Object *ob)
178 {
179         ParticleSystem *psys;
180         short i;
181
182         if (ob == NULL) return 0;
183
184         for (psys = ob->particlesystem.first, i = 0; psys; psys = psys->next, i++)
185                 if (psys->flag & PSYS_CURRENT)
186                         return i;
187         
188         return i;
189 }
190 void psys_set_current_num(Object *ob, int index)
191 {
192         ParticleSystem *psys;
193         short i;
194
195         if (ob == NULL) return;
196
197         for (psys = ob->particlesystem.first, i = 0; psys; psys = psys->next, i++) {
198                 if (i == index)
199                         psys->flag |= PSYS_CURRENT;
200                 else
201                         psys->flag &= ~PSYS_CURRENT;
202         }
203 }
204
205 #if 0 /* UNUSED */
206 Object *psys_find_object(Scene *scene, ParticleSystem *psys)
207 {
208         Base *base;
209         ParticleSystem *tpsys;
210
211         for (base = scene->base.first; base; base = base->next) {
212                 for (tpsys = base->object->particlesystem.first; psys; psys = psys->next) {
213                         if (tpsys == psys)
214                                 return base->object;
215                 }
216         }
217
218         return NULL;
219 }
220 #endif
221
222 Object *psys_get_lattice(ParticleSimulationData *sim)
223 {
224         Object *lattice = NULL;
225         
226         if (psys_in_edit_mode(sim->scene, sim->psys) == 0) {
227
228                 ModifierData *md = (ModifierData *)psys_get_modifier(sim->ob, sim->psys);
229
230                 for (; md; md = md->next) {
231                         if (md->type == eModifierType_Lattice) {
232                                 LatticeModifierData *lmd = (LatticeModifierData *)md;
233                                 lattice = lmd->object;
234                                 break;
235                         }
236                 }
237                 if (lattice)
238                         init_latt_deform(lattice, NULL);
239         }
240
241         return lattice;
242 }
243 void psys_disable_all(Object *ob)
244 {
245         ParticleSystem *psys = ob->particlesystem.first;
246
247         for (; psys; psys = psys->next)
248                 psys->flag |= PSYS_DISABLED;
249 }
250 void psys_enable_all(Object *ob)
251 {
252         ParticleSystem *psys = ob->particlesystem.first;
253
254         for (; psys; psys = psys->next)
255                 psys->flag &= ~PSYS_DISABLED;
256 }
257 int psys_in_edit_mode(Scene *scene, ParticleSystem *psys)
258 {
259         return (scene->basact && (scene->basact->object->mode & OB_MODE_PARTICLE_EDIT) && psys == psys_get_current((scene->basact)->object) && (psys->edit || psys->pointcache->edit) && !psys->renderdata);
260 }
261 static void psys_create_frand(ParticleSystem *psys)
262 {
263         int i;
264         float *rand = psys->frand = MEM_callocN(PSYS_FRAND_COUNT * sizeof(float), "particle randoms");
265
266         BLI_srandom(psys->seed);
267
268         for (i = 0; i < 1024; i++, rand++)
269                 *rand = BLI_frand();
270 }
271 int psys_check_enabled(Object *ob, ParticleSystem *psys)
272 {
273         ParticleSystemModifierData *psmd;
274
275         if (psys->flag & PSYS_DISABLED || psys->flag & PSYS_DELETE || !psys->part)
276                 return 0;
277
278         psmd = psys_get_modifier(ob, psys);
279         if (psys->renderdata || G.is_rendering) {
280                 if (!(psmd->modifier.mode & eModifierMode_Render))
281                         return 0;
282         }
283         else if (!(psmd->modifier.mode & eModifierMode_Realtime))
284                 return 0;
285
286         /* perhaps not the perfect place, but we have to be sure the rands are there before usage */
287         if (!psys->frand)
288                 psys_create_frand(psys);
289         else if (psys->recalc & PSYS_RECALC_RESET) {
290                 MEM_freeN(psys->frand);
291                 psys_create_frand(psys);
292         }
293         
294         return 1;
295 }
296
297 int psys_check_edited(ParticleSystem *psys)
298 {
299         if (psys->part && psys->part->type == PART_HAIR)
300                 return (psys->flag & PSYS_EDITED || (psys->edit && psys->edit->edited));
301         else
302                 return (psys->pointcache->edit && psys->pointcache->edit->edited);
303 }
304
305 void psys_check_group_weights(ParticleSettings *part)
306 {
307         ParticleDupliWeight *dw, *tdw;
308         GroupObject *go;
309         int current = 0;
310
311         if (part->ren_as == PART_DRAW_GR && part->dup_group && part->dup_group->gobject.first) {
312                 /* first remove all weights that don't have an object in the group */
313                 dw = part->dupliweights.first;
314                 while (dw) {
315                         if (!object_in_group(dw->ob, part->dup_group)) {
316                                 tdw = dw->next;
317                                 BLI_freelinkN(&part->dupliweights, dw);
318                                 dw = tdw;
319                         }
320                         else
321                                 dw = dw->next;
322                 }
323
324                 /* then add objects in the group to new list */
325                 go = part->dup_group->gobject.first;
326                 while (go) {
327                         dw = part->dupliweights.first;
328                         while (dw && dw->ob != go->ob)
329                                 dw = dw->next;
330                         
331                         if (!dw) {
332                                 dw = MEM_callocN(sizeof(ParticleDupliWeight), "ParticleDupliWeight");
333                                 dw->ob = go->ob;
334                                 dw->count = 1;
335                                 BLI_addtail(&part->dupliweights, dw);
336                         }
337
338                         go = go->next;
339                 }
340
341                 dw = part->dupliweights.first;
342                 for (; dw; dw = dw->next) {
343                         if (dw->flag & PART_DUPLIW_CURRENT) {
344                                 current = 1;
345                                 break;
346                         }
347                 }
348
349                 if (!current) {
350                         dw = part->dupliweights.first;
351                         if (dw)
352                                 dw->flag |= PART_DUPLIW_CURRENT;
353                 }
354         }
355         else {
356                 BLI_freelistN(&part->dupliweights);
357         }
358 }
359 int psys_uses_gravity(ParticleSimulationData *sim)
360 {
361         return sim->scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY && sim->psys->part && sim->psys->part->effector_weights->global_gravity != 0.0f;
362 }
363 /************************************************/
364 /*                      Freeing stuff                                           */
365 /************************************************/
366 static void fluid_free_settings(SPHFluidSettings *fluid)
367 {
368         if (fluid)
369                 MEM_freeN(fluid); 
370 }
371
372 void BKE_particlesettings_free(ParticleSettings *part)
373 {
374         MTex *mtex;
375         int a;
376         BKE_free_animdata(&part->id);
377         free_partdeflect(part->pd);
378         free_partdeflect(part->pd2);
379
380         if (part->effector_weights)
381                 MEM_freeN(part->effector_weights);
382
383         BLI_freelistN(&part->dupliweights);
384
385         boid_free_settings(part->boids);
386         fluid_free_settings(part->fluid);
387
388         for (a = 0; a < MAX_MTEX; a++) {
389                 mtex = part->mtex[a];
390                 if (mtex && mtex->tex) mtex->tex->id.us--;
391                 if (mtex) MEM_freeN(mtex);
392         }
393 }
394
395 void free_hair(Object *UNUSED(ob), ParticleSystem *psys, int dynamics)
396 {
397         PARTICLE_P;
398
399         LOOP_PARTICLES {
400                 if (pa->hair)
401                         MEM_freeN(pa->hair);
402                 pa->hair = NULL;
403                 pa->totkey = 0;
404         }
405
406         psys->flag &= ~PSYS_HAIR_DONE;
407
408         if (psys->clmd) {
409                 if (dynamics) {
410                         BKE_ptcache_free_list(&psys->ptcaches);
411                         psys->clmd->point_cache = psys->pointcache = NULL;
412                         psys->clmd->ptcaches.first = psys->clmd->ptcaches.last = NULL;
413
414                         modifier_free((ModifierData *)psys->clmd);
415                         
416                         psys->clmd = NULL;
417                         psys->pointcache = BKE_ptcache_add(&psys->ptcaches);
418                 }
419                 else {
420                         cloth_free_modifier(psys->clmd);
421                 }
422         }
423
424         if (psys->hair_in_dm)
425                 psys->hair_in_dm->release(psys->hair_in_dm);
426         psys->hair_in_dm = NULL;
427
428         if (psys->hair_out_dm)
429                 psys->hair_out_dm->release(psys->hair_out_dm);
430         psys->hair_out_dm = NULL;
431 }
432 void free_keyed_keys(ParticleSystem *psys)
433 {
434         PARTICLE_P;
435
436         if (psys->part->type == PART_HAIR)
437                 return;
438
439         if (psys->particles && psys->particles->keys) {
440                 MEM_freeN(psys->particles->keys);
441
442                 LOOP_PARTICLES {
443                         if (pa->keys) {
444                                 pa->keys = NULL;
445                                 pa->totkey = 0;
446                         }
447                 }
448         }
449 }
450 static void free_child_path_cache(ParticleSystem *psys)
451 {
452         psys_free_path_cache_buffers(psys->childcache, &psys->childcachebufs);
453         psys->childcache = NULL;
454         psys->totchildcache = 0;
455 }
456 void psys_free_path_cache(ParticleSystem *psys, PTCacheEdit *edit)
457 {
458         if (edit) {
459                 psys_free_path_cache_buffers(edit->pathcache, &edit->pathcachebufs);
460                 edit->pathcache = NULL;
461                 edit->totcached = 0;
462         }
463         if (psys) {
464                 psys_free_path_cache_buffers(psys->pathcache, &psys->pathcachebufs);
465                 psys->pathcache = NULL;
466                 psys->totcached = 0;
467
468                 free_child_path_cache(psys);
469         }
470 }
471 void psys_free_children(ParticleSystem *psys)
472 {
473         if (psys->child) {
474                 MEM_freeN(psys->child);
475                 psys->child = NULL;
476                 psys->totchild = 0;
477         }
478
479         free_child_path_cache(psys);
480 }
481 void psys_free_particles(ParticleSystem *psys)
482 {
483         PARTICLE_P;
484
485         if (psys->particles) {
486                 if (psys->part->type == PART_HAIR) {
487                         LOOP_PARTICLES {
488                                 if (pa->hair)
489                                         MEM_freeN(pa->hair);
490                         }
491                 }
492                 
493                 if (psys->particles->keys)
494                         MEM_freeN(psys->particles->keys);
495                 
496                 if (psys->particles->boid)
497                         MEM_freeN(psys->particles->boid);
498
499                 MEM_freeN(psys->particles);
500                 psys->particles = NULL;
501                 psys->totpart = 0;
502         }
503 }
504 void psys_free_pdd(ParticleSystem *psys)
505 {
506         if (psys->pdd) {
507                 if (psys->pdd->cdata)
508                         MEM_freeN(psys->pdd->cdata);
509                 psys->pdd->cdata = NULL;
510
511                 if (psys->pdd->vdata)
512                         MEM_freeN(psys->pdd->vdata);
513                 psys->pdd->vdata = NULL;
514
515                 if (psys->pdd->ndata)
516                         MEM_freeN(psys->pdd->ndata);
517                 psys->pdd->ndata = NULL;
518
519                 if (psys->pdd->vedata)
520                         MEM_freeN(psys->pdd->vedata);
521                 psys->pdd->vedata = NULL;
522
523                 psys->pdd->totpoint = 0;
524                 psys->pdd->tot_vec_size = 0;
525         }
526 }
527 /* free everything */
528 void psys_free(Object *ob, ParticleSystem *psys)
529 {       
530         if (psys) {
531                 int nr = 0;
532                 ParticleSystem *tpsys;
533                 
534                 psys_free_path_cache(psys, NULL);
535
536                 free_hair(ob, psys, 1);
537
538                 psys_free_particles(psys);
539
540                 if (psys->edit && psys->free_edit)
541                         psys->free_edit(psys->edit);
542
543                 if (psys->child) {
544                         MEM_freeN(psys->child);
545                         psys->child = NULL;
546                         psys->totchild = 0;
547                 }
548                 
549                 /* check if we are last non-visible particle system */
550                 for (tpsys = ob->particlesystem.first; tpsys; tpsys = tpsys->next) {
551                         if (tpsys->part) {
552                                 if (ELEM(tpsys->part->ren_as, PART_DRAW_OB, PART_DRAW_GR)) {
553                                         nr++;
554                                         break;
555                                 }
556                         }
557                 }
558                 /* clear do-not-draw-flag */
559                 if (!nr)
560                         ob->transflag &= ~OB_DUPLIPARTS;
561
562                 if (psys->part) {
563                         psys->part->id.us--;
564                         psys->part = NULL;
565                 }
566
567                 BKE_ptcache_free_list(&psys->ptcaches);
568                 psys->pointcache = NULL;
569                 
570                 BLI_freelistN(&psys->targets);
571
572                 BLI_bvhtree_free(psys->bvhtree);
573                 BLI_kdtree_free(psys->tree);
574  
575                 if (psys->fluid_springs)
576                         MEM_freeN(psys->fluid_springs);
577
578                 pdEndEffectors(&psys->effectors);
579
580                 if (psys->frand)
581                         MEM_freeN(psys->frand);
582
583                 if (psys->pdd) {
584                         psys_free_pdd(psys);
585                         MEM_freeN(psys->pdd);
586                 }
587
588                 MEM_freeN(psys);
589         }
590 }
591
592 /************************************************/
593 /*                      Rendering                                                       */
594 /************************************************/
595 /* these functions move away particle data and bring it back after
596  * rendering, to make different render settings possible without
597  * removing the previous data. this should be solved properly once */
598
599 typedef struct ParticleRenderElem {
600         int curchild, totchild, reduce;
601         float lambda, t, scalemin, scalemax;
602 } ParticleRenderElem;
603
604 typedef struct ParticleRenderData {
605         ChildParticle *child;
606         ParticleCacheKey **pathcache;
607         ParticleCacheKey **childcache;
608         ListBase pathcachebufs, childcachebufs;
609         int totchild, totcached, totchildcache;
610         DerivedMesh *dm;
611         int totdmvert, totdmedge, totdmface;
612
613         float mat[4][4];
614         float viewmat[4][4], winmat[4][4];
615         int winx, winy;
616
617         int do_simplify;
618         int timeoffset;
619         ParticleRenderElem *elems;
620
621         /* ORIGINDEX */
622         const int *index_mf_to_mpoly;
623         const int *index_mp_to_orig;
624 } ParticleRenderData;
625
626 static float psys_render_viewport_falloff(double rate, float dist, float width)
627 {
628         return pow(rate, dist / width);
629 }
630
631 static float psys_render_projected_area(ParticleSystem *psys, const float center[3], float area, double vprate, float *viewport)
632 {
633         ParticleRenderData *data = psys->renderdata;
634         float co[4], view[3], ortho1[3], ortho2[3], w, dx, dy, radius;
635         
636         /* transform to view space */
637         copy_v3_v3(co, center);
638         co[3] = 1.0f;
639         mul_m4_v4(data->viewmat, co);
640         
641         /* compute two vectors orthogonal to view vector */
642         normalize_v3_v3(view, co);
643         ortho_basis_v3v3_v3(ortho1, ortho2, view);
644
645         /* compute on screen minification */
646         w = co[2] * data->winmat[2][3] + data->winmat[3][3];
647         dx = data->winx * ortho2[0] * data->winmat[0][0];
648         dy = data->winy * ortho2[1] * data->winmat[1][1];
649         w = sqrtf(dx * dx + dy * dy) / w;
650
651         /* w squared because we are working with area */
652         area = area * w * w;
653
654         /* viewport of the screen test */
655
656         /* project point on screen */
657         mul_m4_v4(data->winmat, co);
658         if (co[3] != 0.0f) {
659                 co[0] = 0.5f * data->winx * (1.0f + co[0] / co[3]);
660                 co[1] = 0.5f * data->winy * (1.0f + co[1] / co[3]);
661         }
662
663         /* screen space radius */
664         radius = sqrt(area / (float)M_PI);
665
666         /* make smaller using fallof once over screen edge */
667         *viewport = 1.0f;
668
669         if (co[0] + radius < 0.0f)
670                 *viewport *= psys_render_viewport_falloff(vprate, -(co[0] + radius), data->winx);
671         else if (co[0] - radius > data->winx)
672                 *viewport *= psys_render_viewport_falloff(vprate, (co[0] - radius) - data->winx, data->winx);
673
674         if (co[1] + radius < 0.0f)
675                 *viewport *= psys_render_viewport_falloff(vprate, -(co[1] + radius), data->winy);
676         else if (co[1] - radius > data->winy)
677                 *viewport *= psys_render_viewport_falloff(vprate, (co[1] - radius) - data->winy, data->winy);
678         
679         return area;
680 }
681
682 void psys_render_set(Object *ob, ParticleSystem *psys, float viewmat[4][4], float winmat[4][4], int winx, int winy, int timeoffset)
683 {
684         ParticleRenderData *data;
685         ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys);
686
687         if (psys->renderdata)
688                 return;
689
690         data = MEM_callocN(sizeof(ParticleRenderData), "ParticleRenderData");
691
692         data->child = psys->child;
693         data->totchild = psys->totchild;
694         data->pathcache = psys->pathcache;
695         data->pathcachebufs.first = psys->pathcachebufs.first;
696         data->pathcachebufs.last = psys->pathcachebufs.last;
697         data->totcached = psys->totcached;
698         data->childcache = psys->childcache;
699         data->childcachebufs.first = psys->childcachebufs.first;
700         data->childcachebufs.last = psys->childcachebufs.last;
701         data->totchildcache = psys->totchildcache;
702
703         if (psmd->dm)
704                 data->dm = CDDM_copy(psmd->dm);
705         data->totdmvert = psmd->totdmvert;
706         data->totdmedge = psmd->totdmedge;
707         data->totdmface = psmd->totdmface;
708
709         psys->child = NULL;
710         psys->pathcache = NULL;
711         psys->childcache = NULL;
712         psys->totchild = psys->totcached = psys->totchildcache = 0;
713         psys->pathcachebufs.first = psys->pathcachebufs.last = NULL;
714         psys->childcachebufs.first = psys->childcachebufs.last = NULL;
715
716         copy_m4_m4(data->winmat, winmat);
717         mult_m4_m4m4(data->viewmat, viewmat, ob->obmat);
718         mult_m4_m4m4(data->mat, winmat, data->viewmat);
719         data->winx = winx;
720         data->winy = winy;
721
722         data->timeoffset = timeoffset;
723
724         psys->renderdata = data;
725
726         /* Hair can and has to be recalculated if everything isn't displayed. */
727         if (psys->part->disp != 100 && psys->part->type == PART_HAIR)
728                 psys->recalc |= PSYS_RECALC_RESET;
729 }
730
731 void psys_render_restore(Object *ob, ParticleSystem *psys)
732 {
733         ParticleRenderData *data;
734         ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys);
735
736         data = psys->renderdata;
737         if (!data)
738                 return;
739         
740         if (data->elems)
741                 MEM_freeN(data->elems);
742
743         if (psmd->dm) {
744                 psmd->dm->needsFree = 1;
745                 psmd->dm->release(psmd->dm);
746         }
747
748         psys_free_path_cache(psys, NULL);
749
750         if (psys->child) {
751                 MEM_freeN(psys->child);
752                 psys->child = 0;
753                 psys->totchild = 0;
754         }
755
756         psys->child = data->child;
757         psys->totchild = data->totchild;
758         psys->pathcache = data->pathcache;
759         psys->pathcachebufs.first = data->pathcachebufs.first;
760         psys->pathcachebufs.last = data->pathcachebufs.last;
761         psys->totcached = data->totcached;
762         psys->childcache = data->childcache;
763         psys->childcachebufs.first = data->childcachebufs.first;
764         psys->childcachebufs.last = data->childcachebufs.last;
765         psys->totchildcache = data->totchildcache;
766
767         psmd->dm = data->dm;
768         psmd->totdmvert = data->totdmvert;
769         psmd->totdmedge = data->totdmedge;
770         psmd->totdmface = data->totdmface;
771         psmd->flag &= ~eParticleSystemFlag_psys_updated;
772
773         if (psmd->dm)
774                 psys_calc_dmcache(ob, psmd->dm, psys);
775
776         MEM_freeN(data);
777         psys->renderdata = NULL;
778 }
779
780 /* BMESH_TODO, for orig face data, we need to use MPoly */
781
782 int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot)
783 {
784         DerivedMesh *dm = ctx->dm;
785         Mesh *me = (Mesh *)(ctx->sim.ob->data);
786         MFace *mf, *mface;
787         MVert *mvert;
788         ParticleRenderData *data;
789         ParticleRenderElem *elems, *elem;
790         ParticleSettings *part = ctx->sim.psys->part;
791         float *facearea, (*facecenter)[3], size[3], fac, powrate, scaleclamp;
792         float co1[3], co2[3], co3[3], co4[3], lambda, arearatio, t, area, viewport;
793         double vprate;
794         int *facetotvert;
795         int a, b, totorigface, totface, newtot, skipped;
796
797         /* double lookup */
798         const int *index_mf_to_mpoly;
799         const int *index_mp_to_orig;
800
801         if (part->ren_as != PART_DRAW_PATH || !(part->draw & PART_DRAW_REN_STRAND))
802                 return tot;
803         if (!ctx->sim.psys->renderdata)
804                 return tot;
805
806         data = ctx->sim.psys->renderdata;
807         if (data->timeoffset)
808                 return 0;
809         if (!(part->simplify_flag & PART_SIMPLIFY_ENABLE))
810                 return tot;
811
812         mvert = dm->getVertArray(dm);
813         mface = dm->getTessFaceArray(dm);
814         totface = dm->getNumTessFaces(dm);
815         totorigface = me->totpoly;
816
817         if (totface == 0 || totorigface == 0)
818                 return tot;
819
820         index_mf_to_mpoly = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
821         index_mp_to_orig  = dm->getPolyDataArray(dm, CD_ORIGINDEX);
822         if (index_mf_to_mpoly == NULL) {
823                 index_mp_to_orig = NULL;
824         }
825
826         facearea = MEM_callocN(sizeof(float) * totorigface, "SimplifyFaceArea");
827         facecenter = MEM_callocN(sizeof(float[3]) * totorigface, "SimplifyFaceCenter");
828         facetotvert = MEM_callocN(sizeof(int) * totorigface, "SimplifyFaceArea");
829         elems = MEM_callocN(sizeof(ParticleRenderElem) * totorigface, "SimplifyFaceElem");
830
831         if (data->elems)
832                 MEM_freeN(data->elems);
833
834         data->do_simplify = TRUE;
835         data->elems = elems;
836         data->index_mf_to_mpoly = index_mf_to_mpoly;
837         data->index_mp_to_orig  = index_mp_to_orig;
838
839         /* compute number of children per original face */
840         for (a = 0; a < tot; a++) {
841                 b = (index_mf_to_mpoly) ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, ctx->index[a]) : ctx->index[a];
842                 if (b != ORIGINDEX_NONE) {
843                         elems[b].totchild++;
844                 }
845         }
846
847         /* compute areas and centers of original faces */
848         for (mf = mface, a = 0; a < totface; a++, mf++) {
849                 b = (index_mf_to_mpoly) ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, a) : a;
850
851                 if (b != ORIGINDEX_NONE) {
852                         copy_v3_v3(co1, mvert[mf->v1].co);
853                         copy_v3_v3(co2, mvert[mf->v2].co);
854                         copy_v3_v3(co3, mvert[mf->v3].co);
855
856                         add_v3_v3(facecenter[b], co1);
857                         add_v3_v3(facecenter[b], co2);
858                         add_v3_v3(facecenter[b], co3);
859
860                         if (mf->v4) {
861                                 copy_v3_v3(co4, mvert[mf->v4].co);
862                                 add_v3_v3(facecenter[b], co4);
863                                 facearea[b] += area_quad_v3(co1, co2, co3, co4);
864                                 facetotvert[b] += 4;
865                         }
866                         else {
867                                 facearea[b] += area_tri_v3(co1, co2, co3);
868                                 facetotvert[b] += 3;
869                         }
870                 }
871         }
872
873         for (a = 0; a < totorigface; a++)
874                 if (facetotvert[a] > 0)
875                         mul_v3_fl(facecenter[a], 1.0f / facetotvert[a]);
876
877         /* for conversion from BU area / pixel area to reference screen size */
878         BKE_mesh_texspace_get(me, 0, 0, size);
879         fac = ((size[0] + size[1] + size[2]) / 3.0f) / part->simplify_refsize;
880         fac = fac * fac;
881
882         powrate = log(0.5f) / log(part->simplify_rate * 0.5f);
883         if (part->simplify_flag & PART_SIMPLIFY_VIEWPORT)
884                 vprate = pow(1.0f - part->simplify_viewport, 5.0);
885         else
886                 vprate = 1.0;
887
888         /* set simplification parameters per original face */
889         for (a = 0, elem = elems; a < totorigface; a++, elem++) {
890                 area = psys_render_projected_area(ctx->sim.psys, facecenter[a], facearea[a], vprate, &viewport);
891                 arearatio = fac * area / facearea[a];
892
893                 if ((arearatio < 1.0f || viewport < 1.0f) && elem->totchild) {
894                         /* lambda is percentage of elements to keep */
895                         lambda = (arearatio < 1.0f) ? powf(arearatio, powrate) : 1.0f;
896                         lambda *= viewport;
897
898                         lambda = MAX2(lambda, 1.0f / elem->totchild);
899
900                         /* compute transition region */
901                         t = part->simplify_transition;
902                         elem->t = (lambda - t < 0.0f) ? lambda : (lambda + t > 1.0f) ? 1.0f - lambda : t;
903                         elem->reduce = 1;
904
905                         /* scale at end and beginning of the transition region */
906                         elem->scalemax = (lambda + t < 1.0f) ? 1.0f / lambda : 1.0f / (1.0f - elem->t * elem->t / t);
907                         elem->scalemin = (lambda + t < 1.0f) ? 0.0f : elem->scalemax * (1.0f - elem->t / t);
908
909                         elem->scalemin = sqrt(elem->scalemin);
910                         elem->scalemax = sqrt(elem->scalemax);
911
912                         /* clamp scaling */
913                         scaleclamp = (float)min_ii(elem->totchild, 10);
914                         elem->scalemin = MIN2(scaleclamp, elem->scalemin);
915                         elem->scalemax = MIN2(scaleclamp, elem->scalemax);
916
917                         /* extend lambda to include transition */
918                         lambda = lambda + elem->t;
919                         if (lambda > 1.0f)
920                                 lambda = 1.0f;
921                 }
922                 else {
923                         lambda = arearatio;
924
925                         elem->scalemax = 1.0f; //sqrt(lambda);
926                         elem->scalemin = 1.0f; //sqrt(lambda);
927                         elem->reduce = 0;
928                 }
929
930                 elem->lambda = lambda;
931                 elem->scalemin = sqrt(elem->scalemin);
932                 elem->scalemax = sqrt(elem->scalemax);
933                 elem->curchild = 0;
934         }
935
936         MEM_freeN(facearea);
937         MEM_freeN(facecenter);
938         MEM_freeN(facetotvert);
939
940         /* move indices and set random number skipping */
941         ctx->skip = MEM_callocN(sizeof(int) * tot, "SimplificationSkip");
942
943         skipped = 0;
944         for (a = 0, newtot = 0; a < tot; a++) {
945                 b = (index_mf_to_mpoly) ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, ctx->index[a]) : ctx->index[a];
946
947                 if (b != ORIGINDEX_NONE) {
948                         if (elems[b].curchild++ < ceil(elems[b].lambda * elems[b].totchild)) {
949                                 ctx->index[newtot] = ctx->index[a];
950                                 ctx->skip[newtot] = skipped;
951                                 skipped = 0;
952                                 newtot++;
953                         }
954                         else skipped++;
955                 }
956                 else skipped++;
957         }
958
959         for (a = 0, elem = elems; a < totorigface; a++, elem++)
960                 elem->curchild = 0;
961
962         return newtot;
963 }
964
965 int psys_render_simplify_params(ParticleSystem *psys, ChildParticle *cpa, float *params)
966 {
967         ParticleRenderData *data;
968         ParticleRenderElem *elem;
969         float x, w, scale, alpha, lambda, t, scalemin, scalemax;
970         int b;
971
972         if (!(psys->renderdata && (psys->part->simplify_flag & PART_SIMPLIFY_ENABLE)))
973                 return 0;
974         
975         data = psys->renderdata;
976         if (!data->do_simplify)
977                 return 0;
978         b = (data->index_mf_to_mpoly) ? DM_origindex_mface_mpoly(data->index_mf_to_mpoly, data->index_mp_to_orig, cpa->num) : cpa->num;
979         if (b == ORIGINDEX_NONE) {
980                 return 0;
981         }
982
983         elem = &data->elems[b];
984
985         lambda = elem->lambda;
986         t = elem->t;
987         scalemin = elem->scalemin;
988         scalemax = elem->scalemax;
989
990         if (!elem->reduce) {
991                 scale = scalemin;
992                 alpha = 1.0f;
993         }
994         else {
995                 x = (elem->curchild + 0.5f) / elem->totchild;
996                 if (x < lambda - t) {
997                         scale = scalemax;
998                         alpha = 1.0f;
999                 }
1000                 else if (x >= lambda + t) {
1001                         scale = scalemin;
1002                         alpha = 0.0f;
1003                 }
1004                 else {
1005                         w = (lambda + t - x) / (2.0f * t);
1006                         scale = scalemin + (scalemax - scalemin) * w;
1007                         alpha = w;
1008                 }
1009         }
1010
1011         params[0] = scale;
1012         params[1] = alpha;
1013
1014         elem->curchild++;
1015
1016         return 1;
1017 }
1018
1019 /************************************************/
1020 /*                      Interpolation                                           */
1021 /************************************************/
1022 static float interpolate_particle_value(float v1, float v2, float v3, float v4, const float w[4], int four)
1023 {
1024         float value;
1025
1026         value = w[0] * v1 + w[1] * v2 + w[2] * v3;
1027         if (four)
1028                 value += w[3] * v4;
1029
1030         CLAMP(value, 0.f, 1.f);
1031         
1032         return value;
1033 }
1034
1035 void psys_interpolate_particle(short type, ParticleKey keys[4], float dt, ParticleKey *result, int velocity)
1036 {
1037         float t[4];
1038
1039         if (type < 0) {
1040                 interp_cubic_v3(result->co, result->vel, keys[1].co, keys[1].vel, keys[2].co, keys[2].vel, dt);
1041         }
1042         else {
1043                 key_curve_position_weights(dt, t, type);
1044
1045                 interp_v3_v3v3v3v3(result->co, keys[0].co, keys[1].co, keys[2].co, keys[3].co, t);
1046
1047                 if (velocity) {
1048                         float temp[3];
1049
1050                         if (dt > 0.999f) {
1051                                 key_curve_position_weights(dt - 0.001f, t, type);
1052                                 interp_v3_v3v3v3v3(temp, keys[0].co, keys[1].co, keys[2].co, keys[3].co, t);
1053                                 sub_v3_v3v3(result->vel, result->co, temp);
1054                         }
1055                         else {
1056                                 key_curve_position_weights(dt + 0.001f, t, type);
1057                                 interp_v3_v3v3v3v3(temp, keys[0].co, keys[1].co, keys[2].co, keys[3].co, t);
1058                                 sub_v3_v3v3(result->vel, temp, result->co);
1059                         }
1060                 }
1061         }
1062 }
1063
1064
1065
1066 typedef struct ParticleInterpolationData {
1067         HairKey *hkey[2];
1068
1069         DerivedMesh *dm;
1070         MVert *mvert[2];
1071
1072         int keyed;
1073         ParticleKey *kkey[2];
1074
1075         PointCache *cache;
1076         PTCacheMem *pm;
1077
1078         PTCacheEditPoint *epoint;
1079         PTCacheEditKey *ekey[2];
1080
1081         float birthtime, dietime;
1082         int bspline;
1083 } ParticleInterpolationData;
1084 /* Assumes pointcache->mem_cache exists, so for disk cached particles call psys_make_temp_pointcache() before use */
1085 /* It uses ParticleInterpolationData->pm to store the current memory cache frame so it's thread safe. */
1086 static void get_pointcache_keys_for_time(Object *UNUSED(ob), PointCache *cache, PTCacheMem **cur, int index, float t, ParticleKey *key1, ParticleKey *key2)
1087 {
1088         static PTCacheMem *pm = NULL;
1089         int index1, index2;
1090
1091         if (index < 0) { /* initialize */
1092                 *cur = cache->mem_cache.first;
1093
1094                 if (*cur)
1095                         *cur = (*cur)->next;
1096         }
1097         else {
1098                 if (*cur) {
1099                         while (*cur && (*cur)->next && (float)(*cur)->frame < t)
1100                                 *cur = (*cur)->next;
1101
1102                         pm = *cur;
1103
1104                         index2 = BKE_ptcache_mem_index_find(pm, index);
1105                         index1 = BKE_ptcache_mem_index_find(pm->prev, index);
1106
1107                         BKE_ptcache_make_particle_key(key2, index2, pm->data, (float)pm->frame);
1108                         if (index1 < 0)
1109                                 copy_particle_key(key1, key2, 1);
1110                         else
1111                                 BKE_ptcache_make_particle_key(key1, index1, pm->prev->data, (float)pm->prev->frame);
1112                 }
1113                 else if (cache->mem_cache.first) {
1114                         pm = cache->mem_cache.first;
1115                         index2 = BKE_ptcache_mem_index_find(pm, index);
1116                         BKE_ptcache_make_particle_key(key2, index2, pm->data, (float)pm->frame);
1117                         copy_particle_key(key1, key2, 1);
1118                 }
1119         }
1120 }
1121 static int get_pointcache_times_for_particle(PointCache *cache, int index, float *start, float *end)
1122 {
1123         PTCacheMem *pm;
1124         int ret = 0;
1125
1126         for (pm = cache->mem_cache.first; pm; pm = pm->next) {
1127                 if (BKE_ptcache_mem_index_find(pm, index) >= 0) {
1128                         *start = pm->frame;
1129                         ret++;
1130                         break;
1131                 }
1132         }
1133
1134         for (pm = cache->mem_cache.last; pm; pm = pm->prev) {
1135                 if (BKE_ptcache_mem_index_find(pm, index) >= 0) {
1136                         *end = pm->frame;
1137                         ret++;
1138                         break;
1139                 }
1140         }
1141
1142         return ret == 2;
1143 }
1144
1145 float psys_get_dietime_from_cache(PointCache *cache, int index)
1146 {
1147         PTCacheMem *pm;
1148         int dietime = 10000000; /* some max value so that we can default to pa->time+lifetime */
1149
1150         for (pm = cache->mem_cache.last; pm; pm = pm->prev) {
1151                 if (BKE_ptcache_mem_index_find(pm, index) >= 0)
1152                         return (float)pm->frame;
1153         }
1154
1155         return (float)dietime;
1156 }
1157
1158 static void init_particle_interpolation(Object *ob, ParticleSystem *psys, ParticleData *pa, ParticleInterpolationData *pind)
1159 {
1160
1161         if (pind->epoint) {
1162                 PTCacheEditPoint *point = pind->epoint;
1163
1164                 pind->ekey[0] = point->keys;
1165                 pind->ekey[1] = point->totkey > 1 ? point->keys + 1 : NULL;
1166
1167                 pind->birthtime = *(point->keys->time);
1168                 pind->dietime = *((point->keys + point->totkey - 1)->time);
1169         }
1170         else if (pind->keyed) {
1171                 ParticleKey *key = pa->keys;
1172                 pind->kkey[0] = key;
1173                 pind->kkey[1] = pa->totkey > 1 ? key + 1 : NULL;
1174
1175                 pind->birthtime = key->time;
1176                 pind->dietime = (key + pa->totkey - 1)->time;
1177         }
1178         else if (pind->cache) {
1179                 float start = 0.0f, end = 0.0f;
1180                 get_pointcache_keys_for_time(ob, pind->cache, &pind->pm, -1, 0.0f, NULL, NULL);
1181                 pind->birthtime = pa ? pa->time : pind->cache->startframe;
1182                 pind->dietime = pa ? pa->dietime : pind->cache->endframe;
1183
1184                 if (get_pointcache_times_for_particle(pind->cache, pa - psys->particles, &start, &end)) {
1185                         pind->birthtime = MAX2(pind->birthtime, start);
1186                         pind->dietime = MIN2(pind->dietime, end);
1187                 }
1188         }
1189         else {
1190                 HairKey *key = pa->hair;
1191                 pind->hkey[0] = key;
1192                 pind->hkey[1] = key + 1;
1193
1194                 pind->birthtime = key->time;
1195                 pind->dietime = (key + pa->totkey - 1)->time;
1196
1197                 if (pind->dm) {
1198                         pind->mvert[0] = CDDM_get_vert(pind->dm, pa->hair_index);
1199                         pind->mvert[1] = pind->mvert[0] + 1;
1200                 }
1201         }
1202 }
1203 static void edit_to_particle(ParticleKey *key, PTCacheEditKey *ekey)
1204 {
1205         copy_v3_v3(key->co, ekey->co);
1206         if (ekey->vel) {
1207                 copy_v3_v3(key->vel, ekey->vel);
1208         }
1209         key->time = *(ekey->time);
1210 }
1211 static void hair_to_particle(ParticleKey *key, HairKey *hkey)
1212 {
1213         copy_v3_v3(key->co, hkey->co);
1214         key->time = hkey->time;
1215 }
1216
1217 static void mvert_to_particle(ParticleKey *key, MVert *mvert, HairKey *hkey)
1218 {
1219         copy_v3_v3(key->co, mvert->co);
1220         key->time = hkey->time;
1221 }
1222
1223 static void do_particle_interpolation(ParticleSystem *psys, int p, ParticleData *pa, float t, ParticleInterpolationData *pind, ParticleKey *result)
1224 {
1225         PTCacheEditPoint *point = pind->epoint;
1226         ParticleKey keys[4];
1227         int point_vel = (point && point->keys->vel);
1228         float real_t, dfra, keytime, invdt = 1.f;
1229
1230         /* billboards wont fill in all of these, so start cleared */
1231         memset(keys, 0, sizeof(keys));
1232
1233         /* interpret timing and find keys */
1234         if (point) {
1235                 if (result->time < 0.0f)
1236                         real_t = -result->time;
1237                 else
1238                         real_t = *(pind->ekey[0]->time) + t * (*(pind->ekey[0][point->totkey - 1].time) - *(pind->ekey[0]->time));
1239
1240                 while (*(pind->ekey[1]->time) < real_t)
1241                         pind->ekey[1]++;
1242
1243                 pind->ekey[0] = pind->ekey[1] - 1;
1244         }
1245         else if (pind->keyed) {
1246                 /* we have only one key, so let's use that */
1247                 if (pind->kkey[1] == NULL) {
1248                         copy_particle_key(result, pind->kkey[0], 1);
1249                         return;
1250                 }
1251
1252                 if (result->time < 0.0f)
1253                         real_t = -result->time;
1254                 else
1255                         real_t = pind->kkey[0]->time + t * (pind->kkey[0][pa->totkey - 1].time - pind->kkey[0]->time);
1256
1257                 if (psys->part->phystype == PART_PHYS_KEYED && psys->flag & PSYS_KEYED_TIMING) {
1258                         ParticleTarget *pt = psys->targets.first;
1259
1260                         pt = pt->next;
1261
1262                         while (pt && pa->time + pt->time < real_t)
1263                                 pt = pt->next;
1264
1265                         if (pt) {
1266                                 pt = pt->prev;
1267
1268                                 if (pa->time + pt->time + pt->duration > real_t)
1269                                         real_t = pa->time + pt->time;
1270                         }
1271                         else
1272                                 real_t = pa->time + ((ParticleTarget *)psys->targets.last)->time;
1273                 }
1274
1275                 CLAMP(real_t, pa->time, pa->dietime);
1276
1277                 while (pind->kkey[1]->time < real_t)
1278                         pind->kkey[1]++;
1279                 
1280                 pind->kkey[0] = pind->kkey[1] - 1;
1281         }
1282         else if (pind->cache) {
1283                 if (result->time < 0.0f) /* flag for time in frames */
1284                         real_t = -result->time;
1285                 else
1286                         real_t = pa->time + t * (pa->dietime - pa->time);
1287         }
1288         else {
1289                 if (result->time < 0.0f)
1290                         real_t = -result->time;
1291                 else
1292                         real_t = pind->hkey[0]->time + t * (pind->hkey[0][pa->totkey - 1].time - pind->hkey[0]->time);
1293
1294                 while (pind->hkey[1]->time < real_t) {
1295                         pind->hkey[1]++;
1296                         pind->mvert[1]++;
1297                 }
1298
1299                 pind->hkey[0] = pind->hkey[1] - 1;
1300         }
1301
1302         /* set actual interpolation keys */
1303         if (point) {
1304                 edit_to_particle(keys + 1, pind->ekey[0]);
1305                 edit_to_particle(keys + 2, pind->ekey[1]);
1306         }
1307         else if (pind->dm) {
1308                 pind->mvert[0] = pind->mvert[1] - 1;
1309                 mvert_to_particle(keys + 1, pind->mvert[0], pind->hkey[0]);
1310                 mvert_to_particle(keys + 2, pind->mvert[1], pind->hkey[1]);
1311         }
1312         else if (pind->keyed) {
1313                 memcpy(keys + 1, pind->kkey[0], sizeof(ParticleKey));
1314                 memcpy(keys + 2, pind->kkey[1], sizeof(ParticleKey));
1315         }
1316         else if (pind->cache) {
1317                 get_pointcache_keys_for_time(NULL, pind->cache, &pind->pm, p, real_t, keys + 1, keys + 2);
1318         }
1319         else {
1320                 hair_to_particle(keys + 1, pind->hkey[0]);
1321                 hair_to_particle(keys + 2, pind->hkey[1]);
1322         }
1323
1324         /* set secondary interpolation keys for hair */
1325         if (!pind->keyed && !pind->cache && !point_vel) {
1326                 if (point) {
1327                         if (pind->ekey[0] != point->keys)
1328                                 edit_to_particle(keys, pind->ekey[0] - 1);
1329                         else
1330                                 edit_to_particle(keys, pind->ekey[0]);
1331                 }
1332                 else if (pind->dm) {
1333                         if (pind->hkey[0] != pa->hair)
1334                                 mvert_to_particle(keys, pind->mvert[0] - 1, pind->hkey[0] - 1);
1335                         else
1336                                 mvert_to_particle(keys, pind->mvert[0], pind->hkey[0]);
1337                 }
1338                 else {
1339                         if (pind->hkey[0] != pa->hair)
1340                                 hair_to_particle(keys, pind->hkey[0] - 1);
1341                         else
1342                                 hair_to_particle(keys, pind->hkey[0]);
1343                 }
1344
1345                 if (point) {
1346                         if (pind->ekey[1] != point->keys + point->totkey - 1)
1347                                 edit_to_particle(keys + 3, pind->ekey[1] + 1);
1348                         else
1349                                 edit_to_particle(keys + 3, pind->ekey[1]);
1350                 }
1351                 else if (pind->dm) {
1352                         if (pind->hkey[1] != pa->hair + pa->totkey - 1)
1353                                 mvert_to_particle(keys + 3, pind->mvert[1] + 1, pind->hkey[1] + 1);
1354                         else
1355                                 mvert_to_particle(keys + 3, pind->mvert[1], pind->hkey[1]);
1356                 }
1357                 else {
1358                         if (pind->hkey[1] != pa->hair + pa->totkey - 1)
1359                                 hair_to_particle(keys + 3, pind->hkey[1] + 1);
1360                         else
1361                                 hair_to_particle(keys + 3, pind->hkey[1]);
1362                 }
1363         }
1364
1365         dfra = keys[2].time - keys[1].time;
1366         keytime = (real_t - keys[1].time) / dfra;
1367
1368         /* convert velocity to timestep size */
1369         if (pind->keyed || pind->cache || point_vel) {
1370                 invdt = dfra * 0.04f * (psys ? psys->part->timetweak : 1.f);
1371                 mul_v3_fl(keys[1].vel, invdt);
1372                 mul_v3_fl(keys[2].vel, invdt);
1373                 interp_qt_qtqt(result->rot, keys[1].rot, keys[2].rot, keytime);
1374         }
1375
1376         /* now we should have in chronologiacl order k1<=k2<=t<=k3<=k4 with keytime between [0, 1]->[k2, k3] (k1 & k4 used for cardinal & bspline interpolation)*/
1377         psys_interpolate_particle((pind->keyed || pind->cache || point_vel) ? -1 /* signal for cubic interpolation */
1378                                   : (pind->bspline ? KEY_BSPLINE : KEY_CARDINAL),
1379                                   keys, keytime, result, 1);
1380
1381         /* the velocity needs to be converted back from cubic interpolation */
1382         if (pind->keyed || pind->cache || point_vel)
1383                 mul_v3_fl(result->vel, 1.f / invdt);
1384 }
1385
1386 static void interpolate_pathcache(ParticleCacheKey *first, float t, ParticleCacheKey *result)
1387 {
1388         int i = 0;
1389         ParticleCacheKey *cur = first;
1390
1391         /* scale the requested time to fit the entire path even if the path is cut early */
1392         t *= (first + first->steps)->time;
1393
1394         while (i < first->steps && cur->time < t)
1395                 cur++;
1396
1397         if (cur->time == t)
1398                 *result = *cur;
1399         else {
1400                 float dt = (t - (cur - 1)->time) / (cur->time - (cur - 1)->time);
1401                 interp_v3_v3v3(result->co, (cur - 1)->co, cur->co, dt);
1402                 interp_v3_v3v3(result->vel, (cur - 1)->vel, cur->vel, dt);
1403                 interp_qt_qtqt(result->rot, (cur - 1)->rot, cur->rot, dt);
1404                 result->time = t;
1405         }
1406
1407         /* first is actual base rotation, others are incremental from first */
1408         if (cur == first || cur - 1 == first)
1409                 copy_qt_qt(result->rot, first->rot);
1410         else
1411                 mul_qt_qtqt(result->rot, first->rot, result->rot);
1412 }
1413
1414 /************************************************/
1415 /*                      Particles on a dm                                       */
1416 /************************************************/
1417 /* interpolate a location on a face based on face coordinates */
1418 void psys_interpolate_face(MVert *mvert, MFace *mface, MTFace *tface, float (*orcodata)[3],
1419                            float w[4], float vec[3], float nor[3], float utan[3], float vtan[3],
1420                            float orco[3], float ornor[3])
1421 {
1422         float *v1 = 0, *v2 = 0, *v3 = 0, *v4 = 0;
1423         float e1[3], e2[3], s1, s2, t1, t2;
1424         float *uv1, *uv2, *uv3, *uv4;
1425         float n1[3], n2[3], n3[3], n4[3];
1426         float tuv[4][2];
1427         float *o1, *o2, *o3, *o4;
1428
1429         v1 = mvert[mface->v1].co;
1430         v2 = mvert[mface->v2].co;
1431         v3 = mvert[mface->v3].co;
1432
1433         normal_short_to_float_v3(n1, mvert[mface->v1].no);
1434         normal_short_to_float_v3(n2, mvert[mface->v2].no);
1435         normal_short_to_float_v3(n3, mvert[mface->v3].no);
1436
1437         if (mface->v4) {
1438                 v4 = mvert[mface->v4].co;
1439                 normal_short_to_float_v3(n4, mvert[mface->v4].no);
1440                 
1441                 interp_v3_v3v3v3v3(vec, v1, v2, v3, v4, w);
1442
1443                 if (nor) {
1444                         if (mface->flag & ME_SMOOTH)
1445                                 interp_v3_v3v3v3v3(nor, n1, n2, n3, n4, w);
1446                         else
1447                                 normal_quad_v3(nor, v1, v2, v3, v4);
1448                 }
1449         }
1450         else {
1451                 interp_v3_v3v3v3(vec, v1, v2, v3, w);
1452
1453                 if (nor) {
1454                         if (mface->flag & ME_SMOOTH)
1455                                 interp_v3_v3v3v3(nor, n1, n2, n3, w);
1456                         else
1457                                 normal_tri_v3(nor, v1, v2, v3);
1458                 }
1459         }
1460         
1461         /* calculate tangent vectors */
1462         if (utan && vtan) {
1463                 if (tface) {
1464                         uv1 = tface->uv[0];
1465                         uv2 = tface->uv[1];
1466                         uv3 = tface->uv[2];
1467                         uv4 = tface->uv[3];
1468                 }
1469                 else {
1470                         uv1 = tuv[0]; uv2 = tuv[1]; uv3 = tuv[2]; uv4 = tuv[3];
1471                         map_to_sphere(uv1, uv1 + 1, v1[0], v1[1], v1[2]);
1472                         map_to_sphere(uv2, uv2 + 1, v2[0], v2[1], v2[2]);
1473                         map_to_sphere(uv3, uv3 + 1, v3[0], v3[1], v3[2]);
1474                         if (v4)
1475                                 map_to_sphere(uv4, uv4 + 1, v4[0], v4[1], v4[2]);
1476                 }
1477
1478                 if (v4) {
1479                         s1 = uv3[0] - uv1[0];
1480                         s2 = uv4[0] - uv1[0];
1481
1482                         t1 = uv3[1] - uv1[1];
1483                         t2 = uv4[1] - uv1[1];
1484
1485                         sub_v3_v3v3(e1, v3, v1);
1486                         sub_v3_v3v3(e2, v4, v1);
1487                 }
1488                 else {
1489                         s1 = uv2[0] - uv1[0];
1490                         s2 = uv3[0] - uv1[0];
1491
1492                         t1 = uv2[1] - uv1[1];
1493                         t2 = uv3[1] - uv1[1];
1494
1495                         sub_v3_v3v3(e1, v2, v1);
1496                         sub_v3_v3v3(e2, v3, v1);
1497                 }
1498
1499                 vtan[0] = (s1 * e2[0] - s2 * e1[0]);
1500                 vtan[1] = (s1 * e2[1] - s2 * e1[1]);
1501                 vtan[2] = (s1 * e2[2] - s2 * e1[2]);
1502
1503                 utan[0] = (t1 * e2[0] - t2 * e1[0]);
1504                 utan[1] = (t1 * e2[1] - t2 * e1[1]);
1505                 utan[2] = (t1 * e2[2] - t2 * e1[2]);
1506         }
1507
1508         if (orco) {
1509                 if (orcodata) {
1510                         o1 = orcodata[mface->v1];
1511                         o2 = orcodata[mface->v2];
1512                         o3 = orcodata[mface->v3];
1513
1514                         if (mface->v4) {
1515                                 o4 = orcodata[mface->v4];
1516
1517                                 interp_v3_v3v3v3v3(orco, o1, o2, o3, o4, w);
1518
1519                                 if (ornor)
1520                                         normal_quad_v3(ornor, o1, o2, o3, o4);
1521                         }
1522                         else {
1523                                 interp_v3_v3v3v3(orco, o1, o2, o3, w);
1524
1525                                 if (ornor)
1526                                         normal_tri_v3(ornor, o1, o2, o3);
1527                         }
1528                 }
1529                 else {
1530                         copy_v3_v3(orco, vec);
1531                         if (ornor && nor)
1532                                 copy_v3_v3(ornor, nor);
1533                 }
1534         }
1535 }
1536 void psys_interpolate_uvs(const MTFace *tface, int quad, const float w[4], float uvco[2])
1537 {
1538         float v10 = tface->uv[0][0];
1539         float v11 = tface->uv[0][1];
1540         float v20 = tface->uv[1][0];
1541         float v21 = tface->uv[1][1];
1542         float v30 = tface->uv[2][0];
1543         float v31 = tface->uv[2][1];
1544         float v40, v41;
1545
1546         if (quad) {
1547                 v40 = tface->uv[3][0];
1548                 v41 = tface->uv[3][1];
1549
1550                 uvco[0] = w[0] * v10 + w[1] * v20 + w[2] * v30 + w[3] * v40;
1551                 uvco[1] = w[0] * v11 + w[1] * v21 + w[2] * v31 + w[3] * v41;
1552         }
1553         else {
1554                 uvco[0] = w[0] * v10 + w[1] * v20 + w[2] * v30;
1555                 uvco[1] = w[0] * v11 + w[1] * v21 + w[2] * v31;
1556         }
1557 }
1558
1559 void psys_interpolate_mcol(const MCol *mcol, int quad, const float w[4], MCol *mc)
1560 {
1561         char *cp, *cp1, *cp2, *cp3, *cp4;
1562
1563         cp = (char *)mc;
1564         cp1 = (char *)&mcol[0];
1565         cp2 = (char *)&mcol[1];
1566         cp3 = (char *)&mcol[2];
1567         
1568         if (quad) {
1569                 cp4 = (char *)&mcol[3];
1570
1571                 cp[0] = (int)(w[0] * cp1[0] + w[1] * cp2[0] + w[2] * cp3[0] + w[3] * cp4[0]);
1572                 cp[1] = (int)(w[0] * cp1[1] + w[1] * cp2[1] + w[2] * cp3[1] + w[3] * cp4[1]);
1573                 cp[2] = (int)(w[0] * cp1[2] + w[1] * cp2[2] + w[2] * cp3[2] + w[3] * cp4[2]);
1574                 cp[3] = (int)(w[0] * cp1[3] + w[1] * cp2[3] + w[2] * cp3[3] + w[3] * cp4[3]);
1575         }
1576         else {
1577                 cp[0] = (int)(w[0] * cp1[0] + w[1] * cp2[0] + w[2] * cp3[0]);
1578                 cp[1] = (int)(w[0] * cp1[1] + w[1] * cp2[1] + w[2] * cp3[1]);
1579                 cp[2] = (int)(w[0] * cp1[2] + w[1] * cp2[2] + w[2] * cp3[2]);
1580                 cp[3] = (int)(w[0] * cp1[3] + w[1] * cp2[3] + w[2] * cp3[3]);
1581         }
1582 }
1583
1584 static float psys_interpolate_value_from_verts(DerivedMesh *dm, short from, int index, const float fw[4], const float *values)
1585 {
1586         if (values == 0 || index == -1)
1587                 return 0.0;
1588
1589         switch (from) {
1590                 case PART_FROM_VERT:
1591                         return values[index];
1592                 case PART_FROM_FACE:
1593                 case PART_FROM_VOLUME:
1594                 {
1595                         MFace *mf = dm->getTessFaceData(dm, index, CD_MFACE);
1596                         return interpolate_particle_value(values[mf->v1], values[mf->v2], values[mf->v3], values[mf->v4], fw, mf->v4);
1597                 }
1598                         
1599         }
1600         return 0.0f;
1601 }
1602
1603 /* conversion of pa->fw to origspace layer coordinates */
1604 static void psys_w_to_origspace(const float w[4], float uv[2])
1605 {
1606         uv[0] = w[1] + w[2];
1607         uv[1] = w[2] + w[3];
1608 }
1609
1610 /* conversion of pa->fw to weights in face from origspace */
1611 static void psys_origspace_to_w(OrigSpaceFace *osface, int quad, const float w[4], float neww[4])
1612 {
1613         float v[4][3], co[3];
1614
1615         v[0][0] = osface->uv[0][0]; v[0][1] = osface->uv[0][1]; v[0][2] = 0.0f;
1616         v[1][0] = osface->uv[1][0]; v[1][1] = osface->uv[1][1]; v[1][2] = 0.0f;
1617         v[2][0] = osface->uv[2][0]; v[2][1] = osface->uv[2][1]; v[2][2] = 0.0f;
1618
1619         psys_w_to_origspace(w, co);
1620         co[2] = 0.0f;
1621         
1622         if (quad) {
1623                 v[3][0] = osface->uv[3][0]; v[3][1] = osface->uv[3][1]; v[3][2] = 0.0f;
1624                 interp_weights_poly_v3(neww, v, 4, co);
1625         }
1626         else {
1627                 interp_weights_poly_v3(neww, v, 3, co);
1628                 neww[3] = 0.0f;
1629         }
1630 }
1631
1632 /* find the derived mesh face for a particle, set the mf passed. this is slow
1633  * and can be optimized but only for many lookups. returns the face index. */
1634 int psys_particle_dm_face_lookup(Object *ob, DerivedMesh *dm, int index, const float fw[4], struct LinkNode *node)
1635 {
1636         Mesh *me = (Mesh *)ob->data;
1637         MPoly *mpoly;
1638         OrigSpaceFace *osface;
1639         int quad, findex, totface;
1640         float uv[2], (*faceuv)[2];
1641
1642         /* double lookup */
1643         const int *index_mf_to_mpoly = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
1644         const int *index_mp_to_orig  = dm->getPolyDataArray(dm, CD_ORIGINDEX);
1645         if (index_mf_to_mpoly == NULL) {
1646                 index_mp_to_orig = NULL;
1647         }
1648
1649         mpoly = dm->getPolyArray(dm);
1650         osface = dm->getTessFaceDataArray(dm, CD_ORIGSPACE);
1651
1652         totface = dm->getNumTessFaces(dm);
1653         
1654         if (osface == NULL || index_mf_to_mpoly == NULL) {
1655                 /* Assume we don't need osface data */
1656                 if (index < totface) {
1657                         //printf("\tNO CD_ORIGSPACE, assuming not needed\n");
1658                         return index;
1659                 }
1660                 else {
1661                         printf("\tNO CD_ORIGSPACE, error out of range\n");
1662                         return DMCACHE_NOTFOUND;
1663                 }
1664         }
1665         else if (index >= me->totpoly)
1666                 return DMCACHE_NOTFOUND;  /* index not in the original mesh */
1667
1668         psys_w_to_origspace(fw, uv);
1669         
1670         if (node) { /* we have a linked list of faces that we use, faster! */
1671                 for (; node; node = node->next) {
1672                         findex = GET_INT_FROM_POINTER(node->link);
1673                         faceuv = osface[findex].uv;
1674                         quad = (mpoly[findex].totloop == 4);
1675
1676                         /* check that this intersects - Its possible this misses :/ -
1677                          * could also check its not between */
1678                         if (quad) {
1679                                 if (isect_point_quad_v2(uv, faceuv[0], faceuv[1], faceuv[2], faceuv[3]))
1680                                         return findex;
1681                         }
1682                         else if (isect_point_tri_v2(uv, faceuv[0], faceuv[1], faceuv[2]))
1683                                 return findex;
1684                 }
1685         }
1686         else { /* if we have no node, try every face */
1687                 for (findex = 0; findex < totface; findex++) {
1688                         const int findex_orig = DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, findex);
1689                         if (findex_orig == index) {
1690                                 faceuv = osface[findex].uv;
1691                                 quad = (mpoly[findex].totloop == 4);
1692
1693                                 /* check that this intersects - Its possible this misses :/ -
1694                                  * could also check its not between */
1695                                 if (quad) {
1696                                         if (isect_point_quad_v2(uv, faceuv[0], faceuv[1], faceuv[2], faceuv[3]))
1697                                                 return findex;
1698                                 }
1699                                 else if (isect_point_tri_v2(uv, faceuv[0], faceuv[1], faceuv[2]))
1700                                         return findex;
1701                         }
1702                 }
1703         }
1704
1705         return DMCACHE_NOTFOUND;
1706 }
1707
1708 static int psys_map_index_on_dm(DerivedMesh *dm, int from, int index, int index_dmcache, const float fw[4], float UNUSED(foffset), int *mapindex, float mapfw[4])
1709 {
1710         if (index < 0)
1711                 return 0;
1712
1713         if (dm->deformedOnly || index_dmcache == DMCACHE_ISCHILD) {
1714                 /* for meshes that are either only defined or for child particles, the
1715                  * index and fw do not require any mapping, so we can directly use it */
1716                 if (from == PART_FROM_VERT) {
1717                         if (index >= dm->getNumVerts(dm))
1718                                 return 0;
1719
1720                         *mapindex = index;
1721                 }
1722                 else { /* FROM_FACE/FROM_VOLUME */
1723                         if (index >= dm->getNumTessFaces(dm))
1724                                 return 0;
1725
1726                         *mapindex = index;
1727                         copy_v4_v4(mapfw, fw);
1728                 }
1729         }
1730         else {
1731                 /* for other meshes that have been modified, we try to map the particle
1732                  * to their new location, which means a different index, and for faces
1733                  * also a new face interpolation weights */
1734                 if (from == PART_FROM_VERT) {
1735                         if (index_dmcache == DMCACHE_NOTFOUND || index_dmcache > dm->getNumVerts(dm))
1736                                 return 0;
1737
1738                         *mapindex = index_dmcache;
1739                 }
1740                 else { /* FROM_FACE/FROM_VOLUME */
1741                            /* find a face on the derived mesh that uses this face */
1742                         MFace *mface;
1743                         OrigSpaceFace *osface;
1744                         int i;
1745
1746                         i = index_dmcache;
1747
1748                         if (i == DMCACHE_NOTFOUND || i >= dm->getNumTessFaces(dm))
1749                                 return 0;
1750
1751                         *mapindex = i;
1752
1753                         /* modify the original weights to become
1754                          * weights for the derived mesh face */
1755                         osface = dm->getTessFaceDataArray(dm, CD_ORIGSPACE);
1756                         mface = dm->getTessFaceData(dm, i, CD_MFACE);
1757
1758                         if (osface == NULL)
1759                                 mapfw[0] = mapfw[1] = mapfw[2] = mapfw[3] = 0.0f;
1760                         else
1761                                 psys_origspace_to_w(&osface[i], mface->v4, fw, mapfw);
1762                 }
1763         }
1764
1765         return 1;
1766 }
1767
1768 /* interprets particle data to get a point on a mesh in object space */
1769 void psys_particle_on_dm(DerivedMesh *dm, int from, int index, int index_dmcache,
1770                          const float fw[4], float foffset, float vec[3], float nor[3], float utan[3], float vtan[3],
1771                          float orco[3], float ornor[3])
1772 {
1773         float tmpnor[3], mapfw[4];
1774         float (*orcodata)[3];
1775         int mapindex;
1776
1777         if (!psys_map_index_on_dm(dm, from, index, index_dmcache, fw, foffset, &mapindex, mapfw)) {
1778                 if (vec) { vec[0] = vec[1] = vec[2] = 0.0; }
1779                 if (nor) { nor[0] = nor[1] = 0.0; nor[2] = 1.0; }
1780                 if (orco) { orco[0] = orco[1] = orco[2] = 0.0; }
1781                 if (ornor) { ornor[0] = ornor[1] = 0.0; ornor[2] = 1.0; }
1782                 if (utan) { utan[0] = utan[1] = utan[2] = 0.0; }
1783                 if (vtan) { vtan[0] = vtan[1] = vtan[2] = 0.0; }
1784
1785                 return;
1786         }
1787
1788         orcodata = dm->getVertDataArray(dm, CD_ORCO);
1789
1790         if (from == PART_FROM_VERT) {
1791                 dm->getVertCo(dm, mapindex, vec);
1792
1793                 if (nor) {
1794                         dm->getVertNo(dm, mapindex, nor);
1795                         normalize_v3(nor);
1796                 }
1797
1798                 if (orco)
1799                         copy_v3_v3(orco, orcodata[mapindex]);
1800
1801                 if (ornor) {
1802                         dm->getVertNo(dm, mapindex, nor);
1803                         normalize_v3(nor);
1804                 }
1805
1806                 if (utan && vtan) {
1807                         utan[0] = utan[1] = utan[2] = 0.0f;
1808                         vtan[0] = vtan[1] = vtan[2] = 0.0f;
1809                 }
1810         }
1811         else { /* PART_FROM_FACE / PART_FROM_VOLUME */
1812                 MFace *mface;
1813                 MTFace *mtface;
1814                 MVert *mvert;
1815
1816                 mface = dm->getTessFaceData(dm, mapindex, CD_MFACE);
1817                 mvert = dm->getVertDataArray(dm, CD_MVERT);
1818                 mtface = CustomData_get_layer(&dm->faceData, CD_MTFACE);
1819
1820                 if (mtface)
1821                         mtface += mapindex;
1822
1823                 if (from == PART_FROM_VOLUME) {
1824                         psys_interpolate_face(mvert, mface, mtface, orcodata, mapfw, vec, tmpnor, utan, vtan, orco, ornor);
1825                         if (nor)
1826                                 copy_v3_v3(nor, tmpnor);
1827
1828                         normalize_v3(tmpnor);
1829                         mul_v3_fl(tmpnor, -foffset);
1830                         add_v3_v3(vec, tmpnor);
1831                 }
1832                 else
1833                         psys_interpolate_face(mvert, mface, mtface, orcodata, mapfw, vec, nor, utan, vtan, orco, ornor);
1834         }
1835 }
1836
1837 float psys_particle_value_from_verts(DerivedMesh *dm, short from, ParticleData *pa, float *values)
1838 {
1839         float mapfw[4];
1840         int mapindex;
1841
1842         if (!psys_map_index_on_dm(dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, &mapindex, mapfw))
1843                 return 0.0f;
1844         
1845         return psys_interpolate_value_from_verts(dm, from, mapindex, mapfw, values);
1846 }
1847
1848 ParticleSystemModifierData *psys_get_modifier(Object *ob, ParticleSystem *psys)
1849 {
1850         ModifierData *md;
1851         ParticleSystemModifierData *psmd;
1852
1853         for (md = ob->modifiers.first; md; md = md->next) {
1854                 if (md->type == eModifierType_ParticleSystem) {
1855                         psmd = (ParticleSystemModifierData *) md;
1856                         if (psmd->psys == psys) {
1857                                 return psmd;
1858                         }
1859                 }
1860         }
1861         return NULL;
1862 }
1863 /************************************************/
1864 /*                      Particles on a shape                            */
1865 /************************************************/
1866 /* ready for future use */
1867 static void psys_particle_on_shape(int UNUSED(distr), int UNUSED(index),
1868                                    float *UNUSED(fuv), float vec[3], float nor[3], float utan[3], float vtan[3],
1869                                    float orco[3], float ornor[3])
1870 {
1871         /* TODO */
1872         float zerovec[3] = {0.0f, 0.0f, 0.0f};
1873         if (vec) {
1874                 copy_v3_v3(vec, zerovec);
1875         }
1876         if (nor) {
1877                 copy_v3_v3(nor, zerovec);
1878         }
1879         if (utan) {
1880                 copy_v3_v3(utan, zerovec);
1881         }
1882         if (vtan) {
1883                 copy_v3_v3(vtan, zerovec);
1884         }
1885         if (orco) {
1886                 copy_v3_v3(orco, zerovec);
1887         }
1888         if (ornor) {
1889                 copy_v3_v3(ornor, zerovec);
1890         }
1891 }
1892 /************************************************/
1893 /*                      Particles on emitter                            */
1894 /************************************************/
1895 void psys_particle_on_emitter(ParticleSystemModifierData *psmd, int from, int index, int index_dmcache,
1896                               float fuv[4], float foffset, float vec[3], float nor[3], float utan[3], float vtan[3],
1897                               float orco[3], float ornor[3])
1898 {
1899         if (psmd) {
1900                 if (psmd->psys->part->distr == PART_DISTR_GRID && psmd->psys->part->from != PART_FROM_VERT) {
1901                         if (vec)
1902                                 copy_v3_v3(vec, fuv);
1903
1904                         if (orco)
1905                                 copy_v3_v3(orco, fuv);
1906                         return;
1907                 }
1908                 /* we cant use the num_dmcache */
1909                 psys_particle_on_dm(psmd->dm, from, index, index_dmcache, fuv, foffset, vec, nor, utan, vtan, orco, ornor);
1910         }
1911         else
1912                 psys_particle_on_shape(from, index, fuv, vec, nor, utan, vtan, orco, ornor);
1913
1914 }
1915 /************************************************/
1916 /*                      Path Cache                                                      */
1917 /************************************************/
1918
1919 static void do_kink(ParticleKey *state, ParticleKey *par, float *par_rot, float time, float freq, float shape, float amplitude, float flat, short type, short axis, float obmat[4][4], int smooth_start)
1920 {
1921         float kink[3] = {1.f, 0.f, 0.f}, par_vec[3], q1[4] = {1.f, 0.f, 0.f, 0.f};
1922         float t, dt = 1.f, result[3];
1923
1924         if (par == NULL || type == PART_KINK_NO)
1925                 return;
1926
1927         CLAMP(time, 0.f, 1.f);
1928
1929         if (shape != 0.0f && type != PART_KINK_BRAID) {
1930                 if (shape < 0.0f)
1931                         time = (float)pow(time, 1.f + shape);
1932                 else
1933                         time = (float)pow(time, 1.f / (1.f - shape));
1934         }
1935
1936         t = time * freq * (float)M_PI;
1937         
1938         if (smooth_start) {
1939                 dt = fabs(t);
1940                 /* smooth the beginning of kink */
1941                 CLAMP(dt, 0.f, (float)M_PI);
1942                 dt = sin(dt / 2.f);
1943         }
1944
1945         if (type != PART_KINK_RADIAL) {
1946                 float temp[3];
1947
1948                 kink[axis] = 1.f;
1949
1950                 if (obmat)
1951                         mul_mat3_m4_v3(obmat, kink);
1952                 
1953                 if (par_rot)
1954                         mul_qt_v3(par_rot, kink);
1955
1956                 /* make sure kink is normal to strand */
1957                 project_v3_v3v3(temp, kink, par->vel);
1958                 sub_v3_v3(kink, temp);
1959                 normalize_v3(kink);
1960         }
1961
1962         copy_v3_v3(result, state->co);
1963         sub_v3_v3v3(par_vec, par->co, state->co);
1964
1965         switch (type) {
1966                 case PART_KINK_CURL:
1967                 {
1968                         negate_v3(par_vec);
1969
1970                         if (flat > 0.f) {
1971                                 float proj[3];
1972                                 project_v3_v3v3(proj, par_vec, par->vel);
1973                                 madd_v3_v3fl(par_vec, proj, -flat);
1974
1975                                 project_v3_v3v3(proj, par_vec, kink);
1976                                 madd_v3_v3fl(par_vec, proj, -flat);
1977                         }
1978
1979                         axis_angle_to_quat(q1, kink, (float)M_PI / 2.f);
1980
1981                         mul_qt_v3(q1, par_vec);
1982
1983                         madd_v3_v3fl(par_vec, kink, amplitude);
1984
1985                         /* rotate kink vector around strand tangent */
1986                         if (t != 0.f) {
1987                                 axis_angle_to_quat(q1, par->vel, t);
1988                                 mul_qt_v3(q1, par_vec);
1989                         }
1990
1991                         add_v3_v3v3(result, par->co, par_vec);
1992                         break;
1993                 }
1994                 case PART_KINK_RADIAL:
1995                 {
1996                         if (flat > 0.f) {
1997                                 float proj[3];
1998                                 /* flatten along strand */
1999                                 project_v3_v3v3(proj, par_vec, par->vel);
2000                                 madd_v3_v3fl(result, proj, flat);
2001                         }
2002
2003                         madd_v3_v3fl(result, par_vec, -amplitude * (float)sin(t));
2004                         break;
2005                 }
2006                 case PART_KINK_WAVE:
2007                 {
2008                         madd_v3_v3fl(result, kink, amplitude * (float)sin(t));
2009
2010                         if (flat > 0.f) {
2011                                 float proj[3];
2012                                 /* flatten along wave */
2013                                 project_v3_v3v3(proj, par_vec, kink);
2014                                 madd_v3_v3fl(result, proj, flat);
2015
2016                                 /* flatten along strand */
2017                                 project_v3_v3v3(proj, par_vec, par->vel);
2018                                 madd_v3_v3fl(result, proj, flat);
2019                         }
2020                         break;
2021                 }
2022                 case PART_KINK_BRAID:
2023                 {
2024                         float y_vec[3] = {0.f, 1.f, 0.f};
2025                         float z_vec[3] = {0.f, 0.f, 1.f};
2026                         float vec_one[3], state_co[3];
2027                         float inp_y, inp_z, length;
2028                 
2029                         if (par_rot) {
2030                                 mul_qt_v3(par_rot, y_vec);
2031                                 mul_qt_v3(par_rot, z_vec);
2032                         }
2033
2034                         negate_v3(par_vec);
2035                         normalize_v3_v3(vec_one, par_vec);
2036
2037                         inp_y = dot_v3v3(y_vec, vec_one);
2038                         inp_z = dot_v3v3(z_vec, vec_one);
2039
2040                         if (inp_y > 0.5f) {
2041                                 copy_v3_v3(state_co, y_vec);
2042
2043                                 mul_v3_fl(y_vec, amplitude * (float)cos(t));
2044                                 mul_v3_fl(z_vec, amplitude / 2.f * (float)sin(2.f * t));
2045                         }
2046                         else if (inp_z > 0.0f) {
2047                                 mul_v3_v3fl(state_co, z_vec, (float)sin((float)M_PI / 3.f));
2048                                 madd_v3_v3fl(state_co, y_vec, -0.5f);
2049
2050                                 mul_v3_fl(y_vec, -amplitude * (float)cos(t + (float)M_PI / 3.f));
2051                                 mul_v3_fl(z_vec, amplitude / 2.f * (float)cos(2.f * t + (float)M_PI / 6.f));
2052                         }
2053                         else {
2054                                 mul_v3_v3fl(state_co, z_vec, -(float)sin((float)M_PI / 3.f));
2055                                 madd_v3_v3fl(state_co, y_vec, -0.5f);
2056
2057                                 mul_v3_fl(y_vec, amplitude * (float)-sin(t + (float)M_PI / 6.f));
2058                                 mul_v3_fl(z_vec, amplitude / 2.f * (float)-sin(2.f * t + (float)M_PI / 3.f));
2059                         }
2060
2061                         mul_v3_fl(state_co, amplitude);
2062                         add_v3_v3(state_co, par->co);
2063                         sub_v3_v3v3(par_vec, state->co, state_co);
2064
2065                         length = normalize_v3(par_vec);
2066                         mul_v3_fl(par_vec, MIN2(length, amplitude / 2.f));
2067
2068                         add_v3_v3v3(state_co, par->co, y_vec);
2069                         add_v3_v3(state_co, z_vec);
2070                         add_v3_v3(state_co, par_vec);
2071
2072                         shape = 2.f * (float)M_PI * (1.f + shape);
2073
2074                         if (t < shape) {
2075                                 shape = t / shape;
2076                                 shape = (float)sqrt((double)shape);
2077                                 interp_v3_v3v3(result, result, state_co, shape);
2078                         }
2079                         else {
2080                                 copy_v3_v3(result, state_co);
2081                         }
2082                         break;
2083                 }
2084         }
2085
2086         /* blend the start of the kink */
2087         if (dt < 1.f)
2088                 interp_v3_v3v3(state->co, state->co, result, dt);
2089         else
2090                 copy_v3_v3(state->co, result);
2091 }
2092
2093 static float do_clump(ParticleKey *state, ParticleKey *par, float time, float clumpfac, float clumppow, float pa_clump)
2094 {
2095         float clump = 0.f;
2096
2097         if (par && clumpfac != 0.0f) {
2098                 float cpow;
2099
2100                 if (clumppow < 0.0f)
2101                         cpow = 1.0f + clumppow;
2102                 else
2103                         cpow = 1.0f + 9.0f * clumppow;
2104
2105                 if (clumpfac < 0.0f) /* clump roots instead of tips */
2106                         clump = -clumpfac * pa_clump * (float)pow(1.0 - (double)time, (double)cpow);
2107                 else
2108                         clump = clumpfac * pa_clump * (float)pow((double)time, (double)cpow);
2109
2110                 interp_v3_v3v3(state->co, state->co, par->co, clump);
2111         }
2112
2113         return clump;
2114 }
2115 void precalc_guides(ParticleSimulationData *sim, ListBase *effectors)
2116 {
2117         EffectedPoint point;
2118         ParticleKey state;
2119         EffectorData efd;
2120         EffectorCache *eff;
2121         ParticleSystem *psys = sim->psys;
2122         EffectorWeights *weights = sim->psys->part->effector_weights;
2123         GuideEffectorData *data;
2124         PARTICLE_P;
2125
2126         if (!effectors)
2127                 return;
2128
2129         LOOP_PARTICLES {
2130                 psys_particle_on_emitter(sim->psmd, sim->psys->part->from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, state.co, 0, 0, 0, 0, 0);
2131                 
2132                 mul_m4_v3(sim->ob->obmat, state.co);
2133                 mul_mat3_m4_v3(sim->ob->obmat, state.vel);
2134                 
2135                 pd_point_from_particle(sim, pa, &state, &point);
2136
2137                 for (eff = effectors->first; eff; eff = eff->next) {
2138                         if (eff->pd->forcefield != PFIELD_GUIDE)
2139                                 continue;
2140
2141                         if (!eff->guide_data)
2142                                 eff->guide_data = MEM_callocN(sizeof(GuideEffectorData) * psys->totpart, "GuideEffectorData");
2143
2144                         data = eff->guide_data + p;
2145
2146                         sub_v3_v3v3(efd.vec_to_point, state.co, eff->guide_loc);
2147                         copy_v3_v3(efd.nor, eff->guide_dir);
2148                         efd.distance = len_v3(efd.vec_to_point);
2149
2150                         copy_v3_v3(data->vec_to_point, efd.vec_to_point);
2151                         data->strength = effector_falloff(eff, &efd, &point, weights);
2152                 }
2153         }
2154 }
2155 int do_guides(ListBase *effectors, ParticleKey *state, int index, float time)
2156 {
2157         EffectorCache *eff;
2158         PartDeflect *pd;
2159         Curve *cu;
2160         ParticleKey key, par;
2161         GuideEffectorData *data;
2162
2163         float effect[3] = {0.0f, 0.0f, 0.0f}, veffect[3] = {0.0f, 0.0f, 0.0f};
2164         float guidevec[4], guidedir[3], rot2[4], temp[3];
2165         float guidetime, radius, weight, angle, totstrength = 0.0f;
2166         float vec_to_point[3];
2167
2168         if (effectors) for (eff = effectors->first; eff; eff = eff->next) {
2169                         pd = eff->pd;
2170
2171                         if (pd->forcefield != PFIELD_GUIDE)
2172                                 continue;
2173
2174                         data = eff->guide_data + index;
2175
2176                         if (data->strength <= 0.0f)
2177                                 continue;
2178
2179                         guidetime = time / (1.0f - pd->free_end);
2180
2181                         if (guidetime > 1.0f)
2182                                 continue;
2183
2184                         cu = (Curve *)eff->ob->data;
2185
2186                         if (pd->flag & PFIELD_GUIDE_PATH_ADD) {
2187                                 if (where_on_path(eff->ob, data->strength * guidetime, guidevec, guidedir, NULL, &radius, &weight) == 0)
2188                                         return 0;
2189                         }
2190                         else {
2191                                 if (where_on_path(eff->ob, guidetime, guidevec, guidedir, NULL, &radius, &weight) == 0)
2192                                         return 0;
2193                         }
2194
2195                         mul_m4_v3(eff->ob->obmat, guidevec);
2196                         mul_mat3_m4_v3(eff->ob->obmat, guidedir);
2197
2198                         normalize_v3(guidedir);
2199
2200                         copy_v3_v3(vec_to_point, data->vec_to_point);
2201
2202                         if (guidetime != 0.0f) {
2203                                 /* curve direction */
2204                                 cross_v3_v3v3(temp, eff->guide_dir, guidedir);
2205                                 angle = dot_v3v3(eff->guide_dir, guidedir) / (len_v3(eff->guide_dir));
2206                                 angle = saacos(angle);
2207                                 axis_angle_to_quat(rot2, temp, angle);
2208                                 mul_qt_v3(rot2, vec_to_point);
2209
2210                                 /* curve tilt */
2211                                 axis_angle_to_quat(rot2, guidedir, guidevec[3] - eff->guide_loc[3]);
2212                                 mul_qt_v3(rot2, vec_to_point);
2213                         }
2214
2215                         /* curve taper */
2216                         if (cu->taperobj)
2217                                 mul_v3_fl(vec_to_point, BKE_displist_calc_taper(eff->scene, cu->taperobj, (int)(data->strength * guidetime * 100.0f), 100));
2218
2219                         else { /* curve size*/
2220                                 if (cu->flag & CU_PATH_RADIUS) {
2221                                         mul_v3_fl(vec_to_point, radius);
2222                                 }
2223                         }
2224                         par.co[0] = par.co[1] = par.co[2] = 0.0f;
2225                         copy_v3_v3(key.co, vec_to_point);
2226                         do_kink(&key, &par, 0, guidetime, pd->kink_freq, pd->kink_shape, pd->kink_amp, 0.f, pd->kink, pd->kink_axis, 0, 0);
2227                         do_clump(&key, &par, guidetime, pd->clump_fac, pd->clump_pow, 1.0f);
2228                         copy_v3_v3(vec_to_point, key.co);
2229
2230                         add_v3_v3(vec_to_point, guidevec);
2231
2232                         //sub_v3_v3v3(pa_loc, pa_loc, pa_zero);
2233                         madd_v3_v3fl(effect, vec_to_point, data->strength);
2234                         madd_v3_v3fl(veffect, guidedir, data->strength);
2235                         totstrength += data->strength;
2236
2237                         if (pd->flag & PFIELD_GUIDE_PATH_WEIGHT)
2238                                 totstrength *= weight;
2239                 }
2240
2241         if (totstrength != 0.0f) {
2242                 if (totstrength > 1.0f)
2243                         mul_v3_fl(effect, 1.0f / totstrength);
2244                 CLAMP(totstrength, 0.0f, 1.0f);
2245                 //add_v3_v3(effect, pa_zero);
2246                 interp_v3_v3v3(state->co, state->co, effect, totstrength);
2247
2248                 normalize_v3(veffect);
2249                 mul_v3_fl(veffect, len_v3(state->vel));
2250                 copy_v3_v3(state->vel, veffect);
2251                 return 1;
2252         }
2253         return 0;
2254 }
2255 static void do_rough(float *loc, float mat[4][4], float t, float fac, float size, float thres, ParticleKey *state)
2256 {
2257         float rough[3];
2258         float rco[3];
2259
2260         if (thres != 0.0f)
2261                 if ((float)fabs((float)(-1.5f + loc[0] + loc[1] + loc[2])) < 1.5f * thres) return;
2262
2263         copy_v3_v3(rco, loc);
2264         mul_v3_fl(rco, t);
2265         rough[0] = -1.0f + 2.0f * BLI_gTurbulence(size, rco[0], rco[1], rco[2], 2, 0, 2);
2266         rough[1] = -1.0f + 2.0f * BLI_gTurbulence(size, rco[1], rco[2], rco[0], 2, 0, 2);
2267         rough[2] = -1.0f + 2.0f * BLI_gTurbulence(size, rco[2], rco[0], rco[1], 2, 0, 2);
2268
2269         madd_v3_v3fl(state->co, mat[0], fac * rough[0]);
2270         madd_v3_v3fl(state->co, mat[1], fac * rough[1]);
2271         madd_v3_v3fl(state->co, mat[2], fac * rough[2]);
2272 }
2273 static void do_rough_end(float *loc, float mat[4][4], float t, float fac, float shape, ParticleKey *state)
2274 {
2275         float rough[2];
2276         float roughfac;
2277
2278         roughfac = fac * (float)pow((double)t, shape);
2279         copy_v2_v2(rough, loc);
2280         rough[0] = -1.0f + 2.0f * rough[0];
2281         rough[1] = -1.0f + 2.0f * rough[1];
2282         mul_v2_fl(rough, roughfac);
2283
2284         madd_v3_v3fl(state->co, mat[0], rough[0]);
2285         madd_v3_v3fl(state->co, mat[1], rough[1]);
2286 }
2287 static void do_path_effectors(ParticleSimulationData *sim, int i, ParticleCacheKey *ca, int k, int steps, float *UNUSED(rootco), float effector, float UNUSED(dfra), float UNUSED(cfra), float *length, float *vec)
2288 {
2289         float force[3] = {0.0f, 0.0f, 0.0f};
2290         ParticleKey eff_key;
2291         EffectedPoint epoint;
2292
2293         /* Don't apply effectors for dynamic hair, otherwise the effectors don't get applied twice. */
2294         if (sim->psys->flag & PSYS_HAIR_DYNAMICS)
2295                 return;
2296
2297         copy_v3_v3(eff_key.co, (ca - 1)->co);
2298         copy_v3_v3(eff_key.vel, (ca - 1)->vel);
2299         copy_qt_qt(eff_key.rot, (ca - 1)->rot);
2300
2301         pd_point_from_particle(sim, sim->psys->particles + i, &eff_key, &epoint);
2302         pdDoEffectors(sim->psys->effectors, sim->colliders, sim->psys->part->effector_weights, &epoint, force, NULL);
2303
2304         mul_v3_fl(force, effector * powf((float)k / (float)steps, 100.0f * sim->psys->part->eff_hair) / (float)steps);
2305
2306         add_v3_v3(force, vec);
2307
2308         normalize_v3(force);
2309
2310         if (k < steps)
2311                 sub_v3_v3v3(vec, (ca + 1)->co, ca->co);
2312
2313         madd_v3_v3v3fl(ca->co, (ca - 1)->co, force, *length);
2314
2315         if (k < steps)
2316                 *length = len_v3(vec);
2317 }
2318 static int check_path_length(int k, ParticleCacheKey *keys, ParticleCacheKey *state, float max_length, float *cur_length, float length, float *dvec)
2319 {
2320         if (*cur_length + length > max_length) {
2321                 mul_v3_fl(dvec, (max_length - *cur_length) / length);
2322                 add_v3_v3v3(state->co, (state - 1)->co, dvec);
2323                 keys->steps = k;
2324                 /* something over the maximum step value */
2325                 return k = 100000;
2326         }
2327         else {
2328                 *cur_length += length;
2329                 return k;
2330         }
2331 }
2332 static void offset_child(ChildParticle *cpa, ParticleKey *par, float *par_rot, ParticleKey *child, float flat, float radius)
2333 {
2334         copy_v3_v3(child->co, cpa->fuv);
2335         mul_v3_fl(child->co, radius);
2336
2337         child->co[0] *= flat;
2338
2339         copy_v3_v3(child->vel, par->vel);
2340
2341         if (par_rot) {
2342                 mul_qt_v3(par_rot, child->co);
2343                 copy_qt_qt(child->rot, par_rot);
2344         }
2345         else
2346                 unit_qt(child->rot);
2347
2348         add_v3_v3(child->co, par->co);
2349 }
2350 float *psys_cache_vgroup(DerivedMesh *dm, ParticleSystem *psys, int vgroup)
2351 {
2352         float *vg = 0;
2353
2354         if (vgroup < 0) {
2355                 /* hair dynamics pinning vgroup */
2356
2357         }
2358         else if (psys->vgroup[vgroup]) {
2359                 MDeformVert *dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
2360                 if (dvert) {
2361                         int totvert = dm->getNumVerts(dm), i;
2362                         vg = MEM_callocN(sizeof(float) * totvert, "vg_cache");
2363                         if (psys->vg_neg & (1 << vgroup)) {
2364                                 for (i = 0; i < totvert; i++)
2365                                         vg[i] = 1.0f - defvert_find_weight(&dvert[i], psys->vgroup[vgroup] - 1);
2366                         }
2367                         else {
2368                                 for (i = 0; i < totvert; i++)
2369                                         vg[i] =  defvert_find_weight(&dvert[i], psys->vgroup[vgroup] - 1);
2370                         }
2371                 }
2372         }
2373         return vg;
2374 }
2375 void psys_find_parents(ParticleSimulationData *sim)
2376 {
2377         ParticleSettings *part = sim->psys->part;
2378         KDTree *tree;
2379         ChildParticle *cpa;
2380         int p, totparent, totchild = sim->psys->totchild;
2381         float co[3], orco[3];
2382         int from = PART_FROM_FACE;
2383         totparent = (int)(totchild * part->parents * 0.3f);
2384
2385         if ((sim->psys->renderdata || G.is_rendering) && part->child_nbr && part->ren_child_nbr)
2386                 totparent *= (float)part->child_nbr / (float)part->ren_child_nbr;
2387
2388         tree = BLI_kdtree_new(totparent);
2389
2390         for (p = 0, cpa = sim->psys->child; p < totparent; p++, cpa++) {
2391                 psys_particle_on_emitter(sim->psmd, from, cpa->num, DMCACHE_ISCHILD, cpa->fuv, cpa->foffset, co, 0, 0, 0, orco, 0);
2392                 BLI_kdtree_insert(tree, p, orco, NULL);
2393         }
2394
2395         BLI_kdtree_balance(tree);
2396
2397         for (; p < totchild; p++, cpa++) {
2398                 psys_particle_on_emitter(sim->psmd, from, cpa->num, DMCACHE_ISCHILD, cpa->fuv, cpa->foffset, co, 0, 0, 0, orco, 0);
2399                 cpa->parent = BLI_kdtree_find_nearest(tree, orco, NULL, NULL);
2400         }
2401
2402         BLI_kdtree_free(tree);
2403 }
2404
2405 static void get_strand_normal(Material *ma, const float surfnor[3], float surfdist, float nor[3])
2406 {
2407         float cross[3], nstrand[3], vnor[3], blend;
2408
2409         if (!((ma->mode & MA_STR_SURFDIFF) || (ma->strand_surfnor > 0.0f)))
2410                 return;
2411
2412         if (ma->mode & MA_STR_SURFDIFF) {
2413                 cross_v3_v3v3(cross, surfnor, nor);
2414                 cross_v3_v3v3(nstrand, nor, cross);
2415
2416                 blend = dot_v3v3(nstrand, surfnor);
2417                 CLAMP(blend, 0.0f, 1.0f);
2418
2419                 interp_v3_v3v3(vnor, nstrand, surfnor, blend);
2420                 normalize_v3(vnor);
2421         }
2422         else {
2423                 copy_v3_v3(vnor, nor);
2424         }
2425         
2426         if (ma->strand_surfnor > 0.0f) {
2427                 if (ma->strand_surfnor > surfdist) {
2428                         blend = (ma->strand_surfnor - surfdist) / ma->strand_surfnor;
2429                         interp_v3_v3v3(vnor, vnor, surfnor, blend);
2430                         normalize_v3(vnor);
2431                 }
2432         }
2433
2434         copy_v3_v3(nor, vnor);
2435 }
2436
2437 static int psys_threads_init_path(ParticleThread *threads, Scene *scene, float cfra, int editupdate)
2438 {
2439         ParticleThreadContext *ctx = threads[0].ctx;
2440 /*      Object *ob = ctx->sim.ob; */
2441         ParticleSystem *psys = ctx->sim.psys;
2442         ParticleSettings *part = psys->part;
2443 /*      ParticleEditSettings *pset = &scene->toolsettings->particle; */
2444         int totparent = 0, between = 0;
2445         int steps = (int)pow(2.0, (double)part->draw_step);
2446         int totchild = psys->totchild;
2447         int i, seed, totthread = threads[0].tot;
2448
2449         /*---start figuring out what is actually wanted---*/
2450         if (psys_in_edit_mode(scene, psys)) {
2451                 ParticleEditSettings *pset = &scene->toolsettings->particle;
2452
2453                 if (psys->renderdata == 0 && (psys->edit == NULL || pset->flag & PE_DRAW_PART) == 0)
2454                         totchild = 0;
2455
2456                 steps = (int)pow(2.0, (double)pset->draw_step);
2457         }
2458
2459         if (totchild && part->childtype == PART_CHILD_FACES) {
2460                 totparent = (int)(totchild * part->parents * 0.3f);
2461                 
2462                 if ((psys->renderdata || G.is_rendering) && part->child_nbr && part->ren_child_nbr)
2463                         totparent *= (float)part->child_nbr / (float)part->ren_child_nbr;
2464
2465                 /* part->parents could still be 0 so we can't test with totparent */
2466                 between = 1;
2467         }
2468
2469         if (psys->renderdata)
2470                 steps = (int)pow(2.0, (double)part->ren_step);
2471         else {
2472                 totchild = (int)((float)totchild * (float)part->disp / 100.0f);
2473                 totparent = MIN2(totparent, totchild);
2474         }
2475
2476         if (totchild == 0) return 0;
2477
2478         /* init random number generator */
2479         seed = 31415926 + ctx->sim.psys->seed;
2480         
2481         if (ctx->editupdate || totchild < 10000)
2482                 totthread = 1;
2483         
2484         for (i = 0; i < totthread; i++) {
2485                 threads[i].rng_path = BLI_rng_new(seed);
2486                 threads[i].tot = totthread;
2487         }
2488
2489         /* fill context values */
2490         ctx->between = between;
2491         ctx->steps = steps;
2492         ctx->totchild = totchild;
2493         ctx->totparent = totparent;
2494         ctx->parent_pass = 0;
2495         ctx->cfra = cfra;
2496         ctx->editupdate = editupdate;
2497
2498         psys->lattice = psys_get_lattice(&ctx->sim);
2499
2500         /* cache all relevant vertex groups if they exist */
2501         ctx->vg_length = psys_cache_vgroup(ctx->dm, psys, PSYS_VG_LENGTH);
2502         ctx->vg_clump = psys_cache_vgroup(ctx->dm, psys, PSYS_VG_CLUMP);
2503         ctx->vg_kink = psys_cache_vgroup(ctx->dm, psys, PSYS_VG_KINK);
2504         ctx->vg_rough1 = psys_cache_vgroup(ctx->dm, psys, PSYS_VG_ROUGH1);
2505         ctx->vg_rough2 = psys_cache_vgroup(ctx->dm, psys, PSYS_VG_ROUGH2);
2506         ctx->vg_roughe = psys_cache_vgroup(ctx->dm, psys, PSYS_VG_ROUGHE);
2507         if (psys->part->flag & PART_CHILD_EFFECT)
2508                 ctx->vg_effector = psys_cache_vgroup(ctx->dm, psys, PSYS_VG_EFFECTOR);
2509
2510         /* set correct ipo timing */
2511 #if 0 // XXX old animation system
2512         if (part->flag & PART_ABS_TIME && part->ipo) {
2513                 calc_ipo(part->ipo, cfra);
2514                 execute_ipo((ID *)part, part->ipo);
2515         }
2516 #endif // XXX old animation system
2517
2518         return 1;
2519 }
2520
2521 /* note: this function must be thread safe, except for branching! */
2522 static void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa, ParticleCacheKey *child_keys, int i)
2523 {
2524         ParticleThreadContext *ctx = thread->ctx;
2525         Object *ob = ctx->sim.ob;
2526         ParticleSystem *psys = ctx->sim.psys;
2527         ParticleSettings *part = psys->part;
2528         ParticleCacheKey **cache = psys->childcache;
2529         ParticleCacheKey **pcache = psys_in_edit_mode(ctx->sim.scene, psys) ? psys->edit->pathcache : psys->pathcache;
2530         ParticleCacheKey *child, *par = NULL, *key[4];
2531         ParticleTexture ptex;
2532         float *cpa_fuv = 0, *par_rot = 0, rot[4];
2533         float orco[3], ornor[3], hairmat[4][4], t, dvec[3], off1[4][3], off2[4][3];
2534         float length, max_length = 1.0f, cur_length = 0.0f;
2535         float eff_length, eff_vec[3], weight[4];
2536         int k, cpa_num;
2537         short cpa_from;
2538
2539         if (!pcache)
2540                 return;
2541
2542         if (ctx->between) {
2543                 ParticleData *pa = psys->particles + cpa->pa[0];
2544                 int w, needupdate;
2545                 float foffset, wsum = 0.f;
2546                 float co[3];
2547                 float p_min = part->parting_min;
2548                 float p_max = part->parting_max;
2549                 /* Virtual parents don't work nicely with parting. */
2550                 float p_fac = part->parents > 0.f ? 0.f : part->parting_fac;
2551
2552                 if (ctx->editupdate) {
2553                         needupdate = 0;
2554                         w = 0;
2555                         while (w < 4 && cpa->pa[w] >= 0) {
2556                                 if (psys->edit->points[cpa->pa[w]].flag & PEP_EDIT_RECALC) {
2557                                         needupdate = 1;
2558                                         break;
2559                                 }
2560                                 w++;
2561                         }
2562
2563                         if (!needupdate)
2564                                 return;
2565                         else
2566                                 memset(child_keys, 0, sizeof(*child_keys) * (ctx->steps + 1));
2567                 }
2568
2569                 /* get parent paths */
2570                 for (w = 0; w < 4; w++) {
2571                         if (cpa->pa[w] >= 0) {
2572                                 key[w] = pcache[cpa->pa[w]];
2573                                 weight[w] = cpa->w[w];
2574                         }
2575                         else {
2576                                 key[w] = pcache[0];
2577                                 weight[w] = 0.f;
2578                         }
2579                 }
2580
2581                 /* modify weights to create parting */
2582                 if (p_fac > 0.f) {
2583                         for (w = 0; w < 4; w++) {
2584                                 if (w && weight[w] > 0.f) {
2585                                         float d;
2586                                         if (part->flag & PART_CHILD_LONG_HAIR) {
2587                                                 /* For long hair use tip distance/root distance as parting factor instead of root to tip angle. */
2588                                                 float d1 = len_v3v3(key[0]->co, key[w]->co);
2589                                                 float d2 = len_v3v3((key[0] + key[0]->steps - 1)->co, (key[w] + key[w]->steps - 1)->co);
2590
2591                                                 d = d1 > 0.f ? d2 / d1 - 1.f : 10000.f;
2592                                         }
2593                                         else {
2594                                                 float v1[3], v2[3];
2595                                                 sub_v3_v3v3(v1, (key[0] + key[0]->steps - 1)->co, key[0]->co);
2596                                                 sub_v3_v3v3(v2, (key[w] + key[w]->steps - 1)->co, key[w]->co);
2597                                                 normalize_v3(v1);
2598                                                 normalize_v3(v2);
2599
2600                                                 d = RAD2DEGF(saacos(dot_v3v3(v1, v2)));
2601                                         }
2602
2603                                         if (p_max > p_min)
2604                                                 d = (d - p_min) / (p_max - p_min);
2605                                         else
2606                                                 d = (d - p_min) <= 0.f ? 0.f : 1.f;
2607
2608                                         CLAMP(d, 0.f, 1.f);
2609
2610                                         if (d > 0.f)
2611                                                 weight[w] *= (1.f - d);
2612                                 }
2613                                 wsum += weight[w];
2614                         }
2615                         for (w = 0; w < 4; w++)
2616                                 weight[w] /= wsum;
2617
2618                         interp_v4_v4v4(weight, cpa->w, weight, p_fac);
2619                 }
2620
2621                 /* get the original coordinates (orco) for texture usage */
2622                 cpa_num = cpa->num;
2623                 
2624                 foffset = cpa->foffset;
2625                 cpa_fuv = cpa->fuv;
2626                 cpa_from = PART_FROM_FACE;
2627
2628                 psys_particle_on_emitter(ctx->sim.psmd, cpa_from, cpa_num, DMCACHE_ISCHILD, cpa->fuv, foffset, co, ornor, 0, 0, orco, 0);
2629
2630                 mul_m4_v3(ob->obmat, co);
2631
2632                 for (w = 0; w < 4; w++)
2633                         sub_v3_v3v3(off1[w], co, key[w]->co);
2634
2635                 psys_mat_hair_to_global(ob, ctx->sim.psmd->dm, psys->part->from, pa, hairmat);
2636         }
2637         else {
2638                 ParticleData *pa = psys->particles + cpa->parent;
2639                 float co[3];
2640                 if (ctx->editupdate) {
2641                         if (!(psys->edit->points[cpa->parent].flag & PEP_EDIT_RECALC))
2642                                 return;
2643
2644                         memset(child_keys, 0, sizeof(*child_keys) * (ctx->steps + 1));
2645                 }
2646
2647                 /* get the parent path */
2648                 key[0] = pcache[cpa->parent];
2649
2650                 /* get the original coordinates (orco) for texture usage */
2651                 cpa_from = part->from;
2652                 cpa_num = pa->num;
2653                 cpa_fuv = pa->fuv;
2654
2655                 psys_particle_on_emitter(ctx->sim.psmd, cpa_from, cpa_num, DMCACHE_ISCHILD, cpa_fuv, pa->foffset, co, ornor, 0, 0, orco, 0);
2656
2657                 psys_mat_hair_to_global(ob, ctx->sim.psmd->dm, psys->part->from, pa, hairmat);
2658         }
2659
2660         child_keys->steps = ctx->steps;
2661
2662         /* get different child parameters from textures & vgroups */
2663         get_child_modifier_parameters(part, ctx, cpa, cpa_from, cpa_num, cpa_fuv, orco, &ptex);
2664
2665         if (ptex.exist < PSYS_FRAND(i + 24)) {
2666                 child_keys->steps = -1;
2667                 return;
2668         }
2669
2670         /* create the child path */
2671         for (k = 0, child = child_keys; k <= ctx->steps; k++, child++) {
2672                 if (ctx->between) {
2673                         int w = 0;
2674
2675                         zero_v3(child->co);
2676                         zero_v3(child->vel);
2677                         unit_qt(child->rot);
2678
2679                         for (w = 0; w < 4; w++) {
2680                                 copy_v3_v3(off2[w], off1[w]);
2681
2682                                 if (part->flag & PART_CHILD_LONG_HAIR) {
2683                                         /* Use parent rotation (in addition to emission location) to determine child offset. */
2684                                         if (k)
2685                                                 mul_qt_v3((key[w] + k)->rot, off2[w]);
2686
2687                                         /* Fade the effect of rotation for even lengths in the end */
2688                                         project_v3_v3v3(dvec, off2[w], (key[w] + k)->vel);
2689                                         madd_v3_v3fl(off2[w], dvec, -(float)k / (float)ctx->steps);
2690                                 }
2691
2692                                 add_v3_v3(off2[w], (key[w] + k)->co);
2693                         }
2694
2695                         /* child position is the weighted sum of parent positions */
2696                         interp_v3_v3v3v3v3(child->co, off2[0], off2[1], off2[2], off2[3], weight);
2697                         interp_v3_v3v3v3v3(child->vel, (key[0] + k)->vel, (key[1] + k)->vel, (key[2] + k)->vel, (key[3] + k)->vel, weight);
2698
2699                         copy_qt_qt(child->rot, (key[0] + k)->rot);
2700                 }
2701                 else {
2702                         if (k) {
2703                                 mul_qt_qtqt(rot, (key[0] + k)->rot, key[0]->rot);
2704                                 par_rot = rot;
2705                         }
2706                         else {
2707                                 par_rot = key[0]->rot;
2708                         }
2709                         /* offset the child from the parent position */
2710                         offset_child(cpa, (ParticleKey *)(key[0] + k), par_rot, (ParticleKey *)child, part->childflat, part->childrad);
2711                 }
2712
2713                 child->time = (float)k / (float)ctx->steps;
2714         }
2715
2716         /* apply effectors */
2717         if (part->flag & PART_CHILD_EFFECT) {
2718                 for (k = 0, child = child_keys; k <= ctx->steps; k++, child++) {
2719                         if (k) {
2720                                 do_path_effectors(&ctx->sim, cpa->pa[0], child, k, ctx->steps, child_keys->co, ptex.effector, 0.0f, ctx->cfra, &eff_length, eff_vec);
2721                         }
2722                         else {
2723                                 sub_v3_v3v3(eff_vec, (child + 1)->co, child->co);
2724                                 eff_length = len_v3(eff_vec);
2725                         }
2726                 }
2727         }
2728
2729         for (k = 0, child = child_keys; k <= ctx->steps; k++, child++) {
2730                 t = (float)k / (float)ctx->steps;
2731
2732                 if (ctx->totparent)
2733                         /* this is now threadsafe, virtual parents are calculated before rest of children */
2734                         par = (i >= ctx->totparent) ? cache[cpa->parent] : NULL;
2735                 else if (cpa->parent >= 0)
2736                         par = pcache[cpa->parent];
2737
2738                 if (par) {
2739                         if (k) {
2740                                 mul_qt_qtqt(rot, (par + k)->rot, par->rot);
2741                                 par_rot = rot;
2742                         }
2743                         else {
2744                                 par_rot = par->rot;
2745                         }
2746                         par += k;
2747                 }
2748
2749                 /* apply different deformations to the child path */
2750                 do_child_modifiers(&ctx->sim, &ptex, (ParticleKey *)par, par_rot, cpa, orco, hairmat, (ParticleKey *)child, t);
2751
2752                 /* we have to correct velocity because of kink & clump */
2753                 if (k > 1) {
2754                         sub_v3_v3v3((child - 1)->vel, child->co, (child - 2)->co);
2755                         mul_v3_fl((child - 1)->vel, 0.5);
2756
2757                         if (ctx->ma && (part->draw_col == PART_DRAW_COL_MAT))
2758                                 get_strand_normal(ctx->ma, ornor, cur_length, (child - 1)->vel);
2759                 }
2760
2761                 if (k == ctx->steps)
2762                         sub_v3_v3v3(child->vel, child->co, (child - 1)->co);
2763
2764                 /* check if path needs to be cut before actual end of data points */
2765                 if (k) {
2766                         sub_v3_v3v3(dvec, child->co, (child - 1)->co);
2767                         length = 1.0f / (float)ctx->steps;
2768                         k = check_path_length(k, child_keys, child, max_length, &cur_length, length, dvec);
2769                 }
2770                 else {
2771                         /* initialize length calculation */
2772                         max_length = ptex.length;
2773                         cur_length = 0.0f;
2774                 }
2775
2776                 if (ctx->ma && (part->draw_col == PART_DRAW_COL_MAT)) {
2777                         copy_v3_v3(child->col, &ctx->ma->r);
2778                         get_strand_normal(ctx->ma, ornor, cur_length, child->vel);
2779                 }
2780         }
2781
2782         /* Hide virtual parents */
2783         if (i < ctx->totparent)
2784                 child_keys->steps = -1;
2785 }
2786
2787 static void *exec_child_path_cache(void *data)
2788 {
2789         ParticleThread *thread = (ParticleThread *)data;
2790         ParticleThreadContext *ctx = thread->ctx;
2791         ParticleSystem *psys = ctx->sim.psys;
2792         ParticleCacheKey **cache = psys->childcache;
2793         ChildParticle *cpa;
2794         int i, totchild = ctx->totchild, first = 0;
2795
2796         if (thread->tot > 1) {
2797                 first = ctx->parent_pass ? 0 : ctx->totparent;
2798                 totchild = ctx->parent_pass ? ctx->totparent : ctx->totchild;
2799         }
2800         
2801         cpa = psys->child + first + thread->num;
2802         for (i = first + thread->num; i < totchild; i += thread->tot, cpa += thread->tot)
2803                 psys_thread_create_path(thread, cpa, cache[i], i);
2804
2805         return 0;
2806 }
2807
2808 void psys_cache_child_paths(ParticleSimulationData *sim, float cfra, int editupdate)
2809 {
2810         ParticleThread *pthreads;
2811         ParticleThreadContext *ctx;
2812         ListBase threads;
2813         int i, totchild, totparent, totthread;
2814
2815         if (sim->psys->flag & PSYS_GLOBAL_HAIR)
2816                 return;
2817
2818         pthreads = psys_threads_create(sim);
2819
2820         if (!psys_threads_init_path(pthreads, sim->scene, cfra, editupdate)) {
2821                 psys_threads_free(pthreads);
2822                 return;
2823         }
2824
2825         ctx = pthreads[0].ctx;
2826         totchild = ctx->totchild;
2827         totparent = ctx->totparent;
2828
2829         if (editupdate && sim->psys->childcache && totchild == sim->psys->totchildcache) {
2830                 ; /* just overwrite the existing cache */
2831         }
2832         else {
2833                 /* clear out old and create new empty path cache */
2834                 free_child_path_cache(sim->psys);
2835                 sim->psys->childcache = psys_alloc_path_cache_buffers(&sim->psys->childcachebufs, totchild, ctx->steps + 1);
2836                 sim->psys->totchildcache = totchild;
2837         }
2838
2839         totthread = pthreads[0].tot;
2840
2841         if (totthread > 1) {
2842
2843                 /* make virtual child parents thread safe by calculating them first */
2844                 if (totparent) {
2845                         BLI_init_threads(&threads, exec_child_path_cache, totthread);
2846                         
2847                         for (i = 0; i < totthread; i++) {
2848                                 pthreads[i].ctx->parent_pass = 1;
2849                                 BLI_insert_thread(&threads, &pthreads[i]);
2850                         }
2851
2852                         BLI_end_threads(&threads);
2853
2854                         for (i = 0; i < totthread; i++)
2855                                 pthreads[i].ctx->parent_pass = 0;
2856                 }
2857
2858                 BLI_init_threads(&threads, exec_child_path_cache, totthread);
2859
2860                 for (i = 0; i < totthread; i++)
2861                         BLI_insert_thread(&threads, &pthreads[i]);
2862
2863                 BLI_end_threads(&threads);
2864         }
2865         else
2866                 exec_child_path_cache(&pthreads[0]);
2867
2868         psys_threads_free(pthreads);
2869 }
2870 /* figure out incremental rotations along path starting from unit quat */
2871 static void cache_key_incremental_rotation(ParticleCacheKey *key0, ParticleCacheKey *key1, ParticleCacheKey *key2, float *prev_tangent, int i)
2872 {
2873         float cosangle, angle, tangent[3], normal[3], q[4];
2874
2875         switch (i) {
2876                 case 0:
2877                         /* start from second key */
2878                         break;
2879                 case 1:
2880                         /* calculate initial tangent for incremental rotations */
2881                         sub_v3_v3v3(prev_tangent, key0->co, key1->co);
2882                         normalize_v3(prev_tangent);
2883                         unit_qt(key1->rot);
2884                         break;
2885                 default:
2886                         sub_v3_v3v3(tangent, key0->co, key1->co);
2887                         normalize_v3(tangent);
2888
2889                         cosangle = dot_v3v3(tangent, prev_tangent);
2890
2891                         /* note we do the comparison on cosangle instead of
2892                          * angle, since floating point accuracy makes it give
2893                          * different results across platforms */
2894                         if (cosangle > 0.999999f) {
2895                                 copy_v4_v4(key1->rot, key2->rot);
2896                         }
2897                         else {
2898                                 angle = saacos(cosangle);
2899                                 cross_v3_v3v3(normal, prev_tangent, tangent);
2900                                 axis_angle_to_quat(q, normal, angle);
2901                                 mul_qt_qtqt(key1->rot, q, key2->rot);
2902                         }
2903
2904                         copy_v3_v3(prev_tangent, tangent);
2905         }
2906 }
2907
2908 /**
2909  * Calculates paths ready for drawing/rendering
2910  * - Useful for making use of opengl vertex arrays for super fast strand drawing.
2911  * - Makes child strands possible and creates them too into the cache.
2912  * - Cached path data is also used to determine cut position for the editmode tool. */
2913 void psys_cache_paths(ParticleSimulationData *sim, float cfra)
2914 {
2915         PARTICLE_PSMD;
2916         ParticleEditSettings *pset = &sim->scene->toolsettings->particle;
2917         ParticleSystem *psys = sim->psys;
2918         ParticleSettings *part = psys->part;
2919         ParticleCacheKey *ca, **cache;
2920
2921         DerivedMesh *hair_dm = (psys->part->type == PART_HAIR && psys->flag & PSYS_HAIR_DYNAMICS) ? psys->hair_out_dm : NULL;
2922         
2923         ParticleKey result;
2924         
2925         Material *ma;
2926         ParticleInterpolationData pind;
2927         ParticleTexture ptex;
2928
2929         PARTICLE_P;
2930         
2931         float birthtime = 0.0, dietime = 0.0;
2932         float t, time = 0.0, dfra = 1.0 /* , frs_sec = sim->scene->r.frs_sec*/ /*UNUSED*/;
2933         float col[4] = {0.5f, 0.5f, 0.5f, 1.0f};
2934         float prev_tangent[3] = {0.0f, 0.0f, 0.0f}, hairmat[4][4];
2935         float rotmat[3][3];
2936         int k;
2937         int steps = (int)pow(2.0, (double)(psys->renderdata ? part->ren_step : part->draw_step));
2938         int totpart = psys->totpart;
2939         float length, vec[3];
2940         float *vg_effector = NULL;
2941         float *vg_length = NULL, pa_length = 1.0f;
2942         int keyed, baked;
2943
2944         /* we don't have anything valid to create paths from so let's quit here */
2945         if ((psys->flag & PSYS_HAIR_DONE || psys->flag & PSYS_KEYED || psys->pointcache) == 0)
2946                 return;
2947
2948         if (psys_in_edit_mode(sim->scene, psys))
2949                 if (psys->renderdata == 0 && (psys->edit == NULL || pset->flag & PE_DRAW_PART) == 0)
2950                         return;
2951
2952         keyed = psys->flag & PSYS_KEYED;
2953         baked = psys->pointcache->mem_cache.first && psys->part->type != PART_HAIR;
2954
2955         /* clear out old and create new empty path cache */
2956         psys_free_path_cache(psys, psys->edit);
2957         cache = psys->pathcache = psys_alloc_path_cache_buffers(&psys->pathcachebufs, totpart, steps + 1);
2958
2959         psys->lattice = psys_get_lattice(sim);
2960         ma = give_current_material(sim->ob, psys->part->omat);
2961         if (ma && (psys->part->draw_col == PART_DRAW_COL_MAT))
2962                 copy_v3_v3(col, &ma->r);
2963
2964         if ((psys->flag & PSYS_GLOBAL_HAIR) == 0) {
2965                 if ((psys->part->flag & PART_CHILD_EFFECT) == 0)
2966                         vg_effector = psys_cache_vgroup(psmd->dm, psys, PSYS_VG_EFFECTOR);
2967                 
2968                 if (!psys->totchild)
2969                         vg_length = psys_cache_vgroup(psmd->dm, psys, PSYS_VG_LENGTH);
2970         }
2971
2972         /* ensure we have tessfaces to be used for mapping */
2973         if (part->from != PART_FROM_VERT) {
2974                 DM_ensure_tessface(psmd->dm);
2975         }
2976
2977         /*---first main loop: create all actual particles' paths---*/
2978         LOOP_SHOWN_PARTICLES {
2979                 if (!psys->totchild) {
2980                         psys_get_texture(sim, pa, &ptex, PAMAP_LENGTH, 0.f);
2981                         pa_length = ptex.length * (1.0f - part->randlength * PSYS_FRAND(psys->seed + p));
2982                         if (vg_length)
2983                                 pa_length *= psys_particle_value_from_verts(psmd->dm, part->from, pa, vg_length);
2984                 }
2985
2986                 pind.keyed = keyed;
2987                 pind.cache = baked ? psys->pointcache : NULL;
2988                 pind.epoint = NULL;
2989                 pind.bspline = (psys->part->flag & PART_HAIR_BSPLINE);
2990                 pind.dm = hair_dm;
2991
2992                 memset(cache[p], 0, sizeof(*cache[p]) * (steps + 1));
2993
2994                 cache[p]->steps = steps;
2995
2996                 /*--get the first data points--*/
2997                 init_particle_interpolation(sim->ob, sim->psys, pa, &pind);
2998
2999                 /* hairmat is needed for for non-hair particle too so we get proper rotations */
3000                 psys_mat_hair_to_global(sim->ob, psmd->dm, psys->part->from, pa, hairmat);
3001                 copy_v3_v3(rotmat[0], hairmat[2]);
3002                 copy_v3_v3(rotmat[1], hairmat[1]);
3003                 copy_v3_v3(rotmat[2], hairmat[0]);
3004
3005                 if (part->draw & PART_ABS_PATH_TIME) {
3006                         birthtime = MAX2(pind.birthtime, part->path_start);
3007                         dietime = MIN2(pind.dietime, part->path_end);
3008                 }
3009                 else {
3010                         float tb = pind.birthtime;
3011                         birthtime = tb + part->path_start * (pind.dietime - tb);
3012                         dietime = tb + part->path_end * (pind.dietime - tb);
3013                 }
3014
3015                 if (birthtime >= dietime) {
3016                         cache[p]->steps = -1;
3017                         continue;
3018                 }
3019
3020                 dietime = birthtime + pa_length * (dietime - birthtime);
3021
3022                 /*--interpolate actual path from data points--*/
3023                 for (k = 0, ca = cache[p]; k <= steps; k++, ca++) {
3024                         time = (float)k / (float)steps;
3025                         t = birthtime + time * (dietime - birthtime);
3026                         result.time = -t;
3027                         do_particle_interpolation(psys, p, pa, t, &pind, &result);
3028                         copy_v3_v3(ca->co, result.co);
3029
3030                         /* dynamic hair is in object space */
3031                         /* keyed and baked are already in global space */
3032                         if (hair_dm)
3033                                 mul_m4_v3(sim->ob->obmat, ca->co);
3034                         else if (!keyed && !baked && !(psys->flag & PSYS_GLOBAL_HAIR))
3035                                 mul_m4_v3(hairmat, ca->co);
3036
3037                         copy_v3_v3(ca->col, col);
3038                 }
3039                 
3040                 /*--modify paths and calculate rotation & velocity--*/
3041
3042                 if (!(psys->flag & PSYS_GLOBAL_HAIR)) {
3043                         /* apply effectors */
3044                         if ((psys->part->flag & PART_CHILD_EFFECT) == 0) {
3045                                 float effector = 1.0f;
3046                                 if (vg_effector)
3047                                         effector *= psys_particle_value_from_verts(psmd->dm, psys->part->from, pa, vg_effector);
3048
3049                                 sub_v3_v3v3(vec, (cache[p] + 1)->co, cache[p]->co);
3050                                 length = len_v3(vec);
3051
3052                                 for (k = 1, ca = cache[p] + 1; k <= steps; k++, ca++)
3053                                         do_path_effectors(sim, p, ca, k, steps, cache[p]->co, effector, dfra, cfra, &length, vec);
3054                         }
3055
3056                         /* apply guide curves to path data */
3057                         if (sim->psys->effectors && (psys->part->flag & PART_CHILD_EFFECT) == 0) {
3058                                 for (k = 0, ca = cache[p]; k <= steps; k++, ca++)
3059                                         /* ca is safe to cast, since only co and vel are used */
3060                                         do_guides(sim->psys->effectors, (ParticleKey *)ca, p, (float)k / (float)steps);
3061                         }
3062
3063                         /* lattices have to be calculated separately to avoid mixups between effector calculations */
3064                         if (psys->lattice) {
3065                                 for (k = 0, ca = cache[p]; k <= steps; k++, ca++)
3066                                         calc_latt_deform(psys->lattice, ca->co, 1.0f);
3067                         }
3068                 }
3069
3070                 /* finally do rotation & velocity */
3071                 for (k = 1, ca = cache[p] + 1; k <= steps; k++, ca++) {
3072                         cache_key_incremental_rotation(ca, ca - 1, ca - 2, prev_tangent, k);
3073
3074                         if (k == steps)
3075                                 copy_qt_qt(ca->rot, (ca - 1)->rot);
3076
3077                         /* set velocity */
3078                         sub_v3_v3v3(ca->vel, ca->co, (ca - 1)->co);
3079
3080                         if (k == 1)
3081                                 copy_v3_v3((ca - 1)->vel, ca->vel);
3082
3083                         ca->time = (float)k / (float)steps;
3084                 }
3085                 /* First rotation is based on emitting face orientation.
3086                  * This is way better than having flipping rotations resulting
3087                  * from using a global axis as a rotation pole (vec_to_quat()).
3088                  * It's not an ideal solution though since it disregards the
3089                  * initial tangent, but taking that in to account will allow
3090                  * the possibility of flipping again. -jahka
3091                  */
3092                 mat3_to_quat_is_ok(cache[p]->rot, rotmat);
3093         }
3094
3095         psys->totcached = totpart;
3096
3097         if (psys->lattice) {
3098                 end_latt_deform(psys->lattice);
3099                 psys->lattice = NULL;
3100         }
3101
3102         if (vg_effector)
3103                 MEM_freeN(vg_effector);
3104
3105         if (vg_length)
3106                 MEM_freeN(vg_length);
3107 }
3108 void psys_cache_edit_paths(Scene *scene, Object *ob, PTCacheEdit *edit, float cfra)
3109 {
3110         ParticleCacheKey *ca, **cache = edit->pathcache;
3111         ParticleEditSettings *pset = &scene->toolsettings->particle;
3112         
3113         PTCacheEditPoint *point = NULL;
3114         PTCacheEditKey *ekey = NULL;
3115
3116         ParticleSystem *psys = edit->psys;
3117         ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys);
3118         ParticleData *pa = psys ? psys->particles : NULL;
3119
3120         ParticleInterpolationData pind;
3121         ParticleKey result;
3122         
3123         float birthtime = 0.0f, dietime = 0.0f;
3124         float t, time = 0.0f, keytime = 0.0f /*, frs_sec */;
3125         float hairmat[4][4], rotmat[3][3], prev_tangent[3] = {0.0f, 0.0f, 0.0f};
3126         int k, i;
3127         int steps = (int)pow(2.0, (double)pset->draw_step);
3128         int totpart = edit->totpoint, recalc_set = 0;
3129         float sel_col[3];
3130         float nosel_col[3];
3131
3132         steps = MAX2(steps, 4);
3133
3134         if (!cache || edit->totpoint != edit->totcached) {
3135                 /* clear out old and create new empty path cache */
3136                 psys_free_path_cache(edit->psys, edit);
3137                 cache = edit->pathcache = psys_alloc_path_cache_buffers(&edit->pathcachebufs, totpart, steps + 1);
3138
3139                 /* set flag for update (child particles check this too) */
3140                 for (i = 0, point = edit->points; i < totpart; i++, point++)
3141                         point->flag |= PEP_EDIT_RECALC;
3142                 recalc_set = 1;
3143         }
3144
3145         /* frs_sec = (psys || edit->pid.flag & PTCACHE_VEL_PER_SEC) ? 25.0f : 1.0f; */ /* UNUSED */