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