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