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