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