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