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