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