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