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