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