New: Editable cache. Fixed: Don't clear cache on e.g. lamp moving. Changed: Switched...
[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)
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(ve){
792                 //      if(dt>0.999f){
793                 //              set_four_ipo(dt+0.001f,t,ipo_type);
794                 //              weighted_particle_vector(key0->co,key1->co,key2->co,key3->co,t,temp);
795                 //              VECSUB(ve,temp,co);
796                 //      }
797                 //      else{
798                 //              set_four_ipo(dt-0.001f,t,ipo_type);
799                 //              weighted_particle_vector(key0->co,key1->co,key2->co,key3->co,t,temp);
800                 //              VECSUB(ve,co,temp);
801                 //      }
802                 //}
803         }
804 }
805
806
807
808 /************************************************/
809 /*                      Particles on a dm                                       */
810 /************************************************/
811 /* interpolate a location on a face based on face coordinates */
812 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){
813         float *v1=0, *v2=0, *v3=0, *v4=0;
814         float e1[3],e2[3],s1,s2,t1,t2;
815         float *uv1, *uv2, *uv3, *uv4;
816         float n1[3], n2[3], n3[3], n4[3];
817         float tuv[4][2];
818         float *o1, *o2, *o3, *o4;
819
820         v1= (mvert+mface->v1)->co;
821         v2= (mvert+mface->v2)->co;
822         v3= (mvert+mface->v3)->co;
823         VECCOPY(n1,(mvert+mface->v1)->no);
824         VECCOPY(n2,(mvert+mface->v2)->no);
825         VECCOPY(n3,(mvert+mface->v3)->no);
826         Normalize(n1);
827         Normalize(n2);
828         Normalize(n3);
829
830         if(mface->v4) {
831                 v4= (mvert+mface->v4)->co;
832                 VECCOPY(n4,(mvert+mface->v4)->no);
833                 Normalize(n4);
834                 
835                 vec[0]= w[0]*v1[0] + w[1]*v2[0] + w[2]*v3[0] + w[3]*v4[0];
836                 vec[1]= w[0]*v1[1] + w[1]*v2[1] + w[2]*v3[1] + w[3]*v4[1];
837                 vec[2]= w[0]*v1[2] + w[1]*v2[2] + w[2]*v3[2] + w[3]*v4[2];
838
839                 if(nor){
840                         if(mface->flag & ME_SMOOTH){
841                                 nor[0]= w[0]*n1[0] + w[1]*n2[0] + w[2]*n3[0] + w[3]*n4[0];
842                                 nor[1]= w[0]*n1[1] + w[1]*n2[1] + w[2]*n3[1] + w[3]*n4[1];
843                                 nor[2]= w[0]*n1[2] + w[1]*n2[2] + w[2]*n3[2] + w[3]*n4[2];
844                         }
845                         else
846                                 CalcNormFloat4(v1,v2,v3,v4,nor);
847                 }
848         }
849         else {
850                 vec[0]= w[0]*v1[0] + w[1]*v2[0] + w[2]*v3[0];
851                 vec[1]= w[0]*v1[1] + w[1]*v2[1] + w[2]*v3[1];
852                 vec[2]= w[0]*v1[2] + w[1]*v2[2] + w[2]*v3[2];
853                 
854                 if(nor){
855                         if(mface->flag & ME_SMOOTH){
856                                 nor[0]= w[0]*n1[0] + w[1]*n2[0] + w[2]*n3[0];
857                                 nor[1]= w[0]*n1[1] + w[1]*n2[1] + w[2]*n3[1];
858                                 nor[2]= w[0]*n1[2] + w[1]*n2[2] + w[2]*n3[2];
859                         }
860                         else
861                                 CalcNormFloat(v1,v2,v3,nor);
862                 }
863         }
864         
865         /* calculate tangent vectors */
866         if(utan && vtan){
867                 if(tface){
868                         uv1= tface->uv[0];
869                         uv2= tface->uv[1];
870                         uv3= tface->uv[2];
871                         uv4= tface->uv[3];
872                 }
873                 else{
874                         uv1= tuv[0]; uv2= tuv[1]; uv3= tuv[2]; uv4= tuv[3];
875                         spheremap(v1[0], v1[1], v1[2], uv1, uv1+1);
876                         spheremap(v2[0], v2[1], v2[2], uv2, uv2+1);
877                         spheremap(v3[0], v3[1], v3[2], uv3, uv3+1);
878                         if(v4)
879                                 spheremap(v4[0], v4[1], v4[2], uv4, uv4+1);
880                 }
881
882                 if(v4){
883                         s1= uv3[0] - uv1[0];
884                         s2= uv4[0] - uv1[0];
885
886                         t1= uv3[1] - uv1[1];
887                         t2= uv4[1] - uv1[1];
888
889                         VecSubf(e1, v3, v1);
890                         VecSubf(e2, v4, v1);
891                 }
892                 else{
893                         s1= uv2[0] - uv1[0];
894                         s2= uv3[0] - uv1[0];
895
896                         t1= uv2[1] - uv1[1];
897                         t2= uv3[1] - uv1[1];
898
899                         VecSubf(e1, v2, v1);
900                         VecSubf(e2, v3, v1);
901                 }
902
903                 vtan[0] = (s1*e2[0] - s2*e1[0]);
904                 vtan[1] = (s1*e2[1] - s2*e1[1]);
905                 vtan[2] = (s1*e2[2] - s2*e1[2]);
906
907                 utan[0] = (t1*e2[0] - t2*e1[0]);
908                 utan[1] = (t1*e2[1] - t2*e1[1]);
909                 utan[2] = (t1*e2[2] - t2*e1[2]);
910         }
911
912         if(orco) {
913                 if(orcodata) {
914                         o1= orcodata[mface->v1];
915                         o2= orcodata[mface->v2];
916                         o3= orcodata[mface->v3];
917
918                         if(mface->v4) {
919                                 o4= orcodata[mface->v4];
920                                 orco[0]= w[0]*o1[0] + w[1]*o2[0] + w[2]*o3[0] + w[3]*o4[0];
921                                 orco[1]= w[0]*o1[1] + w[1]*o2[1] + w[2]*o3[1] + w[3]*o4[1];
922                                 orco[2]= w[0]*o1[2] + w[1]*o2[2] + w[2]*o3[2] + w[3]*o4[2];
923
924                                 if(ornor)
925                                         CalcNormFloat4(o1, o2, o3, o4, ornor);
926                         }
927                         else {
928                                 orco[0]= w[0]*o1[0] + w[1]*o2[0] + w[2]*o3[0];
929                                 orco[1]= w[0]*o1[1] + w[1]*o2[1] + w[2]*o3[1];
930                                 orco[2]= w[0]*o1[2] + w[1]*o2[2] + w[2]*o3[2];
931
932                                 if(ornor)
933                                         CalcNormFloat(o1, o2, o3, ornor);
934                         }
935                 }
936                 else {
937                         VECCOPY(orco, vec);
938                         if(ornor)
939                                 VECCOPY(ornor, nor);
940                 }
941         }
942 }
943 void psys_interpolate_uvs(MTFace *tface, int quad, float *w, float *uvco){
944         float v10= tface->uv[0][0];
945         float v11= tface->uv[0][1];
946         float v20= tface->uv[1][0];
947         float v21= tface->uv[1][1];
948         float v30= tface->uv[2][0];
949         float v31= tface->uv[2][1];
950         float v40,v41;
951
952         if(quad) {
953                 v40= tface->uv[3][0];
954                 v41= tface->uv[3][1];
955
956                 uvco[0]= w[0]*v10 + w[1]*v20 + w[2]*v30 + w[3]*v40;
957                 uvco[1]= w[0]*v11 + w[1]*v21 + w[2]*v31 + w[3]*v41;
958         }
959         else {
960                 uvco[0]= w[0]*v10 + w[1]*v20 + w[2]*v30;
961                 uvco[1]= w[0]*v11 + w[1]*v21 + w[2]*v31;
962         }
963 }
964 float psys_interpolate_value_from_verts(DerivedMesh *dm, short from, int index, float *fw, float *values)
965 {
966         if(values==0)
967                 return 0.0;
968
969         switch(from){
970                 case PART_FROM_VERT:
971                         return values[index];
972                 case PART_FROM_FACE:
973                 case PART_FROM_VOLUME:
974                 {
975                         MFace *mf=dm->getFaceData(dm,index,CD_MFACE);
976                         return interpolate_particle_value(values[mf->v1],values[mf->v2],values[mf->v3],values[mf->v4],fw,mf->v4);
977                 }
978                         
979         }
980         return 0.0;
981 }
982
983 /* conversion of pa->fw to origspace layer coordinates */
984 static void psys_w_to_origspace(float *w, float *uv)
985 {
986         uv[0]= w[1] + w[2];
987         uv[1]= w[2] + w[3];
988 }
989
990 /* conversion of pa->fw to weights in face from origspace */
991 static void psys_origspace_to_w(OrigSpaceFace *osface, int quad, float *w, float *neww)
992 {
993         float v[4][3], co[3];
994
995         v[0][0]= osface->uv[0][0]; v[0][1]= osface->uv[0][1]; v[0][2]= 0.0f;
996         v[1][0]= osface->uv[1][0]; v[1][1]= osface->uv[1][1]; v[1][2]= 0.0f;
997         v[2][0]= osface->uv[2][0]; v[2][1]= osface->uv[2][1]; v[2][2]= 0.0f;
998
999         psys_w_to_origspace(w, co);
1000         co[2]= 0.0f;
1001         
1002         if(quad) {
1003                 v[3][0]= osface->uv[3][0]; v[3][1]= osface->uv[3][1]; v[3][2]= 0.0f;
1004                 MeanValueWeights(v, 4, co, neww);
1005         }
1006         else {
1007                 MeanValueWeights(v, 3, co, neww);
1008                 neww[3]= 0.0f;
1009         }
1010 }
1011
1012 /* find the derived mesh face for a particle, set the mf passed.
1013 This is slow, can be optimized but only for many lookups, return the face lookup index*/
1014 int psys_particle_dm_face_lookup(Object *ob, DerivedMesh *dm, int index, float *fw, struct LinkNode *node)
1015 {
1016         Mesh *me= (Mesh*)ob->data;
1017         MFace *mface;
1018         OrigSpaceFace *osface;
1019         int *origindex;
1020         int quad, findex, totface;
1021         float uv[2], (*faceuv)[2];
1022
1023         mface = dm->getFaceDataArray(dm, CD_MFACE);
1024         origindex = dm->getFaceDataArray(dm, CD_ORIGINDEX);
1025         osface = dm->getFaceDataArray(dm, CD_ORIGSPACE);
1026
1027         totface = dm->getNumFaces(dm);
1028         
1029         if(osface==NULL || origindex==NULL) {
1030                 /* Assume we dont need osface data */
1031                 if (index <totface) {
1032                         //printf("\tNO CD_ORIGSPACE, assuming not needed\n");
1033                         return index;
1034                 } else {
1035                         printf("\tNO CD_ORIGSPACE, error out of range\n");
1036                         return DMCACHE_NOTFOUND;
1037                 }
1038         }
1039         else if(index >= me->totface)
1040                 return DMCACHE_NOTFOUND; /* index not in the original mesh */
1041
1042         psys_w_to_origspace(fw, uv);
1043         
1044         if(node) { /* we have a linked list of faces that we use, faster! */
1045                 for(;node; node=node->next) {
1046                         findex= (int)node->link;
1047                         faceuv= osface[findex].uv;
1048                         quad= mface[findex].v4;
1049
1050                         /* check that this intersects - Its possible this misses :/ -
1051                          * could also check its not between */
1052                         if(quad) {
1053                                 if(IsectPQ2Df(uv, faceuv[0], faceuv[1], faceuv[2], faceuv[3]))
1054                                         return findex;
1055                         }
1056                         else if(IsectPT2Df(uv, faceuv[0], faceuv[1], faceuv[2]))
1057                                 return findex;
1058                 }
1059         }
1060         else { /* if we have no node, try every face */
1061                 for(findex=0; findex<totface; findex++) {
1062                         if(origindex[findex] == index) {
1063                                 faceuv= osface[findex].uv;
1064                                 quad= mface[findex].v4;
1065
1066                                 /* check that this intersects - Its possible this misses :/ -
1067                                  * could also check its not between */
1068                                 if(quad) {
1069                                         if(IsectPQ2Df(uv, faceuv[0], faceuv[1], faceuv[2], faceuv[3]))
1070                                                 return findex;
1071                                 }
1072                                 else if(IsectPT2Df(uv, faceuv[0], faceuv[1], faceuv[2]))
1073                                         return findex;
1074                         }
1075                 }
1076         }
1077
1078         return DMCACHE_NOTFOUND;
1079 }
1080
1081 /* interprets particle data to get a point on a mesh in object space */
1082 #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; }
1083 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)
1084 {
1085         float (*orcodata)[3];
1086
1087         if(index < 0){ /* 'no dm' error has happened! */
1088                 PARTICLE_ERROR(nor, vec);
1089                 return;
1090         }
1091         orcodata= dm->getVertDataArray(dm, CD_ORCO);
1092
1093         if (dm->deformedOnly || index_dmcache == DMCACHE_ISCHILD) {
1094                 /* this works for meshes with deform verts only - constructive modifiers wont work properly*/
1095                 float temp1[3];
1096
1097                 if(from == PART_FROM_VERT) {
1098                         if(index >= dm->getNumVerts(dm)) {
1099                                 PARTICLE_ERROR(nor, vec);
1100                                 return;
1101                         }
1102         
1103                         dm->getVertCo(dm,index,vec);
1104                         if(nor){
1105                                 dm->getVertNo(dm,index,nor);
1106                                 Normalize(nor);
1107                         }
1108                         if(orco)
1109                                 VECCOPY(orco, orcodata[index])
1110                         if(ornor) {
1111                                 dm->getVertNo(dm,index,nor);
1112                                 Normalize(nor);
1113                         }
1114                 }
1115                 else { /* PART_FROM_FACE / PART_FROM_VOLUME */
1116                         MFace *mface;
1117                         MTFace *mtface=0;
1118                         MVert *mvert;
1119                         int uv_index;
1120
1121                         if(index >= dm->getNumFaces(dm)) {
1122                                 PARTICLE_ERROR(nor, vec);
1123                                 return;
1124                         }
1125                         
1126                         mface=dm->getFaceData(dm,index,CD_MFACE);
1127                         mvert=dm->getVertDataArray(dm,CD_MVERT);
1128                         uv_index=CustomData_get_active_layer_index(&dm->faceData,CD_MTFACE);
1129
1130                         if(uv_index>=0){
1131                                 CustomDataLayer *layer=&dm->faceData.layers[uv_index];
1132                                 mtface= &((MTFace*)layer->data)[index];
1133                         }
1134
1135                         if(from==PART_FROM_VOLUME){
1136                                 psys_interpolate_face(mvert,mface,mtface,orcodata,fw,vec,temp1,utan,vtan,orco,ornor);
1137                                 if(nor)
1138                                         VECCOPY(nor,temp1);
1139                                 Normalize(temp1);
1140                                 VecMulf(temp1,-foffset);
1141                                 VECADD(vec,vec,temp1);
1142                         }
1143                         else
1144                                 psys_interpolate_face(mvert,mface,mtface,orcodata,fw,vec,nor,utan,vtan,orco,ornor);
1145                 }
1146         } else {
1147                 /* Need to support constructive modifiers, this is a bit more tricky
1148                         we need a customdata layer like UV's so we can position the particle */
1149                 
1150                 /* Only face supported at the moment */
1151                 if (from==PART_FROM_FACE) {
1152                         /* find a face on the derived mesh that uses this face */
1153                         Mesh *me= (Mesh*)ob->data;
1154                         MVert *mvert;
1155                         MFace *mface;
1156                         MTFace *mtface;
1157                         OrigSpaceFace *osface;
1158                         int *origindex;
1159                         float fw_mod[4];
1160                         int i, totface;
1161                         
1162                         mvert= dm->getVertDataArray(dm,CD_MVERT);
1163
1164                         osface= dm->getFaceDataArray(dm, CD_ORIGSPACE);
1165                         origindex= dm->getFaceDataArray(dm, CD_ORIGINDEX);
1166
1167                         /* For this to work we need origindex and OrigSpace coords */
1168                         if(origindex==NULL || osface==NULL || index>=me->totface) {
1169                                 PARTICLE_ERROR(nor, vec);
1170                                 return;
1171                         }
1172                         
1173                         if (index_dmcache == DMCACHE_NOTFOUND)
1174                                 i = psys_particle_dm_face_lookup(ob, dm, index, fw, (LinkNode*)NULL);
1175                         else
1176                                 i = index_dmcache;
1177
1178                         totface = dm->getNumFaces(dm);
1179
1180                         /* Any time this happens, and the face has not been removed,
1181                         * its a BUG watch out for this error! */
1182                         if (i==-1) {
1183                                 printf("Cannot find original face %i\n", index);
1184                                 PARTICLE_ERROR(nor, vec);
1185                                 return;
1186                         }
1187                         else if(i >= totface)
1188                                 return;
1189
1190                         mface= dm->getFaceData(dm, i, CD_MFACE);
1191                         mtface= dm->getFaceData(dm, i, CD_MTFACE); 
1192                         osface += i;
1193
1194                         /* we need to modify the original weights to become weights for
1195                          * the derived mesh face */
1196                         psys_origspace_to_w(osface, mface->v4, fw, fw_mod);
1197                         psys_interpolate_face(mvert,mface,mtface,orcodata,fw_mod,vec,nor,utan,vtan,orco,ornor);
1198                 }
1199                 else {
1200                         /* TODO PARTICLE - support verts and volume */
1201                         PARTICLE_ERROR(nor, vec);
1202                 }
1203         }
1204 }
1205 #undef PARTICLE_ERROR
1206
1207 ParticleSystemModifierData *psys_get_modifier(Object *ob, ParticleSystem *psys)
1208 {
1209         ModifierData *md;
1210         ParticleSystemModifierData *psmd;
1211
1212         for(md=ob->modifiers.first; md; md=md->next){
1213                 if(md->type==eModifierType_ParticleSystem){
1214                         psmd= (ParticleSystemModifierData*) md;
1215                         if(psmd->psys==psys){
1216                                 return psmd;
1217                         }
1218                 }
1219         }
1220         return 0;
1221 }
1222 /************************************************/
1223 /*                      Particles on a shape                            */
1224 /************************************************/
1225 /* ready for future use */
1226 void psys_particle_on_shape(int distr, int index, float *fuv, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor)
1227 {
1228         /* TODO */
1229         float zerovec[3]={0.0f,0.0f,0.0f};
1230         if(vec){
1231                 VECCOPY(vec,zerovec);
1232         }
1233         if(nor){
1234                 VECCOPY(nor,zerovec);
1235         }
1236         if(utan){
1237                 VECCOPY(utan,zerovec);
1238         }
1239         if(vtan){
1240                 VECCOPY(vtan,zerovec);
1241         }
1242         if(orco){
1243                 VECCOPY(orco,zerovec);
1244         }
1245         if(ornor){
1246                 VECCOPY(ornor,zerovec);
1247         }
1248 }
1249 /************************************************/
1250 /*                      Particles on emitter                            */
1251 /************************************************/
1252 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){
1253         if(psmd){
1254                 if(psmd->psys->part->distr==PART_DISTR_GRID){
1255                         if(vec){
1256                                 VECCOPY(vec,fuv);
1257                         }
1258                         return;
1259                 }
1260                 /* we cant use the num_dmcache */
1261                 psys_particle_on_dm(ob, psmd->dm,from,index,index_dmcache,fuv,foffset,vec,nor,utan,vtan,orco,ornor);
1262         }
1263         else
1264                 psys_particle_on_shape(from,index,fuv,vec,nor,utan,vtan,orco,ornor);
1265
1266 }
1267 /************************************************/
1268 /*                      Path Cache                                                      */
1269 /************************************************/
1270 static void hair_to_particle(ParticleKey *key, HairKey *hkey)
1271 {
1272         VECCOPY(key->co, hkey->co);
1273         key->time = hkey->time;
1274 }
1275 static void bp_to_particle(ParticleKey *key, BodyPoint *bp, HairKey *hkey)
1276 {
1277         VECCOPY(key->co, bp->pos);
1278         key->time = hkey->time;
1279 }
1280 static float vert_weight(MDeformVert *dvert, int group)
1281 {
1282         MDeformWeight *dw;
1283         int i;
1284         
1285         if(dvert) {
1286                 dw= dvert->dw;
1287                 for(i= dvert->totweight; i>0; i--, dw++) {
1288                         if(dw->def_nr == group) return dw->weight;
1289                         if(i==1) break; /*otherwise dw will point to somewhere it shouldn't*/
1290                 }
1291         }
1292         return 0.0;
1293 }
1294 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])
1295 {
1296         float vec[3]={0.0,0.0,0.0}, q1[4]={1,0,0,0},*q2;
1297         float t;
1298
1299         CLAMP(time,0.0,1.0);
1300
1301         if(shape!=0.0f && type!=PART_KINK_BRAID) {
1302                 if(shape<0.0f)
1303                         time= (float)pow(time, 1.0+shape);
1304                 else
1305                         time= (float)pow(time, 1.0/(1.0-shape));
1306         }
1307
1308         t=time;
1309
1310         t*=(float)M_PI*freq;
1311
1312         if(par==0) return;
1313
1314         switch(type){
1315                 case PART_KINK_CURL:
1316                         vec[axis]=1.0;
1317                         if(par_rot)
1318                                 q2=par_rot;
1319                         else{
1320                                 q2=vectoquat(par->vel,axis,(axis+1)%3);
1321                         }
1322                         QuatMulVecf(q2,vec);
1323                         VecMulf(vec,amplitude);
1324                         VECADD(state->co,state->co,vec);
1325
1326                         VECSUB(vec,state->co,par->co);
1327
1328                         if(t!=0.0)
1329                                 VecRotToQuat(par->vel,t,q1);
1330                         
1331                         QuatMulVecf(q1,vec);
1332                         
1333                         VECADD(state->co,par->co,vec);
1334                         break;
1335                 case PART_KINK_RADIAL:
1336                         VECSUB(vec,state->co,par->co);
1337
1338                         Normalize(vec);
1339                         VecMulf(vec,amplitude*(float)sin(t));
1340
1341                         VECADD(state->co,state->co,vec);
1342                         break;
1343                 case PART_KINK_WAVE:
1344                         vec[axis]=1.0;
1345                         if(obmat)
1346                                 Mat4MulVecfl(obmat,vec);
1347
1348                         if(par_rot)
1349                                 QuatMulVecf(par_rot,vec);
1350
1351                         Projf(q1,vec,par->vel);
1352                         
1353                         VECSUB(vec,vec,q1);
1354                         Normalize(vec);
1355
1356                         VecMulf(vec,amplitude*(float)sin(t));
1357
1358                         VECADD(state->co,state->co,vec);
1359                         break;
1360                 case PART_KINK_BRAID:
1361                         if(par){
1362                                 float y_vec[3]={0.0,1.0,0.0};
1363                                 float z_vec[3]={0.0,0.0,1.0};
1364                                 float vec_from_par[3], vec_one[3], radius, state_co[3];
1365                                 float inp_y,inp_z,length;
1366                                 
1367                                 if(par_rot)
1368                                         q2=par_rot;
1369                                 else
1370                                         q2=vectoquat(par->vel,axis,(axis+1)%3);
1371                                 QuatMulVecf(q2,y_vec);
1372                                 QuatMulVecf(q2,z_vec);
1373                                 
1374                                 VECSUB(vec_from_par,state->co,par->co);
1375                                 VECCOPY(vec_one,vec_from_par);
1376                                 radius=Normalize(vec_one);
1377
1378                                 inp_y=Inpf(y_vec,vec_one);
1379                                 inp_z=Inpf(z_vec,vec_one);
1380
1381                                 if(inp_y>0.5){
1382                                         VECCOPY(state_co,y_vec);
1383
1384                                         VecMulf(y_vec,amplitude*(float)cos(t));
1385                                         VecMulf(z_vec,amplitude/2.0f*(float)sin(2.0f*t));
1386                                 }
1387                                 else if(inp_z>0.0){
1388                                         VECCOPY(state_co,z_vec);
1389                                         VecMulf(state_co,(float)sin(M_PI/3.0f));
1390                                         VECADDFAC(state_co,state_co,y_vec,-0.5f);
1391
1392                                         VecMulf(y_vec,-amplitude*(float)cos(t + M_PI/3.0f));
1393                                         VecMulf(z_vec,amplitude/2.0f*(float)cos(2.0f*t + M_PI/6.0f));
1394                                 }
1395                                 else{
1396                                         VECCOPY(state_co,z_vec);
1397                                         VecMulf(state_co,-(float)sin(M_PI/3.0f));
1398                                         VECADDFAC(state_co,state_co,y_vec,-0.5f);
1399
1400                                         VecMulf(y_vec,amplitude*(float)-sin(t+M_PI/6.0f));
1401                                         VecMulf(z_vec,amplitude/2.0f*(float)-sin(2.0f*t+M_PI/3.0f));
1402                                 }
1403
1404                                 VecMulf(state_co,amplitude);
1405                                 VECADD(state_co,state_co,par->co);
1406                                 VECSUB(vec_from_par,state->co,state_co);
1407
1408                                 length=Normalize(vec_from_par);
1409                                 VecMulf(vec_from_par,MIN2(length,amplitude/2.0f));
1410
1411                                 VECADD(state_co,par->co,y_vec);
1412                                 VECADD(state_co,state_co,z_vec);
1413                                 VECADD(state_co,state_co,vec_from_par);
1414
1415                                 shape=(2.0f*(float)M_PI)*(1.0f+shape);
1416
1417                                 if(t<shape){
1418                                         shape=t/shape;
1419                                         shape=(float)sqrt((double)shape);
1420                                         VecLerpf(state->co,state->co,state_co,shape);
1421                                 }
1422                                 else{
1423                                         VECCOPY(state->co,state_co);
1424                                 }
1425                         }
1426                         break;
1427                 //case PART_KINK_ROT:
1428                 //      vec[axis]=1.0;
1429
1430                 //      QuatMulVecf(par->rot,vec);
1431
1432                 //      VecMulf(vec,amplitude*(float)sin(t));
1433
1434                 //      VECADD(state->co,state->co,vec);
1435                 //      break;
1436         }
1437 }
1438 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])
1439 {
1440         static ParticleKey first;
1441         static float q[4];
1442         float vec[3]={0.0,0.0,0.0};
1443         float t;
1444
1445         CLAMP(time,0.0,1.0);
1446
1447         t=time;
1448
1449         t*=(float)M_PI*freq;
1450
1451         if(par==0) return;
1452
1453         switch(type){
1454                 case PART_KINK_ROLL:
1455                         if(time<(0.5+shape/2.0f)){
1456                                 float *q2;
1457                                 memcpy(&first,state,sizeof(ParticleKey));
1458                                 Normalize(first.vel);
1459                                 if(par_rot)
1460                                         q2=par_rot;
1461                                 else
1462                                         q2=vectoquat(par->vel,axis,(axis+1)%3);
1463                                 QUATCOPY(q,q2);
1464                         }
1465                         else{
1466                                 float fac;
1467                                 shape=0.5f+shape/2.0f;
1468                                 t-=(float)M_PI*(shape*freq + 0.5f);
1469
1470                                 vec[axis]=1.0;
1471                                 
1472                                 QuatMulVecf(q,vec);
1473
1474                                 fac=amplitude*(1.0f+((1.0f-time)/(1.0f-shape)*(float)sin(t)));
1475                                 VECADDFAC(state->co,first.co,vec,fac);
1476                                 fac=amplitude*((1.0f-time)/(1.0f-shape)*(float)cos(t));
1477                                 VECADDFAC(state->co,state->co,first.vel,fac);
1478                         }
1479                         break;
1480         }
1481 }
1482 static void do_clump(ParticleKey *state, ParticleKey *par, float time, float clumpfac, float clumppow, float pa_clump)
1483 {
1484         if(par && clumpfac!=0.0){
1485                 float clump, cpow;
1486
1487                 if(clumppow<0.0)
1488                         cpow=1.0f+clumppow;
1489                 else
1490                         cpow=1.0f+9.0f*clumppow;
1491
1492                 if(clumpfac<0.0) /* clump roots instead of tips */
1493                         clump = -clumpfac*pa_clump*(float)pow(1.0-(double)time,(double)cpow);
1494                 else
1495                         clump = clumpfac*pa_clump*(float)pow((double)time,(double)cpow);
1496                 VecLerpf(state->co,state->co,par->co,clump);
1497         }
1498 }
1499 int do_guide(ParticleKey *state, int pa_num, float time, ListBase *lb)
1500 {
1501         PartDeflect *pd;
1502         ParticleEffectorCache *ec;
1503         Object *eob;
1504         Curve *cu;
1505         ParticleKey key, par;
1506
1507         float effect[3]={0.0,0.0,0.0}, distance, f_force, mindist, totforce=0.0;
1508         float guidevec[4], guidedir[3], rot2[4], temp[3], angle, pa_loc[3], pa_zero[3]={0.0f,0.0f,0.0f};
1509         float veffect[3]={0.0,0.0,0.0}, guidetime;
1510
1511         effect[0]=effect[1]=effect[2]=0.0;
1512
1513         if(lb->first){
1514                 for(ec = lb->first; ec; ec= ec->next){
1515                         eob= ec->ob;
1516                         if(ec->type & PSYS_EC_EFFECTOR){
1517                                 pd=eob->pd;
1518                                 if(pd->forcefield==PFIELD_GUIDE){
1519                                         cu = (Curve*)eob->data;
1520
1521                                         distance=ec->distances[pa_num];
1522                                         mindist=pd->f_strength;
1523
1524                                         VECCOPY(pa_loc, ec->locations+3*pa_num);
1525                                         VECCOPY(pa_zero,pa_loc);
1526                                         VECADD(pa_zero,pa_zero,ec->firstloc);
1527
1528                                         guidetime=time/(1.0-pd->free_end);
1529
1530                                         /* WARNING: bails out with continue here */
1531                                         if(((pd->flag & PFIELD_USEMAX) && distance>pd->maxdist) || guidetime>1.0f) continue;
1532
1533                                         if(guidetime>1.0f) continue;
1534
1535                                         /* calculate contribution factor for this guide */
1536                                         f_force=1.0f;
1537                                         if(distance<=mindist);
1538                                         else if(pd->flag & PFIELD_USEMAX) {
1539                                                 if(mindist>=pd->maxdist) f_force= 0.0f;
1540                                                 else if(pd->f_power!=0.0f){
1541                                                         f_force= 1.0f - (distance-mindist)/(pd->maxdist - mindist);
1542                                                         f_force = (float)pow(f_force, pd->f_power);
1543                                                 }
1544                                         }
1545                                         else if(pd->f_power!=0.0f){
1546                                                 f_force= 1.0f/(1.0f + distance-mindist);
1547                                                 f_force = (float)pow(f_force, pd->f_power);
1548                                         }
1549
1550                                         if(pd->flag & PFIELD_GUIDE_PATH_ADD)
1551                                                 where_on_path(eob, f_force*guidetime, guidevec, guidedir);
1552                                         else
1553                                                 where_on_path(eob, guidetime, guidevec, guidedir);
1554
1555                                         Mat4MulVecfl(ec->ob->obmat,guidevec);
1556                                         Mat4Mul3Vecfl(ec->ob->obmat,guidedir);
1557
1558                                         Normalize(guidedir);
1559
1560                                         if(guidetime!=0.0){
1561                                                 /* curve direction */
1562                                                 Crossf(temp, ec->firstdir, guidedir);
1563                                                 angle=Inpf(ec->firstdir,guidedir)/(VecLength(ec->firstdir));
1564                                                 angle=saacos(angle);
1565                                                 VecRotToQuat(temp,angle,rot2);
1566                                                 QuatMulVecf(rot2,pa_loc);
1567
1568                                                 /* curve tilt */
1569                                                 VecRotToQuat(guidedir,guidevec[3]-ec->firstloc[3],rot2);
1570                                                 QuatMulVecf(rot2,pa_loc);
1571
1572                                                 //q=vectoquat(guidedir, pd->kink_axis, (pd->kink_axis+1)%3);
1573                                                 //QuatMul(par.rot,rot2,q);
1574                                         }
1575                                         //else{
1576                                         //      par.rot[0]=1.0f;
1577                                         //      par.rot[1]=par.rot[2]=par.rot[3]=0.0f;
1578                                         //}
1579
1580                                         /* curve taper */
1581                                         if(cu->taperobj)
1582                                                 VecMulf(pa_loc,calc_taper(cu->taperobj,(int)(f_force*guidetime*100.0),100));
1583                                         /* TODO */
1584                                         //else{
1585                                         ///* curve size*/
1586                                         //      calc_curve_subdiv_radius(cu,cu->nurb.first,((Nurb*)cu->nurb.first)->
1587                                         //}
1588                                         par.co[0]=par.co[1]=par.co[2]=0.0f;
1589                                         VECCOPY(key.co,pa_loc);
1590                                         do_prekink(&key, &par, 0, guidetime, pd->kink_freq, pd->kink_shape, pd->kink_amp, pd->kink, pd->kink_axis, 0);
1591                                         do_clump(&key, &par, guidetime, pd->clump_fac, pd->clump_pow, 1.0f);
1592                                         do_postkink(&key, &par, 0, guidetime, pd->kink_freq, pd->kink_shape, pd->kink_amp, pd->kink, pd->kink_axis, 0);
1593                                         VECCOPY(pa_loc,key.co);
1594
1595                                         VECADD(pa_loc,pa_loc,guidevec);
1596                                         VECSUB(pa_loc,pa_loc,pa_zero);
1597                                         VECADDFAC(effect,effect,pa_loc,f_force);
1598                                         VECADDFAC(veffect,veffect,guidedir,f_force);
1599                                         totforce+=f_force;
1600                                 }
1601                         }
1602                 }
1603
1604                 if(totforce!=0.0){
1605                         if(totforce>1.0)
1606                                 VecMulf(effect,1.0f/totforce);
1607                         CLAMP(totforce,0.0,1.0);
1608                         VECADD(effect,effect,pa_zero);
1609                         VecLerpf(state->co,state->co,effect,totforce);
1610
1611                         Normalize(veffect);
1612                         VecMulf(veffect,VecLength(state->vel));
1613                         VECCOPY(state->vel,veffect);
1614                         return 1;
1615                 }
1616         }
1617         return 0;
1618 }
1619 static void do_rough(float *loc, float t, float fac, float size, float thres, ParticleKey *state)
1620 {
1621         float rough[3];
1622         float rco[3];
1623
1624         if(thres!=0.0)
1625                 if((float)fabs((float)(-1.5+loc[0]+loc[1]+loc[2]))<1.5f*thres) return;
1626
1627         VECCOPY(rco,loc);
1628         VecMulf(rco,t);
1629         rough[0]=-1.0f+2.0f*BLI_gTurbulence(size, rco[0], rco[1], rco[2], 2,0,2);
1630         rough[1]=-1.0f+2.0f*BLI_gTurbulence(size, rco[1], rco[2], rco[0], 2,0,2);
1631         rough[2]=-1.0f+2.0f*BLI_gTurbulence(size, rco[2], rco[0], rco[1], 2,0,2);
1632         VECADDFAC(state->co,state->co,rough,fac);
1633 }
1634 static void do_rough_end(float *loc, float t, float fac, float shape, ParticleKey *state, ParticleKey *par)
1635 {
1636         float rough[3], rnor[3];
1637         float roughfac;
1638
1639         roughfac=fac*(float)pow((double)t,shape);
1640         VECCOPY(rough,loc);
1641         rough[0]=-1.0f+2.0f*rough[0];
1642         rough[1]=-1.0f+2.0f*rough[1];
1643         rough[2]=-1.0f+2.0f*rough[2];
1644         VecMulf(rough,roughfac);
1645
1646
1647         if(par){
1648                 VECCOPY(rnor,par->vel);
1649         }
1650         else{
1651                 VECCOPY(rnor,state->vel);
1652         }
1653         Normalize(rnor);
1654         Projf(rnor,rough,rnor);
1655         VECSUB(rough,rough,rnor);
1656
1657         VECADD(state->co,state->co,rough);
1658 }
1659 static int check_path_length(int k, ParticleCacheKey *keys, ParticleCacheKey *state, float max_length, float *cur_length, float length, float *dvec)
1660 {
1661         if(*cur_length + length > max_length){
1662                 //if(p<totparent){
1663                 //      if(k<=(int)cache[totpart+p]->time){
1664                 //              /* parents need to be calculated fully first so that they don't mess up their children */
1665                 //              /* we'll make a note of where we got to though so that they're easy to finish later */
1666                 //              state->time=(max_length-*cur_length)/length;
1667                 //              cache[totpart+p]->time=(float)k;
1668                 //      }
1669                 //}
1670                 //else{
1671                 VecMulf(dvec, (max_length - *cur_length) / length);
1672                 VECADD(state->co, (state - 1)->co, dvec);
1673                 keys->steps = k;
1674                 /* something over the maximum step value */
1675                 return k=100000;
1676                 //}
1677         }
1678         else {
1679                 *cur_length+=length;
1680                 return k;
1681         }
1682 }
1683 static void finalize_path_length(ParticleCacheKey *keys)
1684 {
1685         ParticleCacheKey *state = keys;
1686         float dvec[3];
1687         state += state->steps;
1688
1689         VECSUB(dvec, state->co, (state - 1)->co);
1690         VecMulf(dvec, state->steps);
1691         VECADD(state->co, (state - 1)->co, dvec);
1692 }
1693 static void offset_child(ChildParticle *cpa, ParticleKey *par, ParticleKey *child, float flat, float radius)
1694 {
1695         VECCOPY(child->co,cpa->fuv);
1696         VecMulf(child->co,radius);
1697
1698         child->co[0]*=flat;
1699
1700         VECCOPY(child->vel,par->vel);
1701
1702         QuatMulVecf(par->rot,child->co);
1703
1704         QUATCOPY(child->rot,par->rot);
1705
1706         VECADD(child->co,child->co,par->co);
1707 }
1708 float *psys_cache_vgroup(DerivedMesh *dm, ParticleSystem *psys, int vgroup)
1709 {
1710         float *vg=0;
1711
1712         if(psys->vgroup[vgroup]){
1713                 MDeformVert *dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
1714                 if(dvert){
1715                         int totvert=dm->getNumVerts(dm), i;
1716                         vg=MEM_callocN(sizeof(float)*totvert, "vg_cache");
1717                         if(psys->vg_neg&(1<<vgroup)){
1718                                 for(i=0; i<totvert; i++)
1719                                         vg[i]=1.0f-vert_weight(dvert+i,psys->vgroup[vgroup]-1);
1720                         }
1721                         else{
1722                                 for(i=0; i<totvert; i++)
1723                                         vg[i]=vert_weight(dvert+i,psys->vgroup[vgroup]-1);
1724                         }
1725                 }
1726         }
1727         return vg;
1728 }
1729 void psys_find_parents(Object *ob, ParticleSystemModifierData *psmd, ParticleSystem *psys)
1730 {
1731         ParticleSettings *part=psys->part;
1732         KDTree *tree;
1733         ChildParticle *cpa;
1734         int p, totparent,totchild=psys->totchild;
1735         float co[3], orco[3];
1736         int from=PART_FROM_FACE;
1737         totparent=(int)(totchild*part->parents*0.3);
1738
1739         tree=BLI_kdtree_new(totparent);
1740
1741         for(p=0,cpa=psys->child; p<totparent; p++,cpa++){
1742                 psys_particle_on_emitter(ob,psmd,from,cpa->num,-1,cpa->fuv,cpa->foffset,co,0,0,0,orco,0);
1743                 BLI_kdtree_insert(tree, p, orco, NULL);
1744         }
1745
1746         BLI_kdtree_balance(tree);
1747
1748         for(; p<totchild; p++,cpa++){
1749                 psys_particle_on_emitter(ob,psmd,from,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co,0,0,0,orco,0);
1750                 cpa->parent=BLI_kdtree_find_nearest(tree, orco, NULL, NULL);
1751         }
1752
1753         BLI_kdtree_free(tree);
1754 }
1755
1756 static void get_strand_normal(Material *ma, float *surfnor, float surfdist, float *nor)
1757 {
1758         float cross[3], nstrand[3], vnor[3], blend;
1759
1760         if(!((ma->mode & MA_STR_SURFDIFF) || (ma->strand_surfnor > 0.0f)))
1761                 return;
1762
1763         if(ma->mode & MA_STR_SURFDIFF) {
1764                 Crossf(cross, surfnor, nor);
1765                 Crossf(nstrand, nor, cross);
1766
1767                 blend= INPR(nstrand, surfnor);
1768                 CLAMP(blend, 0.0f, 1.0f);
1769
1770                 VecLerpf(vnor, nstrand, surfnor, blend);
1771                 Normalize(vnor);
1772         }
1773         else
1774                 VECCOPY(vnor, nor)
1775         
1776         if(ma->strand_surfnor > 0.0f) {
1777                 if(ma->strand_surfnor > surfdist) {
1778                         blend= (ma->strand_surfnor - surfdist)/ma->strand_surfnor;
1779                         VecLerpf(vnor, vnor, surfnor, blend);
1780                         Normalize(vnor);
1781                 }
1782         }
1783
1784         VECCOPY(nor, vnor);
1785 }
1786
1787 int psys_threads_init_path(ParticleThread *threads, float cfra, int editupdate)
1788 {
1789         ParticleThreadContext *ctx= threads[0].ctx;
1790         Object *ob= ctx->ob;
1791         ParticleSystem *psys= ctx->psys;
1792         ParticleSettings *part = psys->part;
1793         ParticleEditSettings *pset = &G.scene->toolsettings->particle;
1794         int totparent=0, between=0;
1795         int steps = (int)pow(2.0,(double)part->draw_step);
1796         int totchild = psys->totchild;
1797         int i, seed, totthread= threads[0].tot;
1798
1799         /*---start figuring out what is actually wanted---*/
1800         if(psys_in_edit_mode(psys))
1801                 if(psys->renderdata==0 && (psys->edit==NULL || pset->flag & PE_SHOW_CHILD)==0)
1802                         totchild=0;
1803
1804         if(totchild && part->from!=PART_FROM_PARTICLE && part->childtype==PART_CHILD_FACES){
1805                 totparent=(int)(totchild*part->parents*0.3);
1806                 /* part->parents could still be 0 so we can't test with totparent */
1807                 between=1;
1808         }
1809
1810         if(psys->renderdata)
1811                 steps=(int)pow(2.0,(double)part->ren_step);
1812         else{
1813                 totchild=(int)((float)totchild*(float)part->disp/100.0f);
1814                 totparent=MIN2(totparent,totchild);
1815         }
1816
1817         if(totchild==0) return 0;
1818
1819         /* init random number generator */
1820         if(ctx->psys->part->flag & PART_ANIM_BRANCHING)
1821                 seed= 31415926 + ctx->psys->seed + (int)cfra;
1822         else
1823                 seed= 31415926 + ctx->psys->seed;
1824         
1825         if(part->flag & PART_BRANCHING || ctx->editupdate || totchild < 10000)
1826                 totthread= 1;
1827         
1828         for(i=0; i<totthread; i++) {
1829                 threads[i].rng_path= rng_new(seed);
1830                 threads[i].tot= totthread;
1831         }
1832
1833         /* fill context values */
1834         ctx->between= between;
1835         ctx->steps= steps;
1836         ctx->totchild= totchild;
1837         ctx->totparent= totparent;
1838         ctx->cfra= cfra;
1839
1840         psys->lattice = psys_get_lattice(ob, psys);
1841
1842         /* cache all relevant vertex groups if they exist */
1843         if(part->from!=PART_FROM_PARTICLE){
1844                 ctx->vg_length = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_LENGTH);
1845                 ctx->vg_clump = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_CLUMP);
1846                 ctx->vg_kink = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_KINK);
1847                 ctx->vg_rough1 = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGH1);
1848                 ctx->vg_rough2 = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGH2);
1849                 ctx->vg_roughe = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGHE);
1850         }
1851
1852         /* set correct ipo timing */
1853         if(part->flag&PART_ABS_TIME && part->ipo){
1854                 calc_ipo(part->ipo, cfra);
1855                 execute_ipo((ID *)part, part->ipo);
1856         }
1857
1858         return 1;
1859 }
1860
1861 /* note: this function must be thread safe, except for branching! */
1862 void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa, ParticleCacheKey *keys, int i)
1863 {
1864         ParticleThreadContext *ctx= thread->ctx;
1865         Object *ob= ctx->ob;
1866         ParticleSystem *psys = ctx->psys;
1867         ParticleSettings *part = psys->part;
1868         ParticleCacheKey **cache= psys->childcache;
1869         ParticleCacheKey **pcache= psys->pathcache;
1870         ParticleCacheKey *state, *par = NULL, *key[4];
1871         ParticleData *pa;
1872         ParticleTexture ptex;
1873         float *cpa_fuv=0;
1874         float co[3], orco[3], ornor[3], t, rough_t, cpa_1st[3], dvec[3];
1875         float branch_begin, branch_end, branch_prob, branchfac, rough_rand;
1876         float pa_rough1, pa_rough2, pa_roughe;
1877         float length, pa_length, pa_clump, pa_kink;
1878         float max_length = 1.0f, cur_length = 0.0f;
1879         int k, cpa_num, guided=0;
1880         short cpa_from;
1881
1882         if(part->flag & PART_BRANCHING) {
1883                 branch_begin=rng_getFloat(thread->rng_path);
1884                 branch_end=branch_begin+(1.0f-branch_begin)*rng_getFloat(thread->rng_path);
1885                 branch_prob=rng_getFloat(thread->rng_path);
1886                 rough_rand=rng_getFloat(thread->rng_path);
1887         }
1888         else {
1889                 branch_begin= 0.0f;
1890                 branch_end= 0.0f;
1891                 branch_prob= 0.0f;
1892                 rough_rand= 0.0f;
1893         }
1894
1895         if(i<psys->totpart){
1896                 branch_begin=0.0f;
1897                 branch_end=1.0f;
1898                 branch_prob=0.0f;
1899         }
1900
1901         if(ctx->between){
1902                 int w, needupdate;
1903                 float foffset;
1904
1905                 if(ctx->editupdate && !(part->flag & PART_BRANCHING)) {
1906                         needupdate= 0;
1907                         w= 0;
1908                         while(w<4 && cpa->pa[w]>=0) {
1909                                 if(psys->particles[cpa->pa[w]].flag & PARS_EDIT_RECALC) {
1910                                         needupdate= 1;
1911                                         break;
1912                                 }
1913                                 w++;
1914                         }
1915
1916                         if(!needupdate)
1917                                 return;
1918                         else
1919                                 memset(keys, 0, sizeof(*keys)*(ctx->steps+1));
1920                 }
1921
1922                 /* get parent paths */
1923                 w= 0;
1924                 while(w<4 && cpa->pa[w]>=0){
1925                         key[w] = pcache[cpa->pa[w]];
1926                         w++;
1927                 }
1928
1929                 /* get the original coordinates (orco) for texture usage */
1930                 cpa_num = cpa->num;
1931                 
1932                 foffset= cpa->foffset;
1933                 if(part->childtype == PART_CHILD_FACES)
1934                         foffset = -(2.0f + part->childspread);
1935                 cpa_fuv = cpa->fuv;
1936                 cpa_from = PART_FROM_FACE;
1937
1938                 psys_particle_on_emitter(ob,ctx->psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa->fuv,foffset,co,ornor,0,0,orco,0);
1939
1940                 /* we need to save the actual root position of the child for positioning it accurately to the surface of the emitter */
1941                 VECCOPY(cpa_1st,co);
1942                 Mat4MulVecfl(ob->obmat,cpa_1st);
1943
1944                 pa=0;
1945         }
1946         else{
1947                 if(ctx->editupdate && !(part->flag & PART_BRANCHING)) {
1948                         if(!(psys->particles[cpa->parent].flag & PARS_EDIT_RECALC))
1949                                 return;
1950
1951                         memset(keys, 0, sizeof(*keys)*(ctx->steps+1));
1952                 }
1953
1954                 /* get the parent path */
1955                 key[0]=pcache[cpa->parent];
1956
1957                 /* get the original coordinates (orco) for texture usage */
1958                 pa=psys->particles+cpa->parent;
1959
1960                 cpa_from=part->from;
1961                 cpa_num=pa->num;
1962                 cpa_fuv=pa->fuv;
1963
1964                 psys_particle_on_emitter(ob,ctx->psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa_fuv,pa->foffset,co,ornor,0,0,orco,0);
1965         }
1966
1967         keys->steps = ctx->steps;
1968
1969         /* correct child ipo timing */
1970         if((part->flag&PART_ABS_TIME)==0 && part->ipo){
1971                 float dsta=part->end-part->sta;
1972                 calc_ipo(part->ipo, 100.0f*(ctx->cfra-(part->sta+dsta*cpa->rand[1]))/(part->lifetime*(1.0f - part->randlife*cpa->rand[0])));
1973                 execute_ipo((ID *)part, part->ipo);
1974         }
1975
1976         /* get different child parameters from textures & vgroups */
1977         ptex.length=part->length*(1.0f - part->randlength*cpa->rand[0]);
1978         ptex.clump=1.0;
1979         ptex.kink=1.0;
1980         ptex.rough= 1.0;
1981
1982         get_cpa_texture(ctx->dm,ctx->ma,cpa_num,cpa_fuv,orco,&ptex,
1983                 MAP_PA_LENGTH|MAP_PA_CLUMP|MAP_PA_KINK|MAP_PA_ROUGH);
1984         
1985         pa_length=ptex.length;
1986         pa_clump=ptex.clump;
1987         pa_kink=ptex.kink;
1988         pa_rough1=ptex.rough;
1989         pa_rough2=ptex.rough;
1990         pa_roughe=ptex.rough;
1991
1992         if(ctx->vg_length)
1993                 pa_length*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_length);
1994         if(ctx->vg_clump)
1995                 pa_clump*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_clump);
1996         if(ctx->vg_kink)
1997                 pa_kink*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_kink);
1998         if(ctx->vg_rough1)
1999                 pa_rough1*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_rough1);
2000         if(ctx->vg_rough2)
2001                 pa_rough2*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_rough2);
2002         if(ctx->vg_roughe)
2003                 pa_roughe*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_roughe);
2004
2005         /* create the child path */
2006         for(k=0,state=keys; k<=ctx->steps; k++,state++){
2007                 t=(float)k/(float)ctx->steps;
2008
2009                 if(ctx->between){
2010                         int w=0;
2011
2012                         state->co[0] = state->co[1] = state->co[2] = 0.0f;
2013                         state->vel[0] = state->vel[1] = state->vel[2] = 0.0f;
2014
2015                         //QUATCOPY(state->rot,key[0]->rot);
2016
2017                         /* child position is the weighted sum of parent positions */
2018                         while(w<4 && cpa->pa[w]>=0){
2019                                 state->co[0] += cpa->w[w] * key[w]->co[0];
2020                                 state->co[1] += cpa->w[w] * key[w]->co[1];
2021                                 state->co[2] += cpa->w[w] * key[w]->co[2];
2022
2023                                 state->vel[0] += cpa->w[w] * key[w]->vel[0];
2024                                 state->vel[1] += cpa->w[w] * key[w]->vel[1];
2025                                 state->vel[2] += cpa->w[w] * key[w]->vel[2];
2026                                 key[w]++;
2027                                 w++;
2028                         }
2029                         if(k==0){
2030                                 /* calculate the offset between actual child root position and first position interpolated from parents */
2031                                 VECSUB(cpa_1st,cpa_1st,state->co);
2032                         }
2033                         /* apply offset for correct positioning */
2034                         VECADD(state->co,state->co,cpa_1st);
2035                 }
2036                 else{
2037                         /* offset the child from the parent position */
2038                         offset_child(cpa, (ParticleKey*)key[0], (ParticleKey*)state, part->childflat, part->childrad);
2039
2040                         key[0]++;
2041                 }
2042
2043                 if(ctx->totparent){
2044                         if(i>=ctx->totparent)
2045                                 /* this is not threadsafe, but should only happen for
2046                                  * branching particles particles, which are not threaded */
2047                                 par = cache[cpa->parent] + k;
2048                         else
2049                                 par=0;
2050                 }
2051                 else if(cpa->parent>=0){
2052                         par=pcache[cpa->parent]+k;
2053                 }
2054
2055                 /* apply different deformations to the child path */
2056                 if(part->flag & PART_CHILD_GUIDE)
2057                         guided = do_guide((ParticleKey*)state, i, t, &(psys->effectors)); //safe to cast, since only co and vel are used
2058
2059                 if(guided==0){
2060                         if(part->kink)
2061                                 do_prekink((ParticleKey*)state, (ParticleKey*)par, par->rot, t,
2062                                 part->kink_freq * pa_kink, part->kink_shape, part->kink_amp, part->kink, part->kink_axis, ob->obmat);
2063                                         
2064                         do_clump((ParticleKey*)state, (ParticleKey*)par, t, part->clumpfac, part->clumppow, pa_clump);
2065
2066                         if(part->kink)
2067                                 do_postkink((ParticleKey*)state, (ParticleKey*)par, par->rot, t,
2068                                 part->kink_freq * pa_kink, part->kink_shape, part->kink_amp, part->kink, part->kink_axis, ob->obmat);
2069                 }
2070
2071                 if(part->flag & PART_BRANCHING && ctx->between == 0 && part->flag & PART_ANIM_BRANCHING)
2072                         rough_t = t * rough_rand;
2073                 else
2074                         rough_t = t;
2075
2076                 if(part->rough1 != 0.0 && pa_rough1 != 0.0)
2077                                 do_rough(orco, rough_t, pa_rough1*part->rough1, part->rough1_size, 0.0, (ParticleKey*)state);
2078
2079                 if(part->rough2 != 0.0 && pa_rough2 != 0.0)
2080                         do_rough(cpa->rand, rough_t, pa_rough2*part->rough2, part->rough2_size, part->rough2_thres, (ParticleKey*)state);
2081
2082                 if(part->rough_end != 0.0 && pa_roughe != 0.0)
2083                         do_rough_end(cpa->rand, rough_t, pa_roughe*part->rough_end, part->rough_end_shape, (ParticleKey*)state, (ParticleKey*)par);
2084
2085                 if(part->flag & PART_BRANCHING && ctx->between==0){
2086                         if(branch_prob > part->branch_thres){
2087                                 branchfac=0.0f;
2088                         }
2089                         else{
2090                                 if(part->flag & PART_SYMM_BRANCHING){
2091                                         if(t < branch_begin || t > branch_end)
2092                                                 branchfac=0.0f;
2093                                         else{
2094                                                 if((t-branch_begin)/(branch_end-branch_begin)<0.5)
2095                                                         branchfac=2.0f*(t-branch_begin)/(branch_end-branch_begin);
2096                                                 else
2097                                                         branchfac=2.0f*(branch_end-t)/(branch_end-branch_begin);
2098
2099                                                 CLAMP(branchfac,0.0f,1.0f);
2100                                         }
2101                                 }
2102                                 else{
2103                                         if(t < branch_begin){
2104                                                 branchfac=0.0f;
2105                                         }
2106                                         else{
2107                                                 branchfac=(t-branch_begin)/((1.0f-branch_begin)*0.5f);
2108                                                 CLAMP(branchfac,0.0f,1.0f);
2109                                         }
2110                                 }
2111                         }
2112
2113                         if(i<psys->totpart)
2114                                 VecLerpf(state->co, (pcache[i] + k)->co, state->co, branchfac);
2115                         else
2116                                 /* this is not threadsafe, but should only happen for
2117                                  * branching particles particles, which are not threaded */
2118                                 VecLerpf(state->co, (cache[i - psys->totpart] + k)->co, state->co, branchfac);
2119                 }
2120
2121                 /* we have to correct velocity because of kink & clump */
2122                 if(k>1){
2123                         VECSUB((state-1)->vel,state->co,(state-2)->co);
2124                         VecMulf((state-1)->vel,0.5);
2125
2126                         if(ctx->ma && (part->draw & PART_DRAW_MAT_COL))
2127                                 get_strand_normal(ctx->ma, ornor, cur_length, (state-1)->vel);
2128                 }
2129
2130                 /* check if path needs to be cut before actual end of data points */
2131                 if(k){
2132                         VECSUB(dvec,state->co,(state-1)->co);
2133                         if(part->flag&PART_ABS_LENGTH)
2134                                 length=VecLength(dvec);
2135                         else
2136                                 length=1.0f/(float)ctx->steps;
2137
2138                         k=check_path_length(k,keys,state,max_length,&cur_length,length,dvec);
2139                 }
2140                 else{
2141                         /* initialize length calculation */
2142                         if(part->flag&PART_ABS_LENGTH)
2143                                 max_length= part->abslength*pa_length;
2144                         else
2145                                 max_length= pa_length;
2146
2147                         cur_length= 0.0f;
2148                 }
2149
2150                 if(ctx->ma && (part->draw & PART_DRAW_MAT_COL)) {
2151                         VECCOPY(state->col, &ctx->ma->r)
2152                         get_strand_normal(ctx->ma, ornor, cur_length, state->vel);
2153                 }
2154         }
2155
2156         /* now let's finalise the interpolated parents that we might have left half done before */
2157         if(i<ctx->totparent)
2158                 finalize_path_length(keys);
2159 }
2160
2161 void *exec_child_path_cache(void *data)
2162 {
2163         ParticleThread *thread= (ParticleThread*)data;
2164         ParticleThreadContext *ctx= thread->ctx;
2165         ParticleSystem *psys= ctx->psys;
2166         ParticleCacheKey **cache= psys->childcache;
2167         ChildParticle *cpa;
2168         int i, totchild= ctx->totchild;
2169         
2170         cpa= psys->child + thread->num;
2171         for(i=thread->num; i<totchild; i+=thread->tot, cpa+=thread->tot)
2172                 psys_thread_create_path(thread, cpa, cache[i], i);
2173
2174         return 0;
2175 }
2176
2177 void psys_cache_child_paths(Object *ob, ParticleSystem *psys, float cfra, int editupdate)
2178 {
2179         ParticleSettings *part = psys->part;
2180         ParticleThread *pthreads;
2181         ParticleThreadContext *ctx;
2182         ParticleCacheKey **cache, *tcache;
2183         ListBase threads;
2184         int i, totchild, totparent, totthread;
2185         unsigned long totchildstep;
2186
2187         pthreads= psys_threads_create(ob, psys, G.scene->r.threads);
2188
2189         if(!psys_threads_init_path(pthreads, cfra, editupdate)) {
2190                 psys_threads_free(pthreads);
2191                 return;
2192         }
2193
2194         ctx= pthreads[0].ctx;
2195         totchild= ctx->totchild;
2196         totparent= ctx->totparent;
2197
2198         if(editupdate && psys->childcache && !(part->flag & PART_BRANCHING) && totchild == psys->totchildcache) {
2199                 cache = psys->childcache;
2200         }
2201         else {
2202                 /* clear out old and create new empty path cache */
2203                 free_child_path_cache(psys);
2204
2205                 cache = psys->childcache = MEM_callocN(totchild*sizeof(void *), "Child path cache array");
2206                 totchildstep= totchild*(ctx->steps + 1);
2207                 tcache = MEM_callocN(totchildstep*sizeof(ParticleCacheKey), "Child path cache");
2208                 for(i=0; i<totchild; i++)
2209                         cache[i] = tcache + i * (ctx->steps + 1);
2210
2211                 psys->totchildcache = totchild;
2212         }
2213
2214         totthread= pthreads[0].tot;
2215
2216         if(totthread > 1) {
2217                 BLI_init_threads(&threads, exec_child_path_cache, totthread);
2218
2219                 for(i=0; i<totthread; i++)
2220                         BLI_insert_thread(&threads, &pthreads[i]);
2221
2222                 BLI_end_threads(&threads);
2223         }
2224         else
2225                 exec_child_path_cache(&pthreads[0]);
2226
2227         psys_threads_free(pthreads);
2228 }
2229
2230 /* Calculates paths ready for drawing/rendering.                                                                        */
2231 /* -Usefull for making use of opengl vertex arrays for super fast strand drawing.       */
2232 /* -Makes child strands possible and creates them too into the cache.                           */
2233 /* -Cached path data is also used to determine cut position for the editmode tool.      */
2234 void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupdate)
2235 {
2236         ParticleCacheKey *ca, **cache=psys->pathcache;
2237         ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys);
2238         ParticleEditSettings *pset = &G.scene->toolsettings->particle;
2239         
2240         ParticleData *pa;
2241         ParticleKey keys[4], result, *kkey[2] = {NULL, NULL};
2242         HairKey *hkey[2] = {NULL, NULL};
2243
2244         ParticleEdit *edit = 0;
2245         ParticleEditKey *ekey = 0;
2246
2247         SoftBody *soft = 0;
2248         BodyPoint *bp[2] = {NULL, NULL};
2249         
2250         Material *ma;
2251         
2252         float birthtime = 0.0, dietime = 0.0;
2253         float t, time = 0.0, keytime = 0.0, dfra = 1.0, frs_sec = G.scene->r.frs_sec;
2254         float col[3] = {0.5f, 0.5f, 0.5f};
2255         float prev_tangent[3], hairmat[4][4];
2256         int k,i;
2257         int steps = (int)pow(2.0, (double)psys->part->draw_step);
2258         int totpart = psys->totpart;
2259         char nosel[4], sel[4];
2260         float sel_col[3];
2261         float nosel_col[3];
2262         float length, vec[3];
2263
2264         /* we don't have anything valid to create paths from so let's quit here */
2265         if((psys->flag & PSYS_HAIR_DONE)==0 && (psys->flag & PSYS_KEYED)==0)
2266                 return;
2267
2268         if(psys->renderdata)
2269                 steps = (int)pow(2.0, (double)psys->part->ren_step);
2270         else if(psys_in_edit_mode(psys)){
2271                 edit=psys->edit;
2272                 
2273                 //timed = edit->draw_timed;
2274
2275                 PE_get_colors(sel,nosel);
2276                 if(pset->brushtype == PE_BRUSH_WEIGHT){
2277                         sel_col[0] = sel_col[1] = sel_col[2] = 1.0f;
2278                         nosel_col[0] = nosel_col[1] = nosel_col[2] = 0.0f;
2279                 }
2280                 else{
2281                         sel_col[0] = (float)sel[0] / 255.0f;
2282                         sel_col[1] = (float)sel[1] / 255.0f;
2283                         sel_col[2] = (float)sel[2] / 255.0f;
2284                         nosel_col[0] = (float)nosel[0] / 255.0f;
2285                         nosel_col[1] = (float)nosel[1] / 255.0f;
2286                         nosel_col[2] = (float)nosel[2] / 255.0f;
2287                 }
2288         }
2289
2290         if(editupdate && psys->pathcache && totpart == psys->totcached) {
2291                 cache = psys->pathcache;
2292         }
2293         else {
2294                 /* clear out old and create new empty path cache */
2295                 psys_free_path_cache(psys);
2296
2297                 /* allocate cache array for fast access and set pointers to contiguous mem block */
2298                 cache = psys->pathcache = MEM_callocN(MAX2(1, totpart) * sizeof(void *), "Path cache array");
2299                 cache[0] = MEM_callocN(totpart * (steps + 1) * sizeof(ParticleCacheKey), "Path cache");
2300                 for(i=1; i<totpart; i++)
2301                         cache[i] = cache[0] + i * (steps + 1);
2302         }
2303
2304         if(edit==NULL && psys->soft && psys->softflag & OB_SB_ENABLE)
2305                 soft = psys->soft;
2306         
2307         psys->lattice = psys_get_lattice(ob, psys);
2308         ma= give_current_material(ob, psys->part->omat);
2309         if(ma && (psys->part->draw & PART_DRAW_MAT_COL))
2310                 VECCOPY(col, &ma->r)
2311
2312         /*---first main loop: create all actual particles' paths---*/
2313         for(i=0,pa=psys->particles; i<totpart; i++, pa++){
2314                 if(psys && edit==NULL && (pa->flag & PARS_NO_DISP || pa->flag & PARS_UNEXIST)) {
2315                         if(soft)
2316                                 bp[0] += pa->totkey; /* TODO use of initialized value? */
2317                         continue;
2318                 }
2319
2320                 if(editupdate && !(pa->flag & PARS_EDIT_RECALC)) continue;
2321                 else memset(cache[i], 0, sizeof(*cache[i])*(steps+1));
2322
2323                 cache[i]->steps = steps;
2324
2325                 if(edit)
2326                         ekey = edit->keys[i];
2327
2328                 /*--get the first data points--*/
2329                 if(psys->flag & PSYS_KEYED) {
2330                         kkey[0] = pa->keys;
2331                         kkey[1] = kkey[0] + 1;
2332
2333                         birthtime = kkey[0]->time;
2334                         dietime = kkey[0][pa->totkey-1].time;
2335                 }
2336                 else {
2337                         hkey[0] = pa->hair;
2338                         hkey[1] = hkey[0] + 1;
2339
2340                         birthtime = hkey[0]->time;
2341                         dietime = hkey[0][pa->totkey-1].time;
2342
2343                         psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, pa, hairmat);
2344                 }
2345
2346                 if(soft){
2347                         bp[0] = soft->bpoint + pa->bpi;
2348                         bp[1] = bp[0] + 1;
2349                 }
2350
2351                 /*--interpolate actual path from data points--*/
2352                 for(k=0, ca=cache[i]; k<=steps; k++, ca++){
2353                         time = (float)k / (float)steps;
2354
2355                         t = birthtime + time * (dietime - birthtime);
2356
2357                         if(psys->flag & PSYS_KEYED) {
2358                                 while(kkey[1]->time < t) {
2359                                         kkey[1]++;
2360                                 }
2361
2362                                 kkey[0] = kkey[1] - 1;                          
2363                         }
2364                         else {
2365                                 while(hkey[1]->time < t) {
2366                                         hkey[1]++;
2367                                         bp[1]++;
2368                                 }
2369
2370                                 hkey[0] = hkey[1] - 1;
2371                         }
2372
2373                         if(soft) {
2374                                 bp[0] = bp[1] - 1;
2375                                 bp_to_particle(keys + 1, bp[0], hkey[0]);
2376                                 bp_to_particle(keys + 2, bp[1], hkey[1]);
2377                         }
2378                         else if(psys->flag & PSYS_KEYED) {
2379                                 memcpy(keys + 1, kkey[0], sizeof(ParticleKey));
2380                                 memcpy(keys + 2, kkey[1], sizeof(ParticleKey));
2381                         }
2382                         else {
2383                                 hair_to_particle(keys + 1, hkey[0]);
2384                                 hair_to_particle(keys + 2, hkey[1]);
2385                         }
2386
2387
2388                         if((psys->flag & PSYS_KEYED)==0) {
2389                                 if(soft) {
2390                                         if(hkey[0] != pa->hair)
2391                                                 bp_to_particle(keys, bp[0] - 1, hkey[0] - 1);
2392                                         else
2393                                                 bp_to_particle(keys, bp[0], hkey[0]);
2394                                 }
2395                                 else {
2396                                         if(hkey[0] != pa->hair)
2397                                                 hair_to_particle(keys, hkey[0] - 1);
2398                                         else
2399                                                 hair_to_particle(keys, hkey[0]);
2400                                 }
2401
2402                                 if(soft) {
2403                                         if(hkey[1] != pa->hair + pa->totkey - 1)
2404                                                 bp_to_particle(keys + 3, bp[1], hkey[1] + 1);
2405                                         else
2406                                                 bp_to_particle(keys + 3, bp[1], hkey[1]);
2407                                 }
2408                                 else {
2409                                         if(hkey[1] != pa->hair + pa->totkey - 1)
2410                                                 hair_to_particle(keys + 3, hkey[1] + 1);
2411                                         else
2412                                                 hair_to_particle(keys + 3, hkey[1]);
2413                                 }
2414                         }
2415
2416                         dfra = keys[2].time - keys[1].time;
2417
2418                         keytime = (t - keys[1].time) / dfra;
2419
2420                         /* convert velocity to timestep size */
2421                         if(psys->flag & PSYS_KEYED){
2422                                 VecMulf(keys[1].vel, dfra / frs_sec);
2423                                 VecMulf(keys[2].vel, dfra / frs_sec);
2424                         }
2425
2426                         /* 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)*/
2427                         interpolate_particle((psys->flag & PSYS_KEYED) ? -1 /* signal for cubic interpolation */
2428                                 : ((psys->part->flag & PART_HAIR_BSPLINE) ? KEY_BSPLINE : KEY_CARDINAL)
2429                                 ,keys, keytime, &result);
2430
2431                         /* the velocity needs to be converted back from cubic interpolation */
2432                         if(psys->flag & PSYS_KEYED){
2433                                 VecMulf(result.vel, frs_sec / dfra);
2434                         }
2435                         else if(soft==NULL) { /* softbody and keyed are allready in global space */
2436                                 Mat4MulVecfl(hairmat, result.co);
2437                         }
2438
2439                         VECCOPY(ca->co, result.co);
2440                 }
2441                 
2442                 /*--modify paths--*/
2443
2444                 VecSubf(vec,(cache[i]+1)->co,cache[i]->co);
2445                 length = VecLength(vec);
2446
2447                 for(k=0, ca=cache[i]; k<=steps; k++, ca++) {
2448                         /* apply effectors */
2449                         if(edit==0 && k) {
2450                                 float force[3] = {0.0f,0.0f,0.0f}, vel[3] = {0.0f,0.0f,0.0f};
2451                                 ParticleKey eff_key;
2452
2453                                 VECCOPY(eff_key.co,(ca-1)->co);
2454                                 VECCOPY(eff_key.vel,(ca-1)->vel);
2455                                 QUATCOPY(eff_key.rot,(ca-1)->rot);
2456
2457                                 do_effectors(i, pa, &eff_key, ob, psys, force, vel, dfra, cfra);
2458
2459                                 VecMulf(force, pow((float)k / (float)steps, 100.0f * psys->part->eff_hair) / (float)steps);
2460
2461                                 VecAddf(force, force, vec);
2462
2463                                 Normalize(force);
2464
2465                                 if(k < steps) {
2466                                         VecSubf(vec, (ca+1)->co, ca->co);
2467                                         length = VecLength(vec);
2468                                 }
2469
2470                                 VECADDFAC(ca->co, (ca-1)->co, force, length);
2471                         }
2472
2473                         /* apply guide curves to path data */
2474                         if(edit==0 && psys->effectors.first && (psys->part->flag & PART_CHILD_GUIDE)==0)
2475                                 do_guide(&result, i, time, &psys->effectors);
2476
2477                         /* apply lattice */
2478                         if(psys->lattice && edit==0)
2479                                 calc_latt_deform(ca->co, 1.0f);
2480
2481                         /* figure out rotation */
2482                         
2483                         if(k) {
2484                                 float angle, tangent[3], normal[3], q[4];
2485
2486                                 if(k == 1) {
2487                                         float *q2;
2488
2489                                         VECSUB(tangent, ca->co, (ca - 1)->co);
2490
2491                                         q2 = vectoquat(tangent, OB_POSX, OB_POSZ);
2492
2493                                         QUATCOPY((ca - 1)->rot, q2);
2494
2495                                         VECCOPY(prev_tangent, tangent);
2496                                         Normalize(prev_tangent);
2497                                 }
2498                                 else {
2499                                         VECSUB(tangent, ca->co, (ca - 1)->co);
2500                                         Normalize(tangent);
2501                                         angle = saacos(Inpf(tangent, prev_tangent));
2502
2503                                         if((angle > -0.000001) && (angle < 0.000001)){
2504                                                 QUATCOPY((ca - 1)->rot, (ca - 2)->rot);
2505                                         }
2506                                         else{
2507                                                 Crossf(normal, prev_tangent, tangent);
2508                                                 VecRotToQuat(normal, angle, q);
2509                                                 QuatMul((ca - 1)->rot, q, (ca - 2)->rot);
2510                                         }
2511
2512                                         VECCOPY(prev_tangent, tangent);
2513                                 }
2514
2515                                 if(k == steps) {
2516                                         QUATCOPY(ca->rot, (ca - 1)->rot);
2517                                 }
2518                         }
2519
2520                         
2521                         /* set velocity */
2522
2523                         if(k){
2524                                 VECSUB(ca->vel, ca->co, (ca-1)->co);
2525
2526                                 if(k==1) {
2527                                         VECCOPY((ca-1)->vel, ca->vel);
2528                                 }
2529
2530                         }
2531
2532                         /* selection coloring in edit mode */
2533                         if(edit){
2534                                 if(pset->brushtype==PE_BRUSH_WEIGHT){
2535                                         if(k==steps)
2536                                                 VecLerpf(ca->col, nosel_col, sel_col, hkey[0]->weight);
2537                                         else
2538                                                 VecLerpf(ca->col,nosel_col,sel_col,
2539                                                 (1.0f - keytime) * hkey[0]->weight + keytime * hkey[1]->weight);
2540                                 }
2541                                 else{
2542                                         if((ekey + (hkey[0] - pa->hair))->flag & PEK_SELECT){
2543                                                 if((ekey + (hkey[1] - pa->hair))->flag & PEK_SELECT){
2544                                                         VECCOPY(ca->col, sel_col);
2545                                                 }
2546                                                 else{
2547                                                         VecLerpf(ca->col, sel_col, nosel_col, keytime);
2548                                                 }
2549                                         }
2550                                         else{
2551                                                 if((ekey + (hkey[1] - pa->hair))->flag & PEK_SELECT){
2552                                                         VecLerpf(ca->col, nosel_col, sel_col, keytime);
2553                                                 }
2554                                                 else{
2555                                                         VECCOPY(ca->col, nosel_col);
2556                                                 }
2557                                         }
2558                                 }
2559                         }
2560                         else{
2561                                 VECCOPY(ca->col, col);
2562                         }
2563                 }
2564         }
2565
2566         psys->totcached = totpart;
2567
2568         if(psys && psys->lattice){
2569                 end_latt_deform();
2570                 psys->lattice=0;
2571         }
2572 }
2573 /************************************************/
2574 /*                      Particle Key handling                           */
2575 /************************************************/
2576 void copy_particle_key(ParticleKey *to, ParticleKey *from, int time){
2577         if(time){
2578                 memcpy(to,from,sizeof(ParticleKey));
2579         }
2580         else{
2581                 float to_time=to->time;
2582                 memcpy(to,from,sizeof(ParticleKey));
2583                 to->time=to_time;
2584         }
2585         /*
2586         VECCOPY(to->co,from->co);
2587         VECCOPY(to->vel,from->vel);
2588         QUATCOPY(to->rot,from->rot);
2589         if(time)
2590                 to->time=from->time;
2591         to->flag=from->flag;
2592         to->sbw=from->sbw;
2593         */
2594 }
2595 void psys_get_from_key(ParticleKey *key, float *loc, float *vel, float *rot, float *time){
2596         if(loc) VECCOPY(loc,key->co);
2597         if(vel) VECCOPY(vel,key->vel);
2598         if(rot) QUATCOPY(rot,key->rot);
2599         if(time) *time=key->time;
2600 }
2601 /*-------changing particle keys from space to another-------*/
2602 void psys_key_to_object(Object *ob, ParticleKey *key, float imat[][4]){
2603         float q[4], imat2[4][4];
2604
2605         if(imat==0){
2606                 Mat4Invert(imat2,ob->obmat);
2607                 imat=imat2;
2608         }
2609
2610         VECADD(key->vel,key->vel,key->co);
2611
2612         Mat4MulVecfl(imat,key->co);
2613         Mat4MulVecfl(imat,key->vel);
2614         Mat4ToQuat(imat,q);
2615
2616         VECSUB(key->vel,key->vel,key->co);
2617         QuatMul(key->rot,q,key->rot);
2618 }
2619 static void key_from_object(Object *ob, ParticleKey *key){
2620         float q[4];
2621
2622         VECADD(key->vel,key->vel,key->co);
2623
2624         Mat4MulVecfl(ob->obmat,key->co);
2625         Mat4MulVecfl(ob->obmat,key->vel);
2626         Mat4ToQuat(ob->obmat,q);
2627
2628         VECSUB(key->vel,key->vel,key->co);
2629         QuatMul(key->rot,q,key->rot);
2630 }
2631
2632 static void triatomat(float *v1, float *v2, float *v3, float (*uv)[2], float mat[][4])
2633 {
2634         float det, w1, w2, d1[2], d2[2];
2635
2636         memset(mat, 0, sizeof(float)*4*4);
2637         mat[3][3]= 1.0f;
2638
2639         /* first axis is the normal */
2640         CalcNormFloat(v1, v2, v3, mat[2]);
2641
2642         /* second axis along (1, 0) in uv space */
2643         if(uv) {
2644                 d1[0]= uv[1][0] - uv[0][0];
2645                 d1[1]= uv[1][1] - uv[0][1];
2646                 d2[0]= uv[2][0] - uv[0][0];
2647                 d2[1]= uv[2][1] - uv[0][1];
2648
2649                 det = d2[0]*d1[1] - d2[1]*d1[0];
2650
2651                 if(det != 0.0f) {
2652                         det= 1.0f/det;
2653                         w1= -d2[1]*det;
2654                         w2= d1[1]*det;
2655
2656                         mat[1][0]= w1*(v2[0] - v1[0]) + w2*(v3[0] - v1[0]);
2657                         mat[1][1]= w1*(v2[1] - v1[1]) + w2*(v3[1] - v1[1]);
2658                         mat[1][2]= w1*(v2[2] - v1[2]) + w2*(v3[2] - v1[2]);
2659                         Normalize(mat[1]);
2660                 }
2661                 else
2662                         mat[1][0]= mat[1][1]= mat[1][2]= 0.0f;
2663         }
2664         else {
2665                 VecSubf(mat[1], v2, v1);
2666                 Normalize(mat[1]);
2667         }
2668         
2669         /* third as a cross product */
2670         Crossf(mat[0], mat[1], mat[2]);
2671 }
2672
2673 static void psys_face_mat(Object *ob, DerivedMesh *dm, ParticleData *pa, float mat[][4], int orco)
2674 {
2675         float v[3][3];
2676         MFace *mface;
2677         OrigSpaceFace *osface;
2678         float (*orcodata)[3];
2679
2680         int i = pa->num_dmcache==DMCACHE_NOTFOUND ? pa->num : pa->num_dmcache;
2681         
2682         if (i==-1 || i >= dm->getNumFaces(dm)) { Mat4One(mat); return; }
2683
2684         mface=dm->getFaceData(dm,i,CD_MFACE);
2685         osface=dm->getFaceData(dm,i,CD_ORIGSPACE);
2686         
2687         if(orco && (orcodata=dm->getVertDataArray(dm, CD_ORCO))) {
2688                 VECCOPY(v[0], orcodata[mface->v1]);
2689                 VECCOPY(v[1], orcodata[mface->v2]);
2690                 VECCOPY(v[2], orcodata[mface->v3]);
2691
2692                 /* ugly hack to use non-transformed orcos, since only those
2693                  * give symmetric results for mirroring in particle mode */
2694                 transform_mesh_orco_verts(ob->data, v, 3, 1);
2695         }
2696         else {
2697                 dm->getVertCo(dm,mface->v1,v[0]);
2698                 dm->getVertCo(dm,mface->v2,v[1]);
2699                 dm->getVertCo(dm,mface->v3,v[2]);
2700         }
2701
2702         triatomat(v[0], v[1], v[2], (osface)? osface->uv: NULL, mat);
2703 }
2704
2705 void psys_mat_hair_to_object(Object *ob, DerivedMesh *dm, short from, ParticleData *pa, float hairmat[][4])
2706 {
2707         float vec[3];
2708
2709         psys_face_mat(0, dm, pa, hairmat, 0);
2710         psys_particle_on_dm(ob, dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, vec, 0, 0, 0, 0, 0);
2711         VECCOPY(hairmat[3],vec);
2712 }
2713
2714 void psys_mat_hair_to_orco(Object *ob, DerivedMesh *dm, short from, ParticleData *pa, float hairmat[][4])
2715 {
2716         float vec[3], orco[3];
2717
2718         psys_face_mat(ob, dm, pa, hairmat, 1);
2719         psys_particle_on_dm(ob, dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, vec, 0, 0, 0, orco, 0);
2720
2721         /* see psys_face_mat for why this function is called */
2722         transform_mesh_orco_verts(ob->data, &orco, 1, 1);
2723         VECCOPY(hairmat[3],orco);
2724 }
2725
2726 /*
2727 void psys_key_to_geometry(DerivedMesh *dm, ParticleData *pa, ParticleKey *key)
2728 {
2729         float q[4], v1[3], v2[3], v3[3];
2730
2731         dm->getVertCo(dm,pa->verts[0],v1);
2732         dm->getVertCo(dm,pa->verts[1],v2);
2733         dm->getVertCo(dm,pa->verts[2],v3);
2734
2735         triatoquat(v1, v2, v3, q);
2736
2737         QuatInv(q);
2738
2739         VECSUB(key->co,key->co,v1);
2740
2741         VECADD(key->vel,key->vel,key->co);
2742
2743         QuatMulVecf(q, key->co);
2744         QuatMulVecf(q, key->vel);
2745         
2746         VECSUB(key->vel,key->vel,key->co);
2747
2748         QuatMul(key->rot,q,key->rot);
2749 }
2750
2751 void psys_key_from_geometry(DerivedMesh *dm, ParticleData *pa, ParticleKey *key)
2752 {
2753         float q[4], v1[3], v2[3], v3[3];
2754
2755         dm->getVertCo(dm,pa->verts[0],v1);
2756         dm->getVertCo(dm,pa->verts[1],v2);
2757         dm->getVertCo(dm,pa->verts[2],v3);
2758
2759         triatoquat(v1, v2, v3, q);
2760
2761         VECADD(key->vel,key->vel,key->co);
2762
2763         QuatMulVecf(q, key->co);
2764         QuatMulVecf(q, key->vel);
2765         
2766         VECSUB(key->vel,key->vel,key->co);
2767
2768         VECADD(key->co,key->co,v1);
2769
2770         QuatMul(key->rot,q,key->rot);
2771 }
2772 */
2773
2774 void psys_vec_rot_to_face(DerivedMesh *dm, ParticleData *pa, float *vec)//to_geometry(DerivedMesh *dm, ParticleData *pa, float *vec)
2775 {
2776         float mat[4][4];
2777
2778         psys_face_mat(0, dm, pa, mat, 0);
2779         Mat4Transp(mat); /* cheap inverse for rotation matrix */
2780         Mat4Mul3Vecfl(mat, vec);
2781 }
2782
2783 /* unused */
2784 #if 0
2785 static void psys_vec_rot_from_face(DerivedMesh *dm, ParticleData *pa, float *vec)//from_geometry(DerivedMesh *dm, ParticleData *pa, float *vec)
2786 {
2787         float q[4], v1[3], v2[3], v3[3];
2788         /*
2789         dm->getVertCo(dm,pa->verts[0],v1);
2790         dm->getVertCo(dm,pa->verts[1],v2);
2791         dm->getVertCo(dm,pa->verts[2],v3);
2792         */
2793         /* replace with this */
2794         MFace *mface;
2795         int i; // = psys_particle_dm_face_lookup(dm, pa->num, pa->fuv, pa->foffset, (LinkNode*)NULL);
2796         i = pa->num_dmcache==DMCACHE_NOTFOUND ? pa->num : pa->num_dmcache;
2797         if (i==-1 || i >= dm->getNumFaces(dm)) { vec[0] = vec[1] = 0; vec[2] = 1; return; }
2798         mface=dm->getFaceData(dm,i,CD_MFACE);
2799         
2800         dm->getVertCo(dm,mface->v1,v1);
2801         dm->getVertCo(dm,mface->v2,v2);
2802         dm->getVertCo(dm,mface->v3,v3);
2803         /* done */
2804         
2805         triatoquat(v1, v2, v3, q);
2806
2807         QuatMulVecf(q, vec);
2808
2809         //VECADD(vec,vec,v1);
2810 }
2811 #endif
2812
2813 void psys_mat_hair_to_global(Object *ob, DerivedMesh *dm, short from, ParticleData *pa, float hairmat[][4])
2814 {
2815         float facemat[4][4];
2816
2817         psys_mat_hair_to_object(ob, dm, from, pa, facemat);
2818
2819         Mat4MulMat4(hairmat, facemat, ob->obmat);
2820 }
2821
2822 /************************************************/
2823 /*                      ParticleSettings handling                       */
2824 /************************************************/
2825 static void default_particle_settings(ParticleSettings *part)
2826 {
2827         int i;
2828
2829         part->type= PART_EMITTER;
2830         part->distr= PART_DISTR_JIT;
2831         part->draw_as=PART_DRAW_DOT;
2832         part->bb_uv_split=1;
2833         part->bb_align=PART_BB_VIEW;
2834         part->bb_split_offset=PART_BB_OFF_LINEAR;
2835         part->flag=PART_REACT_MULTIPLE|PART_HAIR_GEOMETRY;
2836
2837         part->sta= 1.0;
2838         part->end= 100.0;
2839         part->lifetime= 50.0;
2840         part->jitfac= 1.0;
2841         part->totpart= 1000;
2842         part->grid_res= 10;
2843         part->timetweak= 1.0;
2844         part->keyed_time= 0.5;
2845         //part->userjit;
2846         
2847         part->integrator= PART_INT_MIDPOINT;
2848         part->phystype= PART_PHYS_NEWTON;
2849         part->hair_step= 10;
2850         part->keys_step= 5;
2851         part->draw_step= 4;
2852         part->ren_step= 6;
2853         part->adapt_angle= 5;
2854         part->adapt_pix= 3;
2855         part->kink_axis= 2;
2856         part->reactevent= PART_EVENT_DEATH;
2857         part->disp=100;
2858         part->from= PART_FROM_FACE;
2859         part->length= 1.0;
2860         part->nbetween= 4;
2861         part->boidneighbours= 5;
2862
2863         part->max_vel = 10.0f;
2864         part->average_vel = 0.3f;
2865         part->max_tan_acc = 0.2f;
2866         part->max_lat_acc = 1.0f;
2867
2868         part->reactshape=1.0f;
2869
2870         part->mass=1.0;
2871         part->size=1.0;
2872         part->childsize=1.0;
2873
2874         part->child_nbr=10;
2875         part->ren_child_nbr=100;
2876         part->childrad=0.2f;
2877         part->childflat=0.0f;
2878         part->clumppow=0.0f;
2879         part->kink_amp=0.2f;
2880         part->kink_freq=2.0;
2881
2882         part->rough1_size=1.0;
2883         part->rough2_size=1.0;
2884         part->rough_end_shape=1.0;
2885
2886         part->draw_line[0]=0.5;
2887
2888         part->banking=1.0;
2889         part->max_bank=1.0;
2890
2891         for(i=0; i<BOID_TOT_RULES; i++){
2892                 part->boidrule[i]=(char)i;
2893                 part->boidfac[i]=0.5;
2894         }
2895
2896         part->ipo = NULL;
2897
2898         part->simplify_refsize= 1920;
2899         part->simplify_rate= 1.0f;
2900         part->simplify_transition= 0.1f;
2901         part->simplify_viewport= 0.8;
2902 }
2903
2904
2905 ParticleSettings *psys_new_settings(char *name, Main *main)
2906 {
2907         ParticleSettings *part;
2908
2909         part= alloc_libblock(&main->particle, ID_PA, name);
2910         
2911         default_particle_settings(part);
2912
2913         return part;
2914 }
2915
2916 ParticleSettings *psys_copy_settings(ParticleSettings *part)
2917 {
2918         ParticleSettings *partn;
2919         
2920         partn= copy_libblock(part);
2921         if(partn->pd) partn->pd= MEM_dupallocN(part->pd);
2922         
2923         return partn;
2924 }
2925
2926 void psys_make_local_settings(ParticleSettings *part)
2927 {
2928         Object *ob;
2929         ParticleSettings *par;
2930         int local=0, lib=0;
2931
2932         /* - only lib users: do nothing
2933             * - only local users: set flag
2934             * - mixed: make copy
2935             */
2936         
2937         if(part->id.lib==0) return;
2938         if(part->id.us==1) {
2939                 part->id.lib= 0;
2940                 part->id.flag= LIB_LOCAL;
2941                 new_id(0, (ID *)part, 0);
2942                 return;
2943         }
2944         
2945         /* test objects */
2946         ob= G.main->object.first;
2947         while(ob) {
2948                 ParticleSystem *psys=ob->particlesystem.first;
2949                 for(; psys; psys=psys->next){
2950                         if(psys->part==part) {
2951                                 if(ob->id.lib) lib= 1;
2952                                 else local= 1;
2953                         }
2954                 }
2955                 ob= ob->id.next;
2956         }
2957         
2958         if(local && lib==0) {
2959                 part->id.lib= 0;
2960                 part->id.flag= LIB_LOCAL;
2961                 new_id(0, (ID *)part, 0);
2962         }
2963         else if(local && lib) {
2964                 
2965                 par= psys_copy_settings(part);
2966                 par->id.us= 0;
2967                 
2968                 /* do objects */
2969                 ob= G.main->object.first;
2970                 while(ob) {
2971                         ParticleSystem *psys=ob->particlesystem.first;
2972                         for(; psys; psys=psys->next){
2973                                 if(psys->part==part && ob->id.lib==0) {
2974                                         psys->part= par;
2975                                         par->id.us++;
2976                                         part->id.us--;
2977                                 }
2978                         }
2979                         ob= ob->id.next;
2980                 }
2981         }
2982 }
2983
2984 /* should be integrated to depgraph signals */
2985 void psys_flush_settings(ParticleSettings *part, int event, int hair_recalc)
2986 {
2987         Base *base;
2988         Object *ob, *tob;
2989         ParticleSystem *psys;
2990         int flush;
2991
2992         /* update all that have same particle settings */
2993         for(base = G.scene->base.first; base; base= base->next) {
2994                 if(base->object->particlesystem.first) {
2995                         ob=base->object;
2996                         flush=0;
2997                         for(psys=ob->particlesystem.first; psys; psys=psys->next){
2998                                 if(psys->part==part){
2999                                         psys->recalc |= event;
3000                                         if(hair_recalc)
3001                                                 psys->recalc |= PSYS_RECALC_HAIR;
3002                                         flush++;
3003                                 }
3004                                 else if(psys->part->type==PART_REACTOR){
3005                                         ParticleSystem *tpsys;
3006                                         tob=psys->target_ob;
3007                                         if(tob==0)
3008                                                 tob=ob;
3009                                         tpsys=BLI_findlink(&tob->particlesystem,psys->target_psys-1);
3010
3011                                         if(tpsys && tpsys->part==part){
3012                                                 psys->flag |= event;
3013                                                 flush++;
3014                                         }
3015                                 }
3016                         }
3017                         if(flush)
3018                                 DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
3019                 }
3020         }
3021 }
3022 /************************************************/
3023 /*                      Textures                                                        */
3024 /************************************************/
3025 static void get_cpa_texture(DerivedMesh *dm, Material *ma, int face_index, float *fw, float *orco, ParticleTexture *ptex, int event)
3026 {
3027         MTex *mtex;
3028         int m,setvars=0;
3029         float value, rgba[4], texco[3];
3030
3031         if(ma) for(m=0; m<MAX_MTEX; m++){
3032                 mtex=ma->mtex[m];
3033                 if(mtex && (ma->septex & (1<<m))==0){
3034                         float var=mtex->varfac;
3035                         short blend=mtex->blendtype;
3036                         short neg=mtex->pmaptoneg;
3037
3038                         if(mtex->texco & TEXCO_UV && fw){
3039                                 int uv_index=CustomData_get_named_layer_index(&dm->faceData,CD_MTFACE,mtex->uvname);
3040                                 if(uv_index<0){
3041                                         uv_index=CustomData_get_active_layer_index(&dm->faceData,CD_MTFACE);
3042                                 }
3043                                 if(uv_index>=0){
3044                                         CustomDataLayer *layer=&dm->faceData.layers[uv_index];
3045                                         MTFace *mtface= &((MTFace*)layer->data)[face_index];
3046                                         MFace *mf=dm->getFaceData(dm,face_index,CD_MFACE);
3047                                         psys_interpolate_uvs(mtface,mf->v4,fw,texco);
3048                                         texco[0]*=2.0;
3049                                         texco[1]*=2.0;
3050                                         texco[0]-=1.0;
3051                                         texco[1]-=1.0;
3052                                 }
3053                                 else
3054                                         VECCOPY(texco,orco);
3055                         }
3056                         else{
3057                                 VECCOPY(texco,orco);
3058                         }
3059                         externtex(mtex, texco, &value, rgba, rgba+1, rgba+2, rgba+3);
3060                         if((event & mtex->pmapto) & MAP_PA_TIME){
3061                                 if((setvars&MAP_PA_TIME)==0){
3062                                         ptex->time=0.0;
3063                                         setvars|=MAP_PA_TIME;
3064                                 }
3065                                 ptex->time= texture_value_blend(mtex->def_var,ptex->time,value,var,blend,neg & MAP_PA_TIME);
3066                         }
3067                         if((event & mtex->pmapto) & MAP_PA_LENGTH)
3068                                 ptex->length= texture_value_blend(value,ptex->length,value,var,blend,neg & MAP_PA_LENGTH);
3069                         if((event & mtex->pmapto) & MAP_PA_CLUMP)
3070                                 ptex->clump= texture_value_blend(value,ptex->clump,value,var,blend,neg & MAP_PA_CLUMP);
3071                         if((event & mtex->pmapto) & MAP_PA_KINK)
3072                                 ptex->kink= texture_value_blend(value,ptex->kink,value,var,blend,neg & MAP_PA_KINK);
3073                         if((event & mtex->pmapto) & MAP_PA_ROUGH)
3074                                 ptex->rough= texture_value_blend(value,ptex->rough,value,var,blend,neg & MAP_PA_ROUGH);
3075                 }
3076         }
3077         if(event & MAP_PA_TIME) { CLAMP(ptex->time,0.0,1.0); }
3078         if(event & MAP_PA_LENGTH) { CLAMP(ptex->length,0.0,1.0); }
3079         if(event & MAP_PA_CLUMP) { CLAMP(ptex->clump,0.0,1.0); }
3080         if(event & MAP_PA_KINK) { CLAMP(ptex->kink,0.0,1.0); }
3081         if(event & MAP_PA_ROUGH) { CLAMP(ptex->rough,0.0,1.0); }
3082 }
3083 void psys_get_texture(Object *ob, Material *ma, ParticleSystemModifierData *psmd, ParticleSystem *psys, ParticleData *pa, ParticleTexture *ptex, int event)
3084 {
3085         MTex *mtex;
3086         int m;
3087         float value, rgba[4], co[3], texco[3];
3088         int setvars=0;
3089
3090         if(ma) for(m=0; m<MAX_MTEX; m++){
3091                 mtex=ma->mtex[m];
3092                 if(mtex && (ma->septex & (1<<m))==0){
3093                         float var=mtex->varfac;
3094                         short blend=mtex->blendtype;
3095                         short neg=mtex->pmaptoneg;
3096
3097                         if(mtex->texco & TEXCO_UV){
3098                                 int uv_index=CustomData_get_named_layer_index(&psmd->dm->faceData,CD_MTFACE,mtex->uvname);
3099                                 if(uv_index<0){
3100                                         uv_index=CustomData_get_active_layer_index(&psmd->dm->faceData,CD_MTFACE);
3101                                 }
3102                                 if(uv_index>=0){
3103                                         CustomDataLayer *layer=&psmd->dm->faceData.layers[uv_index];
3104