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