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