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