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