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