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