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