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