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