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