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