commit before doing some hefty shapekey change, will break compilation
[blender-staging.git] / source / blender / blenkernel / intern / particle.c
1 /* particle.c
2  *
3  *
4  * $Id$
5  *
6  * ***** BEGIN GPL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, 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_scene_types.h"
39 #include "DNA_boid_types.h"
40 #include "DNA_group_types.h"
41 #include "DNA_particle_types.h"
42 #include "DNA_mesh_types.h"
43 #include "DNA_meshdata_types.h"
44 #include "DNA_modifier_types.h"
45 #include "DNA_object_force.h"
46 #include "DNA_texture_types.h"
47 #include "DNA_material_types.h"
48 #include "DNA_object_types.h"
49 #include "DNA_curve_types.h"
50 #include "DNA_key_types.h"
51 #include "DNA_ipo_types.h"      // XXX old animation system stuff to remove!
52
53 #include "BLI_arithb.h"
54 #include "BLI_blenlib.h"
55 #include "BLI_dynstr.h"
56 #include "BLI_kdtree.h"
57 #include "BLI_listbase.h"
58 #include "BLI_rand.h"
59 #include "BLI_threads.h"
60 #include "BLI_cellalloc.h"
61
62 #include "BKE_anim.h"
63
64 #include "BKE_boids.h"
65 #include "BKE_cloth.h"
66 #include "BKE_effect.h"
67 #include "BKE_global.h"
68 #include "BKE_group.h"
69 #include "BKE_main.h"
70 #include "BKE_lattice.h"
71 #include "BKE_utildefines.h"
72 #include "BKE_displist.h"
73 #include "BKE_particle.h"
74 #include "BKE_DerivedMesh.h"
75 #include "BKE_object.h"
76 #include "BKE_cloth.h"
77 #include "BKE_material.h"
78 #include "BKE_key.h"
79 #include "BKE_library.h"
80 #include "BKE_depsgraph.h"
81 #include "BKE_modifier.h"
82 #include "BKE_mesh.h"
83 #include "BKE_cdderivedmesh.h"
84 #include "BKE_pointcache.h"
85
86 #include "RE_render_ext.h"
87
88 static void get_cpa_texture(DerivedMesh *dm, Material *ma, int face_index,
89                                 float *fuv, float *orco, ParticleTexture *ptex, int event);
90 static void get_child_modifier_parameters(ParticleSettings *part, ParticleThreadContext *ctx,
91                                 ChildParticle *cpa, short cpa_from, int cpa_num, float *cpa_fuv, float *orco, ParticleTexture *ptex);
92 static void do_child_modifiers(ParticleSimulationData *sim,
93                                 ParticleTexture *ptex, ParticleKey *par, float *par_rot, ChildParticle *cpa,
94                                 float *orco, float mat[4][4], ParticleKey *state, float t);
95
96 /* few helpers for countall etc. */
97 int count_particles(ParticleSystem *psys){
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 tot++;
106         }
107         return tot;
108 }
109 int count_particles_mod(ParticleSystem *psys, int totgr, int cur){
110         ParticleSettings *part=psys->part;
111         PARTICLE_P;
112         int tot=0;
113
114         LOOP_SHOWN_PARTICLES {
115                 if(pa->alive == PARS_UNBORN && (part->flag & PART_UNBORN)==0);
116                 else if(pa->alive == PARS_DEAD && (part->flag & PART_DIED)==0);
117                 else if(p%totgr==cur) tot++;
118         }
119         return tot;
120 }
121 /* we allocate path cache memory in chunks instead of a big continguous
122  * chunk, windows' memory allocater fails to find big blocks of memory often */
123
124 #define PATH_CACHE_BUF_SIZE 1024
125
126 static ParticleCacheKey **psys_alloc_path_cache_buffers(ListBase *bufs, int tot, int steps)
127 {
128         LinkData *buf;
129         ParticleCacheKey **cache;
130         int i, totkey, totbufkey;
131
132         tot= MAX2(tot, 1);
133         totkey = 0;
134         cache = MEM_callocN(tot*sizeof(void*), "PathCacheArray");
135
136         while(totkey < tot) {
137                 totbufkey= MIN2(tot-totkey, PATH_CACHE_BUF_SIZE);
138                 buf= MEM_callocN(sizeof(LinkData), "PathCacheLinkData");
139                 buf->data= MEM_callocN(sizeof(ParticleCacheKey)*totbufkey*steps, "ParticleCacheKey");
140
141                 for(i=0; i<totbufkey; i++)
142                         cache[totkey+i] = ((ParticleCacheKey*)buf->data) + i*steps;
143
144                 totkey += totbufkey;
145                 BLI_addtail(bufs, buf);
146         }
147
148         return cache;
149 }
150
151 static void psys_free_path_cache_buffers(ParticleCacheKey **cache, ListBase *bufs)
152 {
153         LinkData *buf;
154
155         if(cache)
156                 MEM_freeN(cache);
157
158         for(buf= bufs->first; buf; buf=buf->next)
159                 MEM_freeN(buf->data);
160         BLI_freelistN(bufs);
161 }
162
163 /************************************************/
164 /*                      Getting stuff                                           */
165 /************************************************/
166 /* get object's active particle system safely */
167 ParticleSystem *psys_get_current(Object *ob)
168 {
169         ParticleSystem *psys;
170         if(ob==0) return 0;
171
172         for(psys=ob->particlesystem.first; psys; psys=psys->next){
173                 if(psys->flag & PSYS_CURRENT)
174                         return psys;
175         }
176         
177         return 0;
178 }
179 short psys_get_current_num(Object *ob)
180 {
181         ParticleSystem *psys;
182         short i;
183
184         if(ob==0) return 0;
185
186         for(psys=ob->particlesystem.first, i=0; psys; psys=psys->next, i++)
187                 if(psys->flag & PSYS_CURRENT)
188                         return i;
189         
190         return i;
191 }
192 void psys_set_current_num(Object *ob, int index)
193 {
194         ParticleSystem *psys;
195         short i;
196
197         if(ob==0) return;
198
199         for(psys=ob->particlesystem.first, i=0; psys; psys=psys->next, i++) {
200                 if(i == index)
201                         psys->flag |= PSYS_CURRENT;
202                 else
203                         psys->flag &= ~PSYS_CURRENT;
204         }
205 }
206 Object *psys_find_object(Scene *scene, ParticleSystem *psys)
207 {
208         Base *base = scene->base.first;
209         ParticleSystem *tpsys;
210
211         for(base = scene->base.first; base; base = base->next) {
212                 for(tpsys = base->object->particlesystem.first; psys; psys=psys->next) {
213                         if(tpsys == psys)
214                                 return base->object;
215                 }
216         }
217
218         return NULL;
219 }
220 Object *psys_get_lattice(ParticleSimulationData *sim)
221 {
222         Object *lattice=0;
223         
224         if(psys_in_edit_mode(sim->scene, sim->psys)==0){
225
226                 ModifierData *md = (ModifierData*)psys_get_modifier(sim->ob, sim->psys);
227
228                 for(; md; md=md->next){
229                         if(md->type==eModifierType_Lattice){
230                                 LatticeModifierData *lmd = (LatticeModifierData *)md;
231                                 lattice=lmd->object;
232                                 break;
233                         }
234                 }
235                 if(lattice)
236                         init_latt_deform(lattice,0);
237         }
238
239         return lattice;
240 }
241 void psys_disable_all(Object *ob)
242 {
243         ParticleSystem *psys=ob->particlesystem.first;
244
245         for(; psys; psys=psys->next)
246                 psys->flag |= PSYS_DISABLED;
247 }
248 void psys_enable_all(Object *ob)
249 {
250         ParticleSystem *psys=ob->particlesystem.first;
251
252         for(; psys; psys=psys->next)
253                 psys->flag &= ~PSYS_DISABLED;
254 }
255 int psys_in_edit_mode(Scene *scene, ParticleSystem *psys)
256 {
257         return (scene->basact && (scene->basact->object->mode & OB_MODE_PARTICLE_EDIT) && psys==psys_get_current((scene->basact)->object) && (psys->edit || psys->pointcache->edit));
258 }
259 static void psys_create_frand(ParticleSystem *psys)
260 {
261         int i;
262         float *rand = psys->frand = MEM_callocN(PSYS_FRAND_COUNT * sizeof(float), "particle randoms");
263
264         BLI_srandom(psys->seed);
265
266         for(i=0; i<1024; i++, rand++)
267                 *rand = BLI_frand();
268 }
269 int psys_check_enabled(Object *ob, ParticleSystem *psys)
270 {
271         ParticleSystemModifierData *psmd;
272         Mesh *me;
273
274         if(psys->flag & PSYS_DISABLED || psys->flag & PSYS_DELETE || !psys->part)
275                 return 0;
276
277         if(ob->type == OB_MESH) {
278                 me= (Mesh*)ob->data;
279                 if(me->mr && me->mr->current != 1)
280                         return 0;
281         }
282
283         psmd= psys_get_modifier(ob, psys);
284         if(psys->renderdata) {
285                 if(!(psmd->modifier.mode & eModifierMode_Render))
286                         return 0;
287         }
288         else if(!(psmd->modifier.mode & eModifierMode_Realtime))
289                 return 0;
290
291         /* perhaps not the perfect place, but we have to be sure the rands are there before usage */
292         if(!psys->frand)
293                 psys_create_frand(psys);
294         else if(psys->recalc & PSYS_RECALC_RESET) {
295                 MEM_freeN(psys->frand);
296                 psys_create_frand(psys);
297         }
298         
299         return 1;
300 }
301
302 int psys_check_edited(ParticleSystem *psys)
303 {
304         if(psys->part && psys->part->type==PART_HAIR)
305                 return (psys->flag & PSYS_EDITED || (psys->edit && psys->edit->edited));
306         else
307                 return (psys->pointcache->edit && psys->pointcache->edit->edited);
308 }
309
310 void psys_check_group_weights(ParticleSettings *part)
311 {
312         ParticleDupliWeight *dw, *tdw;
313         GroupObject *go;
314         int current = 0;
315
316         if(part->ren_as == PART_DRAW_GR && part->dup_group && part->dup_group->gobject.first) {
317                 /* first remove all weights that don't have an object in the group */
318                 dw = part->dupliweights.first;
319                 while(dw) {
320                         if(!object_in_group(dw->ob, part->dup_group)) {
321                                 tdw = dw->next;
322                                 BLI_freelinkN(&part->dupliweights, dw);
323                                 dw = tdw;
324                         }
325                         else
326                                 dw = dw->next;
327                 }
328
329                 /* then add objects in the group to new list */
330                 go = part->dup_group->gobject.first;
331                 while(go) {
332                         dw = part->dupliweights.first;
333                         while(dw && dw->ob != go->ob)
334                                 dw = dw->next;
335                         
336                         if(!dw) {
337                                 dw = MEM_callocN(sizeof(ParticleDupliWeight), "ParticleDupliWeight");
338                                 dw->ob = go->ob;
339                                 dw->count = 1;
340                                 BLI_addtail(&part->dupliweights, dw);
341                         }
342
343                         go = go->next;  
344                 }
345
346                 dw = part->dupliweights.first;
347                 for(; dw; dw=dw->next) {
348                         if(dw->flag & PART_DUPLIW_CURRENT) {
349                                 current = 1;
350                                 break;
351                         }
352                 }
353
354                 if(!current) {
355                         dw = part->dupliweights.first;
356                         if(dw)
357                                 dw->flag |= PART_DUPLIW_CURRENT;
358                 }
359         }
360         else {
361                 BLI_freelistN(&part->dupliweights);
362         }
363 }
364 /************************************************/
365 /*                      Freeing stuff                                           */
366 /************************************************/
367 void psys_free_settings(ParticleSettings *part)
368 {
369         free_partdeflect(part->pd);
370         free_partdeflect(part->pd2);
371
372         if(part->effector_weights)
373                 MEM_freeN(part->effector_weights);
374
375         BLI_freelistN(&part->dupliweights);
376
377         boid_free_settings(part->boids);
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.first = 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 static void 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                 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         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         Mat4MulVec4fl(data->viewmat, co);
622         
623         /* compute two vectors orthogonal to view vector */
624         VECCOPY(view, co);
625         Normalize(view);
626         VecOrthoBasisf(view, ortho1, ortho2);
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         Mat4MulVec4fl(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         Mat4CpyMat4(data->winmat, winmat);
702         Mat4MulMat4(data->viewmat, ob->obmat, viewmat);
703         Mat4MulMat4(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 || origindex == NULL)
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[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[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] += AreaQ3Dfl(co1, co2, co3, co4);
832                                 facetotvert[b] += 4;
833                         }
834                         else {
835                                 facearea[b] += AreaT3Dfl(co1, co2, co3);
836                                 facetotvert[b] += 3;
837                         }
838                 }
839         }
840
841         for(a=0; a<totorigface; a++)
842                 if(facetotvert[a] > 0)
843                         VecMulf(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[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[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 static void weighted_particle_vector(float *v1, float *v2, float *v3, float *v4, float *weights, float *vec)
1000 {
1001         vec[0]= weights[0]*v1[0] + weights[1]*v2[0] + weights[2]*v3[0] + weights[3]*v4[0];
1002         vec[1]= weights[0]*v1[1] + weights[1]*v2[1] + weights[2]*v3[1] + weights[3]*v4[1];
1003         vec[2]= weights[0]*v1[2] + weights[1]*v2[2] + weights[2]*v3[2] + weights[3]*v4[2];
1004 }
1005 void psys_interpolate_particle(short type, ParticleKey keys[4], float dt, ParticleKey *result, int velocity)
1006 {
1007         float t[4];
1008
1009         if(type<0) {
1010                 VecfCubicInterpol(keys[1].co, keys[1].vel, keys[2].co, keys[2].vel, dt, result->co, result->vel);
1011         }
1012         else {
1013                 key_curve_position_weights(dt, t, type);
1014
1015                 weighted_particle_vector(keys[0].co, keys[1].co, keys[2].co, keys[3].co, t, result->co);
1016
1017                 if(velocity){
1018                         float temp[3];
1019
1020                         if(dt>0.999f){
1021                                 key_curve_position_weights(dt-0.001f, t, type);
1022                                 weighted_particle_vector(keys[0].co, keys[1].co, keys[2].co, keys[3].co, t, temp);
1023                                 VECSUB(result->vel, result->co, temp);
1024                         }
1025                         else{
1026                                 key_curve_position_weights(dt+0.001f, t, type);
1027                                 weighted_particle_vector(keys[0].co, keys[1].co, keys[2].co, keys[3].co, t, temp);
1028                                 VECSUB(result->vel, temp, result->co);
1029                         }
1030                 }
1031         }
1032 }
1033
1034
1035
1036 typedef struct ParticleInterpolationData {
1037         HairKey *hkey[2];
1038
1039         DerivedMesh *dm;
1040         MVert *mvert[2];
1041
1042         int keyed;
1043         ParticleKey *kkey[2];
1044
1045         PointCache *cache;
1046
1047         PTCacheEditPoint *epoint;
1048         PTCacheEditKey *ekey[2];
1049
1050         float birthtime, dietime;
1051         int bspline;
1052 } ParticleInterpolationData;
1053 /* Assumes pointcache->mem_cache exists, so for disk cached particles call psys_make_temp_pointcache() before use */
1054 static void get_pointcache_keys_for_time(Object *ob, PointCache *cache, int index, float t, ParticleKey *key1, ParticleKey *key2)
1055 {
1056         static PTCacheMem *pm = NULL; /* not thread safe */
1057
1058         if(index < 0) { /* initialize */
1059                 pm = cache->mem_cache.first;
1060
1061                 if(pm)
1062                         pm = pm->next;
1063         }
1064         else {
1065                 if(pm) {
1066                         while(pm && pm->next && (float)pm->frame < t)
1067                                 pm = pm->next;
1068
1069                         BKE_ptcache_make_particle_key(key2, pm->index_array ? pm->index_array[index] : index, pm->data, (float)pm->frame);
1070                         BKE_ptcache_make_particle_key(key1, pm->prev->index_array ? pm->prev->index_array[index] : index, pm->prev->data, (float)pm->prev->frame);
1071                 }
1072                 else if(cache->mem_cache.first) {
1073                         PTCacheMem *pm2 = cache->mem_cache.first;
1074                         BKE_ptcache_make_particle_key(key2, pm2->index_array ? pm2->index_array[index] : index, pm2->data, (float)pm2->frame);
1075                         copy_particle_key(key1, key2, 1);
1076                 }
1077         }
1078 }
1079 static void init_particle_interpolation(Object *ob, ParticleSystem *psys, ParticleData *pa, ParticleInterpolationData *pind)
1080 {
1081
1082         if(pind->epoint) {
1083                 PTCacheEditPoint *point = pind->epoint;
1084
1085                 pind->ekey[0] = point->keys;
1086                 pind->ekey[1] = point->totkey > 1 ? point->keys + 1 : NULL;
1087
1088                 pind->birthtime = *(point->keys->time);
1089                 pind->dietime = *((point->keys + point->totkey - 1)->time);
1090         }
1091         else if(pind->keyed) {
1092                 ParticleKey *key = pa->keys;
1093                 pind->kkey[0] = key;
1094                 pind->kkey[1] = pa->totkey > 1 ? key + 1 : NULL;
1095
1096                 pind->birthtime = key->time;
1097                 pind->dietime = (key + pa->totkey - 1)->time;
1098         }
1099         else if(pind->cache) {
1100                 get_pointcache_keys_for_time(ob, pind->cache, -1, 0.0f, NULL, NULL);
1101
1102                 pind->birthtime = pa ? pa->time : pind->cache->startframe;
1103                 pind->dietime = pa ? pa->dietime : pind->cache->endframe;
1104         }
1105         else {
1106                 HairKey *key = pa->hair;
1107                 pind->hkey[0] = key;
1108                 pind->hkey[1] = key + 1;
1109
1110                 pind->birthtime = key->time;
1111                 pind->dietime = (key + pa->totkey - 1)->time;
1112
1113                 if(pind->dm) {
1114                         pind->mvert[0] = CDDM_get_vert(pind->dm, pa->hair_index);
1115                         pind->mvert[1] = pind->mvert[0] + 1;
1116                 }
1117         }
1118 }
1119 static void edit_to_particle(ParticleKey *key, PTCacheEditKey *ekey)
1120 {
1121         VECCOPY(key->co, ekey->co);
1122         if(ekey->vel) {
1123                 VECCOPY(key->vel, ekey->vel);
1124         }
1125         key->time = *(ekey->time);
1126 }
1127 static void hair_to_particle(ParticleKey *key, HairKey *hkey)
1128 {
1129         VECCOPY(key->co, hkey->co);
1130         key->time = hkey->time;
1131 }
1132
1133 static void mvert_to_particle(ParticleKey *key, MVert *mvert, HairKey *hkey)
1134 {
1135         VECCOPY(key->co, mvert->co);
1136         key->time = hkey->time;
1137 }
1138
1139 static void do_particle_interpolation(ParticleSystem *psys, int p, ParticleData *pa, float t, float frs_sec, ParticleInterpolationData *pind, ParticleKey *result)
1140 {
1141         PTCacheEditPoint *point = pind->epoint;
1142         ParticleKey keys[4];
1143         int point_vel = (point && point->keys->vel);
1144         float real_t, dfra, keytime;
1145
1146         /* interpret timing and find keys */
1147         if(point) {
1148                 if(result->time < 0.0f)
1149                         real_t = -result->time;
1150                 else
1151                         real_t = *(pind->ekey[0]->time) + t * (*(pind->ekey[0][point->totkey-1].time) - *(pind->ekey[0]->time));
1152
1153                 while(*(pind->ekey[1]->time) < real_t)
1154                         pind->ekey[1]++;
1155
1156                 pind->ekey[0] = pind->ekey[1] - 1;
1157         }
1158         else if(pind->keyed) {
1159                 /* we have only one key, so let's use that */
1160                 if(pind->kkey[1]==NULL) {
1161                         copy_particle_key(result, pind->kkey[0], 1);
1162                         return;
1163                 }
1164
1165                 if(result->time < 0.0f)
1166                         real_t = -result->time;
1167                 else
1168                         real_t = pind->kkey[0]->time + t * (pind->kkey[0][pa->totkey-1].time - pind->kkey[0]->time);
1169
1170                 if(psys->part->phystype==PART_PHYS_KEYED && psys->flag & PSYS_KEYED_TIMING) {
1171                         ParticleTarget *pt = psys->targets.first;
1172
1173                         pt=pt->next;
1174
1175                         while(pt && pa->time + pt->time < real_t)
1176                                 pt= pt->next;
1177
1178                         if(pt) {
1179                                 pt=pt->prev;
1180
1181                                 if(pa->time + pt->time + pt->duration > real_t)
1182                                         real_t = pa->time + pt->time;
1183                         }
1184                         else
1185                                 real_t = pa->time + ((ParticleTarget*)psys->targets.last)->time;
1186                 }
1187
1188                 CLAMP(real_t, pa->time, pa->dietime);
1189
1190                 while(pind->kkey[1]->time < real_t)
1191                         pind->kkey[1]++;
1192                 
1193                 pind->kkey[0] = pind->kkey[1] - 1;
1194         }
1195         else if(pind->cache) {
1196                 if(result->time < 0.0f) /* flag for time in frames */
1197                         real_t = -result->time;
1198                 else
1199                         real_t = pa->time + t * (pa->dietime - pa->time);
1200         }
1201         else {
1202                 if(result->time < 0.0f)
1203                         real_t = -result->time;
1204                 else
1205                         real_t = pind->hkey[0]->time + t * (pind->hkey[0][pa->totkey-1].time - pind->hkey[0]->time);
1206
1207                 while(pind->hkey[1]->time < real_t) {
1208                         pind->hkey[1]++;
1209                         pind->mvert[1]++;
1210                 }
1211
1212                 pind->hkey[0] = pind->hkey[1] - 1;
1213         }
1214
1215         /* set actual interpolation keys */
1216         if(point) {
1217                 edit_to_particle(keys + 1, pind->ekey[0]);
1218                 edit_to_particle(keys + 2, pind->ekey[1]);
1219         }
1220         else if(pind->dm) {
1221                 pind->mvert[0] = pind->mvert[1] - 1;
1222                 mvert_to_particle(keys + 1, pind->mvert[0], pind->hkey[0]);
1223                 mvert_to_particle(keys + 2, pind->mvert[1], pind->hkey[1]);
1224         }
1225         else if(pind->keyed) {
1226                 memcpy(keys + 1, pind->kkey[0], sizeof(ParticleKey));
1227                 memcpy(keys + 2, pind->kkey[1], sizeof(ParticleKey));
1228         }
1229         else if(pind->cache) {
1230                 get_pointcache_keys_for_time(NULL, pind->cache, p, real_t, keys+1, keys+2);
1231         }
1232         else {
1233                 hair_to_particle(keys + 1, pind->hkey[0]);
1234                 hair_to_particle(keys + 2, pind->hkey[1]);
1235         }
1236
1237         /* set secondary interpolation keys for hair */
1238         if(!pind->keyed && !pind->cache && !point_vel) {
1239                 if(point) {
1240                         if(pind->ekey[0] != point->keys)
1241                                 edit_to_particle(keys, pind->ekey[0] - 1);
1242                         else
1243                                 edit_to_particle(keys, pind->ekey[0]);
1244                 }
1245                 else if(pind->dm) {
1246                         if(pind->hkey[0] != pa->hair)
1247                                 mvert_to_particle(keys, pind->mvert[0] - 1, pind->hkey[0] - 1);
1248                         else
1249                                 mvert_to_particle(keys, pind->mvert[0], pind->hkey[0]);
1250                 }
1251                 else {
1252                         if(pind->hkey[0] != pa->hair)
1253                                 hair_to_particle(keys, pind->hkey[0] - 1);
1254                         else
1255                                 hair_to_particle(keys, pind->hkey[0]);
1256                 }
1257
1258                 if(point) {
1259                         if(pind->ekey[1] != point->keys + point->totkey - 1)
1260                                 edit_to_particle(keys + 3, pind->ekey[1] + 1);
1261                         else
1262                                 edit_to_particle(keys + 3, pind->ekey[1]);
1263                 }
1264                 else if(pind->dm) {
1265                         if(pind->hkey[1] != pa->hair + pa->totkey - 1)
1266                                 mvert_to_particle(keys + 3, pind->mvert[1] + 1, pind->hkey[1] + 1);
1267                         else
1268                                 mvert_to_particle(keys + 3, pind->mvert[1], pind->hkey[1]);
1269                 }
1270                 else {
1271                         if(pind->hkey[1] != pa->hair + pa->totkey - 1)
1272                                 hair_to_particle(keys + 3, pind->hkey[1] + 1);
1273                         else
1274                                 hair_to_particle(keys + 3, pind->hkey[1]);
1275                 }
1276         }
1277
1278         dfra = keys[2].time - keys[1].time;
1279         keytime = (real_t - keys[1].time) / dfra;
1280
1281         /* convert velocity to timestep size */
1282         if(pind->keyed || pind->cache || point_vel){
1283                 VecMulf(keys[1].vel, dfra / frs_sec);
1284                 VecMulf(keys[2].vel, dfra / frs_sec);
1285                 QuatInterpol(result->rot,keys[1].rot,keys[2].rot,keytime);
1286         }
1287
1288         /* 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)*/
1289         psys_interpolate_particle((pind->keyed || pind->cache || point_vel) ? -1 /* signal for cubic interpolation */
1290                 : (pind->bspline ? KEY_BSPLINE : KEY_CARDINAL)
1291                 ,keys, keytime, result, 1);
1292
1293         /* the velocity needs to be converted back from cubic interpolation */
1294         if(pind->keyed || pind->cache || point_vel)
1295                 VecMulf(result->vel, frs_sec / dfra);
1296 }
1297 /************************************************/
1298 /*                      Particles on a dm                                       */
1299 /************************************************/
1300 /* interpolate a location on a face based on face coordinates */
1301 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){
1302         float *v1=0, *v2=0, *v3=0, *v4=0;
1303         float e1[3],e2[3],s1,s2,t1,t2;
1304         float *uv1, *uv2, *uv3, *uv4;
1305         float n1[3], n2[3], n3[3], n4[3];
1306         float tuv[4][2];
1307         float *o1, *o2, *o3, *o4;
1308
1309         v1= (mvert+mface->v1)->co;
1310         v2= (mvert+mface->v2)->co;
1311         v3= (mvert+mface->v3)->co;
1312         VECCOPY(n1,(mvert+mface->v1)->no);
1313         VECCOPY(n2,(mvert+mface->v2)->no);
1314         VECCOPY(n3,(mvert+mface->v3)->no);
1315         Normalize(n1);
1316         Normalize(n2);
1317         Normalize(n3);
1318
1319         if(mface->v4) {
1320                 v4= (mvert+mface->v4)->co;
1321                 VECCOPY(n4,(mvert+mface->v4)->no);
1322                 Normalize(n4);
1323                 
1324                 vec[0]= w[0]*v1[0] + w[1]*v2[0] + w[2]*v3[0] + w[3]*v4[0];
1325                 vec[1]= w[0]*v1[1] + w[1]*v2[1] + w[2]*v3[1] + w[3]*v4[1];
1326                 vec[2]= w[0]*v1[2] + w[1]*v2[2] + w[2]*v3[2] + w[3]*v4[2];
1327
1328                 if(nor){
1329                         if(mface->flag & ME_SMOOTH){
1330                                 nor[0]= w[0]*n1[0] + w[1]*n2[0] + w[2]*n3[0] + w[3]*n4[0];
1331                                 nor[1]= w[0]*n1[1] + w[1]*n2[1] + w[2]*n3[1] + w[3]*n4[1];
1332                                 nor[2]= w[0]*n1[2] + w[1]*n2[2] + w[2]*n3[2] + w[3]*n4[2];
1333                         }
1334                         else
1335                                 CalcNormFloat4(v1,v2,v3,v4,nor);
1336                 }
1337         }
1338         else {
1339                 vec[0]= w[0]*v1[0] + w[1]*v2[0] + w[2]*v3[0];
1340                 vec[1]= w[0]*v1[1] + w[1]*v2[1] + w[2]*v3[1];
1341                 vec[2]= w[0]*v1[2] + w[1]*v2[2] + w[2]*v3[2];
1342                 
1343                 if(nor){
1344                         if(mface->flag & ME_SMOOTH){
1345                                 nor[0]= w[0]*n1[0] + w[1]*n2[0] + w[2]*n3[0];
1346                                 nor[1]= w[0]*n1[1] + w[1]*n2[1] + w[2]*n3[1];
1347                                 nor[2]= w[0]*n1[2] + w[1]*n2[2] + w[2]*n3[2];
1348                         }
1349                         else
1350                                 CalcNormFloat(v1,v2,v3,nor);
1351                 }
1352         }
1353         
1354         /* calculate tangent vectors */
1355         if(utan && vtan){
1356                 if(tface){
1357                         uv1= tface->uv[0];
1358                         uv2= tface->uv[1];
1359                         uv3= tface->uv[2];
1360                         uv4= tface->uv[3];
1361                 }
1362                 else{
1363                         uv1= tuv[0]; uv2= tuv[1]; uv3= tuv[2]; uv4= tuv[3];
1364                         spheremap(v1[0], v1[1], v1[2], uv1, uv1+1);
1365                         spheremap(v2[0], v2[1], v2[2], uv2, uv2+1);
1366                         spheremap(v3[0], v3[1], v3[2], uv3, uv3+1);
1367                         if(v4)
1368                                 spheremap(v4[0], v4[1], v4[2], uv4, uv4+1);
1369                 }
1370
1371                 if(v4){
1372                         s1= uv3[0] - uv1[0];
1373                         s2= uv4[0] - uv1[0];
1374
1375                         t1= uv3[1] - uv1[1];
1376                         t2= uv4[1] - uv1[1];
1377
1378                         VecSubf(e1, v3, v1);
1379                         VecSubf(e2, v4, v1);
1380                 }
1381                 else{
1382                         s1= uv2[0] - uv1[0];
1383                         s2= uv3[0] - uv1[0];
1384
1385                         t1= uv2[1] - uv1[1];
1386                         t2= uv3[1] - uv1[1];
1387
1388                         VecSubf(e1, v2, v1);
1389                         VecSubf(e2, v3, v1);
1390                 }
1391
1392                 vtan[0] = (s1*e2[0] - s2*e1[0]);
1393                 vtan[1] = (s1*e2[1] - s2*e1[1]);
1394                 vtan[2] = (s1*e2[2] - s2*e1[2]);
1395
1396                 utan[0] = (t1*e2[0] - t2*e1[0]);
1397                 utan[1] = (t1*e2[1] - t2*e1[1]);
1398                 utan[2] = (t1*e2[2] - t2*e1[2]);
1399         }
1400
1401         if(orco) {
1402                 if(orcodata) {
1403                         o1= orcodata[mface->v1];
1404                         o2= orcodata[mface->v2];
1405                         o3= orcodata[mface->v3];
1406
1407                         if(mface->v4) {
1408                                 o4= orcodata[mface->v4];
1409                                 orco[0]= w[0]*o1[0] + w[1]*o2[0] + w[2]*o3[0] + w[3]*o4[0];
1410                                 orco[1]= w[0]*o1[1] + w[1]*o2[1] + w[2]*o3[1] + w[3]*o4[1];
1411                                 orco[2]= w[0]*o1[2] + w[1]*o2[2] + w[2]*o3[2] + w[3]*o4[2];
1412
1413                                 if(ornor)
1414                                         CalcNormFloat4(o1, o2, o3, o4, ornor);
1415                         }
1416                         else {
1417                                 orco[0]= w[0]*o1[0] + w[1]*o2[0] + w[2]*o3[0];
1418                                 orco[1]= w[0]*o1[1] + w[1]*o2[1] + w[2]*o3[1];
1419                                 orco[2]= w[0]*o1[2] + w[1]*o2[2] + w[2]*o3[2];
1420
1421                                 if(ornor)
1422                                         CalcNormFloat(o1, o2, o3, ornor);
1423                         }
1424                 }
1425                 else {
1426                         VECCOPY(orco, vec);
1427                         if(ornor)
1428                                 VECCOPY(ornor, nor);
1429                 }
1430         }
1431 }
1432 void psys_interpolate_uvs(MTFace *tface, int quad, float *w, float *uvco)
1433 {
1434         float v10= tface->uv[0][0];
1435         float v11= tface->uv[0][1];
1436         float v20= tface->uv[1][0];
1437         float v21= tface->uv[1][1];
1438         float v30= tface->uv[2][0];
1439         float v31= tface->uv[2][1];
1440         float v40,v41;
1441
1442         if(quad) {
1443                 v40= tface->uv[3][0];
1444                 v41= tface->uv[3][1];
1445
1446                 uvco[0]= w[0]*v10 + w[1]*v20 + w[2]*v30 + w[3]*v40;
1447                 uvco[1]= w[0]*v11 + w[1]*v21 + w[2]*v31 + w[3]*v41;
1448         }
1449         else {
1450                 uvco[0]= w[0]*v10 + w[1]*v20 + w[2]*v30;
1451                 uvco[1]= w[0]*v11 + w[1]*v21 + w[2]*v31;
1452         }
1453 }
1454
1455 void psys_interpolate_mcol(MCol *mcol, int quad, float *w, MCol *mc)
1456 {
1457         char *cp, *cp1, *cp2, *cp3, *cp4;
1458
1459         cp= (char *)mc;
1460         cp1= (char *)&mcol[0];
1461         cp2= (char *)&mcol[1];
1462         cp3= (char *)&mcol[2];
1463         
1464         if(quad) {
1465                 cp4= (char *)&mcol[3];
1466
1467                 cp[0]= (int)(w[0]*cp1[0] + w[1]*cp2[0] + w[2]*cp3[0] + w[3]*cp4[0]);
1468                 cp[1]= (int)(w[0]*cp1[1] + w[1]*cp2[1] + w[2]*cp3[1] + w[3]*cp4[1]);
1469                 cp[2]= (int)(w[0]*cp1[2] + w[1]*cp2[2] + w[2]*cp3[2] + w[3]*cp4[2]);
1470                 cp[3]= (int)(w[0]*cp1[3] + w[1]*cp2[3] + w[2]*cp3[3] + w[3]*cp4[3]);
1471         }
1472         else {
1473                 cp[0]= (int)(w[0]*cp1[0] + w[1]*cp2[0] + w[2]*cp3[0]);
1474                 cp[1]= (int)(w[0]*cp1[1] + w[1]*cp2[1] + w[2]*cp3[1]);
1475                 cp[2]= (int)(w[0]*cp1[2] + w[1]*cp2[2] + w[2]*cp3[2]);
1476                 cp[3]= (int)(w[0]*cp1[3] + w[1]*cp2[3] + w[2]*cp3[3]);
1477         }
1478 }
1479
1480 static float psys_interpolate_value_from_verts(DerivedMesh *dm, short from, int index, float *fw, float *values)
1481 {
1482         if(values==0 || index==-1)
1483                 return 0.0;
1484
1485         switch(from){
1486                 case PART_FROM_VERT:
1487                         return values[index];
1488                 case PART_FROM_FACE:
1489                 case PART_FROM_VOLUME:
1490                 {
1491                         MFace *mf=dm->getTessFaceData(dm,index,CD_MFACE);
1492                         return interpolate_particle_value(values[mf->v1],values[mf->v2],values[mf->v3],values[mf->v4],fw,mf->v4);
1493                 }
1494                         
1495         }
1496         return 0.0;
1497 }
1498
1499 /* conversion of pa->fw to origspace layer coordinates */
1500 static void psys_w_to_origspace(float *w, float *uv)
1501 {
1502         uv[0]= w[1] + w[2];
1503         uv[1]= w[2] + w[3];
1504 }
1505
1506 /* conversion of pa->fw to weights in face from origspace */
1507 static void psys_origspace_to_w(OrigSpaceFace *osface, int quad, float *w, float *neww)
1508 {
1509         float v[4][3], co[3];
1510
1511         v[0][0]= osface->uv[0][0]; v[0][1]= osface->uv[0][1]; v[0][2]= 0.0f;
1512         v[1][0]= osface->uv[1][0]; v[1][1]= osface->uv[1][1]; v[1][2]= 0.0f;
1513         v[2][0]= osface->uv[2][0]; v[2][1]= osface->uv[2][1]; v[2][2]= 0.0f;
1514
1515         psys_w_to_origspace(w, co);
1516         co[2]= 0.0f;
1517         
1518         if(quad) {
1519                 v[3][0]= osface->uv[3][0]; v[3][1]= osface->uv[3][1]; v[3][2]= 0.0f;
1520                 MeanValueWeights(v, 4, co, neww);
1521         }
1522         else {
1523                 MeanValueWeights(v, 3, co, neww);
1524                 neww[3]= 0.0f;
1525         }
1526 }
1527
1528 /* find the derived mesh face for a particle, set the mf passed. this is slow
1529  * and can be optimized but only for many lookups. returns the face index. */
1530 int psys_particle_dm_face_lookup(Object *ob, DerivedMesh *dm, int index, float *fw, struct LinkNode *node)
1531 {
1532         Mesh *me= (Mesh*)ob->data;
1533         MFace *mface;
1534         OrigSpaceFace *osface;
1535         int *origindex;
1536         int quad, findex, totface;
1537         float uv[2], (*faceuv)[2];
1538
1539         mface = dm->getTessFaceDataArray(dm, CD_MFACE);
1540         origindex = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
1541         osface = dm->getTessFaceDataArray(dm, CD_ORIGSPACE);
1542
1543         totface = dm->getNumTessFaces(dm);
1544         
1545         if(osface==NULL || origindex==NULL) {
1546                 /* Assume we dont need osface data */
1547                 if (index <totface) {
1548                         //printf("\tNO CD_ORIGSPACE, assuming not needed\n");
1549                         return index;
1550                 } else {
1551                         printf("\tNO CD_ORIGSPACE, error out of range\n");
1552                         return DMCACHE_NOTFOUND;
1553                 }
1554         }
1555         else if(index >= me->totface)
1556                 return DMCACHE_NOTFOUND; /* index not in the original mesh */
1557
1558         psys_w_to_origspace(fw, uv);
1559         
1560         if(node) { /* we have a linked list of faces that we use, faster! */
1561                 for(;node; node=node->next) {
1562                         findex= GET_INT_FROM_POINTER(node->link);
1563                         faceuv= osface[findex].uv;
1564                         quad= mface[findex].v4;
1565
1566                         /* check that this intersects - Its possible this misses :/ -
1567                          * could also check its not between */
1568                         if(quad) {
1569                                 if(IsectPQ2Df(uv, faceuv[0], faceuv[1], faceuv[2], faceuv[3]))
1570                                         return findex;
1571                         }
1572                         else if(IsectPT2Df(uv, faceuv[0], faceuv[1], faceuv[2]))
1573                                 return findex;
1574                 }
1575         }
1576         else { /* if we have no node, try every face */
1577                 for(findex=0; findex<totface; findex++) {
1578                         if(origindex[findex] == index) {
1579                                 faceuv= osface[findex].uv;
1580                                 quad= mface[findex].v4;
1581
1582                                 /* check that this intersects - Its possible this misses :/ -
1583                                  * could also check its not between */
1584                                 if(quad) {
1585                                         if(IsectPQ2Df(uv, faceuv[0], faceuv[1], faceuv[2], faceuv[3]))
1586                                                 return findex;
1587                                 }
1588                                 else if(IsectPT2Df(uv, faceuv[0], faceuv[1], faceuv[2]))
1589                                         return findex;
1590                         }
1591                 }
1592         }
1593
1594         return DMCACHE_NOTFOUND;
1595 }
1596
1597 static int psys_map_index_on_dm(DerivedMesh *dm, int from, int index, int index_dmcache, float *fw, float foffset, int *mapindex, float *mapfw)
1598 {
1599         if(index < 0)
1600                 return 0;
1601
1602         if (dm->deformedOnly || index_dmcache == DMCACHE_ISCHILD) {
1603                 /* for meshes that are either only defined or for child particles, the
1604                  * index and fw do not require any mapping, so we can directly use it */
1605                 if(from == PART_FROM_VERT) {
1606                         if(index >= dm->getNumVerts(dm))
1607                                 return 0;
1608
1609                         *mapindex = index;
1610                 }
1611                 else  { /* FROM_FACE/FROM_VOLUME */
1612                         if(index >= dm->getNumTessFaces(dm))
1613                                 return 0;
1614
1615                         *mapindex = index;
1616                         QUATCOPY(mapfw, fw);
1617                 }
1618         } else {
1619                 /* for other meshes that have been modified, we try to map the particle
1620                  * to their new location, which means a different index, and for faces
1621                  * also a new face interpolation weights */
1622                 if(from == PART_FROM_VERT) {
1623                         if (index_dmcache == DMCACHE_NOTFOUND || index_dmcache > dm->getNumVerts(dm))
1624                                 return 0;
1625
1626                         *mapindex = index_dmcache;
1627                 }
1628                 else  { /* FROM_FACE/FROM_VOLUME */
1629                         /* find a face on the derived mesh that uses this face */
1630                         MFace *mface;
1631                         OrigSpaceFace *osface;
1632                         int i;
1633
1634                         i = index_dmcache;
1635
1636                         if(i== DMCACHE_NOTFOUND || i >= dm->getNumTessFaces(dm))
1637                                 return 0;
1638
1639                         *mapindex = i;
1640
1641                         /* modify the original weights to become
1642                          * weights for the derived mesh face */
1643                         osface= dm->getTessFaceDataArray(dm, CD_ORIGSPACE);
1644                         mface= dm->getTessFaceData(dm, i, CD_MFACE);
1645
1646                         if(osface == NULL)
1647                                 mapfw[0]= mapfw[1]= mapfw[2]= mapfw[3]= 0.0f;
1648                         else
1649                                 psys_origspace_to_w(&osface[i], mface->v4, fw, mapfw);
1650                 }
1651         }
1652
1653         return 1;
1654 }
1655
1656 /* interprets particle data to get a point on a mesh in object space */
1657 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)
1658 {
1659         float tmpnor[3], mapfw[4];
1660         float (*orcodata)[3];
1661         int mapindex;
1662
1663         if(!psys_map_index_on_dm(dm, from, index, index_dmcache, fw, foffset, &mapindex, mapfw)) {
1664                 if(vec) { vec[0]=vec[1]=vec[2]=0.0; }
1665                 if(nor) { nor[0]=nor[1]=0.0; nor[2]=1.0; }
1666                 if(orco) { orco[0]=orco[1]=orco[2]=0.0; }
1667                 if(ornor) { ornor[0]=ornor[1]=0.0; ornor[2]=1.0; }
1668                 if(utan) { utan[0]=utan[1]=utan[2]=0.0; }
1669                 if(vtan) { vtan[0]=vtan[1]=vtan[2]=0.0; }
1670
1671                 return;
1672         }
1673
1674         orcodata= dm->getVertDataArray(dm, CD_ORCO);
1675
1676         if(from == PART_FROM_VERT) {
1677                 dm->getVertCo(dm,mapindex,vec);
1678
1679                 if(nor) {
1680                         dm->getVertNo(dm,mapindex,nor);
1681                         Normalize(nor);
1682                 }
1683
1684                 if(orco)
1685                         VECCOPY(orco, orcodata[mapindex])
1686
1687                 if(ornor) {
1688                         dm->getVertNo(dm,mapindex,nor);
1689                         Normalize(nor);
1690                 }
1691
1692                 if(utan && vtan) {
1693                         utan[0]= utan[1]= utan[2]= 0.0f;
1694                         vtan[0]= vtan[1]= vtan[2]= 0.0f;
1695                 }
1696         }
1697         else { /* PART_FROM_FACE / PART_FROM_VOLUME */
1698                 MFace *mface;
1699                 MTFace *mtface;
1700                 MVert *mvert;
1701
1702                 mface=dm->getTessFaceData(dm,mapindex,CD_MFACE);
1703                 mvert=dm->getVertDataArray(dm,CD_MVERT);
1704                 mtface=CustomData_get_layer(&dm->faceData,CD_MTFACE);
1705
1706                 if(mtface)
1707                         mtface += mapindex;
1708
1709                 if(from==PART_FROM_VOLUME) {
1710                         psys_interpolate_face(mvert,mface,mtface,orcodata,mapfw,vec,tmpnor,utan,vtan,orco,ornor);
1711                         if(nor)
1712                                 VECCOPY(nor,tmpnor);
1713
1714                         Normalize(tmpnor);
1715                         VecMulf(tmpnor,-foffset);
1716                         VECADD(vec,vec,tmpnor);
1717                 }
1718                 else
1719                         psys_interpolate_face(mvert,mface,mtface,orcodata,mapfw,vec,nor,utan,vtan,orco,ornor);
1720         }
1721 }
1722
1723 float psys_particle_value_from_verts(DerivedMesh *dm, short from, ParticleData *pa, float *values)
1724 {
1725         float mapfw[4];
1726         int mapindex;
1727
1728         if(!psys_map_index_on_dm(dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, &mapindex, mapfw))
1729                 return 0.0f;
1730         
1731         return psys_interpolate_value_from_verts(dm, from, mapindex, mapfw, values);
1732 }
1733
1734 ParticleSystemModifierData *psys_get_modifier(Object *ob, ParticleSystem *psys)
1735 {
1736         ModifierData *md;
1737         ParticleSystemModifierData *psmd;
1738
1739         for(md=ob->modifiers.first; md; md=md->next){
1740                 if(md->type==eModifierType_ParticleSystem){
1741                         psmd= (ParticleSystemModifierData*) md;
1742                         if(psmd->psys==psys){
1743                                 return psmd;
1744                         }
1745                 }
1746         }
1747         return NULL;
1748 }
1749 /************************************************/
1750 /*                      Particles on a shape                            */
1751 /************************************************/
1752 /* ready for future use */
1753 static void psys_particle_on_shape(int distr, int index, float *fuv, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor)
1754 {
1755         /* TODO */
1756         float zerovec[3]={0.0f,0.0f,0.0f};
1757         if(vec){
1758                 VECCOPY(vec,zerovec);
1759         }
1760         if(nor){
1761                 VECCOPY(nor,zerovec);
1762         }
1763         if(utan){
1764                 VECCOPY(utan,zerovec);
1765         }
1766         if(vtan){
1767                 VECCOPY(vtan,zerovec);
1768         }
1769         if(orco){
1770                 VECCOPY(orco,zerovec);
1771         }
1772         if(ornor){
1773                 VECCOPY(ornor,zerovec);
1774         }
1775 }
1776 /************************************************/
1777 /*                      Particles on emitter                            */
1778 /************************************************/
1779 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){
1780         if(psmd){
1781                 if(psmd->psys->part->distr==PART_DISTR_GRID && psmd->psys->part->from != PART_FROM_VERT){
1782                         if(vec){
1783                                 VECCOPY(vec,fuv);
1784                         }
1785                         return;
1786                 }
1787                 /* we cant use the num_dmcache */
1788                 psys_particle_on_dm(psmd->dm,from,index,index_dmcache,fuv,foffset,vec,nor,utan,vtan,orco,ornor);
1789         }
1790         else
1791                 psys_particle_on_shape(from,index,fuv,vec,nor,utan,vtan,orco,ornor);
1792
1793 }
1794 /************************************************/
1795 /*                      Path Cache                                                      */
1796 /************************************************/
1797 static float vert_weight(MDeformVert *dvert, int group)
1798 {
1799         MDeformWeight *dw;
1800         int i;
1801         
1802         if(dvert) {
1803                 dw= dvert->dw;
1804                 for(i= dvert->totweight; i>0; i--, dw++) {
1805                         if(dw->def_nr == group) return dw->weight;
1806                         if(i==1) break; /*otherwise dw will point to somewhere it shouldn't*/
1807                 }
1808         }
1809         return 0.0;
1810 }
1811
1812 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])
1813 {
1814         float vec[3]={0.0,0.0,0.0}, q1[4]={1,0,0,0},q2[4];
1815         float t;
1816
1817         CLAMP(time,0.0,1.0);
1818
1819         if(shape!=0.0f && type!=PART_KINK_BRAID) {
1820                 if(shape<0.0f)
1821                         time= (float)pow(time, 1.0+shape);
1822                 else
1823                         time= (float)pow(time, 1.0/(1.0-shape));
1824         }
1825
1826         t=time;
1827
1828         t*=(float)M_PI*freq;
1829
1830         if(par==0) return;
1831
1832         switch(type){
1833                 case PART_KINK_CURL:
1834                         vec[axis]=1.0;
1835                         if(par_rot)
1836                                 QUATCOPY(q2,par_rot)
1837                         else
1838                                 vectoquat(par->vel,axis,(axis+1)%3, q2);
1839                         QuatMulVecf(q2,vec);
1840                         VecMulf(vec,amplitude);
1841                         VECADD(state->co,state->co,vec);
1842
1843                         VECSUB(vec,state->co,par->co);
1844
1845                         if(t!=0.0)
1846                                 VecRotToQuat(par->vel,t,q1);
1847                         
1848                         QuatMulVecf(q1,vec);
1849                         
1850                         VECADD(state->co,par->co,vec);
1851                         break;
1852                 case PART_KINK_RADIAL:
1853                         VECSUB(vec,state->co,par->co);
1854
1855                         Normalize(vec);
1856                         VecMulf(vec,amplitude*(float)sin(t));
1857
1858                         VECADD(state->co,state->co,vec);
1859                         break;
1860                 case PART_KINK_WAVE:
1861                         vec[axis]=1.0;
1862                         if(obmat)
1863                                 Mat4Mul3Vecfl(obmat,vec);
1864
1865                         if(par_rot)
1866                                 QuatMulVecf(par_rot,vec);
1867
1868                         Projf(q1,vec,par->vel);
1869                         
1870                         VECSUB(vec,vec,q1);
1871                         Normalize(vec);
1872
1873                         VecMulf(vec,amplitude*(float)sin(t));
1874
1875                         VECADD(state->co,state->co,vec);
1876                         break;
1877                 case PART_KINK_BRAID:
1878                         if(par){
1879                                 float y_vec[3]={0.0,1.0,0.0};
1880                                 float z_vec[3]={0.0,0.0,1.0};
1881                                 float vec_from_par[3], vec_one[3], radius, state_co[3];
1882                                 float inp_y,inp_z,length;
1883                                 
1884                                 if(par_rot)
1885                                         QUATCOPY(q2,par_rot)
1886                                 else
1887                                         vectoquat(par->vel,axis,(axis+1)%3,q2);
1888                                 QuatMulVecf(q2,y_vec);
1889                                 QuatMulVecf(q2,z_vec);
1890                                 
1891                                 VECSUB(vec_from_par,state->co,par->co);
1892                                 VECCOPY(vec_one,vec_from_par);
1893                                 radius=Normalize(vec_one);
1894
1895                                 inp_y=Inpf(y_vec,vec_one);
1896                                 inp_z=Inpf(z_vec,vec_one);
1897
1898                                 if(inp_y>0.5){
1899                                         VECCOPY(state_co,y_vec);
1900
1901                                         VecMulf(y_vec,amplitude*(float)cos(t));
1902                                         VecMulf(z_vec,amplitude/2.0f*(float)sin(2.0f*t));
1903                                 }
1904                                 else if(inp_z>0.0){
1905                                         VECCOPY(state_co,z_vec);
1906                                         VecMulf(state_co,(float)sin(M_PI/3.0f));
1907                                         VECADDFAC(state_co,state_co,y_vec,-0.5f);
1908
1909                                         VecMulf(y_vec,-amplitude*(float)cos(t + M_PI/3.0f));
1910                                         VecMulf(z_vec,amplitude/2.0f*(float)cos(2.0f*t + M_PI/6.0f));
1911                                 }
1912                                 else{
1913                                         VECCOPY(state_co,z_vec);
1914                                         VecMulf(state_co,-(float)sin(M_PI/3.0f));
1915                                         VECADDFAC(state_co,state_co,y_vec,-0.5f);
1916
1917                                         VecMulf(y_vec,amplitude*(float)-sin(t+M_PI/6.0f));
1918                                         VecMulf(z_vec,amplitude/2.0f*(float)-sin(2.0f*t+M_PI/3.0f));
1919                                 }
1920
1921                                 VecMulf(state_co,amplitude);
1922                                 VECADD(state_co,state_co,par->co);
1923                                 VECSUB(vec_from_par,state->co,state_co);
1924
1925                                 length=Normalize(vec_from_par);
1926                                 VecMulf(vec_from_par,MIN2(length,amplitude/2.0f));
1927
1928                                 VECADD(state_co,par->co,y_vec);
1929                                 VECADD(state_co,state_co,z_vec);
1930                                 VECADD(state_co,state_co,vec_from_par);
1931
1932                                 shape=(2.0f*(float)M_PI)*(1.0f+shape);
1933
1934                                 if(t<shape){
1935                                         shape=t/shape;
1936                                         shape=(float)sqrt((double)shape);
1937                                         VecLerpf(state->co,state->co,state_co,shape);
1938                                 }
1939                                 else{
1940                                         VECCOPY(state->co,state_co);
1941                                 }
1942                         }
1943                         break;
1944         }
1945 }
1946
1947 static void do_clump(ParticleKey *state, ParticleKey *par, float time, float clumpfac, float clumppow, float pa_clump)
1948 {
1949         if(par && clumpfac!=0.0){
1950                 float clump, cpow;
1951
1952                 if(clumppow<0.0)
1953                         cpow=1.0f+clumppow;
1954                 else
1955                         cpow=1.0f+9.0f*clumppow;
1956
1957                 if(clumpfac<0.0) /* clump roots instead of tips */
1958                         clump = -clumpfac*pa_clump*(float)pow(1.0-(double)time,(double)cpow);
1959                 else
1960                         clump = clumpfac*pa_clump*(float)pow((double)time,(double)cpow);
1961                 VecLerpf(state->co,state->co,par->co,clump);
1962         }
1963 }
1964 void precalc_guides(ParticleSimulationData *sim, ListBase *effectors)
1965 {
1966         EffectedPoint point;
1967         ParticleKey state;
1968         EffectorData efd;
1969         EffectorCache *eff;
1970         ParticleSystem *psys = sim->psys;
1971         EffectorWeights *weights = sim->psys->part->effector_weights;
1972         GuideEffectorData *data;
1973         PARTICLE_P;
1974
1975         if(!effectors)
1976                 return;
1977
1978         LOOP_PARTICLES {
1979                 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);
1980                 pd_point_from_particle(sim, pa, &state, &point);
1981
1982                 for(eff = effectors->first; eff; eff=eff->next) {
1983                         if(eff->pd->forcefield != PFIELD_GUIDE)
1984                                 continue;
1985
1986                         if(!eff->guide_data)
1987                                 eff->guide_data = MEM_callocN(sizeof(GuideEffectorData)*psys->totpart, "GuideEffectorData");
1988
1989                         data = eff->guide_data + p;
1990
1991                         VECSUB(efd.vec_to_point, state.co, eff->guide_loc);
1992                         VECCOPY(efd.nor, eff->guide_dir);
1993                         efd.distance = VecLength(efd.vec_to_point);
1994
1995                         VECCOPY(data->vec_to_point, efd.vec_to_point);
1996                         data->strength = effector_falloff(eff, &efd, &point, weights);
1997                 }
1998         }
1999 }
2000 int do_guides(ListBase *effectors, ParticleKey *state, int index, float time)
2001 {
2002         EffectorCache *eff;
2003         PartDeflect *pd;
2004         Curve *cu;
2005         ParticleKey key, par;
2006         GuideEffectorData *data;
2007
2008         float effect[3] = {0.0f, 0.0f, 0.0f}, veffect[3] = {0.0f, 0.0f, 0.0f};
2009         float guidevec[4], guidedir[3], rot2[4], temp[3];
2010         float guidetime, radius, angle, totstrength = 0.0f;
2011         float vec_to_point[3];
2012
2013         if(effectors) for(eff = effectors->first; eff; eff=eff->next) {
2014                 pd = eff->pd;
2015
2016                 if(pd->forcefield != PFIELD_GUIDE)
2017                         continue;
2018
2019                 data = eff->guide_data + index;
2020
2021                 if(data->strength <= 0.0f)
2022                         continue;
2023
2024                 guidetime = time / (1.0 - pd->free_end);
2025
2026                 if(guidetime>1.0f)
2027                         continue;
2028
2029                 cu = (Curve*)eff->ob->data;
2030
2031                 if(pd->flag & PFIELD_GUIDE_PATH_ADD) {
2032                         if(where_on_path(eff->ob, data->strength * guidetime, guidevec, guidedir, NULL, &radius)==0)
2033                                 return 0;
2034                 }
2035                 else {
2036                         if(where_on_path(eff->ob, guidetime, guidevec, guidedir, NULL, &radius)==0)
2037                                 return 0;
2038                 }
2039
2040                 Mat4MulVecfl(eff->ob->obmat, guidevec);
2041                 Mat4Mul3Vecfl(eff->ob->obmat, guidedir);
2042
2043                 Normalize(guidedir);
2044
2045                 VECCOPY(vec_to_point, data->vec_to_point);
2046
2047                 if(guidetime != 0.0){
2048                         /* curve direction */
2049                         Crossf(temp, eff->guide_dir, guidedir);
2050                         angle = Inpf(eff->guide_dir, guidedir)/(VecLength(eff->guide_dir));
2051                         angle = saacos(angle);
2052                         VecRotToQuat(temp, angle, rot2);
2053                         QuatMulVecf(rot2, vec_to_point);
2054
2055                         /* curve tilt */
2056                         VecRotToQuat(guidedir, guidevec[3] - eff->guide_loc[3], rot2);
2057                         QuatMulVecf(rot2, vec_to_point);
2058                 }
2059
2060                 /* curve taper */
2061                 if(cu->taperobj)
2062                         VecMulf(vec_to_point, calc_taper(eff->scene, cu->taperobj, (int)(data->strength*guidetime*100.0), 100));
2063
2064                 else{ /* curve size*/
2065                         if(cu->flag & CU_PATH_RADIUS) {
2066                                 VecMulf(vec_to_point, radius);
2067                         }
2068                 }
2069                 par.co[0] = par.co[1] = par.co[2] = 0.0f;
2070                 VECCOPY(key.co, vec_to_point);
2071                 do_prekink(&key, &par, 0, guidetime, pd->kink_freq, pd->kink_shape, pd->kink_amp, pd->kink, pd->kink_axis, 0);
2072                 do_clump(&key, &par, guidetime, pd->clump_fac, pd->clump_pow, 1.0f);
2073                 VECCOPY(vec_to_point, key.co);
2074
2075                 VECADD(vec_to_point, vec_to_point, guidevec);
2076                 //VECSUB(pa_loc,pa_loc,pa_zero);
2077                 VECADDFAC(effect, effect, vec_to_point, data->strength);
2078                 VECADDFAC(veffect, veffect, guidedir, data->strength);
2079                 totstrength += data->strength;
2080         }
2081
2082         if(totstrength != 0.0){
2083                 if(totstrength > 1.0)
2084                         VecMulf(effect, 1.0f / totstrength);
2085                 CLAMP(totstrength, 0.0, 1.0);
2086                 //VECADD(effect,effect,pa_zero);
2087                 VecLerpf(state->co, state->co, effect, totstrength);
2088
2089                 Normalize(veffect);
2090                 VecMulf(veffect, VecLength(state->vel));
2091                 VECCOPY(state->vel, veffect);
2092                 return 1;
2093         }
2094         return 0;
2095 }
2096 static void do_rough(float *loc, float mat[4][4], float t, float fac, float size, float thres, ParticleKey *state)
2097 {
2098         float rough[3];
2099         float rco[3];
2100
2101         if(thres!=0.0)
2102                 if((float)fabs((float)(-1.5+loc[0]+loc[1]+loc[2]))<1.5f*thres) return;
2103
2104         VECCOPY(rco,loc);
2105         VecMulf(rco,t);
2106         rough[0]=-1.0f+2.0f*BLI_gTurbulence(size, rco[0], rco[1], rco[2], 2,0,2);
2107         rough[1]=-1.0f+2.0f*BLI_gTurbulence(size, rco[1], rco[2], rco[0], 2,0,2);
2108         rough[2]=-1.0f+2.0f*BLI_gTurbulence(size, rco[2], rco[0], rco[1], 2,0,2);
2109
2110         VECADDFAC(state->co,state->co,mat[0],fac*rough[0]);
2111         VECADDFAC(state->co,state->co,mat[1],fac*rough[1]);
2112         VECADDFAC(state->co,state->co,mat[2],fac*rough[2]);
2113 }
2114 static void do_rough_end(float *loc, float mat[4][4], float t, float fac, float shape, ParticleKey *state)
2115 {
2116         float rough[2];
2117         float roughfac;
2118
2119         roughfac=fac*(float)pow((double)t,shape);
2120         Vec2Copyf(rough,loc);
2121         rough[0]=-1.0f+2.0f*rough[0];
2122         rough[1]=-1.0f+2.0f*rough[1];
2123         Vec2Mulf(rough,roughfac);
2124
2125         VECADDFAC(state->co,state->co,mat[0],rough[0]);
2126         VECADDFAC(state->co,state->co,mat[1],rough[1]);
2127 }
2128 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)
2129 {
2130         float force[3] = {0.0f,0.0f,0.0f};
2131         ParticleKey eff_key;
2132         EffectedPoint epoint;
2133
2134         /* Don't apply effectors for dynamic hair, otherwise the effectors don't get applied twice. */
2135         if(sim->psys->flag & PSYS_HAIR_DYNAMICS)
2136                 return;
2137
2138         VECCOPY(eff_key.co,(ca-1)->co);
2139         VECCOPY(eff_key.vel,(ca-1)->vel);
2140         QUATCOPY(eff_key.rot,(ca-1)->rot);
2141
2142         pd_point_from_particle(sim, sim->psys->particles+i, &eff_key, &epoint);
2143         pdDoEffectors(sim->psys->effectors, sim->colliders, sim->psys->part->effector_weights, &epoint, force, NULL);
2144
2145         VecMulf(force, effector*pow((float)k / (float)steps, 100.0f * sim->psys->part->eff_hair) / (float)steps);
2146
2147         VecAddf(force, force, vec);
2148
2149         Normalize(force);
2150
2151         VECADDFAC(ca->co, (ca-1)->co, force, *length);
2152
2153         if(k < steps) {
2154                 VecSubf(vec, (ca+1)->co, ca->co);
2155                 *length = VecLength(vec);
2156         }
2157 }
2158 static int check_path_length(int k, ParticleCacheKey *keys, ParticleCacheKey *state, float max_length, float *cur_length, float length, float *dvec)
2159 {
2160         if(*cur_length + length > max_length){
2161                 VecMulf(dvec, (max_length - *cur_length) / length);
2162                 VECADD(state->co, (state - 1)->co, dvec);
2163                 keys->steps = k;
2164                 /* something over the maximum step value */
2165                 return k=100000;
2166         }
2167         else {
2168                 *cur_length+=length;
2169                 return k;
2170         }
2171 }
2172 static void offset_child(ChildParticle *cpa, ParticleKey *par, ParticleKey *child, float flat, float radius)
2173 {
2174         VECCOPY(child->co,cpa->fuv);
2175         VecMulf(child->co,radius);
2176
2177         child->co[0]*=flat;
2178
2179         VECCOPY(child->vel,par->vel);
2180
2181         QuatMulVecf(par->rot,child->co);
2182
2183         QUATCOPY(child->rot,par->rot);
2184
2185         VECADD(child->co,child->co,par->co);
2186 }
2187 float *psys_cache_vgroup(DerivedMesh *dm, ParticleSystem *psys, int vgroup)
2188 {
2189         float *vg=0;
2190
2191         if(vgroup < 0) {
2192                 /* hair dynamics pinning vgroup */
2193
2194         }
2195         else if(psys->vgroup[vgroup]){
2196                 MDeformVert *dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
2197                 if(dvert){
2198                         int totvert=dm->getNumVerts(dm), i;
2199                         vg=MEM_callocN(sizeof(float)*totvert, "vg_cache");
2200                         if(psys->vg_neg&(1<<vgroup)){
2201                                 for(i=0; i<totvert; i++)
2202                                         vg[i]=1.0f-vert_weight(dvert+i,psys->vgroup[vgroup]-1);
2203                         }
2204                         else{
2205                                 for(i=0; i<totvert; i++)
2206                                         vg[i]=vert_weight(dvert+i,psys->vgroup[vgroup]-1);
2207                         }
2208                 }
2209         }
2210         return vg;
2211 }
2212 void psys_find_parents(ParticleSimulationData *sim)
2213 {
2214         ParticleSettings *part=sim->psys->part;
2215         KDTree *tree;
2216         ChildParticle *cpa;
2217         int p, totparent,totchild=sim->psys->totchild;
2218         float co[3], orco[3];
2219         int from=PART_FROM_FACE;
2220         totparent=(int)(totchild*part->parents*0.3);
2221
2222         if(G.rendering && part->child_nbr && part->ren_child_nbr)
2223                 totparent*=(float)part->child_nbr/(float)part->ren_child_nbr;
2224
2225         tree=BLI_kdtree_new(totparent);
2226
2227         for(p=0,cpa=sim->psys->child; p<totparent; p++,cpa++){
2228                 psys_particle_on_emitter(sim->psmd,from,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co,0,0,0,orco,0);
2229                 BLI_kdtree_insert(tree, p, orco, NULL);
2230         }
2231
2232         BLI_kdtree_balance(tree);
2233
2234         for(; p<totchild; p++,cpa++){
2235                 psys_particle_on_emitter(sim->psmd,from,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co,0,0,0,orco,0);
2236                 cpa->parent=BLI_kdtree_find_nearest(tree, orco, NULL, NULL);
2237         }
2238
2239         BLI_kdtree_free(tree);
2240 }
2241
2242 static void get_strand_normal(Material *ma, float *surfnor, float surfdist, float *nor)
2243 {
2244         float cross[3], nstrand[3], vnor[3], blend;
2245
2246         if(!((ma->mode & MA_STR_SURFDIFF) || (ma->strand_surfnor > 0.0f)))
2247                 return;
2248
2249         if(ma->mode & MA_STR_SURFDIFF) {
2250                 Crossf(cross, surfnor, nor);
2251                 Crossf(nstrand, nor, cross);
2252
2253                 blend= INPR(nstrand, surfnor);
2254                 CLAMP(blend, 0.0f, 1.0f);
2255
2256                 VecLerpf(vnor, nstrand, surfnor, blend);
2257                 Normalize(vnor);
2258         }
2259         else
2260                 VECCOPY(vnor, nor)
2261         
2262         if(ma->strand_surfnor > 0.0f) {
2263                 if(ma->strand_surfnor > surfdist) {
2264                         blend= (ma->strand_surfnor - surfdist)/ma->strand_surfnor;
2265                         VecLerpf(vnor, vnor, surfnor, blend);
2266                         Normalize(vnor);
2267                 }
2268         }
2269
2270         VECCOPY(nor, vnor);
2271 }
2272
2273 static int psys_threads_init_path(ParticleThread *threads, Scene *scene, float cfra, int editupdate)
2274 {
2275         ParticleThreadContext *ctx= threads[0].ctx;
2276 /*      Object *ob= ctx->sim.ob; */
2277         ParticleSystem *psys= ctx->sim.psys;
2278         ParticleSettings *part = psys->part;
2279         ParticleEditSettings *pset = &scene->toolsettings->particle;
2280         int totparent=0, between=0;
2281         int steps = (int)pow(2.0, (double)part->draw_step);
2282         int totchild = psys->totchild;
2283         int i, seed, totthread= threads[0].tot;
2284
2285         /*---start figuring out what is actually wanted---*/
2286         if(psys_in_edit_mode(scene, psys)) {
2287                 ParticleEditSettings *pset = &scene->toolsettings->particle;
2288
2289                 if(psys->renderdata==0 && (psys->edit==NULL || pset->flag & PE_DRAW_PART)==0)
2290                         totchild=0;
2291
2292                 steps = (int)pow(2.0, (double)pset->draw_step);
2293         }
2294
2295         if(totchild && part->from!=PART_FROM_PARTICLE && part->childtype==PART_CHILD_FACES){
2296                 totparent=(int)(totchild*part->parents*0.3);
2297                 
2298                 if(G.rendering && part->child_nbr && part->ren_child_nbr)
2299                         totparent*=(float)part->child_nbr/(float)part->ren_child_nbr;
2300
2301                 /* part->parents could still be 0 so we can't test with totparent */
2302                 between=1;
2303         }
2304
2305         if(psys->renderdata)
2306                 steps=(int)pow(2.0,(double)part->ren_step);
2307         else{
2308                 totchild=(int)((float)totchild*(float)part->disp/100.0f);
2309                 totparent=MIN2(totparent,totchild);
2310         }
2311
2312         if(totchild==0) return 0;
2313
2314         /* init random number generator */
2315         if(ctx->sim.psys->part->flag & PART_ANIM_BRANCHING)
2316                 seed= 31415926 + ctx->sim.psys->seed + (int)cfra;
2317         else
2318                 seed= 31415926 + ctx->sim.psys->seed;
2319         
2320         if(part->flag & PART_BRANCHING || ctx->editupdate || totchild < 10000)
2321                 totthread= 1;
2322         
2323         for(i=0; i<totthread; i++) {
2324                 threads[i].rng_path= rng_new(seed);
2325                 threads[i].tot= totthread;
2326         }
2327
2328         /* fill context values */
2329         ctx->between= between;
2330         ctx->steps= steps;
2331         ctx->totchild= totchild;
2332         ctx->totparent= totparent;
2333         ctx->parent_pass= 0;
2334         ctx->cfra= cfra;
2335
2336         psys->lattice = psys_get_lattice(&ctx->sim);
2337
2338         /* cache all relevant vertex groups if they exist */
2339         if(part->from!=PART_FROM_PARTICLE){
2340                 ctx->vg_length = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_LENGTH);
2341                 ctx->vg_clump = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_CLUMP);
2342                 ctx->vg_kink = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_KINK);
2343                 ctx->vg_rough1 = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGH1);
2344                 ctx->vg_rough2 = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGH2);
2345                 ctx->vg_roughe = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGHE);
2346                 if(psys->part->flag & PART_CHILD_EFFECT)
2347                         ctx->vg_effector = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_EFFECTOR);
2348         }
2349
2350         /* set correct ipo timing */
2351 #if 0 // XXX old animation system
2352         if(part->flag&PART_ABS_TIME && part->ipo){
2353                 calc_ipo(part->ipo, cfra);
2354                 execute_ipo((ID *)part, part->ipo);
2355         }
2356 #endif // XXX old animation system
2357
2358         return 1;
2359 }
2360
2361 /* note: this function must be thread safe, except for branching! */
2362 static void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa, ParticleCacheKey *keys, int i)
2363 {
2364         ParticleThreadContext *ctx= thread->ctx;
2365         Object *ob= ctx->sim.ob;
2366         ParticleSystem *psys = ctx->sim.psys;
2367         ParticleSettings *part = psys->part;
2368         ParticleCacheKey **cache= psys->childcache;
2369         ParticleCacheKey **pcache= psys_in_edit_mode(ctx->sim.scene, psys) ? psys->edit->pathcache : psys->pathcache;
2370         ParticleCacheKey *state, *par = NULL, *key[4];
2371         ParticleData *pa=NULL;
2372         ParticleTexture ptex;
2373         float *cpa_fuv=0, *par_rot=0;
2374         float co[3], orco[3], ornor[3], hairmat[4][4], t, cpa_1st[3], dvec[3];
2375         float branch_begin, branch_end, branch_prob, rough_rand;
2376         float length, max_length = 1.0f, cur_length = 0.0f;
2377         float eff_length, eff_vec[3];
2378         int k, cpa_num;
2379         short cpa_from;
2380
2381         if(!pcache)
2382                 return;
2383
2384         if(part->flag & PART_BRANCHING) {
2385                 branch_begin=rng_getFloat(thread->rng_path);
2386                 branch_end=branch_begin+(1.0f-branch_begin)*rng_getFloat(thread->rng_path);
2387                 branch_prob=rng_getFloat(thread->rng_path);
2388                 rough_rand=rng_getFloat(thread->rng_path);
2389         }
2390         else {
2391                 branch_begin= 0.0f;
2392                 branch_end= 0.0f;
2393                 branch_prob= 0.0f;
2394                 rough_rand= 0.0f;
2395         }
2396
2397         if(i<psys->totpart){
2398                 branch_begin=0.0f;
2399                 branch_end=1.0f;
2400                 branch_prob=0.0f;
2401         }
2402
2403         if(ctx->between){
2404                 int w, needupdate;
2405                 float foffset;
2406
2407                 if(ctx->editupdate && !(part->flag & PART_BRANCHING)) {
2408                         needupdate= 0;
2409                         w= 0;
2410                         while(w<4 && cpa->pa[w]>=0) {
2411                                 if(psys->edit->points[cpa->pa[w]].flag & PEP_EDIT_RECALC) {
2412                                         needupdate= 1;
2413                                         break;
2414                                 }
2415                                 w++;
2416                         }
2417
2418                         if(!needupdate)
2419                                 return;
2420                         else
2421                                 memset(keys, 0, sizeof(*keys)*(ctx->steps+1));
2422                 }
2423
2424                 /* get parent paths */
2425                 w= 0;
2426                 while(w<4 && cpa->pa[w]>=0){
2427                         key[w] = pcache[cpa->pa[w]];
2428                         w++;
2429                 }
2430
2431                 /* get the original coordinates (orco) for texture usage */
2432                 cpa_num = cpa->num;
2433                 
2434                 foffset= cpa->foffset;
2435                 cpa_fuv = cpa->fuv;
2436                 cpa_from = PART_FROM_FACE;
2437
2438                 psys_particle_on_emitter(ctx->sim.psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa->fuv,foffset,co,ornor,0,0,orco,0);
2439
2440                 if(part->path_start==0.0f) {
2441                         /* we need to save the actual root position of the child for positioning it accurately to the surface of the emitter */
2442                         VECCOPY(cpa_1st,co);
2443                         Mat4MulVecfl(ob->obmat,cpa_1st);
2444                 }
2445
2446                 pa = psys->particles + cpa->parent;
2447
2448                 psys_mat_hair_to_global(ob, ctx->sim.psmd->dm, psys->part->from, pa, hairmat);
2449
2450                 pa=0;
2451         }
2452         else{
2453                 if(ctx->editupdate && !(part->flag & PART_BRANCHING)) {
2454                         if(!(psys->edit->points[cpa->parent].flag & PEP_EDIT_RECALC))
2455                                 return;
2456
2457                         memset(keys, 0, sizeof(*keys)*(ctx->steps+1));
2458                 }
2459
2460                 /* get the parent path */
2461                 key[0]=pcache[cpa->parent];
2462
2463                 /* get the original coordinates (orco) for texture usage */
2464                 pa=psys->particles+cpa->parent;
2465
2466                 cpa_from=part->from;
2467                 cpa_num=pa->num;
2468                 cpa_fuv=pa->fuv;
2469
2470                 psys_particle_on_emitter(ctx->sim.psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa_fuv,pa->foffset,co,ornor,0,0,orco,0);
2471
2472                 psys_mat_hair_to_global(ob, ctx->sim.psmd->dm, psys->part->from, pa, hairmat);
2473         }
2474
2475         keys->steps = ctx->steps;
2476
2477         /* correct child ipo timing */
2478 #if 0 // XXX old animation system
2479         if((part->flag&PART_ABS_TIME)==0 && part->ipo){
2480                 float dsta=part->end-part->sta;
2481                 calc_ipo(part->ipo, 100.0f*(ctx->cfra-(part->sta+dsta*cpa->rand[1]))/(part->lifetime*(1.0f - part->randlife*cpa->rand[0])));
2482                 execute_ipo((ID *)part, part->ipo);
2483         }
2484 #endif // XXX old animation system
2485
2486         /* get different child parameters from textures & vgroups */
2487         get_child_modifier_parameters(part, ctx, cpa, cpa_from, cpa_num, cpa_fuv, orco, &ptex);
2488
2489         if(ptex.exist < PSYS_FRAND(i + 24)) {
2490                 keys->steps = -1;
2491                 return;
2492         }
2493
2494         /* create the child path */
2495         for(k=0,state=keys; k<=ctx->steps; k++,state++){
2496                 if(ctx->between){
2497                         int w=0;
2498
2499                         state->co[0] = state->co[1] = state->co[2] = 0.0f;
2500                         state->vel[0] = state->vel[1] = state->vel[2] = 0.0f;
2501                         state->rot[0] = state->rot[1] = state->rot[2] = state->rot[3] = 0.0f;
2502
2503                         //QUATCOPY(state->rot,key[0]->rot);
2504
2505                         /* child position is the weighted sum of parent positions */
2506                         while(w<4 && cpa->pa[w]>=0){
2507                                 state->co[0] += cpa->w[w] * key[w]->co[0];
2508                                 state->co[1] += cpa->w[w] * key[w]->co[1];
2509                                 state->co[2] += cpa->w[w] * key[w]->co[2];
2510
2511                                 state->vel[0] += cpa->w[w] * key[w]->vel[0];
2512                                 state->vel[1] += cpa->w[w] * key[w]->vel[1];
2513                                 state->vel[2] += cpa->w[w] * key[w]->vel[2];
2514                                 key[w]++;
2515                                 w++;
2516                         }
2517                         if(part->path_start==0.0f) {
2518                                 if(k==0){
2519                                         /* calculate the offset between actual child root position and first position interpolated from parents */
2520                                         VECSUB(cpa_1st,cpa_1st,state->co);
2521                                 }
2522                                 /* apply offset for correct positioning */
2523                                 VECADD(state->co,state->co,cpa_1st);
2524                         }
2525                 }
2526                 else{
2527                         /* offset the child from the parent position */
2528                         offset_child(cpa, (ParticleKey*)key[0], (ParticleKey*)state, part->childflat, part->childrad);
2529
2530                         key[0]++;
2531                 }
2532         }
2533
2534         /* apply effectors */
2535         if(part->flag & PART_CHILD_EFFECT) {
2536                 for(k=0,state=keys; k<=ctx->steps; k++,state++) {
2537                         if(k) {
2538                                 do_path_effectors(&ctx->sim, cpa->pa[0], state, k, ctx->steps, keys->co, ptex.effector, 0.0f, ctx->cfra, &eff_length, eff_vec);
2539                         }
2540                         else {
2541                                 VecSubf(eff_vec,(state+1)->co,state->co);
2542                                 eff_length= VecLength(eff_vec);
2543                         }
2544                 }
2545         }
2546
2547         for(k=0,state=keys; k<=ctx->steps; k++,state++){
2548                 t=(float)k/(float)ctx->steps;
2549
2550                 if(ctx->totparent){
2551                         if(i>=ctx->totparent) {
2552                                 /* this is now threadsafe, virtual parents are calculated before rest of children */
2553                                 par = cache[cpa->parent] + k;
2554                         }
2555                         else
2556                                 par=0;
2557                 }
2558                 else if(cpa->parent>=0){
2559                         par=pcache[cpa->parent]+k;
2560                         par_rot = par->rot;
2561                 }
2562
2563                 /* apply different deformations to the child path */
2564                 do_child_modifiers(&ctx->sim, &ptex, (ParticleKey *)par, par_rot, cpa, orco, hairmat, (ParticleKey *)state, t);
2565
2566                 /* TODO: better branching */
2567                 //if(part->flag & PART_BRANCHING && ctx->between == 0 && part->flag & PART_ANIM_BRANCHING)
2568                 //      rough_t = t * rough_rand;
2569                 //else
2570                 //      rough_t = t;
2571
2572                 /* TODO: better branching */
2573                 //if(part->flag & PART_BRANCHING && ctx->between==0){
2574                 //      if(branch_prob > part->branch_thres){
2575                 //              branchfac=0.0f;
2576                 //      }
2577                 //      else{
2578                 //              if(part->flag & PART_SYMM_BRANCHING){
2579                 //                      if(t < branch_begin || t > branch_end)
2580                 //                              branchfac=0.0f;
2581                 //                      else{
2582                 //                              if((t-branch_begin)/(branch_end-branch_begin)<0.5)
2583                 //                                      branchfac=2.0f*(t-branch_begin)/(branch_end-branch_begin);
2584                 //                              else
2585                 //                                      branchfac=2.0f*(branch_end-t)/(branch_end-branch_begin);
2586
2587                 //                              CLAMP(branchfac,0.0f,1.0f);
2588                 //                      }
2589                 //              }
2590                 //              else{
2591                 //                      if(t < branch_begin){
2592                 //                              branchfac=0.0f;
2593                 //                      }
2594                 //                      else{
2595                 //                              branchfac=(t-branch_begin)/((1.0f-branch_begin)*0.5f);
2596                 //                              CLAMP(branchfac,0.0f,1.0f);
2597                 //                      }
2598                 //              }
2599                 //      }
2600
2601                 //      if(i<psys->totpart)
2602                 //              VecLerpf(state->co, (pcache[i] + k)->co, state->co, branchfac);
2603                 //      else
2604                 //              /* this is not threadsafe, but should only happen for
2605                 //               * branching particles particles, which are not threaded */
2606                 //              VecLerpf(state->co, (cache[i - psys->totpart] + k)->co, state->co, branchfac);
2607                 //}
2608
2609                 /* we have to correct velocity because of kink & clump */
2610                 if(k>1){
2611                         VECSUB((state-1)->vel,state->co,(state-2)->co);
2612                         VecMulf((state-1)->vel,0.5);
2613
2614                         if(ctx->ma && (part->draw & PART_DRAW_MAT_COL))
2615                                 get_strand_normal(ctx->ma, ornor, cur_length, (state-1)->vel);
2616                 }
2617
2618                 /* check if path needs to be cut before actual end of data points */
2619                 if(k){
2620                         VECSUB(dvec,state->co,(state-1)->co);
2621                         length=1.0f/(float)ctx->steps;
2622                         k=check_path_length(k,keys,state,max_length,&cur_length,length,dvec);
2623                 }
2624                 else{
2625                         /* initialize length calculation */
2626                         max_length= ptex.length;
2627                         cur_length= 0.0f;
2628                 }
2629
2630                 if(ctx->ma && (part->draw & PART_DRAW_MAT_COL)) {
2631                         VECCOPY(state->col, &ctx->ma->r)
2632                         get_strand_normal(ctx->ma, ornor, cur_length, state->vel);
2633                 }
2634         }
2635 }
2636
2637 static void *exec_child_path_cache(void *data)
2638 {
2639         ParticleThread *thread= (ParticleThread*)data;
2640         ParticleThreadContext *ctx= thread->ctx;
2641         ParticleSystem *psys= ctx->sim.psys;
2642         ParticleCacheKey **cache= psys->childcache;
2643         ChildParticle *cpa;
2644         int i, totchild= ctx->totchild, first= 0;
2645
2646         if(thread->tot > 1){
2647                 first= ctx->parent_pass? 0 : ctx->totparent;
2648                 totchild= ctx->parent_pass? ctx->totparent : ctx->totchild;
2649         }
2650         
2651         cpa= psys->child + first + thread->num;
2652         for(i=first+thread->num; i<totchild; i+=thread->tot, cpa+=thread->tot)
2653                 psys_thread_create_path(thread, cpa, cache[i], i);
2654
2655         return 0;
2656 }
2657
2658 void psys_cache_child_paths(ParticleSimulationData *sim, float cfra, int editupdate)
2659 {
2660         ParticleSettings *part = sim->psys->part;
2661         ParticleThread *pthreads;
2662         ParticleThreadContext *ctx;
2663         ParticleCacheKey **cache;
2664         ListBase threads;
2665         int i, totchild, totparent, totthread;
2666
2667         if(sim->psys->flag & PSYS_GLOBAL_HAIR)
2668                 return;
2669
2670         pthreads= psys_threads_create(sim);
2671
2672         if(!psys_threads_init_path(pthreads, sim->scene, cfra, editupdate)) {
2673                 psys_threads_free(pthreads);
2674                 return;
2675         }
2676
2677         ctx= pthreads[0].ctx;
2678         totchild= ctx->totchild;
2679         totparent= ctx->totparent;
2680
2681         if(editupdate && sim->psys->childcache && !(part->flag & PART_BRANCHING) && totchild == sim->psys->totchildcache) {
2682                 cache = sim->psys->childcache;
2683         }
2684         else {
2685                 /* clear out old and create new empty path cache */
2686                 free_child_path_cache(sim->psys);
2687                 sim->psys->childcache= psys_alloc_path_cache_buffers(&sim->psys->childcachebufs, totchild, ctx->steps+1);
2688                 sim->psys->totchildcache = totchild;
2689         }
2690
2691         totthread= pthreads[0].tot;
2692
2693         if(totthread > 1) {
2694
2695                 /* make virtual child parents thread safe by calculating them first */
2696                 if(totparent) {
2697                         BLI_init_threads(&threads, exec_child_path_cache, totthread);
2698                         
2699                         for(i=0; i<totthread; i++) {
2700                                 pthreads[i].ctx->parent_pass = 1;
2701                                 BLI_insert_thread(&threads, &pthreads[i]);
2702                         }
2703
2704                         BLI_end_threads(&threads);
2705
2706                         for(i=0; i<totthread; i++)
2707                                 pthreads[i].ctx->parent_pass = 0;
2708                 }
2709
2710                 BLI_init_threads(&threads, exec_child_path_cache, totthread);
2711
2712                 for(i=0; i<totthread; i++)
2713                         BLI_insert_thread(&threads, &pthreads[i]);
2714
2715                 BLI_end_threads(&threads);
2716         }
2717         else
2718                 exec_child_path_cache(&pthreads[0]);
2719
2720         psys_threads_free(pthreads);
2721 }
2722 /* Calculates paths ready for drawing/rendering.                                                                        */
2723 /* -Usefull for making use of opengl vertex arrays for super fast strand drawing.       */
2724 /* -Makes child strands possible and creates them too into the cache.                           */
2725 /* -Cached path data is also used to determine cut position for the editmode tool.      */
2726 void psys_cache_paths(ParticleSimulationData *sim, float cfra)
2727 {
2728         PARTICLE_PSMD;
2729         ParticleEditSettings *pset = &sim->scene->toolsettings->particle;
2730         ParticleSystem *psys = sim->psys;
2731         ParticleSettings *part = psys->part;
2732         ParticleCacheKey *ca, **cache= psys->pathcache;
2733
2734         DerivedMesh *hair_dm = psys->hair_out_dm;
2735         
2736         ParticleKey result;
2737         
2738         Material *ma;
2739         ParticleInterpolationData pind;
2740
2741         PARTICLE_P;
2742         
2743         float birthtime = 0.0, dietime = 0.0;
2744         float t, time = 0.0, dfra = 1.0, frs_sec = sim->scene->r.frs_sec;
2745         float col[4] = {0.5f, 0.5f, 0.5f, 1.0f};
2746         float prev_tangent[3], hairmat[4][4];
2747         float rotmat[3][3];
2748         int k;
2749         int steps = (int)pow(2.0, (double)(psys->renderdata ? part->ren_step : part->draw_step));
2750         int totpart = psys->totpart;
2751         float length, vec[3];
2752         float *vg_effector= NULL, effector=0.0f;
2753         float *vg_length= NULL, pa_length=1.0f;
2754         int keyed, baked;
2755
2756         /* we don't have anything valid to create paths from so let's quit here */
2757         if((psys->flag & PSYS_HAIR_DONE || psys->flag & PSYS_KEYED || psys->pointcache->flag & PTCACHE_BAKED)==0)
2758                 return;
2759
2760         if(psys_in_edit_mode(sim->scene, psys))
2761                 if(psys->renderdata==0 && (psys->edit==NULL || pset->flag & PE_DRAW_PART)==0)
2762                         return;
2763         
2764         BLI_srandom(psys->seed);
2765
2766         keyed = psys->flag & PSYS_KEYED;
2767         baked = !hair_dm && psys->pointcache->flag & PTCACHE_BAKED;
2768
2769         /* clear out old and create new empty path cache */
2770         psys_free_path_cache(psys, psys->edit);
2771         cache= psys->pathcache= psys_alloc_path_cache_buffers(&psys->pathcachebufs, totpart, steps+1);
2772
2773         psys->lattice = psys_get_lattice(sim);
2774         ma= give_current_material(sim->ob, psys->part->omat);
2775         if(ma && (psys->part->draw & PART_DRAW_MAT_COL))
2776                 VECCOPY(col, &ma->r)
2777
2778         if(psys->part->from!=PART_FROM_PARTICLE && !(psys->flag & PSYS_GLOBAL_HAIR)) {
2779                 if(!(psys->part->flag & PART_CHILD_EFFECT))
2780                         vg_effector = psys_cache_vgroup(psmd->dm, psys, PSYS_VG_EFFECTOR);
2781                 
2782                 if(!psys->totchild)
2783                         vg_length = psys_cache_vgroup(psmd->dm, psys, PSYS_VG_LENGTH);
2784         }
2785
2786         /*---first main loop: create all actual particles' paths---*/
2787         LOOP_SHOWN_PARTICLES {
2788                 if(!psys->totchild) {
2789                         BLI_srandom(psys->seed + p);
2790                         pa_length = 1.0f - part->randlength * BLI_frand();
2791                         if(vg_length)
2792                                 pa_length *= psys_particle_value_from_verts(psmd->dm,part->from,pa,vg_length);
2793                 }
2794
2795                 pind.keyed = keyed;
2796                 pind.cache = baked ? psys->pointcache : NULL;
2797                 pind.epoint = NULL;
2798                 pind.bspline = (psys->part->flag & PART_HAIR_BSPLINE);
2799                 pind.dm = hair_dm;
2800
2801                 memset(cache[p], 0, sizeof(*cache[p])*(steps+1));
2802
2803                 cache[p]->steps = steps;
2804
2805                 /*--get the first data points--*/
2806                 init_particle_interpolation(sim->ob, sim->psys, pa, &pind);
2807
2808                 /* hairmat is needed for for non-hair particle too so we get proper rotations */
2809                 psys_mat_hair_to_global(sim->ob, psmd->dm, psys->part->from, pa, hairmat);
2810                 VECCOPY(rotmat[0], hairmat[2]);
2811                 VECCOPY(rotmat[1], hairmat[1]);
2812                 VECCOPY(rotmat[2], hairmat[0]);
2813
2814                 if(part->draw & PART_ABS_PATH_TIME) {
2815                         birthtime = MAX2(pind.birthtime, part->path_start);
2816                         dietime = MIN2(pind.dietime, part->path_end);
2817                 }
2818                 else {
2819                         float tb = pind.birthtime;
2820                         birthtime = tb + part->path_start * (pind.dietime - tb);
2821                         dietime = tb + part->path_end * (pind.dietime - tb);
2822                 }
2823
2824                 if(birthtime >= dietime) {
2825                         cache[p]->steps = -1;
2826                         continue;
2827                 }
2828
2829                 dietime = birthtime + pa_length * (dietime - birthtime);
2830
2831                 /*--interpolate actual path from data points--*/
2832                 for(k=0, ca=cache[p]; k<=steps; k++, ca++){
2833                         time = (float)k / (float)steps;
2834
2835                         t = birthtime + time * (dietime - birthtime);
2836
2837                         result.time = -t;
2838
2839                         do_particle_interpolation(psys, p, pa, t, frs_sec, &pind, &result);
2840
2841                         /* dynamic hair is in object space */
2842                         /* keyed and baked are allready in global space */
2843                         if(hair_dm)
2844                                 Mat4MulVecfl(sim->ob->obmat, result.co);
2845                         else if(!keyed && !baked && !(psys->flag & PSYS_GLOBAL_HAIR))
2846                                 Mat4MulVecfl(hairmat, result.co);
2847
2848                         VECCOPY(ca->co, result.co);
2849                         VECCOPY(ca->col, col);
2850                 }
2851                 
2852                 /*--modify paths and calculate rotation & velocity--*/
2853
2854                 VecSubf(vec,(cache[p]+1)->co,cache[p]->co);
2855                 length = VecLength(vec);
2856
2857                 effector= 1.0f;
2858                 if(vg_effector)
2859                         effector*= psys_particle_value_from_verts(psmd->dm,psys->part->from,pa,vg_effector);
2860
2861                 for(k=0, ca=cache[p]; k<=steps; k++, ca++) {
2862                         if(!(psys->flag & PSYS_GLOBAL_HAIR)) {
2863                         /* apply effectors */
2864                                 if(!(psys->part->flag & PART_CHILD_EFFECT) && k)
2865                                         do_path_effectors(sim, p, ca, k, steps, cache[p]->co, effector, dfra, cfra, &length, vec);
2866
2867                                 /* apply guide curves to path data */
2868                                 if(sim->psys->effectors && (psys->part->flag & PART_CHILD_EFFECT)==0)
2869                                         /* ca is safe to cast, since only co and vel are used */
2870                                         do_guides(sim->psys->effectors, (ParticleKey*)ca, p, (float)k/(float)steps);
2871
2872                                 /* apply lattice */
2873                                 if(psys->lattice)
2874                                         calc_latt_deform(psys->lattice, ca->co, 1.0f);
2875
2876                                 /* figure out rotation */
2877                                 
2878                                 if(k) {
2879                                         float cosangle, angle, tangent[3], normal[3], q[4];
2880
2881                                         if(k == 1) {
2882                                                 /* calculate initial tangent for incremental rotations */
2883                                                 VECSUB(tangent, ca->co, (ca - 1)->co);
2884                                                 VECCOPY(prev_tangent, tangent);
2885                                                 Normalize(prev_tangent);
2886
2887                                                 /* First rotation is based on emitting face orientation.                */
2888                                                 /* This is way better than having flipping rotations resulting  */
2889                                                 /* from using a global axis as a rotation pole (vec_to_quat()). */
2890                                                 /* It's not an ideal solution though since it disregards the    */
2891                                                 /* initial tangent, but taking that in to account will allow    */
2892                                                 /* the possibility of flipping again. -jahka                                    */
2893                                                 Mat3ToQuat_is_ok(rotmat, (ca-1)->rot);
2894                                         }
2895                                         else {
2896                                                 VECSUB(tangent, ca->co, (ca - 1)->co);
2897                                                 Normalize(tangent);
2898
2899                                                 cosangle= Inpf(tangent, prev_tangent);
2900
2901                                                 /* note we do the comparison on cosangle instead of
2902                                                 * angle, since floating point accuracy makes it give
2903                                                 * different results across platforms */
2904                                                 if(cosangle > 0.999999f) {
2905                                                         QUATCOPY((ca - 1)->rot, (ca - 2)->rot);
2906                                                 }
2907                                                 else {
2908                                                         angle= saacos(cosangle);
2909                                                         Crossf(normal, prev_tangent, tangent);
2910                                                         VecRotToQuat(normal, angle, q);
2911                                                         QuatMul((ca - 1)->rot, q, (ca - 2)->rot);
2912                                                 }
2913
2914                                                 VECCOPY(prev_tangent, tangent);
2915                                         }
2916
2917                                         if(k == steps)
2918                                                 QUATCOPY(ca->rot, (ca - 1)->rot);
2919                                 }
2920
2921                         }
2922                         
2923                         /* set velocity */
2924
2925                         if(k){
2926                                 VECSUB(ca->vel, ca->co, (ca-1)->co);
2927
2928                                 if(k==1) {
2929                                         VECCOPY((ca-1)->vel, ca->vel);
2930                                 }
2931
2932                         }
2933                 }
2934         }
2935
2936         psys->totcached = totpart;
2937
2938         if(psys && psys->lattice){
2939                 end_latt_deform(psys->lattice);
2940                 psys->lattice= NULL;
2941         }
2942
2943         if(vg_effector)
2944                 MEM_freeN(vg_effector);
2945
2946         if(vg_length)
2947                 MEM_freeN(vg_length);
2948 }
2949 void psys_cache_edit_paths(Scene *scene, Object *ob, PTCacheEdit *edit, float cfra)
2950 {
2951         ParticleCacheKey *ca, **cache= edit->pathcache;
2952         ParticleEditSettings *pset = &scene->toolsettings->particle;
2953         
2954         PTCacheEditPoint *point = edit->points;
2955         PTCacheEditKey *ekey = NULL;
2956
2957         ParticleSystem *psys = edit->psys;
2958         ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys);
2959         ParticleData *pa = psys ? psys->particles : NULL;
2960
2961         ParticleInterpolationData pind;
2962         ParticleKey result;
2963         
2964         float birthtime = 0.0, dietime = 0.0;
2965         float t, time = 0.0, keytime = 0.0, frs_sec;
2966         float hairmat[4][4], rotmat[3][3], prev_tangent[3];
2967         int k,i;
2968         int steps = (int)pow(2.0, (double)pset->draw_step);
2969         int totpart = edit->totpoint;
2970         float sel_col[3];
2971         float nosel_col[3];
2972
2973         steps = MAX2(steps, 4);
2974
2975         if(!cache || edit->totpoint != edit->totcached) {
2976                 /* clear out old and create new empty path cache */
2977                 psys_free_path_cache(edit->psys, edit);
2978                 cache= edit->pathcache= psys_alloc_path_cache_buffers(&edit->pathcachebufs, totpart, steps+1);
2979         }
2980
2981         frs_sec = (psys || edit->pid.flag & PTCACHE_VEL_PER_SEC) ? 25.0f : 1.0f;
2982
2983         sel_col[0] = (float)edit->sel_col[0] / 255.0f;
2984         sel_col[1] = (float)edit->sel_col[1] / 255.0f;
2985         sel_col[2] = (float)edit->sel_col[2] / 255.0f;
2986         nosel_col[0] = (float)edit->nosel_col[0] / 255.0f;
2987         nosel_col[1] = (float)edit->nosel_col[1] / 255.0f;
2988         nosel_col[2] = (float)edit->nosel_col[2] / 255.0f;
2989
2990         /*---first main loop: create all actual particles' paths---*/
2991         for(i=0; i<totpart; i++, pa+=pa?1:0, point++){
2992                 if(edit->totcached && !(point->flag & PEP_EDIT_RECALC))
2993                         continue;
2994
2995                 ekey = point->keys;
2996
2997                 pind.keyed = 0;
2998                 pind.cache = NULL;
2999                 pind.epoint = point;
3000                 pind.bspline = psys ? (psys->part->flag & PART_HAIR_BSPLINE) : 0;
3001                 pind.dm = NULL;
3002
3003                 memset(cache[i], 0, sizeof(*cache[i])*(steps+1));
3004
3005                 cache[i]->steps = steps;
3006
3007                 /*--get the first data points--*/
3008                 init_particle_interpolation(ob, psys, pa, &pind);
3009
3010                 if(psys) {
3011                         psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, pa, hairmat);
3012                         VECCOPY(rotmat[0], hairmat[2]);
3013                         VECCOPY(rotmat[1], hairmat[1]);
3014                         VECCOPY(rotmat[2], hairmat[0]);
3015                 }
3016
3017                 birthtime = pind.birthtime;
3018                 dietime = pind.dietime;
3019
3020                 if(birthtime >= dietime) {
3021                         cache[i]->steps = -1;
3022                         continue;
3023                 }
3024
3025                 /*--interpolate actual path from data points--*/
3026                 for(k=0, ca=cache[i]; k<=steps; k++, ca++){
3027                         time = (float)k / (float)steps;
3028
3029                         t = birthtime + time * (dietime - birthtime);
3030
3031                         result.time = -t;
3032
3033                         do_particle_interpolation(psys, i, pa, t, frs_sec, &pind, &result);
3034
3035                          /* non-hair points are allready in global space */
3036                         if(psys && !(psys->flag & PSYS_GLOBAL_HAIR)) {
3037                                 Mat4MulVecfl(hairmat, result.co);
3038
3039                                 /* create rotations for proper creation of children */
3040                                 if(k) {
3041                                         float cosangle, angle, tangent[3], normal[3], q[4];
3042
3043                                         if(k == 1) {
3044                                                 /* calculate initial tangent for incremental rotations */
3045                                                 VECSUB(tangent, ca->co, (ca - 1)->co);
3046                                                 VECCOPY(prev_tangent, tangent);
3047                                                 Normalize(prev_tangent);
3048
3049                                                 /* First rotation is based on emitting face orientation.                */
3050                                                 /* This is way better than having flipping rotations resulting  */
3051                                                 /* from using a global axis as a rotation pole (vec_to_quat()). */
3052                                                 /* It's not an ideal solution though since it disregards the    */
3053                                                 /* initial tangent, but taking that in to account will allow    */
3054                                                 /* the possibility of flipping again. -jahka                                    */
3055                                                 Mat3ToQuat_is_ok(rotmat, (ca-1)->rot);
3056                                         }
3057                                         else {
3058                                                 VECSUB(tangent, ca->co, (ca - 1)->co);
3059                                                 Normalize(tangent);
3060
3061                                                 cosangle= Inpf(tangent, prev_tangent);
3062
3063                                                 /* note we do the comparison on cosangle instead of
3064                                                 * angle, since floating point accuracy makes it give
3065                                                 * different results across platforms */
3066                                                 if(cosangle > 0.999999f) {
3067                                                         QUATCOPY((ca - 1)->rot, (ca - 2)->rot);
3068                                           &nbs