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