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