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