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