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