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