Merge branch 'master' into blender2.8
[blender.git] / source / blender / blenkernel / intern / smoke.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) Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Daniel Genrich
24  *                 Blender Foundation
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 /** \file blender/blenkernel/intern/smoke.c
30  *  \ingroup bke
31  */
32
33
34 /* Part of the code copied from elbeem fluid library, copyright by Nils Thuerey */
35
36 #include "MEM_guardedalloc.h"
37
38 #include <float.h>
39 #include <math.h>
40 #include <stdio.h>
41 #include <string.h> /* memset */
42
43 #include "BLI_blenlib.h"
44 #include "BLI_math.h"
45 #include "BLI_kdtree.h"
46 #include "BLI_kdopbvh.h"
47 #include "BLI_task.h"
48 #include "BLI_threads.h"
49 #include "BLI_utildefines.h"
50 #include "BLI_voxel.h"
51
52 #include "DNA_anim_types.h"
53 #include "DNA_armature_types.h"
54 #include "DNA_constraint_types.h"
55 #include "DNA_customdata_types.h"
56 #include "DNA_lamp_types.h"
57 #include "DNA_mesh_types.h"
58 #include "DNA_meshdata_types.h"
59 #include "DNA_modifier_types.h"
60 #include "DNA_object_types.h"
61 #include "DNA_particle_types.h"
62 #include "DNA_scene_types.h"
63 #include "DNA_smoke_types.h"
64
65 #include "BKE_appdir.h"
66 #include "BKE_animsys.h"
67 #include "BKE_armature.h"
68 #include "BKE_bvhutils.h"
69 #include "BKE_collision.h"
70 #include "BKE_colortools.h"
71 #include "BKE_constraint.h"
72 #include "BKE_customdata.h"
73 #include "BKE_deform.h"
74 #include "BKE_effect.h"
75 #include "BKE_global.h"
76 #include "BKE_library.h"
77 #include "BKE_main.h"
78 #include "BKE_mesh.h"
79 #include "BKE_mesh_runtime.h"
80 #include "BKE_modifier.h"
81 #include "BKE_object.h"
82 #include "BKE_particle.h"
83 #include "BKE_pointcache.h"
84 #include "BKE_scene.h"
85 #include "BKE_smoke.h"
86 #include "BKE_texture.h"
87
88 #include "DEG_depsgraph.h"
89 #include "DEG_depsgraph_query.h"
90
91 #include "RE_shader_ext.h"
92
93 #include "GPU_glew.h"
94
95 /* UNUSED so far, may be enabled later */
96 /* #define USE_SMOKE_COLLISION_DM */
97
98 //#define DEBUG_TIME
99
100 #ifdef DEBUG_TIME
101 #       include "PIL_time.h"
102 #endif
103
104 #include "smoke_API.h"
105
106 #ifdef WITH_SMOKE
107
108 static ThreadMutex object_update_lock = BLI_MUTEX_INITIALIZER;
109
110 struct Mesh;
111 struct Object;
112 struct Scene;
113 struct SmokeModifierData;
114
115 // timestep default value for nice appearance 0.1f
116 #define DT_DEFAULT 0.1f
117
118 #define ADD_IF_LOWER_POS(a, b) (min_ff((a) + (b), max_ff((a), (b))))
119 #define ADD_IF_LOWER_NEG(a, b) (max_ff((a) + (b), min_ff((a), (b))))
120 #define ADD_IF_LOWER(a, b) (((b) > 0) ? ADD_IF_LOWER_POS((a), (b)) : ADD_IF_LOWER_NEG((a), (b)))
121
122 #else /* WITH_SMOKE */
123
124 /* Stubs to use when smoke is disabled */
125 struct WTURBULENCE *smoke_turbulence_init(int *UNUSED(res), int UNUSED(amplify), int UNUSED(noisetype), const char *UNUSED(noisefile_path), int UNUSED(use_fire), int UNUSED(use_colors)) { return NULL; }
126 //struct FLUID_3D *smoke_init(int *UNUSED(res), float *UNUSED(dx), float *UNUSED(dtdef), int UNUSED(use_heat), int UNUSED(use_fire), int UNUSED(use_colors)) { return NULL; }
127 void smoke_free(struct FLUID_3D *UNUSED(fluid)) {}
128 float *smoke_get_density(struct FLUID_3D *UNUSED(fluid)) { return NULL; }
129 void smoke_turbulence_free(struct WTURBULENCE *UNUSED(wt)) {}
130 void smoke_initWaveletBlenderRNA(struct WTURBULENCE *UNUSED(wt), float *UNUSED(strength)) {}
131 void smoke_initBlenderRNA(struct FLUID_3D *UNUSED(fluid), float *UNUSED(alpha), float *UNUSED(beta), float *UNUSED(dt_factor), float *UNUSED(vorticity),
132                           int *UNUSED(border_colli), float *UNUSED(burning_rate), float *UNUSED(flame_smoke), float *UNUSED(flame_smoke_color),
133                           float *UNUSED(flame_vorticity), float *UNUSED(flame_ignition_temp), float *UNUSED(flame_max_temp)) {}
134 struct Mesh *smokeModifier_do(SmokeModifierData *UNUSED(smd), Depsgraph *UNUSED(depsgraph), Scene *UNUSED(scene), Object *UNUSED(ob), Mesh *UNUSED(me)) { return NULL; }
135 float smoke_get_velocity_at(struct Object *UNUSED(ob), float UNUSED(position[3]), float UNUSED(velocity[3])) { return 0.0f; }
136
137 #endif /* WITH_SMOKE */
138
139 #ifdef WITH_SMOKE
140
141 void smoke_reallocate_fluid(SmokeDomainSettings *sds, float dx, int res[3], int free_old)
142 {
143         int use_heat = (sds->active_fields & SM_ACTIVE_HEAT);
144         int use_fire = (sds->active_fields & SM_ACTIVE_FIRE);
145         int use_colors = (sds->active_fields & SM_ACTIVE_COLORS);
146
147         if (free_old && sds->fluid)
148                 smoke_free(sds->fluid);
149         if (!min_iii(res[0], res[1], res[2])) {
150                 sds->fluid = NULL;
151                 return;
152         }
153         sds->fluid = smoke_init(res, dx, DT_DEFAULT, use_heat, use_fire, use_colors);
154         smoke_initBlenderRNA(sds->fluid, &(sds->alpha), &(sds->beta), &(sds->time_scale), &(sds->vorticity), &(sds->border_collisions),
155                              &(sds->burning_rate), &(sds->flame_smoke), sds->flame_smoke_color, &(sds->flame_vorticity), &(sds->flame_ignition), &(sds->flame_max_temp));
156
157         /* reallocate shadow buffer */
158         if (sds->shadow)
159                 MEM_freeN(sds->shadow);
160         sds->shadow = MEM_callocN(sizeof(float) * res[0] * res[1] * res[2], "SmokeDomainShadow");
161 }
162
163 void smoke_reallocate_highres_fluid(SmokeDomainSettings *sds, float dx, int res[3], int free_old)
164 {
165         int use_fire = (sds->active_fields & (SM_ACTIVE_HEAT | SM_ACTIVE_FIRE));
166         int use_colors = (sds->active_fields & SM_ACTIVE_COLORS);
167
168         if (free_old && sds->wt)
169                 smoke_turbulence_free(sds->wt);
170         if (!min_iii(res[0], res[1], res[2])) {
171                 sds->wt = NULL;
172                 return;
173         }
174
175         /* smoke_turbulence_init uses non-threadsafe functions from fftw3 lib (like fftw_plan & co). */
176         BLI_thread_lock(LOCK_FFTW);
177
178         sds->wt = smoke_turbulence_init(res, sds->amplify + 1, sds->noise, BKE_tempdir_session(), use_fire, use_colors);
179
180         BLI_thread_unlock(LOCK_FFTW);
181
182         sds->res_wt[0] = res[0] * (sds->amplify + 1);
183         sds->res_wt[1] = res[1] * (sds->amplify + 1);
184         sds->res_wt[2] = res[2] * (sds->amplify + 1);
185         sds->dx_wt = dx / (sds->amplify + 1);
186         smoke_initWaveletBlenderRNA(sds->wt, &(sds->strength));
187 }
188
189 /* convert global position to domain cell space */
190 static void smoke_pos_to_cell(SmokeDomainSettings *sds, float pos[3])
191 {
192         mul_m4_v3(sds->imat, pos);
193         sub_v3_v3(pos, sds->p0);
194         pos[0] *= 1.0f / sds->cell_size[0];
195         pos[1] *= 1.0f / sds->cell_size[1];
196         pos[2] *= 1.0f / sds->cell_size[2];
197 }
198
199 /* set domain transformations and base resolution from object mesh */
200 static void smoke_set_domain_from_mesh(SmokeDomainSettings *sds, Object *ob, Mesh *me, bool init_resolution)
201 {
202         size_t i;
203         float min[3] = {FLT_MAX, FLT_MAX, FLT_MAX}, max[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX};
204         float size[3];
205         MVert *verts = me->mvert;
206         float scale = 0.0;
207         int res;
208
209         res = sds->maxres;
210
211         // get BB of domain
212         for (i = 0; i < me->totvert; i++)
213         {
214                 // min BB
215                 min[0] = MIN2(min[0], verts[i].co[0]);
216                 min[1] = MIN2(min[1], verts[i].co[1]);
217                 min[2] = MIN2(min[2], verts[i].co[2]);
218
219                 // max BB
220                 max[0] = MAX2(max[0], verts[i].co[0]);
221                 max[1] = MAX2(max[1], verts[i].co[1]);
222                 max[2] = MAX2(max[2], verts[i].co[2]);
223         }
224
225         /* set domain bounds */
226         copy_v3_v3(sds->p0, min);
227         copy_v3_v3(sds->p1, max);
228         sds->dx = 1.0f / res;
229
230         /* calculate domain dimensions */
231         sub_v3_v3v3(size, max, min);
232         if (init_resolution) {
233                 zero_v3_int(sds->base_res);
234                 copy_v3_v3(sds->cell_size, size);
235         }
236         /* apply object scale */
237         for (i = 0; i < 3; i++) {
238                 size[i] = fabsf(size[i] * ob->size[i]);
239         }
240         copy_v3_v3(sds->global_size, size);
241         copy_v3_v3(sds->dp0, min);
242
243         invert_m4_m4(sds->imat, ob->obmat);
244
245         // prevent crash when initializing a plane as domain
246         if (!init_resolution || (size[0] < FLT_EPSILON) || (size[1] < FLT_EPSILON) || (size[2] < FLT_EPSILON))
247                 return;
248
249         /* define grid resolutions from longest domain side */
250         if (size[0] >= MAX2(size[1], size[2])) {
251                 scale = res / size[0];
252                 sds->scale = size[0] / fabsf(ob->size[0]);
253                 sds->base_res[0] = res;
254                 sds->base_res[1] = max_ii((int)(size[1] * scale + 0.5f), 4);
255                 sds->base_res[2] = max_ii((int)(size[2] * scale + 0.5f), 4);
256         }
257         else if (size[1] >= MAX2(size[0], size[2])) {
258                 scale = res / size[1];
259                 sds->scale = size[1] / fabsf(ob->size[1]);
260                 sds->base_res[0] = max_ii((int)(size[0] * scale + 0.5f), 4);
261                 sds->base_res[1] = res;
262                 sds->base_res[2] = max_ii((int)(size[2] * scale + 0.5f), 4);
263         }
264         else {
265                 scale = res / size[2];
266                 sds->scale = size[2] / fabsf(ob->size[2]);
267                 sds->base_res[0] = max_ii((int)(size[0] * scale + 0.5f), 4);
268                 sds->base_res[1] = max_ii((int)(size[1] * scale + 0.5f), 4);
269                 sds->base_res[2] = res;
270         }
271
272         /* set cell size */
273         sds->cell_size[0] /= (float)sds->base_res[0];
274         sds->cell_size[1] /= (float)sds->base_res[1];
275         sds->cell_size[2] /= (float)sds->base_res[2];
276 }
277
278 static int smokeModifier_init(SmokeModifierData *smd, Object *ob, int scene_framenr, Mesh *me)
279 {
280         if ((smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain && !smd->domain->fluid)
281         {
282                 SmokeDomainSettings *sds = smd->domain;
283                 int res[3];
284                 /* set domain dimensions from mesh */
285                 smoke_set_domain_from_mesh(sds, ob, me, true);
286                 /* reset domain values */
287                 zero_v3_int(sds->shift);
288                 zero_v3(sds->shift_f);
289                 add_v3_fl(sds->shift_f, 0.5f);
290                 zero_v3(sds->prev_loc);
291                 mul_m4_v3(ob->obmat, sds->prev_loc);
292                 copy_m4_m4(sds->obmat, ob->obmat);
293
294                 /* set resolutions */
295                 if (smd->domain->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) {
296                         res[0] = res[1] = res[2] = 1; /* use minimum res for adaptive init */
297                 }
298                 else {
299                         VECCOPY(res, sds->base_res);
300                 }
301                 VECCOPY(sds->res, res);
302                 sds->total_cells = sds->res[0] * sds->res[1] * sds->res[2];
303                 sds->res_min[0] = sds->res_min[1] = sds->res_min[2] = 0;
304                 VECCOPY(sds->res_max, res);
305
306                 /* allocate fluid */
307                 smoke_reallocate_fluid(sds, sds->dx, sds->res, 0);
308
309                 smd->time = scene_framenr;
310
311                 /* allocate highres fluid */
312                 if (sds->flags & MOD_SMOKE_HIGHRES) {
313                         smoke_reallocate_highres_fluid(sds, sds->dx, sds->res, 0);
314                 }
315                 /* allocate shadow buffer */
316                 if (!sds->shadow)
317                         sds->shadow = MEM_callocN(sizeof(float) * sds->res[0] * sds->res[1] * sds->res[2], "SmokeDomainShadow");
318
319                 return 1;
320         }
321         else if ((smd->type & MOD_SMOKE_TYPE_FLOW) && smd->flow)
322         {
323                 smd->time = scene_framenr;
324
325                 return 1;
326         }
327         else if ((smd->type & MOD_SMOKE_TYPE_COLL))
328         {
329                 if (!smd->coll)
330                 {
331                         smokeModifier_createType(smd);
332                 }
333
334                 smd->time = scene_framenr;
335
336                 return 1;
337         }
338
339         return 2;
340 }
341
342 #endif /* WITH_SMOKE */
343
344 static void smokeModifier_freeDomain(SmokeModifierData *smd)
345 {
346         if (smd->domain)
347         {
348                 if (smd->domain->shadow)
349                         MEM_freeN(smd->domain->shadow);
350                 smd->domain->shadow = NULL;
351
352                 if (smd->domain->fluid)
353                         smoke_free(smd->domain->fluid);
354
355                 if (smd->domain->fluid_mutex)
356                         BLI_rw_mutex_free(smd->domain->fluid_mutex);
357
358                 if (smd->domain->wt)
359                         smoke_turbulence_free(smd->domain->wt);
360
361                 if (smd->domain->effector_weights)
362                         MEM_freeN(smd->domain->effector_weights);
363                 smd->domain->effector_weights = NULL;
364
365                 if (!(smd->modifier.flag & eModifierFlag_SharedCaches)) {
366                         BKE_ptcache_free_list(&(smd->domain->ptcaches[0]));
367                         smd->domain->point_cache[0] = NULL;
368                 }
369
370                 if (smd->domain->coba) {
371                         MEM_freeN(smd->domain->coba);
372                 }
373
374                 MEM_freeN(smd->domain);
375                 smd->domain = NULL;
376         }
377 }
378
379 static void smokeModifier_freeFlow(SmokeModifierData *smd)
380 {
381         if (smd->flow)
382         {
383                 if (smd->flow->mesh) BKE_id_free(NULL, smd->flow->mesh);
384                 if (smd->flow->verts_old) MEM_freeN(smd->flow->verts_old);
385                 MEM_freeN(smd->flow);
386                 smd->flow = NULL;
387         }
388 }
389
390 static void smokeModifier_freeCollision(SmokeModifierData *smd)
391 {
392         if (smd->coll)
393         {
394                 SmokeCollSettings *scs = smd->coll;
395
396                 if (scs->numverts)
397                 {
398                         if (scs->verts_old)
399                         {
400                                 MEM_freeN(scs->verts_old);
401                                 scs->verts_old = NULL;
402                         }
403                 }
404
405                 if (smd->coll->mesh)
406                         BKE_id_free(NULL, smd->coll->mesh);
407                 smd->coll->mesh = NULL;
408
409                 MEM_freeN(smd->coll);
410                 smd->coll = NULL;
411         }
412 }
413
414 void smokeModifier_reset_turbulence(struct SmokeModifierData *smd)
415 {
416         if (smd && smd->domain && smd->domain->wt)
417         {
418                 smoke_turbulence_free(smd->domain->wt);
419                 smd->domain->wt = NULL;
420         }
421 }
422
423 static void smokeModifier_reset_ex(struct SmokeModifierData *smd, bool need_lock)
424 {
425         if (smd)
426         {
427                 if (smd->domain)
428                 {
429                         if (smd->domain->shadow)
430                                 MEM_freeN(smd->domain->shadow);
431                         smd->domain->shadow = NULL;
432
433                         if (smd->domain->fluid)
434                         {
435                                 if (need_lock)
436                                         BLI_rw_mutex_lock(smd->domain->fluid_mutex, THREAD_LOCK_WRITE);
437
438                                 smoke_free(smd->domain->fluid);
439                                 smd->domain->fluid = NULL;
440
441                                 if (need_lock)
442                                         BLI_rw_mutex_unlock(smd->domain->fluid_mutex);
443                         }
444
445                         smokeModifier_reset_turbulence(smd);
446
447                         smd->time = -1;
448                         smd->domain->total_cells = 0;
449                         smd->domain->active_fields = 0;
450                 }
451                 else if (smd->flow)
452                 {
453                         if (smd->flow->verts_old) MEM_freeN(smd->flow->verts_old);
454                         smd->flow->verts_old = NULL;
455                         smd->flow->numverts = 0;
456                 }
457                 else if (smd->coll)
458                 {
459                         SmokeCollSettings *scs = smd->coll;
460
461                         if (scs->numverts && scs->verts_old)
462                         {
463                                 MEM_freeN(scs->verts_old);
464                                 scs->verts_old = NULL;
465                         }
466                 }
467         }
468 }
469
470 void smokeModifier_reset(struct SmokeModifierData *smd)
471 {
472         smokeModifier_reset_ex(smd, true);
473 }
474
475 void smokeModifier_free(SmokeModifierData *smd)
476 {
477         if (smd)
478         {
479                 smokeModifier_freeDomain(smd);
480                 smokeModifier_freeFlow(smd);
481                 smokeModifier_freeCollision(smd);
482         }
483 }
484
485 void smokeModifier_createType(struct SmokeModifierData *smd)
486 {
487         if (smd)
488         {
489                 if (smd->type & MOD_SMOKE_TYPE_DOMAIN)
490                 {
491                         if (smd->domain)
492                                 smokeModifier_freeDomain(smd);
493
494                         smd->domain = MEM_callocN(sizeof(SmokeDomainSettings), "SmokeDomain");
495
496                         smd->domain->smd = smd;
497
498                         smd->domain->point_cache[0] = BKE_ptcache_add(&(smd->domain->ptcaches[0]));
499                         smd->domain->point_cache[0]->flag |= PTCACHE_DISK_CACHE;
500                         smd->domain->point_cache[0]->step = 1;
501
502                         /* Deprecated */
503                         smd->domain->point_cache[1] = NULL;
504                         BLI_listbase_clear(&smd->domain->ptcaches[1]);
505                         /* set some standard values */
506                         smd->domain->fluid = NULL;
507                         smd->domain->fluid_mutex = BLI_rw_mutex_alloc();
508                         smd->domain->wt = NULL;
509                         smd->domain->eff_group = NULL;
510                         smd->domain->fluid_group = NULL;
511                         smd->domain->coll_group = NULL;
512                         smd->domain->maxres = 32;
513                         smd->domain->amplify = 1;
514                         smd->domain->alpha = -0.001;
515                         smd->domain->beta = 0.1;
516                         smd->domain->time_scale = 1.0;
517                         smd->domain->vorticity = 2.0;
518                         smd->domain->border_collisions = SM_BORDER_OPEN; // open domain
519                         smd->domain->flags = MOD_SMOKE_DISSOLVE_LOG;
520                         smd->domain->highres_sampling = SM_HRES_FULLSAMPLE;
521                         smd->domain->strength = 2.0;
522                         smd->domain->noise = MOD_SMOKE_NOISEWAVE;
523                         smd->domain->diss_speed = 5;
524                         smd->domain->active_fields = 0;
525
526                         smd->domain->adapt_margin = 4;
527                         smd->domain->adapt_res = 0;
528                         smd->domain->adapt_threshold = 0.02f;
529
530                         smd->domain->burning_rate = 0.75f;
531                         smd->domain->flame_smoke = 1.0f;
532                         smd->domain->flame_vorticity = 0.5f;
533                         smd->domain->flame_ignition = 1.5f;
534                         smd->domain->flame_max_temp = 3.0f;
535                         /* color */
536                         smd->domain->flame_smoke_color[0] = 0.7f;
537                         smd->domain->flame_smoke_color[1] = 0.7f;
538                         smd->domain->flame_smoke_color[2] = 0.7f;
539
540                         smd->domain->viewsettings = MOD_SMOKE_VIEW_SHOWBIG;
541                         smd->domain->effector_weights = BKE_effector_add_weights(NULL);
542
543 #ifdef WITH_OPENVDB_BLOSC
544                         smd->domain->openvdb_comp = VDB_COMPRESSION_BLOSC;
545 #else
546                         smd->domain->openvdb_comp = VDB_COMPRESSION_ZIP;
547 #endif
548                         smd->domain->data_depth = 0;
549                         smd->domain->cache_file_format = PTCACHE_FILE_PTCACHE;
550
551                         smd->domain->display_thickness = 1.0f;
552                         smd->domain->slice_method = MOD_SMOKE_SLICE_VIEW_ALIGNED;
553                         smd->domain->axis_slice_method = AXIS_SLICE_FULL;
554                         smd->domain->slice_per_voxel = 5.0f;
555                         smd->domain->slice_depth = 0.5f;
556                         smd->domain->slice_axis = 0;
557                         smd->domain->vector_scale = 1.0f;
558
559                         smd->domain->coba = NULL;
560                         smd->domain->coba_field = FLUID_FIELD_DENSITY;
561
562                         smd->domain->clipping = 1e-3f;
563                 }
564                 else if (smd->type & MOD_SMOKE_TYPE_FLOW)
565                 {
566                         if (smd->flow)
567                                 smokeModifier_freeFlow(smd);
568
569                         smd->flow = MEM_callocN(sizeof(SmokeFlowSettings), "SmokeFlow");
570
571                         smd->flow->smd = smd;
572
573                         /* set some standard values */
574                         smd->flow->density = 1.0f;
575                         smd->flow->fuel_amount = 1.0f;
576                         smd->flow->temp = 1.0f;
577                         smd->flow->flags = MOD_SMOKE_FLOW_ABSOLUTE | MOD_SMOKE_FLOW_USE_PART_SIZE;
578                         smd->flow->vel_multi = 1.0f;
579                         smd->flow->volume_density = 0.0f;
580                         smd->flow->surface_distance = 1.5f;
581                         smd->flow->source = MOD_SMOKE_FLOW_SOURCE_MESH;
582                         smd->flow->texture_size = 1.0f;
583                         smd->flow->particle_size = 1.0f;
584                         smd->flow->subframes = 0;
585
586                         smd->flow->color[0] = 0.7f;
587                         smd->flow->color[1] = 0.7f;
588                         smd->flow->color[2] = 0.7f;
589
590                         smd->flow->mesh = NULL;
591                         smd->flow->psys = NULL;
592
593                 }
594                 else if (smd->type & MOD_SMOKE_TYPE_COLL)
595                 {
596                         if (smd->coll)
597                                 smokeModifier_freeCollision(smd);
598
599                         smd->coll = MEM_callocN(sizeof(SmokeCollSettings), "SmokeColl");
600
601                         smd->coll->smd = smd;
602                         smd->coll->verts_old = NULL;
603                         smd->coll->numverts = 0;
604                         smd->coll->type = 0; // static obstacle
605                         smd->coll->mesh = NULL;
606                 }
607         }
608 }
609
610 void smokeModifier_copy(const struct SmokeModifierData *smd, struct SmokeModifierData *tsmd, const int flag)
611 {
612         tsmd->type = smd->type;
613         tsmd->time = smd->time;
614
615         smokeModifier_createType(tsmd);
616
617         if (tsmd->domain) {
618                 SmokeDomainSettings *tsds = tsmd->domain;
619                 SmokeDomainSettings *sds = smd->domain;
620
621                 BKE_ptcache_free_list(&(tsds->ptcaches[0]));
622
623                 if (flag & LIB_ID_CREATE_NO_MAIN) {
624                         /* Share the cache with the original object's modifier. */
625                         tsmd->modifier.flag |= eModifierFlag_SharedCaches;
626                         tsds->point_cache[0] = sds->point_cache[0];
627                         tsds->ptcaches[0] = sds->ptcaches[0];
628                 }
629                 else {
630                         tsds->point_cache[0] = BKE_ptcache_copy_list(&(tsds->ptcaches[0]), &(sds->ptcaches[0]), flag);
631                 }
632
633                 tsds->fluid_group = sds->fluid_group;
634                 tsds->coll_group = sds->coll_group;
635
636                 tsds->adapt_margin = sds->adapt_margin;
637                 tsds->adapt_res = sds->adapt_res;
638                 tsds->adapt_threshold = sds->adapt_threshold;
639
640                 tsds->alpha = sds->alpha;
641                 tsds->beta = sds->beta;
642                 tsds->amplify = sds->amplify;
643                 tsds->maxres = sds->maxres;
644                 tsds->flags = sds->flags;
645                 tsds->highres_sampling = sds->highres_sampling;
646                 tsds->viewsettings = sds->viewsettings;
647                 tsds->noise = sds->noise;
648                 tsds->diss_speed = sds->diss_speed;
649                 tsds->strength = sds->strength;
650
651                 tsds->border_collisions = sds->border_collisions;
652                 tsds->vorticity = sds->vorticity;
653                 tsds->time_scale = sds->time_scale;
654
655                 tsds->burning_rate = sds->burning_rate;
656                 tsds->flame_smoke = sds->flame_smoke;
657                 tsds->flame_vorticity = sds->flame_vorticity;
658                 tsds->flame_ignition = sds->flame_ignition;
659                 tsds->flame_max_temp = sds->flame_max_temp;
660                 copy_v3_v3(tsds->flame_smoke_color, sds->flame_smoke_color);
661
662                 MEM_freeN(tsds->effector_weights);
663                 tsds->effector_weights = MEM_dupallocN(sds->effector_weights);
664                 tsds->openvdb_comp = sds->openvdb_comp;
665                 tsds->data_depth = sds->data_depth;
666                 tsds->cache_file_format = sds->cache_file_format;
667
668                 tsds->display_thickness = sds->display_thickness;
669                 tsds->slice_method = sds->slice_method;
670                 tsds->axis_slice_method = sds->axis_slice_method;
671                 tsds->slice_per_voxel = sds->slice_per_voxel;
672                 tsds->slice_depth = sds->slice_depth;
673                 tsds->slice_axis = sds->slice_axis;
674                 tsds->interp_method = sds->interp_method;
675                 tsds->draw_velocity = sds->draw_velocity;
676                 tsds->vector_draw_type = sds->vector_draw_type;
677                 tsds->vector_scale = sds->vector_scale;
678
679                 tsds->use_coba = sds->use_coba;
680                 tsds->coba_field = sds->coba_field;
681                 if (sds->coba) {
682                         tsds->coba = MEM_dupallocN(sds->coba);
683                 }
684         }
685         else if (tsmd->flow) {
686                 SmokeFlowSettings *tsfs = tsmd->flow;
687                 SmokeFlowSettings *sfs = smd->flow;
688
689                 tsfs->psys = sfs->psys;
690                 tsfs->noise_texture = sfs->noise_texture;
691
692                 tsfs->vel_multi = sfs->vel_multi;
693                 tsfs->vel_normal = sfs->vel_normal;
694                 tsfs->vel_random = sfs->vel_random;
695
696                 tsfs->density = sfs->density;
697                 copy_v3_v3(tsfs->color, sfs->color);
698                 tsfs->fuel_amount = sfs->fuel_amount;
699                 tsfs->temp = sfs->temp;
700                 tsfs->volume_density = sfs->volume_density;
701                 tsfs->surface_distance = sfs->surface_distance;
702                 tsfs->particle_size = sfs->particle_size;
703                 tsfs->subframes = sfs->subframes;
704
705                 tsfs->texture_size = sfs->texture_size;
706                 tsfs->texture_offset = sfs->texture_offset;
707                 BLI_strncpy(tsfs->uvlayer_name, sfs->uvlayer_name, sizeof(tsfs->uvlayer_name));
708                 tsfs->vgroup_density = sfs->vgroup_density;
709
710                 tsfs->type = sfs->type;
711                 tsfs->source = sfs->source;
712                 tsfs->texture_type = sfs->texture_type;
713                 tsfs->flags = sfs->flags;
714         }
715         else if (tsmd->coll) {
716                 /* leave it as initialized, collision settings is mostly caches */
717         }
718 }
719
720 #ifdef WITH_SMOKE
721
722 // forward declaration
723 static void smoke_calc_transparency(SmokeDomainSettings *sds, ViewLayer *view_layer);
724 static float calc_voxel_transp(float *result, float *input, int res[3], int *pixel, float *tRay, float correct);
725
726 static int get_lamp(ViewLayer *view_layer, float *light)
727 {
728         Base *base_tmp = NULL;
729         int found_lamp = 0;
730
731         // try to find a lamp, preferably local
732         for (base_tmp = FIRSTBASE(view_layer); base_tmp; base_tmp = base_tmp->next) {
733                 if (base_tmp->object->type == OB_LAMP) {
734                         Lamp *la = base_tmp->object->data;
735
736                         if (la->type == LA_LOCAL) {
737                                 copy_v3_v3(light, base_tmp->object->obmat[3]);
738                                 return 1;
739                         }
740                         else if (!found_lamp) {
741                                 copy_v3_v3(light, base_tmp->object->obmat[3]);
742                                 found_lamp = 1;
743                         }
744                 }
745         }
746
747         return found_lamp;
748 }
749
750 /**********************************************************
751  * Obstacles
752  **********************************************************/
753
754 typedef struct ObstaclesFromDMData {
755         SmokeDomainSettings *sds;
756         const MVert *mvert;
757         const MLoop *mloop;
758         const MLoopTri *looptri;
759         BVHTreeFromMesh *tree;
760         unsigned char *obstacle_map;
761
762         bool has_velocity;
763         float *vert_vel;
764         float *velocityX, *velocityY, *velocityZ;
765         int *num_obstacles;
766 } ObstaclesFromDMData;
767
768 static void obstacles_from_mesh_task_cb(
769         void *__restrict userdata,
770         const int z,
771         const ParallelRangeTLS *__restrict UNUSED(tls))
772 {
773         ObstaclesFromDMData *data = userdata;
774         SmokeDomainSettings *sds = data->sds;
775
776         /* slightly rounded-up sqrt(3 * (0.5)^2) == max. distance of cell boundary along the diagonal */
777         const float surface_distance = 0.867f;
778
779         for (int x = sds->res_min[0]; x < sds->res_max[0]; x++) {
780                 for (int y = sds->res_min[1]; y < sds->res_max[1]; y++) {
781                         const int index = smoke_get_index(x - sds->res_min[0], sds->res[0], y - sds->res_min[1], sds->res[1], z - sds->res_min[2]);
782
783                         float ray_start[3] = {(float)x + 0.5f, (float)y + 0.5f, (float)z + 0.5f};
784                         BVHTreeNearest nearest = {0};
785                         nearest.index = -1;
786                         nearest.dist_sq = surface_distance * surface_distance; /* find_nearest uses squared distance */
787
788                         /* find the nearest point on the mesh */
789                         if (BLI_bvhtree_find_nearest(data->tree->tree, ray_start, &nearest, data->tree->nearest_callback, data->tree) != -1) {
790                                 const MLoopTri *lt = &data->looptri[nearest.index];
791                                 float weights[3];
792                                 int v1, v2, v3;
793
794                                 /* calculate barycentric weights for nearest point */
795                                 v1 = data->mloop[lt->tri[0]].v;
796                                 v2 = data->mloop[lt->tri[1]].v;
797                                 v3 = data->mloop[lt->tri[2]].v;
798                                 interp_weights_tri_v3(weights, data->mvert[v1].co, data->mvert[v2].co, data->mvert[v3].co, nearest.co);
799
800                                 // DG TODO
801                                 if (data->has_velocity)
802                                 {
803                                         /* apply object velocity */
804                                         {
805                                                 float hit_vel[3];
806                                                 interp_v3_v3v3v3(hit_vel, &data->vert_vel[v1 * 3], &data->vert_vel[v2 * 3], &data->vert_vel[v3 * 3], weights);
807                                                 data->velocityX[index] += hit_vel[0];
808                                                 data->velocityY[index] += hit_vel[1];
809                                                 data->velocityZ[index] += hit_vel[2];
810                                         }
811                                 }
812
813                                 /* tag obstacle cells */
814                                 data->obstacle_map[index] = 1;
815
816                                 if (data->has_velocity) {
817                                         data->obstacle_map[index] |= 8;
818                                         data->num_obstacles[index]++;
819                                 }
820                         }
821                 }
822         }
823 }
824
825 static void obstacles_from_mesh(
826         Object *coll_ob, SmokeDomainSettings *sds, SmokeCollSettings *scs,
827         unsigned char *obstacle_map, float *velocityX, float *velocityY, float *velocityZ, int *num_obstacles, float dt)
828 {
829         if (!scs->mesh) return;
830         {
831                 Mesh *me = NULL;
832                 MVert *mvert = NULL;
833                 const MLoopTri *looptri;
834                 const MLoop *mloop;
835                 BVHTreeFromMesh treeData = {NULL};
836                 int numverts, i;
837
838                 float *vert_vel = NULL;
839                 bool has_velocity = false;
840
841                 me = BKE_mesh_copy_for_eval(scs->mesh, true);
842                 BKE_mesh_ensure_normals(me);
843                 mvert = me->mvert;
844                 mloop = me->mloop;
845                 looptri = BKE_mesh_runtime_looptri_ensure(me);
846                 numverts = me->totvert;
847
848                 // DG TODO
849                 // if (scs->type > SM_COLL_STATIC)
850                 // if line above is used, the code is in trouble if the object moves but is declared as "does not move"
851
852                 {
853                         vert_vel = MEM_callocN(sizeof(float) * numverts * 3, "smoke_obs_velocity");
854
855                         if (scs->numverts != numverts || !scs->verts_old) {
856                                 if (scs->verts_old) MEM_freeN(scs->verts_old);
857
858                                 scs->verts_old = MEM_callocN(sizeof(float) * numverts * 3, "smoke_obs_verts_old");
859                                 scs->numverts = numverts;
860                         }
861                         else {
862                                 has_velocity = true;
863                         }
864                 }
865
866                 /*      Transform collider vertices to
867                  *   domain grid space for fast lookups */
868                 for (i = 0; i < numverts; i++) {
869                         float n[3];
870                         float co[3];
871
872                         /* vert pos */
873                         mul_m4_v3(coll_ob->obmat, mvert[i].co);
874                         smoke_pos_to_cell(sds, mvert[i].co);
875
876                         /* vert normal */
877                         normal_short_to_float_v3(n, mvert[i].no);
878                         mul_mat3_m4_v3(coll_ob->obmat, n);
879                         mul_mat3_m4_v3(sds->imat, n);
880                         normalize_v3(n);
881                         normal_float_to_short_v3(mvert[i].no, n);
882
883                         /* vert velocity */
884                         VECADD(co, mvert[i].co, sds->shift);
885                         if (has_velocity)
886                         {
887                                 sub_v3_v3v3(&vert_vel[i * 3], co, &scs->verts_old[i * 3]);
888                                 mul_v3_fl(&vert_vel[i * 3], sds->dx / dt);
889                         }
890                         copy_v3_v3(&scs->verts_old[i * 3], co);
891                 }
892
893                 if (BKE_bvhtree_from_mesh_get(&treeData, me, BVHTREE_FROM_LOOPTRI, 4)) {
894                         ObstaclesFromDMData data = {
895                             .sds = sds, .mvert = mvert, .mloop = mloop, .looptri = looptri,
896                             .tree = &treeData, .obstacle_map = obstacle_map,
897                             .has_velocity = has_velocity, .vert_vel = vert_vel,
898                             .velocityX = velocityX, .velocityY = velocityY, .velocityZ = velocityZ,
899                             .num_obstacles = num_obstacles
900                         };
901                         ParallelRangeSettings settings;
902                         BLI_parallel_range_settings_defaults(&settings);
903                         settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC;
904                         BLI_task_parallel_range(sds->res_min[2], sds->res_max[2],
905                                                 &data,
906                                                 obstacles_from_mesh_task_cb,
907                                                 &settings);
908                 }
909                 /* free bvh tree */
910                 free_bvhtree_from_mesh(&treeData);
911                 BKE_id_free(NULL, me);
912
913                 if (vert_vel) MEM_freeN(vert_vel);
914         }
915 }
916
917 /* Animated obstacles: dx_step = ((x_new - x_old) / totalsteps) * substep */
918 static void update_obstacles(Depsgraph *depsgraph, Object *ob, SmokeDomainSettings *sds, float dt,
919                              int UNUSED(substep), int UNUSED(totalsteps))
920 {
921         Object **collobjs = NULL;
922         unsigned int numcollobj = 0;
923
924         unsigned int collIndex;
925         unsigned char *obstacles = smoke_get_obstacle(sds->fluid);
926         float *velx = NULL;
927         float *vely = NULL;
928         float *velz = NULL;
929         float *velxOrig = smoke_get_velocity_x(sds->fluid);
930         float *velyOrig = smoke_get_velocity_y(sds->fluid);
931         float *velzOrig = smoke_get_velocity_z(sds->fluid);
932         float *density = smoke_get_density(sds->fluid);
933         float *fuel = smoke_get_fuel(sds->fluid);
934         float *flame = smoke_get_flame(sds->fluid);
935         float *r = smoke_get_color_r(sds->fluid);
936         float *g = smoke_get_color_g(sds->fluid);
937         float *b = smoke_get_color_b(sds->fluid);
938         unsigned int z;
939
940         int *num_obstacles = MEM_callocN(sizeof(int) * sds->res[0] * sds->res[1] * sds->res[2], "smoke_num_obstacles");
941
942         smoke_get_ob_velocity(sds->fluid, &velx, &vely, &velz);
943
944         // TODO: delete old obstacle flags
945         for (z = 0; z < sds->res[0] * sds->res[1] * sds->res[2]; z++)
946         {
947                 if (obstacles[z] & 8) // Do not delete static obstacles
948                 {
949                         obstacles[z] = 0;
950                 }
951
952                 velx[z] = 0;
953                 vely[z] = 0;
954                 velz[z] = 0;
955         }
956
957
958         collobjs = BKE_collision_objects_create(depsgraph, ob, sds->coll_group, &numcollobj, eModifierType_Smoke);
959
960         // update obstacle tags in cells
961         for (collIndex = 0; collIndex < numcollobj; collIndex++)
962         {
963                 Object *collob = collobjs[collIndex];
964                 SmokeModifierData *smd2 = (SmokeModifierData *)modifiers_findByType(collob, eModifierType_Smoke);
965
966                 // DG TODO: check if modifier is active?
967
968                 if ((smd2->type & MOD_SMOKE_TYPE_COLL) && smd2->coll)
969                 {
970                         SmokeCollSettings *scs = smd2->coll;
971                         obstacles_from_mesh(collob, sds, scs, obstacles, velx, vely, velz, num_obstacles, dt);
972                 }
973         }
974
975         BKE_collision_objects_free(collobjs);
976
977         /* obstacle cells should not contain any velocity from the smoke simulation */
978         for (z = 0; z < sds->res[0] * sds->res[1] * sds->res[2]; z++)
979         {
980                 if (obstacles[z])
981                 {
982                         velxOrig[z] = 0;
983                         velyOrig[z] = 0;
984                         velzOrig[z] = 0;
985                         density[z] = 0;
986                         if (fuel) {
987                                 fuel[z] = 0;
988                                 flame[z] = 0;
989                         }
990                         if (r) {
991                                 r[z] = 0;
992                                 g[z] = 0;
993                                 b[z] = 0;
994                         }
995                 }
996                 /* average velocities from multiple obstacles in one cell */
997                 if (num_obstacles[z]) {
998                         velx[z] /= num_obstacles[z];
999                         vely[z] /= num_obstacles[z];
1000                         velz[z] /= num_obstacles[z];
1001                 }
1002         }
1003
1004         MEM_freeN(num_obstacles);
1005 }
1006
1007 /**********************************************************
1008  * Flow emission code
1009  **********************************************************/
1010
1011 typedef struct EmissionMap {
1012         float *influence;
1013         float *influence_high;
1014         float *velocity;
1015         int min[3], max[3], res[3];
1016         int hmin[3], hmax[3], hres[3];
1017         int total_cells, valid;
1018 } EmissionMap;
1019
1020 static void em_boundInsert(EmissionMap *em, float point[3])
1021 {
1022         int i = 0;
1023         if (!em->valid) {
1024                 for (; i < 3; i++) {
1025                         em->min[i] = (int)floor(point[i]);
1026                         em->max[i] = (int)ceil(point[i]);
1027                 }
1028                 em->valid = 1;
1029         }
1030         else {
1031                 for (; i < 3; i++) {
1032                         if (point[i] < em->min[i]) em->min[i] = (int)floor(point[i]);
1033                         if (point[i] > em->max[i]) em->max[i] = (int)ceil(point[i]);
1034                 }
1035         }
1036 }
1037
1038 static void clampBoundsInDomain(SmokeDomainSettings *sds, int min[3], int max[3], float *min_vel, float *max_vel, int margin, float dt)
1039 {
1040         int i;
1041         for (i = 0; i < 3; i++) {
1042                 int adapt = (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) ? sds->adapt_res : 0;
1043                 /* add margin */
1044                 min[i] -= margin;
1045                 max[i] += margin;
1046
1047                 /* adapt to velocity */
1048                 if (min_vel && min_vel[i] < 0.0f) {
1049                         min[i] += (int)floor(min_vel[i] * dt);
1050                 }
1051                 if (max_vel && max_vel[i] > 0.0f) {
1052                         max[i] += (int)ceil(max_vel[i] * dt);
1053                 }
1054
1055                 /* clamp within domain max size */
1056                 CLAMP(min[i], -adapt, sds->base_res[i] + adapt);
1057                 CLAMP(max[i], -adapt, sds->base_res[i] + adapt);
1058         }
1059 }
1060
1061 static void em_allocateData(EmissionMap *em, bool use_velocity, int hires_mul)
1062 {
1063         int i, res[3];
1064
1065         for (i = 0; i < 3; i++) {
1066                 res[i] = em->max[i] - em->min[i];
1067                 if (res[i] <= 0)
1068                         return;
1069         }
1070         em->total_cells = res[0] * res[1] * res[2];
1071         copy_v3_v3_int(em->res, res);
1072
1073
1074         em->influence = MEM_callocN(sizeof(float) * em->total_cells, "smoke_flow_influence");
1075         if (use_velocity)
1076                 em->velocity = MEM_callocN(sizeof(float) * em->total_cells * 3, "smoke_flow_velocity");
1077
1078         /* allocate high resolution map if required */
1079         if (hires_mul > 1) {
1080                 int total_cells_high = em->total_cells * (hires_mul * hires_mul * hires_mul);
1081
1082                 for (i = 0; i < 3; i++) {
1083                         em->hmin[i] = em->min[i] * hires_mul;
1084                         em->hmax[i] = em->max[i] * hires_mul;
1085                         em->hres[i] = em->res[i] * hires_mul;
1086                 }
1087
1088                 em->influence_high = MEM_callocN(sizeof(float) * total_cells_high, "smoke_flow_influence_high");
1089         }
1090         em->valid = 1;
1091 }
1092
1093 static void em_freeData(EmissionMap *em)
1094 {
1095         if (em->influence)
1096                 MEM_freeN(em->influence);
1097         if (em->influence_high)
1098                 MEM_freeN(em->influence_high);
1099         if (em->velocity)
1100                 MEM_freeN(em->velocity);
1101 }
1102
1103 static void em_combineMaps(EmissionMap *output, EmissionMap *em2, int hires_multiplier, int additive, float sample_size)
1104 {
1105         int i, x, y, z;
1106
1107         /* copyfill input 1 struct and clear output for new allocation */
1108         EmissionMap em1;
1109         memcpy(&em1, output, sizeof(EmissionMap));
1110         memset(output, 0, sizeof(EmissionMap));
1111
1112         for (i = 0; i < 3; i++) {
1113                 if (em1.valid) {
1114                         output->min[i] = MIN2(em1.min[i], em2->min[i]);
1115                         output->max[i] = MAX2(em1.max[i], em2->max[i]);
1116                 }
1117                 else {
1118                         output->min[i] = em2->min[i];
1119                         output->max[i] = em2->max[i];
1120                 }
1121         }
1122         /* allocate output map */
1123         em_allocateData(output, (em1.velocity || em2->velocity), hires_multiplier);
1124
1125         /* base resolution inputs */
1126         for (x = output->min[0]; x < output->max[0]; x++)
1127                 for (y = output->min[1]; y < output->max[1]; y++)
1128                         for (z = output->min[2]; z < output->max[2]; z++) {
1129                                 int index_out = smoke_get_index(x - output->min[0], output->res[0], y - output->min[1], output->res[1], z - output->min[2]);
1130
1131                                 /* initialize with first input if in range */
1132                                 if (x >= em1.min[0] && x < em1.max[0] &&
1133                                     y >= em1.min[1] && y < em1.max[1] &&
1134                                     z >= em1.min[2] && z < em1.max[2])
1135                                 {
1136                                         int index_in = smoke_get_index(x - em1.min[0], em1.res[0], y - em1.min[1], em1.res[1], z - em1.min[2]);
1137
1138                                         /* values */
1139                                         output->influence[index_out] = em1.influence[index_in];
1140                                         if (output->velocity && em1.velocity) {
1141                                                 copy_v3_v3(&output->velocity[index_out * 3], &em1.velocity[index_in * 3]);
1142                                         }
1143                                 }
1144
1145                                 /* apply second input if in range */
1146                                 if (x >= em2->min[0] && x < em2->max[0] &&
1147                                     y >= em2->min[1] && y < em2->max[1] &&
1148                                     z >= em2->min[2] && z < em2->max[2])
1149                                 {
1150                                         int index_in = smoke_get_index(x - em2->min[0], em2->res[0], y - em2->min[1], em2->res[1], z - em2->min[2]);
1151
1152                                         /* values */
1153                                         if (additive) {
1154                                                 output->influence[index_out] += em2->influence[index_in] * sample_size;
1155                                         }
1156                                         else {
1157                                                 output->influence[index_out] = MAX2(em2->influence[index_in], output->influence[index_out]);
1158                                         }
1159                                         if (output->velocity && em2->velocity) {
1160                                                 /* last sample replaces the velocity */
1161                                                 output->velocity[index_out * 3]         = ADD_IF_LOWER(output->velocity[index_out * 3], em2->velocity[index_in * 3]);
1162                                                 output->velocity[index_out * 3 + 1] = ADD_IF_LOWER(output->velocity[index_out * 3 + 1], em2->velocity[index_in * 3 + 1]);
1163                                                 output->velocity[index_out * 3 + 2] = ADD_IF_LOWER(output->velocity[index_out * 3 + 2], em2->velocity[index_in * 3 + 2]);
1164                                         }
1165                                 }
1166         } // low res loop
1167
1168
1169
1170         /* initialize high resolution input if available */
1171         if (output->influence_high) {
1172                 for (x = output->hmin[0]; x < output->hmax[0]; x++)
1173                         for (y = output->hmin[1]; y < output->hmax[1]; y++)
1174                                 for (z = output->hmin[2]; z < output->hmax[2]; z++) {
1175                                         int index_out = smoke_get_index(x - output->hmin[0], output->hres[0], y - output->hmin[1], output->hres[1], z - output->hmin[2]);
1176
1177                                         /* initialize with first input if in range */
1178                                         if (x >= em1.hmin[0] && x < em1.hmax[0] &&
1179                                             y >= em1.hmin[1] && y < em1.hmax[1] &&
1180                                             z >= em1.hmin[2] && z < em1.hmax[2])
1181                                         {
1182                                                 int index_in = smoke_get_index(x - em1.hmin[0], em1.hres[0], y - em1.hmin[1], em1.hres[1], z - em1.hmin[2]);
1183                                                 /* values */
1184                                                 output->influence_high[index_out] = em1.influence_high[index_in];
1185                                         }
1186
1187                                         /* apply second input if in range */
1188                                         if (x >= em2->hmin[0] && x < em2->hmax[0] &&
1189                                             y >= em2->hmin[1] && y < em2->hmax[1] &&
1190                                             z >= em2->hmin[2] && z < em2->hmax[2])
1191                                         {
1192                                                 int index_in = smoke_get_index(x - em2->hmin[0], em2->hres[0], y - em2->hmin[1], em2->hres[1], z - em2->hmin[2]);
1193
1194                                                 /* values */
1195                                                 if (additive) {
1196                                                         output->influence_high[index_out] += em2->influence_high[index_in] * sample_size;
1197                                                 }
1198                                                 else {
1199                                                         output->influence_high[index_out] = MAX2(em2->influence_high[index_in], output->influence_high[index_out]);
1200                                                 }
1201                                         }
1202                 } // high res loop
1203         }
1204
1205         /* free original data */
1206         em_freeData(&em1);
1207 }
1208
1209 typedef struct EmitFromParticlesData {
1210         SmokeFlowSettings *sfs;
1211         KDTree *tree;
1212         int hires_multiplier;
1213
1214         EmissionMap *em;
1215         float *particle_vel;
1216         float hr;
1217
1218         int *min, *max, *res;
1219
1220         float solid;
1221         float smooth;
1222         float hr_smooth;
1223 } EmitFromParticlesData;
1224
1225 static void emit_from_particles_task_cb(
1226         void *__restrict userdata,
1227         const int z,
1228         const ParallelRangeTLS *__restrict UNUSED(tls))
1229 {
1230         EmitFromParticlesData *data = userdata;
1231         SmokeFlowSettings *sfs = data->sfs;
1232         EmissionMap *em = data->em;
1233         const int hires_multiplier = data->hires_multiplier;
1234
1235         for (int x = data->min[0]; x < data->max[0]; x++) {
1236                 for (int y = data->min[1]; y < data->max[1]; y++) {
1237                         /* take low res samples where possible */
1238                         if (hires_multiplier <= 1 || !(x % hires_multiplier || y % hires_multiplier || z % hires_multiplier)) {
1239                                 /* get low res space coordinates */
1240                                 const int lx = x / hires_multiplier;
1241                                 const int ly = y / hires_multiplier;
1242                                 const int lz = z / hires_multiplier;
1243
1244                                 const int index = smoke_get_index(lx - em->min[0], em->res[0], ly - em->min[1], em->res[1], lz - em->min[2]);
1245                                 const float ray_start[3] = {((float)lx) + 0.5f, ((float)ly) + 0.5f, ((float)lz) + 0.5f};
1246
1247                                 /* find particle distance from the kdtree */
1248                                 KDTreeNearest nearest;
1249                                 const float range = data->solid + data->smooth;
1250                                 BLI_kdtree_find_nearest(data->tree, ray_start, &nearest);
1251
1252                                 if (nearest.dist < range) {
1253                                         em->influence[index] = (nearest.dist < data->solid) ?
1254                                                                1.0f : (1.0f - (nearest.dist - data->solid) / data->smooth);
1255                                         /* Uses particle velocity as initial velocity for smoke */
1256                                         if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY && (sfs->psys->part->phystype != PART_PHYS_NO)) {
1257                                                 VECADDFAC(&em->velocity[index * 3], &em->velocity[index * 3],
1258                                                           &data->particle_vel[nearest.index * 3], sfs->vel_multi);
1259                                         }
1260                                 }
1261                         }
1262
1263                         /* take high res samples if required */
1264                         if (hires_multiplier > 1) {
1265                                 /* get low res space coordinates */
1266                                 const float lx = ((float)x) * data->hr;
1267                                 const float ly = ((float)y) * data->hr;
1268                                 const float lz = ((float)z) * data->hr;
1269
1270                                 const int index = smoke_get_index(
1271                                                       x - data->min[0], data->res[0], y - data->min[1], data->res[1], z - data->min[2]);
1272                                 const float ray_start[3] = {lx + 0.5f * data->hr, ly + 0.5f * data->hr, lz + 0.5f * data->hr};
1273
1274                                 /* find particle distance from the kdtree */
1275                                 KDTreeNearest nearest;
1276                                 const float range = data->solid + data->hr_smooth;
1277                                 BLI_kdtree_find_nearest(data->tree, ray_start, &nearest);
1278
1279                                 if (nearest.dist < range) {
1280                                         em->influence_high[index] = (nearest.dist < data->solid) ?
1281                                                                     1.0f : (1.0f - (nearest.dist - data->solid) / data->smooth);
1282                                 }
1283                         }
1284
1285                 }
1286         }
1287 }
1288
1289 static void emit_from_particles(
1290         Object *flow_ob, SmokeDomainSettings *sds, SmokeFlowSettings *sfs, EmissionMap *em, Depsgraph *depsgraph, Scene *scene, float dt)
1291 {
1292         if (sfs && sfs->psys && sfs->psys->part && ELEM(sfs->psys->part->type, PART_EMITTER, PART_FLUID)) // is particle system selected
1293         {
1294                 ParticleSimulationData sim;
1295                 ParticleSystem *psys = sfs->psys;
1296                 float *particle_pos;
1297                 float *particle_vel;
1298                 int totpart = psys->totpart, totchild;
1299                 int p = 0;
1300                 int valid_particles = 0;
1301                 int bounds_margin = 1;
1302
1303                 /* radius based flow */
1304                 const float solid = sfs->particle_size * 0.5f;
1305                 const float smooth = 0.5f; /* add 0.5 cells of linear falloff to reduce aliasing */
1306                 int hires_multiplier = 1;
1307                 KDTree *tree = NULL;
1308
1309                 sim.depsgraph = depsgraph;
1310                 sim.scene = scene;
1311                 sim.ob = flow_ob;
1312                 sim.psys = psys;
1313                 sim.psys->lattice_deform_data = psys_create_lattice_deform_data(&sim);
1314
1315                 /* prepare curvemapping tables */
1316                 if ((psys->part->child_flag & PART_CHILD_USE_CLUMP_CURVE) && psys->part->clumpcurve)
1317                         curvemapping_changed_all(psys->part->clumpcurve);
1318                 if ((psys->part->child_flag & PART_CHILD_USE_ROUGH_CURVE) && psys->part->roughcurve)
1319                         curvemapping_changed_all(psys->part->roughcurve);
1320                 if ((psys->part->child_flag & PART_CHILD_USE_TWIST_CURVE) && psys->part->twistcurve)
1321                         curvemapping_changed_all(psys->part->twistcurve);
1322
1323                 /* initialize particle cache */
1324                 if (psys->part->type == PART_HAIR) {
1325                         // TODO: PART_HAIR not supported whatsoever
1326                         totchild = 0;
1327                 }
1328                 else {
1329                         totchild = psys->totchild * psys->part->disp / 100;
1330                 }
1331
1332                 particle_pos = MEM_callocN(sizeof(float) * (totpart + totchild) * 3, "smoke_flow_particles");
1333                 particle_vel = MEM_callocN(sizeof(float) * (totpart + totchild) * 3, "smoke_flow_particles");
1334
1335                 /* setup particle radius emission if enabled */
1336                 if (sfs->flags & MOD_SMOKE_FLOW_USE_PART_SIZE) {
1337                         tree = BLI_kdtree_new(psys->totpart + psys->totchild);
1338
1339                         /* check need for high resolution map */
1340                         if ((sds->flags & MOD_SMOKE_HIGHRES) && (sds->highres_sampling == SM_HRES_FULLSAMPLE)) {
1341                                 hires_multiplier = sds->amplify + 1;
1342                         }
1343
1344                         bounds_margin = (int)ceil(solid + smooth);
1345                 }
1346
1347                 /* calculate local position for each particle */
1348                 for (p = 0; p < totpart + totchild; p++)
1349                 {
1350                         ParticleKey state;
1351                         float *pos;
1352                         if (p < totpart) {
1353                                 if (psys->particles[p].flag & (PARS_NO_DISP | PARS_UNEXIST))
1354                                         continue;
1355                         }
1356                         else {
1357                                 /* handle child particle */
1358                                 ChildParticle *cpa = &psys->child[p - totpart];
1359                                 if (psys->particles[cpa->parent].flag & (PARS_NO_DISP | PARS_UNEXIST))
1360                                         continue;
1361                         }
1362
1363                         state.time = DEG_get_ctime(depsgraph); /* use depsgraph time */
1364                         if (psys_get_particle_state(&sim, p, &state, 0) == 0)
1365                                 continue;
1366
1367                         /* location */
1368                         pos = &particle_pos[valid_particles * 3];
1369                         copy_v3_v3(pos, state.co);
1370                         smoke_pos_to_cell(sds, pos);
1371
1372                         /* velocity */
1373                         copy_v3_v3(&particle_vel[valid_particles * 3], state.vel);
1374                         mul_mat3_m4_v3(sds->imat, &particle_vel[valid_particles * 3]);
1375
1376                         if (sfs->flags & MOD_SMOKE_FLOW_USE_PART_SIZE) {
1377                                 BLI_kdtree_insert(tree, valid_particles, pos);
1378                         }
1379
1380                         /* calculate emission map bounds */
1381                         em_boundInsert(em, pos);
1382                         valid_particles++;
1383                 }
1384
1385                 /* set emission map */
1386                 clampBoundsInDomain(sds, em->min, em->max, NULL, NULL, bounds_margin, dt);
1387                 em_allocateData(em, sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY, hires_multiplier);
1388
1389                 if (!(sfs->flags & MOD_SMOKE_FLOW_USE_PART_SIZE)) {
1390                         for (p = 0; p < valid_particles; p++)
1391                         {
1392                                 int cell[3];
1393                                 size_t i = 0;
1394                                 size_t index = 0;
1395                                 int badcell = 0;
1396
1397                                 /* 1. get corresponding cell */
1398                                 cell[0] = floor(particle_pos[p * 3]) - em->min[0];
1399                                 cell[1] = floor(particle_pos[p * 3 + 1]) - em->min[1];
1400                                 cell[2] = floor(particle_pos[p * 3 + 2]) - em->min[2];
1401                                 /* check if cell is valid (in the domain boundary) */
1402                                 for (i = 0; i < 3; i++) {
1403                                         if ((cell[i] > em->res[i] - 1) || (cell[i] < 0)) {
1404                                                 badcell = 1;
1405                                                 break;
1406                                         }
1407                                 }
1408                                 if (badcell)
1409                                         continue;
1410                                 /* get cell index */
1411                                 index = smoke_get_index(cell[0], em->res[0], cell[1], em->res[1], cell[2]);
1412                                 /* Add influence to emission map */
1413                                 em->influence[index] = 1.0f;
1414                                 /* Uses particle velocity as initial velocity for smoke */
1415                                 if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY && (psys->part->phystype != PART_PHYS_NO))
1416                                 {
1417                                         VECADDFAC(&em->velocity[index * 3], &em->velocity[index * 3], &particle_vel[p * 3], sfs->vel_multi);
1418                                 }
1419                         }   // particles loop
1420                 }
1421                 else if (valid_particles > 0) { // MOD_SMOKE_FLOW_USE_PART_SIZE
1422                         int min[3], max[3], res[3];
1423                         const float hr = 1.0f / ((float)hires_multiplier);
1424                         /* slightly adjust high res antialias smoothness based on number of divisions
1425                          * to allow smaller details but yet not differing too much from the low res size */
1426                         const float hr_smooth = smooth * powf(hr, 1.0f / 3.0f);
1427
1428                         /* setup loop bounds */
1429                         for (int i = 0; i < 3; i++) {
1430                                 min[i] = em->min[i] * hires_multiplier;
1431                                 max[i] = em->max[i] * hires_multiplier;
1432                                 res[i] = em->res[i] * hires_multiplier;
1433                         }
1434
1435                         BLI_kdtree_balance(tree);
1436
1437                         EmitFromParticlesData data = {
1438                                 .sfs = sfs, .tree = tree, .hires_multiplier = hires_multiplier, .hr = hr,
1439                             .em = em, .particle_vel = particle_vel, .min = min, .max = max, .res = res,
1440                             .solid = solid, .smooth = smooth, .hr_smooth = hr_smooth,
1441                         };
1442
1443                         ParallelRangeSettings settings;
1444                         BLI_parallel_range_settings_defaults(&settings);
1445                         settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC;
1446                         BLI_task_parallel_range(min[2], max[2],
1447                                                 &data,
1448                                                 emit_from_particles_task_cb,
1449                                                 &settings);
1450                 }
1451
1452                 if (sfs->flags & MOD_SMOKE_FLOW_USE_PART_SIZE) {
1453                         BLI_kdtree_free(tree);
1454                 }
1455
1456                 /* free data */
1457                 if (particle_pos)
1458                         MEM_freeN(particle_pos);
1459                 if (particle_vel)
1460                         MEM_freeN(particle_vel);
1461         }
1462 }
1463
1464 static void sample_mesh(
1465         SmokeFlowSettings *sfs,
1466         const MVert *mvert, const MLoop *mloop, const MLoopTri *mlooptri, const MLoopUV *mloopuv,
1467         float *influence_map, float *velocity_map, int index, const int base_res[3], float flow_center[3],
1468         BVHTreeFromMesh *treeData, const float ray_start[3], const float *vert_vel,
1469         bool has_velocity, int defgrp_index, MDeformVert *dvert,
1470         float x, float y, float z)
1471 {
1472         float ray_dir[3] = {1.0f, 0.0f, 0.0f};
1473         BVHTreeRayHit hit = {0};
1474         BVHTreeNearest nearest = {0};
1475
1476         float volume_factor = 0.0f;
1477         float sample_str = 0.0f;
1478
1479         hit.index = -1;
1480         hit.dist = 9999;
1481         nearest.index = -1;
1482         nearest.dist_sq = sfs->surface_distance * sfs->surface_distance; /* find_nearest uses squared distance */
1483
1484         /* Check volume collision */
1485         if (sfs->volume_density) {
1486                 if (BLI_bvhtree_ray_cast(treeData->tree, ray_start, ray_dir, 0.0f, &hit, treeData->raycast_callback, treeData) != -1) {
1487                         float dot = ray_dir[0] * hit.no[0] + ray_dir[1] * hit.no[1] + ray_dir[2] * hit.no[2];
1488                         /* If ray and hit face normal are facing same direction
1489                          * hit point is inside a closed mesh. */
1490                         if (dot >= 0) {
1491                                 /* Also cast a ray in opposite direction to make sure
1492                                  * point is at least surrounded by two faces */
1493                                 negate_v3(ray_dir);
1494                                 hit.index = -1;
1495                                 hit.dist = 9999;
1496
1497                                 BLI_bvhtree_ray_cast(treeData->tree, ray_start, ray_dir, 0.0f, &hit, treeData->raycast_callback, treeData);
1498                                 if (hit.index != -1) {
1499                                         volume_factor = sfs->volume_density;
1500                                 }
1501                         }
1502                 }
1503         }
1504
1505         /* find the nearest point on the mesh */
1506         if (BLI_bvhtree_find_nearest(treeData->tree, ray_start, &nearest, treeData->nearest_callback, treeData) != -1) {
1507                 float weights[3];
1508                 int v1, v2, v3, f_index = nearest.index;
1509                 float n1[3], n2[3], n3[3], hit_normal[3];
1510
1511                 /* emit from surface based on distance */
1512                 if (sfs->surface_distance) {
1513                         sample_str = sqrtf(nearest.dist_sq) / sfs->surface_distance;
1514                         CLAMP(sample_str, 0.0f, 1.0f);
1515                         sample_str = pow(1.0f - sample_str, 0.5f);
1516                 }
1517                 else
1518                         sample_str = 0.0f;
1519
1520                 /* calculate barycentric weights for nearest point */
1521                 v1 = mloop[mlooptri[f_index].tri[0]].v;
1522                 v2 = mloop[mlooptri[f_index].tri[1]].v;
1523                 v3 = mloop[mlooptri[f_index].tri[2]].v;
1524                 interp_weights_tri_v3(weights, mvert[v1].co, mvert[v2].co, mvert[v3].co, nearest.co);
1525
1526                 if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY && velocity_map) {
1527                         /* apply normal directional velocity */
1528                         if (sfs->vel_normal) {
1529                                 /* interpolate vertex normal vectors to get nearest point normal */
1530                                 normal_short_to_float_v3(n1, mvert[v1].no);
1531                                 normal_short_to_float_v3(n2, mvert[v2].no);
1532                                 normal_short_to_float_v3(n3, mvert[v3].no);
1533                                 interp_v3_v3v3v3(hit_normal, n1, n2, n3, weights);
1534                                 normalize_v3(hit_normal);
1535                                 /* apply normal directional and random velocity
1536                                  * - TODO: random disabled for now since it doesn't really work well as pressure calc smoothens it out... */
1537                                 velocity_map[index * 3]   += hit_normal[0] * sfs->vel_normal * 0.25f;
1538                                 velocity_map[index * 3 + 1] += hit_normal[1] * sfs->vel_normal * 0.25f;
1539                                 velocity_map[index * 3 + 2] += hit_normal[2] * sfs->vel_normal * 0.25f;
1540                                 /* TODO: for fire emitted from mesh surface we can use
1541                                  * Vf = Vs + (Ps/Pf - 1)*S to model gaseous expansion from solid to fuel */
1542                         }
1543                         /* apply object velocity */
1544                         if (has_velocity && sfs->vel_multi) {
1545                                 float hit_vel[3];
1546                                 interp_v3_v3v3v3(hit_vel, &vert_vel[v1 * 3], &vert_vel[v2 * 3], &vert_vel[v3 * 3], weights);
1547                                 velocity_map[index * 3]   += hit_vel[0] * sfs->vel_multi;
1548                                 velocity_map[index * 3 + 1] += hit_vel[1] * sfs->vel_multi;
1549                                 velocity_map[index * 3 + 2] += hit_vel[2] * sfs->vel_multi;
1550                         }
1551                 }
1552
1553                 /* apply vertex group influence if used */
1554                 if (defgrp_index != -1 && dvert) {
1555                         float weight_mask = defvert_find_weight(&dvert[v1], defgrp_index) * weights[0] +
1556                                             defvert_find_weight(&dvert[v2], defgrp_index) * weights[1] +
1557                                             defvert_find_weight(&dvert[v3], defgrp_index) * weights[2];
1558                         sample_str *= weight_mask;
1559                 }
1560
1561                 /* apply emission texture */
1562                 if ((sfs->flags & MOD_SMOKE_FLOW_TEXTUREEMIT) && sfs->noise_texture) {
1563                         float tex_co[3] = {0};
1564                         TexResult texres;
1565
1566                         if (sfs->texture_type == MOD_SMOKE_FLOW_TEXTURE_MAP_AUTO) {
1567                                 tex_co[0] = ((x - flow_center[0]) / base_res[0]) / sfs->texture_size;
1568                                 tex_co[1] = ((y - flow_center[1]) / base_res[1]) / sfs->texture_size;
1569                                 tex_co[2] = ((z - flow_center[2]) / base_res[2] - sfs->texture_offset) / sfs->texture_size;
1570                         }
1571                         else if (mloopuv) {
1572                                 const float *uv[3];
1573                                 uv[0] = mloopuv[mlooptri[f_index].tri[0]].uv;
1574                                 uv[1] = mloopuv[mlooptri[f_index].tri[1]].uv;
1575                                 uv[2] = mloopuv[mlooptri[f_index].tri[2]].uv;
1576
1577                                 interp_v2_v2v2v2(tex_co, UNPACK3(uv), weights);
1578
1579                                 /* map between -1.0f and 1.0f */
1580                                 tex_co[0] = tex_co[0] * 2.0f - 1.0f;
1581                                 tex_co[1] = tex_co[1] * 2.0f - 1.0f;
1582                                 tex_co[2] = sfs->texture_offset;
1583                         }
1584                         texres.nor = NULL;
1585                         BKE_texture_get_value(NULL, sfs->noise_texture, tex_co, &texres, false);
1586                         sample_str *= texres.tin;
1587                 }
1588         }
1589
1590         /* multiply initial velocity by emitter influence */
1591         if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY && velocity_map) {
1592                 mul_v3_fl(&velocity_map[index * 3], sample_str);
1593         }
1594
1595         /* apply final influence based on volume factor */
1596         influence_map[index] = MAX2(volume_factor, sample_str);
1597 }
1598
1599 typedef struct EmitFromDMData {
1600         SmokeDomainSettings *sds;
1601         SmokeFlowSettings *sfs;
1602         const MVert *mvert;
1603         const MLoop *mloop;
1604         const MLoopTri *mlooptri;
1605         const MLoopUV *mloopuv;
1606         MDeformVert *dvert;
1607         int defgrp_index;
1608
1609         BVHTreeFromMesh *tree;
1610         int hires_multiplier;
1611         float hr;
1612
1613         EmissionMap *em;
1614         bool has_velocity;
1615         float *vert_vel;
1616
1617         float *flow_center;
1618         int *min, *max, *res;
1619 } EmitFromDMData;
1620
1621 static void emit_from_mesh_task_cb(
1622         void *__restrict userdata,
1623         const int z,
1624         const ParallelRangeTLS *__restrict UNUSED(tls))
1625 {
1626         EmitFromDMData *data = userdata;
1627         EmissionMap *em = data->em;
1628         const int hires_multiplier = data->hires_multiplier;
1629
1630         for (int x = data->min[0]; x < data->max[0]; x++) {
1631                 for (int y = data->min[1]; y < data->max[1]; y++) {
1632                         /* take low res samples where possible */
1633                         if (hires_multiplier <= 1 || !(x % hires_multiplier || y % hires_multiplier || z % hires_multiplier)) {
1634                                 /* get low res space coordinates */
1635                                 const int lx = x / hires_multiplier;
1636                                 const int ly = y / hires_multiplier;
1637                                 const int lz = z / hires_multiplier;
1638
1639                                 const int index = smoke_get_index(
1640                                                       lx - em->min[0], em->res[0], ly - em->min[1], em->res[1], lz - em->min[2]);
1641                                 const float ray_start[3] = {((float)lx) + 0.5f, ((float)ly) + 0.5f, ((float)lz) + 0.5f};
1642
1643                                 sample_mesh(
1644                                         data->sfs, data->mvert, data->mloop, data->mlooptri, data->mloopuv,
1645                                         em->influence, em->velocity, index, data->sds->base_res, data->flow_center,
1646                                         data->tree, ray_start, data->vert_vel, data->has_velocity, data->defgrp_index, data->dvert,
1647                                         (float)lx, (float)ly, (float)lz);
1648                         }
1649
1650                         /* take high res samples if required */
1651                         if (hires_multiplier > 1) {
1652                                 /* get low res space coordinates */
1653                                 const float lx = ((float)x) * data->hr;
1654                                 const float ly = ((float)y) * data->hr;
1655                                 const float lz = ((float)z) * data->hr;
1656
1657                                 const int index = smoke_get_index(
1658                                                       x - data->min[0], data->res[0], y - data->min[1], data->res[1], z - data->min[2]);
1659                                 const float ray_start[3] = {lx + 0.5f * data->hr, ly + 0.5f * data->hr, lz + 0.5f * data->hr};
1660
1661                                 sample_mesh(
1662                                         data->sfs, data->mvert, data->mloop, data->mlooptri, data->mloopuv,
1663                                         em->influence_high, NULL, index, data->sds->base_res, data->flow_center,
1664                                         data->tree, ray_start, data->vert_vel, data->has_velocity, data->defgrp_index, data->dvert,
1665                                         /* x,y,z needs to be always lowres */
1666                                         lx, ly, lz);
1667                         }
1668                 }
1669         }
1670 }
1671
1672 static void emit_from_mesh(Object *flow_ob, SmokeDomainSettings *sds, SmokeFlowSettings *sfs, EmissionMap *em, float dt)
1673 {
1674         if (sfs->mesh) {
1675                 Mesh *me;
1676                 int defgrp_index = sfs->vgroup_density - 1;
1677                 MDeformVert *dvert = NULL;
1678                 MVert *mvert = NULL;
1679                 const MLoopTri *mlooptri = NULL;
1680                 const MLoopUV *mloopuv = NULL;
1681                 const MLoop *mloop = NULL;
1682                 BVHTreeFromMesh treeData = {NULL};
1683                 int numOfVerts, i;
1684                 float flow_center[3] = {0};
1685
1686                 float *vert_vel = NULL;
1687                 int has_velocity = 0;
1688                 int min[3], max[3], res[3];
1689                 int hires_multiplier = 1;
1690
1691                 /* copy mesh for thread safety because we modify it,
1692                  * main issue is its VertArray being modified, then replaced and freed
1693                  */
1694                 me = BKE_mesh_copy_for_eval(sfs->mesh, true);
1695
1696                 /* Duplicate vertices to modify. */
1697                 if (me->mvert) {
1698                         me->mvert = MEM_dupallocN(me->mvert);
1699                         CustomData_set_layer(&me->vdata, CD_MVERT, me->mvert);
1700                 }
1701
1702                 BKE_mesh_ensure_normals(me);
1703                 mvert = me->mvert;
1704                 numOfVerts = me->totvert;
1705                 dvert = CustomData_get_layer(&me->vdata, CD_MDEFORMVERT);
1706                 mloopuv = CustomData_get_layer_named(&me->ldata, CD_MLOOPUV, sfs->uvlayer_name);
1707                 mloop = me->mloop;
1708                 mlooptri = BKE_mesh_runtime_looptri_ensure(me);
1709
1710                 if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY) {
1711                         vert_vel = MEM_callocN(sizeof(float) * numOfVerts * 3, "smoke_flow_velocity");
1712
1713                         if (sfs->numverts != numOfVerts || !sfs->verts_old) {
1714                                 if (sfs->verts_old) MEM_freeN(sfs->verts_old);
1715                                 sfs->verts_old = MEM_callocN(sizeof(float) * numOfVerts * 3, "smoke_flow_verts_old");
1716                                 sfs->numverts = numOfVerts;
1717                         }
1718                         else {
1719                                 has_velocity = 1;
1720                         }
1721                 }
1722
1723                 /*      Transform mesh vertices to
1724                  *   domain grid space for fast lookups */
1725                 for (i = 0; i < numOfVerts; i++) {
1726                         float n[3];
1727                         /* vert pos */
1728                         mul_m4_v3(flow_ob->obmat, mvert[i].co);
1729                         smoke_pos_to_cell(sds, mvert[i].co);
1730                         /* vert normal */
1731                         normal_short_to_float_v3(n, mvert[i].no);
1732                         mul_mat3_m4_v3(flow_ob->obmat, n);
1733                         mul_mat3_m4_v3(sds->imat, n);
1734                         normalize_v3(n);
1735                         normal_float_to_short_v3(mvert[i].no, n);
1736                         /* vert velocity */
1737                         if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY) {
1738                                 float co[3];
1739                                 VECADD(co, mvert[i].co, sds->shift);
1740                                 if (has_velocity) {
1741                                         sub_v3_v3v3(&vert_vel[i * 3], co, &sfs->verts_old[i * 3]);
1742                                         mul_v3_fl(&vert_vel[i * 3], sds->dx / dt);
1743                                 }
1744                                 copy_v3_v3(&sfs->verts_old[i * 3], co);
1745                         }
1746
1747                         /* calculate emission map bounds */
1748                         em_boundInsert(em, mvert[i].co);
1749                 }
1750                 mul_m4_v3(flow_ob->obmat, flow_center);
1751                 smoke_pos_to_cell(sds, flow_center);
1752
1753                 /* check need for high resolution map */
1754                 if ((sds->flags & MOD_SMOKE_HIGHRES) && (sds->highres_sampling == SM_HRES_FULLSAMPLE)) {
1755                         hires_multiplier = sds->amplify + 1;
1756                 }
1757
1758                 /* set emission map */
1759                 clampBoundsInDomain(sds, em->min, em->max, NULL, NULL, (int)ceil(sfs->surface_distance), dt);
1760                 em_allocateData(em, sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY, hires_multiplier);
1761
1762                 /* setup loop bounds */
1763                 for (i = 0; i < 3; i++) {
1764                         min[i] = em->min[i] * hires_multiplier;
1765                         max[i] = em->max[i] * hires_multiplier;
1766                         res[i] = em->res[i] * hires_multiplier;
1767                 }
1768
1769                 if (BKE_bvhtree_from_mesh_get(&treeData, me, BVHTREE_FROM_LOOPTRI, 4)) {
1770                         const float hr = 1.0f / ((float)hires_multiplier);
1771
1772                         EmitFromDMData data = {
1773                                 .sds = sds, .sfs = sfs,
1774                             .mvert = mvert, .mloop = mloop, .mlooptri = mlooptri, .mloopuv = mloopuv,
1775                             .dvert = dvert, .defgrp_index = defgrp_index,
1776                             .tree = &treeData, .hires_multiplier = hires_multiplier, .hr = hr,
1777                             .em = em, .has_velocity = has_velocity, .vert_vel = vert_vel,
1778                             .flow_center = flow_center, .min = min, .max = max, .res = res,
1779                         };
1780
1781                         ParallelRangeSettings settings;
1782                         BLI_parallel_range_settings_defaults(&settings);
1783                         settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC;
1784                         BLI_task_parallel_range(min[2], max[2],
1785                                                 &data,
1786                                                 emit_from_mesh_task_cb,
1787                                                 &settings);
1788                 }
1789                 /* free bvh tree */
1790                 free_bvhtree_from_mesh(&treeData);
1791
1792                 if (vert_vel) {
1793                         MEM_freeN(vert_vel);
1794                 }
1795
1796                 if (me->mvert) {
1797                         MEM_freeN(me->mvert);
1798                 }
1799                 BKE_id_free(NULL, me);
1800         }
1801 }
1802
1803 /**********************************************************
1804  *  Smoke step
1805  **********************************************************/
1806
1807 static void adjustDomainResolution(SmokeDomainSettings *sds, int new_shift[3], EmissionMap *emaps, unsigned int numflowobj, float dt)
1808 {
1809         const int block_size = sds->amplify + 1;
1810         int min[3] = {32767, 32767, 32767}, max[3] = {-32767, -32767, -32767}, res[3];
1811         int total_cells = 1, res_changed = 0, shift_changed = 0;
1812         float min_vel[3], max_vel[3];
1813         int x, y, z;
1814         float *density = smoke_get_density(sds->fluid);
1815         float *fuel = smoke_get_fuel(sds->fluid);
1816         float *bigdensity = smoke_turbulence_get_density(sds->wt);
1817         float *bigfuel = smoke_turbulence_get_fuel(sds->wt);
1818         float *vx = smoke_get_velocity_x(sds->fluid);
1819         float *vy = smoke_get_velocity_y(sds->fluid);
1820         float *vz = smoke_get_velocity_z(sds->fluid);
1821         int wt_res[3];
1822
1823         if (sds->flags & MOD_SMOKE_HIGHRES && sds->wt) {
1824                 smoke_turbulence_get_res(sds->wt, wt_res);
1825         }
1826
1827         INIT_MINMAX(min_vel, max_vel);
1828
1829         /* Calculate bounds for current domain content */
1830         for (x = sds->res_min[0]; x <  sds->res_max[0]; x++)
1831                 for (y =  sds->res_min[1]; y <  sds->res_max[1]; y++)
1832                         for (z =  sds->res_min[2]; z <  sds->res_max[2]; z++)
1833                         {
1834                                 int xn = x - new_shift[0];
1835                                 int yn = y - new_shift[1];
1836                                 int zn = z - new_shift[2];
1837                                 int index;
1838                                 float max_den;
1839
1840                                 /* skip if cell already belongs to new area */
1841                                 if (xn >= min[0] && xn <= max[0] && yn >= min[1] && yn <= max[1] && zn >= min[2] && zn <= max[2])
1842                                         continue;
1843
1844                                 index = smoke_get_index(x - sds->res_min[0], sds->res[0], y - sds->res_min[1], sds->res[1], z - sds->res_min[2]);
1845                                 max_den = (fuel) ? MAX2(density[index], fuel[index]) : density[index];
1846
1847                                 /* check high resolution bounds if max density isnt already high enough */
1848                                 if (max_den < sds->adapt_threshold && sds->flags & MOD_SMOKE_HIGHRES && sds->wt) {
1849                                         int i, j, k;
1850                                         /* high res grid index */
1851                                         int xx = (x - sds->res_min[0]) * block_size;
1852                                         int yy = (y - sds->res_min[1]) * block_size;
1853                                         int zz = (z - sds->res_min[2]) * block_size;
1854
1855                                         for (i = 0; i < block_size; i++)
1856                                                 for (j = 0; j < block_size; j++)
1857                                                         for (k = 0; k < block_size; k++)
1858                                                         {
1859                                                                 int big_index = smoke_get_index(xx + i, wt_res[0], yy + j, wt_res[1], zz + k);
1860                                                                 float den = (bigfuel) ? MAX2(bigdensity[big_index], bigfuel[big_index]) : bigdensity[big_index];
1861                                                                 if (den > max_den) {
1862                                                                         max_den = den;
1863                                                                 }
1864                                                         }
1865                                 }
1866
1867                                 /* content bounds (use shifted coordinates) */
1868                                 if (max_den >= sds->adapt_threshold) {
1869                                         if (min[0] > xn) min[0] = xn;
1870                                         if (min[1] > yn) min[1] = yn;
1871                                         if (min[2] > zn) min[2] = zn;
1872                                         if (max[0] < xn) max[0] = xn;
1873                                         if (max[1] < yn) max[1] = yn;
1874                                         if (max[2] < zn) max[2] = zn;
1875                                 }
1876
1877                                 /* velocity bounds */
1878                                 if (min_vel[0] > vx[index]) min_vel[0] = vx[index];
1879                                 if (min_vel[1] > vy[index]) min_vel[1] = vy[index];
1880                                 if (min_vel[2] > vz[index]) min_vel[2] = vz[index];
1881                                 if (max_vel[0] < vx[index]) max_vel[0] = vx[index];
1882                                 if (max_vel[1] < vy[index]) max_vel[1] = vy[index];
1883                                 if (max_vel[2] < vz[index]) max_vel[2] = vz[index];
1884                         }
1885
1886         /* also apply emission maps */
1887         for (int i = 0; i < numflowobj; i++) {
1888                 EmissionMap *em = &emaps[i];
1889
1890                 for (x = em->min[0]; x < em->max[0]; x++)
1891                         for (y = em->min[1]; y < em->max[1]; y++)
1892                                 for (z = em->min[2]; z < em->max[2]; z++)
1893                                 {
1894                                         int index = smoke_get_index(x - em->min[0], em->res[0], y - em->min[1], em->res[1], z - em->min[2]);
1895                                         float max_den = em->influence[index];
1896
1897                                         /* density bounds */
1898                                         if (max_den >= sds->adapt_threshold) {
1899                                                 if (min[0] > x) min[0] = x;
1900                                                 if (min[1] > y) min[1] = y;
1901                                                 if (min[2] > z) min[2] = z;
1902                                                 if (max[0] < x) max[0] = x;
1903                                                 if (max[1] < y) max[1] = y;
1904                                                 if (max[2] < z) max[2] = z;
1905                                         }
1906                                 }
1907         }
1908
1909         /* calculate new bounds based on these values */
1910         mul_v3_fl(min_vel, 1.0f / sds->dx);
1911         mul_v3_fl(max_vel, 1.0f / sds->dx);
1912         clampBoundsInDomain(sds, min, max, min_vel, max_vel, sds->adapt_margin + 1, dt);
1913
1914         for (int i = 0; i < 3; i++) {
1915                 /* calculate new resolution */
1916                 res[i] = max[i] - min[i];
1917                 total_cells *= res[i];
1918
1919                 if (new_shift[i])
1920                         shift_changed = 1;
1921
1922                 /* if no content set minimum dimensions */
1923                 if (res[i] <= 0) {
1924                         int j;
1925                         for (j = 0; j < 3; j++) {
1926                                 min[j] = 0;
1927                                 max[j] = 1;
1928                                 res[j] = 1;
1929                         }
1930                         res_changed = 1;
1931                         total_cells = 1;
1932                         break;
1933                 }
1934                 if (min[i] != sds->res_min[i] || max[i] != sds->res_max[i])
1935                         res_changed = 1;
1936         }
1937
1938         if (res_changed || shift_changed) {
1939                 struct FLUID_3D *fluid_old = sds->fluid;
1940                 struct WTURBULENCE *turb_old = sds->wt;
1941                 /* allocate new fluid data */
1942                 smoke_reallocate_fluid(sds, sds->dx, res, 0);
1943                 if (sds->flags & MOD_SMOKE_HIGHRES) {
1944                         smoke_reallocate_highres_fluid(sds, sds->dx, res, 0);
1945                 }
1946
1947                 /* copy values from old fluid to new */
1948                 if (sds->total_cells > 1 && total_cells > 1) {
1949                         /* low res smoke */
1950                         float *o_dens, *o_react, *o_flame, *o_fuel, *o_heat, *o_heatold, *o_vx, *o_vy, *o_vz, *o_r, *o_g, *o_b;
1951                         float *n_dens, *n_react, *n_flame, *n_fuel, *n_heat, *n_heatold, *n_vx, *n_vy, *n_vz, *n_r, *n_g, *n_b;
1952                         float dummy;
1953                         unsigned char *dummy_p;
1954                         /* high res smoke */
1955                         int wt_res_old[3];
1956                         float *o_wt_dens, *o_wt_react, *o_wt_flame, *o_wt_fuel, *o_wt_tcu, *o_wt_tcv, *o_wt_tcw, *o_wt_r, *o_wt_g, *o_wt_b;
1957                         float *n_wt_dens, *n_wt_react, *n_wt_flame, *n_wt_fuel, *n_wt_tcu, *n_wt_tcv, *n_wt_tcw, *n_wt_r, *n_wt_g, *n_wt_b;
1958
1959                         smoke_export(fluid_old, &dummy, &dummy, &o_dens, &o_react, &o_flame, &o_fuel, &o_heat, &o_heatold, &o_vx, &o_vy, &o_vz, &o_r, &o_g, &o_b, &dummy_p);
1960                         smoke_export(sds->fluid, &dummy, &dummy, &n_dens, &n_react, &n_flame, &n_fuel, &n_heat, &n_heatold, &n_vx, &n_vy, &n_vz, &n_r, &n_g, &n_b, &dummy_p);
1961
1962                         if (sds->flags & MOD_SMOKE_HIGHRES) {
1963                                 smoke_turbulence_export(turb_old, &o_wt_dens, &o_wt_react, &o_wt_flame, &o_wt_fuel, &o_wt_r, &o_wt_g, &o_wt_b, &o_wt_tcu, &o_wt_tcv, &o_wt_tcw);
1964                                 smoke_turbulence_get_res(turb_old, wt_res_old);
1965                                 smoke_turbulence_export(sds->wt, &n_wt_dens, &n_wt_react, &n_wt_flame, &n_wt_fuel, &n_wt_r, &n_wt_g, &n_wt_b, &n_wt_tcu, &n_wt_tcv, &n_wt_tcw);
1966                         }
1967
1968
1969                         for (x = sds->res_min[0]; x < sds->res_max[0]; x++)
1970                                 for (y = sds->res_min[1]; y < sds->res_max[1]; y++)
1971                                         for (z = sds->res_min[2]; z < sds->res_max[2]; z++)
1972                                         {
1973                                                 /* old grid index */
1974                                                 int xo = x - sds->res_min[0];
1975                                                 int yo = y - sds->res_min[1];
1976                                                 int zo = z - sds->res_min[2];
1977                                                 int index_old = smoke_get_index(xo, sds->res[0], yo, sds->res[1], zo);
1978                                                 /* new grid index */
1979                                                 int xn = x - min[0] - new_shift[0];
1980                                                 int yn = y - min[1] - new_shift[1];
1981                                                 int zn = z - min[2] - new_shift[2];
1982                                                 int index_new = smoke_get_index(xn, res[0], yn, res[1], zn);
1983
1984                                                 /* skip if outside new domain */
1985                                                 if (xn < 0 || xn >= res[0] ||
1986                                                     yn < 0 || yn >= res[1] ||
1987                                                     zn < 0 || zn >= res[2])
1988                                                         continue;
1989
1990                                                 /* copy data */
1991                                                 n_dens[index_new] = o_dens[index_old];
1992                                                 /* heat */
1993                                                 if (n_heat && o_heat) {
1994                                                         n_heat[index_new] = o_heat[index_old];
1995                                                         n_heatold[index_new] = o_heatold[index_old];
1996                                                 }
1997                                                 /* fuel */
1998                                                 if (n_fuel && o_fuel) {
1999                                                         n_flame[index_new] = o_flame[index_old];
2000                                                         n_fuel[index_new] = o_fuel[index_old];
2001                                                         n_react[index_new] = o_react[index_old];
2002                                                 }
2003                                                 /* color */
2004                                                 if (o_r && n_r) {
2005                                                         n_r[index_new] = o_r[index_old];
2006                                                         n_g[index_new] = o_g[index_old];
2007                                                         n_b[index_new] = o_b[index_old];
2008                                                 }
2009                                                 n_vx[index_new] = o_vx[index_old];
2010                                                 n_vy[index_new] = o_vy[index_old];
2011                                                 n_vz[index_new] = o_vz[index_old];
2012
2013                                                 if (sds->flags & MOD_SMOKE_HIGHRES && turb_old) {
2014                                                         int i, j, k;
2015                                                         /* old grid index */
2016                                                         int xx_o = xo * block_size;
2017                                                         int yy_o = yo * block_size;
2018                                                         int zz_o = zo * block_size;
2019                                                         /* new grid index */
2020                                                         int xx_n = xn * block_size;
2021                                                         int yy_n = yn * block_size;
2022                                                         int zz_n = zn * block_size;
2023
2024                                                         n_wt_tcu[index_new] = o_wt_tcu[index_old];
2025                                                         n_wt_tcv[index_new] = o_wt_tcv[index_old];
2026                                                         n_wt_tcw[index_new] = o_wt_tcw[index_old];
2027
2028                                                         for (i = 0; i < block_size; i++)
2029                                                                 for (j = 0; j < block_size; j++)
2030                                                                         for (k = 0; k < block_size; k++)
2031                                                                         {
2032                                                                                 int big_index_old = smoke_get_index(xx_o + i, wt_res_old[0], yy_o + j, wt_res_old[1], zz_o + k);
2033                                                                                 int big_index_new = smoke_get_index(xx_n + i, sds->res_wt[0], yy_n + j, sds->res_wt[1], zz_n + k);
2034                                                                                 /* copy data */
2035                                                                                 n_wt_dens[big_index_new] = o_wt_dens[big_index_old];
2036                                                                                 if (n_wt_flame && o_wt_flame) {
2037                                                                                         n_wt_flame[big_index_new] = o_wt_flame[big_index_old];
2038                                                                                         n_wt_fuel[big_index_new] = o_wt_fuel[big_index_old];
2039                                                                                         n_wt_react[big_index_new] = o_wt_react[big_index_old];
2040                                                                                 }
2041                                                                                 if (n_wt_r && o_wt_r) {
2042                                                                                         n_wt_r[big_index_new] = o_wt_r[big_index_old];
2043                                                                                         n_wt_g[big_index_new] = o_wt_g[big_index_old];
2044                                                                                         n_wt_b[big_index_new] = o_wt_b[big_index_old];
2045                                                                                 }
2046                                                                         }
2047                                                 }
2048                                         }
2049                 }
2050                 smoke_free(fluid_old);
2051                 if (turb_old)
2052                         smoke_turbulence_free(turb_old);
2053
2054                 /* set new domain dimensions */
2055                 VECCOPY(sds->res_min, min);
2056                 VECCOPY(sds->res_max, max);
2057                 VECCOPY(sds->res, res);
2058                 sds->total_cells = total_cells;
2059         }
2060 }
2061
2062 BLI_INLINE void apply_outflow_fields(int index, float *density, float *heat, float *fuel, float *react, float *color_r, float *color_g, float *color_b)
2063 {
2064         density[index] = 0.f;
2065         if (heat) {
2066                 heat[index] = 0.f;
2067         }
2068         if (fuel) {
2069                 fuel[index] = 0.f;
2070                 react[index] = 0.f;
2071         }
2072         if (color_r) {
2073                 color_r[index] = 0.f;
2074                 color_g[index] = 0.f;
2075                 color_b[index] = 0.f;
2076         }
2077 }
2078
2079 BLI_INLINE void apply_inflow_fields(SmokeFlowSettings *sfs, float emission_value, int index, float *density, float *heat, float *fuel, float *react, float *color_r, float *color_g, float *color_b)
2080 {
2081         int absolute_flow = (sfs->flags & MOD_SMOKE_FLOW_ABSOLUTE);
2082         float dens_old = density[index];
2083         // float fuel_old = (fuel) ? fuel[index] : 0.0f;  /* UNUSED */
2084         float dens_flow = (sfs->type == MOD_SMOKE_FLOW_TYPE_FIRE) ? 0.0f : emission_value * sfs->density;
2085         float fuel_flow = emission_value * sfs->fuel_amount;
2086         /* add heat */
2087         if (heat && emission_value > 0.0f) {
2088                 heat[index] = ADD_IF_LOWER(heat[index], sfs->temp);
2089         }
2090         /* absolute */
2091         if (absolute_flow) {
2092                 if (sfs->type != MOD_SMOKE_FLOW_TYPE_FIRE) {
2093                         if (dens_flow > density[index])
2094                                 density[index] = dens_flow;
2095                 }
2096                 if (sfs->type != MOD_SMOKE_FLOW_TYPE_SMOKE && fuel && fuel_flow) {
2097                         if (fuel_flow > fuel[index])
2098                                 fuel[index] = fuel_flow;
2099                 }
2100         }
2101         /* additive */
2102         else {
2103                 if (sfs->type != MOD_SMOKE_FLOW_TYPE_FIRE) {
2104                         density[index] += dens_flow;
2105                         CLAMP(density[index], 0.0f, 1.0f);
2106                 }
2107                 if (sfs->type != MOD_SMOKE_FLOW_TYPE_SMOKE && fuel && sfs->fuel_amount) {
2108                         fuel[index] += fuel_flow;
2109                         CLAMP(fuel[index], 0.0f, 10.0f);
2110                 }
2111         }
2112
2113         /* set color */
2114         if (color_r && dens_flow) {
2115                 float total_dens = density[index] / (dens_old + dens_flow);
2116                 color_r[index] = (color_r[index] + sfs->color[0] * dens_flow) * total_dens;
2117                 color_g[index] = (color_g[index] + sfs->color[1] * dens_flow) * total_dens;
2118                 color_b[index] = (color_b[index] + sfs->color[2] * dens_flow) * total_dens;
2119         }
2120
2121         /* set fire reaction coordinate */
2122         if (fuel && fuel[index] > FLT_EPSILON) {
2123                 /* instead of using 1.0 for all new fuel add slight falloff
2124                  * to reduce flow blockiness */
2125                 float value = 1.0f - pow2f(1.0f - emission_value);
2126
2127                 if (value > react[index]) {
2128                         float f = fuel_flow / fuel[index];
2129                         react[index] = value * f + (1.0f - f) * react[index];
2130                         CLAMP(react[index], 0.0f, value);
2131                 }
2132         }
2133 }
2134
2135 static void update_flowsfluids(
2136         Depsgraph *depsgraph, Scene *scene, Object *ob, SmokeDomainSettings *sds, float dt)
2137 {
2138         Object **flowobjs = NULL;
2139         EmissionMap *emaps = NULL;
2140         unsigned int numflowobj = 0;
2141         unsigned int flowIndex;
2142         int new_shift[3] = {0};
2143         int active_fields = sds->active_fields;
2144
2145         /* calculate domain shift for current frame if using adaptive domain */
2146         if (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) {
2147                 int total_shift[3];
2148                 float frame_shift_f[3];
2149                 float ob_loc[3] = {0};
2150
2151                 mul_m4_v3(ob->obmat, ob_loc);
2152
2153                 VECSUB(frame_shift_f, ob_loc, sds->prev_loc);
2154                 copy_v3_v3(sds->prev_loc, ob_loc);
2155                 /* convert global space shift to local "cell" space */
2156                 mul_mat3_m4_v3(sds->imat, frame_shift_f);
2157                 frame_shift_f[0] = frame_shift_f[0] / sds->cell_size[0];
2158                 frame_shift_f[1] = frame_shift_f[1] / sds->cell_size[1];
2159                 frame_shift_f[2] = frame_shift_f[2] / sds->cell_size[2];
2160                 /* add to total shift */
2161                 VECADD(sds->shift_f, sds->shift_f, frame_shift_f);
2162                 /* convert to integer */
2163                 total_shift[0] = floor(sds->shift_f[0]);
2164                 total_shift[1] = floor(sds->shift_f[1]);
2165                 total_shift[2] = floor(sds->shift_f[2]);
2166                 VECSUB(new_shift, total_shift, sds->shift);
2167                 copy_v3_v3_int(sds->shift, total_shift);
2168
2169                 /* calculate new domain boundary points so that smoke doesn't slide on sub-cell movement */
2170                 sds->p0[0] = sds->dp0[0] - sds->cell_size[0] * (sds->shift_f[0] - total_shift[0] - 0.5f);
2171                 sds->p0[1] = sds->dp0[1] - sds->cell_size[1] * (sds->shift_f[1] - total_shift[1] - 0.5f);
2172                 sds->p0[2] = sds->dp0[2] - sds->cell_size[2] * (sds->shift_f[2] - total_shift[2] - 0.5f);
2173                 sds->p1[0] = sds->p0[0] + sds->cell_size[0] * sds->base_res[0];
2174                 sds->p1[1] = sds->p0[1] + sds->cell_size[1] * sds->base_res[1];
2175                 sds->p1[2] = sds->p0[2] + sds->cell_size[2] * sds->base_res[2];
2176         }
2177
2178         flowobjs = BKE_collision_objects_create(depsgraph, ob, sds->fluid_group, &numflowobj, eModifierType_Smoke);
2179
2180         /* init emission maps for each flow */
2181         emaps = MEM_callocN(sizeof(struct EmissionMap) * numflowobj, "smoke_flow_maps");
2182
2183         /* Prepare flow emission maps */
2184         for (flowIndex = 0; flowIndex < numflowobj; flowIndex++)
2185         {
2186                 Object *collob = flowobjs[flowIndex];
2187                 SmokeModifierData *smd2 = (SmokeModifierData *)modifiers_findByType(collob, eModifierType_Smoke);
2188
2189                 // check for initialized smoke object
2190                 if ((smd2->type & MOD_SMOKE_TYPE_FLOW) && smd2->flow)
2191                 {
2192                         // we got nice flow object
2193                         SmokeFlowSettings *sfs = smd2->flow;
2194                         int subframes = sfs->subframes;
2195                         EmissionMap *em = &emaps[flowIndex];
2196
2197                         /* just sample flow directly to emission map if no subframes */
2198                         if (!subframes) {
2199                                 if (sfs->source == MOD_SMOKE_FLOW_SOURCE_PARTICLES) {
2200                                         emit_from_particles(collob, sds, sfs, em, depsgraph, scene, dt);
2201                                 }
2202                                 else {
2203                                         emit_from_mesh(collob, sds, sfs, em, dt);
2204                                 }
2205                         }
2206                         /* sample subframes */
2207                         else {
2208 #if 0
2209                                 int scene_frame = (int)DEG_get_ctime(depsgraph);
2210 #endif
2211                                 // float scene_subframe = scene->r.subframe;  // UNUSED
2212                                 int subframe;
2213                                 for (subframe = 0; subframe <= subframes; subframe++) {
2214                                         EmissionMap em_temp = {NULL};
2215                                         float sample_size = 1.0f / (float)(subframes+1);
2216 #if 0
2217                                         float prev_frame_pos = sample_size * (float)(subframe+1);
2218 #endif
2219                                         float sdt = dt * sample_size;
2220                                         int hires_multiplier = 1;
2221
2222                                         if ((sds->flags & MOD_SMOKE_HIGHRES) && (sds->highres_sampling == SM_HRES_FULLSAMPLE)) {
2223                                                 hires_multiplier = sds->amplify + 1;
2224                                         }
2225
2226                                         /* TODO: setting the scene frame no longer works with the new depsgraph. */
2227 #if 0
2228                                         /* set scene frame to match previous frame + subframe
2229                                          * or use current frame for last sample */
2230                                         if (subframe < subframes) {
2231                                                 scene->r.cfra = scene_frame - 1;
2232                                                 scene->r.subframe = prev_frame_pos;
2233                                         }
2234                                         else {
2235                                                 scene->r.cfra = scene_frame;
2236                                                 scene->r.subframe = 0.0f;
2237                                         }
2238 #endif
2239
2240                                         if (sfs->source == MOD_SMOKE_FLOW_SOURCE_PARTICLES) {
2241                                                 /* emit_from_particles() updates timestep internally */
2242                                                 emit_from_particles(collob, sds, sfs, &em_temp, depsgraph, scene, sdt);
2243                                                 if (!(sfs->flags & MOD_SMOKE_FLOW_USE_PART_SIZE)) {
2244                                                         hires_multiplier = 1;
2245                                                 }
2246                                         }
2247                                         else { /* MOD_SMOKE_FLOW_SOURCE_MESH */
2248                                                 /* update flow object frame */
2249                                                 BLI_mutex_lock(&object_update_lock);
2250                                                 BKE_object_modifier_update_subframe(depsgraph, scene, collob, true, 5, DEG_get_ctime(depsgraph), eModifierType_Smoke);
2251                                                 BLI_mutex_unlock(&object_update_lock);
2252
2253                                                 /* apply flow */
2254                                                 emit_from_mesh(collob, sds, sfs, &em_temp, sdt);
2255                                         }
2256
2257                                         /* combine emission maps */
2258                                         em_combineMaps(em, &em_temp, hires_multiplier, !(sfs->flags & MOD_SMOKE_FLOW_ABSOLUTE), sample_size);
2259                                         em_freeData(&em_temp);
2260                                 }
2261                         }
2262
2263                         /* update required data fields */
2264                         if (em->total_cells && sfs->type != MOD_SMOKE_FLOW_TYPE_OUTFLOW) {
2265                                 /* activate heat field if flow produces any heat */
2266                                 if (sfs->temp) {
2267                                         active_fields |= SM_ACTIVE_HEAT;
2268                                 }
2269                                 /* activate fuel field if flow adds any fuel */
2270                                 if (sfs->type != MOD_SMOKE_FLOW_TYPE_SMOKE && sfs->fuel_amount) {
2271                                         active_fields |= SM_ACTIVE_FIRE;
2272                                 }
2273                                 /* activate color field if flows add smoke with varying colors */
2274                                 if (sfs->type != MOD_SMOKE_FLOW_TYPE_FIRE && sfs->density) {
2275                                         if (!(active_fields & SM_ACTIVE_COLOR_SET)) {
2276                                                 copy_v3_v3(sds->active_color, sfs->color);
2277                                                 active_fields |= SM_ACTIVE_COLOR_SET;
2278                                         }
2279                                         else if (!equals_v3v3(sds->active_color, sfs->color)) {
2280                                                 copy_v3_v3(sds->active_color, sfs->color);
2281                                                 active_fields |= SM_ACTIVE_COLORS;
2282                                         }
2283                                 }
2284                         }
2285                 }
2286         }
2287
2288         /* monitor active fields based on domain settings */
2289         /* if domain has fire, activate new fields if required */
2290         if (active_fields & SM_ACTIVE_FIRE) {
2291                 /* heat is always needed for fire */
2292                 active_fields |= SM_ACTIVE_HEAT;
2293                 /* also activate colors if domain smoke color differs from active color */
2294                 if (!(active_fields & SM_ACTIVE_COLOR_SET)) {
2295                         copy_v3_v3(sds->active_color, sds->flame_smoke_color);
2296                         active_fields |= SM_ACTIVE_COLOR_SET;
2297                 }
2298                 else if (!equals_v3v3(sds->active_color, sds->flame_smoke_color)) {
2299                         copy_v3_v3(sds->active_color, sds->flame_smoke_color);
2300                         active_fields |= SM_ACTIVE_COLORS;
2301                 }
2302         }
2303
2304         /* Adjust domain size if needed */
2305         if (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) {
2306                 adjustDomainResolution(sds, new_shift, emaps, numflowobj, dt);
2307         }
2308
2309         /* Initialize new data fields if any */
2310         if (active_fields & SM_ACTIVE_HEAT) {
2311                 smoke_ensure_heat(sds->fluid);
2312         }
2313         if (active_fields & SM_ACTIVE_FIRE) {
2314                 smoke_ensure_fire(sds->fluid, sds->wt);
2315         }
2316         if (active_fields & SM_ACTIVE_COLORS) {
2317                 /* initialize all smoke with "active_color" */
2318                 smoke_ensure_colors(sds->fluid, sds->wt, sds->active_color[0], sds->active_color[1], sds->active_color[2]);
2319         }
2320         sds->active_fields = active_fields;
2321
2322         /* Apply emission data */
2323         if (sds->fluid) {
2324                 for (flowIndex = 0; flowIndex < numflowobj; flowIndex++)
2325                 {
2326                         Object *collob = flowobjs[flowIndex];
2327                         SmokeModifierData *smd2 = (SmokeModifierData *)modifiers_findByType(collob, eModifierType_Smoke);
2328
2329                         // check for initialized smoke object
2330                         if ((smd2->type & MOD_SMOKE_TYPE_FLOW) && smd2->flow)
2331                         {
2332                                 // we got nice flow object
2333                                 SmokeFlowSettings *sfs = smd2->flow;
2334                                 EmissionMap *em = &emaps[flowIndex];
2335
2336                                 float *density = smoke_get_density(sds->fluid);
2337                                 float *color_r = smoke_get_color_r(sds->fluid);
2338                                 float *color_g = smoke_get_color_g(sds->fluid);
2339                                 float *color_b = smoke_get_color_b(sds->fluid);
2340                                 float *fuel = smoke_get_fuel(sds->fluid);
2341                                 float *react = smoke_get_react(sds->fluid);
2342                                 float *bigdensity = smoke_turbulence_get_density(sds->wt);
2343                                 float *bigfuel = smoke_turbulence_get_fuel(sds->wt);
2344                                 float *bigreact = smoke_turbulence_get_react(sds->wt);
2345                                 float *bigcolor_r = smoke_turbulence_get_color_r(sds->wt);
2346                                 float *bigcolor_g = smoke_turbulence_get_color_g(sds->wt);
2347                                 float *bigcolor_b = smoke_turbulence_get_color_b(sds->wt);
2348                                 float *heat = smoke_get_heat(sds->fluid);
2349                                 float *velocity_x = smoke_get_velocity_x(sds->fluid);
2350                                 float *velocity_y = smoke_get_velocity_y(sds->fluid);
2351                                 float *velocity_z = smoke_get_velocity_z(sds->fluid);
2352                                 //unsigned char *obstacle = smoke_get_obstacle(sds->fluid);
2353                                 // DG TODO UNUSED unsigned char *obstacleAnim = smoke_get_obstacle_anim(sds->fluid);
2354                                 int bigres[3];
2355                                 float *velocity_map = em->velocity;
2356                                 float *emission_map = em->influence;
2357                                 float *emission_map_high = em->influence_high;
2358
2359                                 int ii, jj, kk, gx, gy, gz, ex, ey, ez, dx, dy, dz, block_size;
2360                                 size_t e_index, d_index, index_big;
2361
2362                                 // loop through every emission map cell
2363                                 for (gx = em->min[0]; gx < em->max[0]; gx++)
2364                                         for (gy = em->min[1]; gy < em->max[1]; gy++)
2365                                                 for (gz = em->min[2]; gz < em->max[2]; gz++)
2366                                                 {
2367                                                         /* get emission map index */
2368                                                         ex = gx - em->min[0];
2369                                                         ey = gy - em->min[1];
2370                                                         ez = gz - em->min[2];
2371                                                         e_index = smoke_get_index(ex, em->res[0], ey, em->res[1], ez);
2372
2373                                                         /* get domain index */
2374                                                         dx = gx - sds->res_min[0];
2375                                                         dy = gy - sds->res_min[1];
2376                                                         dz = gz - sds->res_min[2];
2377                                                         d_index = smoke_get_index(dx, sds->res[0], dy, sds->res[1], dz);
2378                                                         /* make sure emission cell is inside the new domain boundary */
2379                                                         if (dx < 0 || dy < 0 || dz < 0 || dx >= sds->res[0] || dy >= sds->res[1] || dz >= sds->res[2]) continue;
2380
2381                                                         if (sfs->type == MOD_SMOKE_FLOW_TYPE_OUTFLOW) { // outflow
2382                                                                 apply_outflow_fields(d_index, density, heat, fuel, react, color_r, color_g, color_b);
2383                                                         }
2384                                                         else { // inflow
2385                                                                 apply_inflow_fields(sfs, emission_map[e_index], d_index, density, heat, fuel, react, color_r, color_g, color_b);
2386
2387                                                                 /* initial velocity */
2388                                                                 if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY) {
2389                                                                         velocity_x[d_index] = ADD_IF_LOWER(velocity_x[d_index], velocity_map[e_index * 3]);
2390                                                                         velocity_y[d_index] = ADD_IF_LOWER(velocity_y[d_index], velocity_map[e_index * 3 + 1]);
2391                                                                         velocity_z[d_index] = ADD_IF_LOWER(velocity_z[d_index], velocity_map[e_index * 3 + 2]);
2392                                                                 }
2393                                                         }
2394
2395                                                         /* loop through high res blocks if high res enabled */
2396                                                         if (bigdensity) {
2397                                                                 // neighbor cell emission densities (for high resolution smoke smooth interpolation)
2398                                                                 float c000, c001, c010, c011,  c100, c101, c110, c111;
2399
2400                                                                 smoke_turbulence_get_res(sds->wt, bigres);
2401                                                                 block_size = sds->amplify + 1;  // high res block size
2402
2403                                                                 c000 = (ex > 0 && ey > 0 && ez > 0) ? emission_map[smoke_get_index(ex - 1, em->res[0], ey - 1, em->res[1], ez - 1)] : 0;
2404                                                                 c001 = (ex > 0 && ey > 0) ? emission_map[smoke_get_index(ex - 1, em->res[0], ey - 1, em->res[1], ez)] : 0;
2405                                                                 c010 = (ex > 0 && ez > 0) ? emission_map[smoke_get_index(ex - 1, em->res[0], ey, em->res[1], ez - 1)] : 0;
2406                                                                 c011 = (ex > 0) ? emission_map[smoke_get_index(ex - 1, em->res[0], ey, em->res[1], ez)] : 0;
2407
2408                                                                 c100 = (ey > 0 && ez > 0) ? emission_map[smoke_get_index(ex, em->res[0], ey - 1, em->res[1], ez - 1)] : 0;
2409                                                                 c101 = (ey > 0) ? emission_map[smoke_get_index(ex, em->res[0], ey - 1, em->res[1], ez)] : 0;
2410                                                                 c110 = (ez > 0) ? emission_map[smoke_get_index(ex, em->res[0], ey, em->res[1], ez - 1)] : 0;
2411                                                                 c111 = emission_map[smoke_get_index(ex, em->res[0], ey, em->res[1], ez)]; // this cell
2412
2413                                                                 for (ii = 0; ii < block_size; ii++)
2414                                                                         for (jj = 0; jj < block_size; jj++)
2415                                                                                 for (kk = 0; kk < block_size; kk++)
2416                                                                                 {
2417
2418                                                                                         float fx, fy, fz, interpolated_value;
2419                                                                                         int shift_x = 0, shift_y = 0, shift_z = 0;
2420
2421
2422                                                                                         /* Use full sample emission map if enabled and available */
2423                                                                                         if ((sds->highres_sampling == SM_HRES_FULLSAMPLE) && emission_map_high) {
2424                                                                                                 interpolated_value = emission_map_high[smoke_get_index(ex * block_size + ii, em->res[0] * block_size, ey * block_size + jj, em->res[1] * block_size, ez * block_size + kk)]; // this cell
2425                                                                                         }
2426                                                                                         else if (sds->highres_sampling == SM_HRES_NEAREST) {
2427                                                                                                 /* without interpolation use same low resolution
2428                                                                                                  * block value for all hi-res blocks */
2429                                                                                                 interpolated_value = c111;
2430                                                                                         }
2431                                                                                         /* Fall back to interpolated */
2432                                                                                         else
2433                                                                                         {
2434                                                                                                 /* get relative block position
2435                                                                                                  * for interpolation smoothing */
2436                                                                                                 fx = (float)ii / block_size + 0.5f / block_size;
2437                                                                                                 fy = (float)jj / block_size + 0.5f / block_size;
2438                                                                                                 fz = (float)kk / block_size + 0.5f / block_size;
2439
2440                                                                                                 /* calculate trilinear interpolation */
2441                                                                                                 interpolated_value = c000 * (1 - fx) * (1 - fy) * (1 - fz) +
2442                                                                                                                      c100 * fx * (1 - fy) * (1 - fz) +
2443                                                                                                                      c010 * (1 - fx) * fy * (1 - fz) +
2444                                                                                                                      c001 * (1 - fx) * (1 - fy) * fz +
2445                                                                                                                      c101 * fx * (1 - fy) * fz +
2446                                                                                                                      c011 * (1 - fx) * fy * fz +
2447                                                                                                                      c110 * fx * fy * (1 - fz) +
2448                                                                                                                      c111 * fx * fy * fz;
2449
2450
2451                                                                                                 /* add some contrast / sharpness
2452                                                                                                  * depending on hi-res block size */
2453                                                                                                 interpolated_value = (interpolated_value - 0.4f) * (block_size / 2) + 0.4f;
2454                                                                                                 CLAMP(interpolated_value, 0.0f, 1.0f);
2455
2456                                                                                                 /* shift smoke block index
2457                                                                                                  * (because pixel center is actually
2458                                                                                                  * in halfway of the low res block) */
2459                                                                                                 shift_x = (dx < 1) ? 0 : block_size / 2;
2460                                                                                                 shift_y = (dy < 1) ? 0 : block_size / 2;
2461                                                                                                 shift_z = (dz < 1) ? 0 : block_size / 2;
2462                                                                                         }
2463
2464                                                                                         /* get shifted index for current high resolution block */
2465                                                                                         index_big = smoke_get_index(block_size * dx + ii - shift_x, bigres[0], block_size * dy + jj - shift_y, bigres[1], block_size * dz + kk - shift_z);
2466
2467                                                                                         if (sfs->type == MOD_SMOKE_FLOW_TYPE_OUTFLOW) { // outflow
2468                                                                                                 if (interpolated_value) {
2469                                                                                                         apply_outflow_fields(index_big, bigdensity, NULL, bigfuel, bigreact, bigcolor_r, bigcolor_g, bigcolor_b);
2470                                                                                                 }
2471                                                                                         }
2472                                                                                         else { // inflow
2473                                                                                                 apply_inflow_fields(sfs, interpolated_value, index_big, bigdensity, NULL, bigfuel, bigreact, bigcolor_r, bigcolor_g, bigcolor_b);
2474                                                                                         }
2475                                                                                 } // hires loop
2476                                                         }  // bigdensity
2477                                                 } // low res loop
2478
2479                                 // free emission maps
2480                                 em_freeData(em);
2481
2482                         } // end emission
2483                 }
2484         }
2485
2486         BKE_collision_objects_free(flowobjs);
2487         if (emaps)
2488                 MEM_freeN(emaps);
2489 }
2490
2491 typedef struct UpdateEffectorsData {
2492         Scene *scene;
2493         SmokeDomainSettings *sds;
2494         ListBase *effectors;
2495
2496         float *density;
2497         float *fuel;
2498         float *force_x;
2499         float *force_y;
2500         float *force_z;
2501         float *velocity_x;
2502         float *velocity_y;
2503         float *velocity_z;
2504         unsigned char *obstacle;
2505 } UpdateEffectorsData;
2506
2507 static void update_effectors_task_cb(
2508         void *__restrict userdata,
2509         const int x,
2510         const ParallelRangeTLS *__restrict UNUSED(tls))
2511 {
2512         UpdateEffectorsData *data = userdata;
2513         SmokeDomainSettings *sds = data->sds;
2514
2515         for (int y = 0; y < sds->res[1]; y++) {
2516                 for (int z = 0; z < sds->res[2]; z++)
2517                 {
2518                         EffectedPoint epoint;
2519                         float mag;
2520                         float voxelCenter[3] = {0, 0, 0}, vel[3] = {0, 0, 0}, retvel[3] = {0, 0, 0};
2521                         const unsigned int index = smoke_get_index(x, sds->res[0], y, sds->res[1], z);
2522
2523                         if (((data->fuel ? MAX2(data->density[index], data->fuel[index]) : data->density[index]) < FLT_EPSILON) ||
2524                             data->obstacle[index])
2525                         {
2526                                 continue;
2527                         }
2528
2529                         vel[0] = data->velocity_x[index];
2530                         vel[1] = data->velocity_y[index];
2531                         vel[2] = data->velocity_z[index];
2532
2533                         /* convert vel to global space */
2534                         mag = len_v3(vel);
2535                         mul_mat3_m4_v3(sds->obmat, vel);
2536                         normalize_v3(vel);
2537                         mul_v3_fl(vel, mag);
2538
2539                         voxelCenter[0] = sds->p0[0] + sds->cell_size[0] * ((float)(x + sds->res_min[0]) + 0.5f);
2540                         voxelCenter[1] = sds->p0[1] + sds->cell_size[1] * ((float)(y + sds->res_min[1]) + 0.5f);
2541                         voxelCenter[2] = sds->p0[2] + sds->cell_size[2] * ((float)(z + sds->res_min[2]) + 0.5f);
2542                         mul_m4_v3(sds->obmat, voxelCenter);
2543
2544                         pd_point_from_loc(data->scene, voxelCenter, vel, index, &epoint);
2545                         BKE_effectors_apply(data->effectors, NULL, sds->effector_weights, &epoint, retvel, NULL);
2546
2547                         /* convert retvel to local space */
2548                         mag = len_v3(retvel);
2549                         mul_mat3_m4_v3(sds->imat, retvel);
2550                         normalize_v3(retvel);
2551                         mul_v3_fl(retvel, mag);
2552
2553                         // TODO dg - do in force!
2554                         data->force_x[index] = min_ff(max_ff(-1.0f, retvel[0] * 0.2f), 1.0f);
2555                         data->force_y[index] = min_ff(max_ff(-1.0f, retvel[1] * 0.2f), 1.0f);
2556                         data->force_z[index] = min_ff(max_ff(-1.0f, retvel[2] * 0.2f), 1.0f);
2557                 }
2558         }
2559 }
2560
2561 static void update_effectors(Depsgraph *depsgraph, Scene *scene, Object *ob, SmokeDomainSettings *sds, float UNUSED(dt))
2562 {
2563         ListBase *effectors;
2564         /* make sure smoke flow influence is 0.0f */
2565         sds->effector_weights->weight[PFIELD_SMOKEFLOW] = 0.0f;
2566         effectors = BKE_effectors_create(depsgraph, ob, NULL, sds->effector_weights);
2567
2568         if (effectors) {
2569                 // precalculate wind forces
2570                 UpdateEffectorsData data;
2571                 data.scene = scene;
2572                 data.sds = sds;
2573                 data.effectors = effectors;
2574                 data.density = smoke_get_density(sds->fluid);
2575                 data.fuel = smoke_get_fuel(sds->fluid);
2576                 data.force_x = smoke_get_force_x(sds->fluid);
2577                 data.force_y = smoke_get_force_y(sds->fluid);
2578                 data.force_z = smoke_get_force_z(sds->fluid);
2579                 data.velocity_x = smoke_get_velocity_x(sds->fluid);
2580                 data.velocity_y = smoke_get_velocity_y(sds->fluid);
2581                 data.velocity_z = smoke_get_velocity_z(sds->fluid);
2582                 data.obstacle = smoke_get_obstacle(sds->fluid);
2583
2584                 ParallelRangeSettings settings;
2585                 BLI_parallel_range_settings_defaults(&settings);
2586                 settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC;
2587                 BLI_task_parallel_range(0, sds->res[0],
2588                                         &data,
2589                                         update_effectors_task_cb,
2590                                         &settings);
2591         }
2592
2593         BKE_effectors_free(effectors);
2594 }
2595
2596 static void step(
2597         Depsgraph *depsgraph,
2598         Scene *scene, Object *ob, SmokeModifierData *smd, Mesh *domain_me, float fps)
2599 {
2600         SmokeDomainSettings *sds = smd->domain;
2601         /* stability values copied from wturbulence.cpp */
2602         const int maxSubSteps = 25;
2603         float maxVel;
2604         // maxVel should be 1.5 (1.5 cell max movement) * dx (cell size)
2605
2606         float dt;
2607         float maxVelMag = 0.0f;
2608         int totalSubsteps;
2609         int substep = 0;
2610         float dtSubdiv;
2611         float gravity[3] = {0.0f, 0.0f, -1.0f};
2612         float gravity_mag;
2613
2614         /* update object state */
2615         invert_m4_m4(sds->imat, ob->obmat);
2616         copy_m4_m4(sds->obmat, ob->obmat);
2617         smoke_set_domain_from_mesh(sds, ob, domain_me, (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) != 0);
2618
2619         /* use global gravity if enabled */
2620         if (scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) {
2621                 copy_v3_v3(gravity, scene->physics_settings.gravity);
2622                 /* map default value to 1.0 */
2623                 mul_v3_fl(gravity, 1.0f / 9.810f);
2624         }
2625         /* convert gravity to domain space */
2626         gravity_mag = len_v3(gravity);
2627         mul_mat3_m4_v3(sds->imat, gravity);
2628         normalize_v3(gravity);
2629         mul_v3_fl(gravity, gravity_mag);
2630
2631         /* adapt timestep for different framerates, dt = 0.1 is at 25fps */
2632         dt = DT_DEFAULT * (25.0f / fps);
2633         // maximum timestep/"CFL" constraint: dt < 5.0 *dx / maxVel
2634         maxVel = (sds->dx * 5.0f);
2635
2636         maxVelMag = sqrtf(maxVelMag) * dt * sds->time_scale;
2637         totalSubsteps = (int)((maxVelMag / maxVel) + 1.0f); /* always round up */
2638         totalSubsteps = (totalSubsteps < 1) ? 1 : totalSubsteps;
2639         totalSubsteps = (totalSubsteps > maxSubSteps) ? maxSubSteps : totalSubsteps;
2640
2641         /* Disable substeps for now, since it results in numerical instability */
2642         totalSubsteps = 1.0f;
2643
2644         dtSubdiv = (float)dt / (float)totalSubsteps;
2645
2646         // printf("totalSubsteps: %d, maxVelMag: %f, dt: %f\n", totalSubsteps, maxVelMag, dt);
2647
2648         for (substep = 0; substep < totalSubsteps; substep++)
2649         {
2650                 // calc animated obstacle velocities
2651                 update_flowsfluids(depsgraph, scene, ob, sds, dtSubdiv);
2652                 update_obstacles(depsgraph, ob, sds, dtSubdiv, substep, totalSubsteps);
2653
2654                 if (sds->total_cells > 1) {
2655                         update_effectors(depsgraph, scene, ob, sds, dtSubdiv); // DG TODO? problem --> uses forces instead of velocity, need to check how they need to be changed with variable dt
2656                         smoke_step(sds->fluid, gravity, dtSubdiv);
2657                 }
2658         }
2659 }
2660
2661 static Mesh *createDomainGeometry(SmokeDomainSettings *sds, Object *ob)
2662 {
2663         Mesh *result;
2664         MVert *mverts;
2665         MPoly *mpolys;
2666         MLoop *mloops;
2667         float min[3];
2668         float max[3];
2669         float *co;
2670         MPoly *mp;
2671         MLoop *ml;
2672
2673         int num_verts = 8;
2674         int num_faces = 6;
2675         int i;
2676         float ob_loc[3] = {0};
2677         float ob_cache_loc[3] = {0};
2678
2679         /* dont generate any mesh if there isnt any content */
2680         if (sds->total_cells <= 1) {
2681                 num_verts = 0;
2682                 num_faces = 0;
2683         }
2684
2685         result = BKE_mesh_new_nomain(num_verts, 0, 0, num_faces * 4, num_faces);
2686         mverts = result->mvert;
2687         mpolys = result->mpoly;
2688         mloops = result->mloop;
2689
2690         if (num_verts) {
2691                 /* volume bounds */
2692                 VECMADD(min, sds->p0, sds->cell_size, sds->res_min);
2693                 VECMADD(max, sds->p0, sds->cell_size, sds->res_max);
2694
2695                 /* set vertices */
2696                 /* top slab */
2697                 co = mverts[0].co; co[0] = min[0]; co[1] = min[1]; co[2] = max[2];
2698                 co = mverts[1].co; co[0] = max[0]; co[1] = min[1]; co[2] = max[2];
2699                 co = mverts[2].co; co[0] = max[0]; co[1] = max[1]; co[2] = max[2];
2700                 co = mverts[3].co; co[0] = min[0]; co[1] = max[1]; co[2] = max[2];
2701                 /* bottom slab */
2702                 co = mverts[4].co; co[0] = min[0]; co[1] = min[1]; co[2] = min[2];
2703                 co = mverts[5].co; co[0] = max[0]; co[1] = min[1]; co[2] = min[2];
2704                 co = mverts[6].co; co[0] = max[0]; co[1] = max[1]; co[2] = min[2];
2705                 co = mverts[7].co; co[0] = min[0]; co[1] = max[1]; co[2] = min[2];
2706
2707                 /* create faces */
2708                 /* top */
2709                 mp = &mpolys[0]; ml = &mloops[0 * 4]; mp->loopstart = 0 * 4; mp->totloop = 4;
2710                 ml[0].v = 0; ml[1].v = 1; ml[2].v = 2; ml[3].v = 3;
2711                 /* right */
2712                 mp = &mpolys[1]; ml = &mloops[1 * 4]; mp->loopstart = 1 * 4; mp->totloop = 4;
2713                 ml[0].v = 2; ml[1].v = 1; ml[2].v = 5; ml[3].v = 6;
2714                 /* bottom */
2715                 mp = &mpolys[2]; ml = &mloops[2 * 4]; mp->loopstart = 2 * 4; mp->totloop = 4;
2716                 ml[0].v = 7; ml[1].v = 6; ml[2].v = 5; ml[3].v = 4;
2717                 /* left */
2718                 mp = &mpolys[3]; ml = &mloops[3 * 4]; mp->loopstart = 3 * 4; mp->totloop = 4;
2719                 ml[0].v = 0; ml[1].v = 3; ml[2].v = 7; ml[3].v = 4;
2720                 /* front */
2721                 mp = &mpolys[4]; ml = &mloops[4 * 4]; mp->loopstart = 4 * 4; mp->totloop = 4;
2722                 ml[0].v = 3; ml[1].v = 2; ml[2].v = 6; ml[3].v = 7;
2723                 /* back */
2724                 mp = &mpolys[5]; ml = &mloops[5 * 4]; mp->loopstart = 5 * 4; mp->totloop = 4;
2725                 ml[0].v = 1; ml[1].v = 0; ml[2].v = 4; ml[3].v = 5;
2726
2727                 /* calculate required shift to match domain's global position
2728                  * it was originally simulated at (if object moves without smoke step) */
2729                 invert_m4_m4(ob->imat, ob->obmat);
2730                 mul_m4_v3(ob->obmat, ob_loc);
2731                 mul_m4_v3(sds->obmat, ob_cache_loc);
2732                 VECSUB(sds->obj_shift_f, ob_cache_loc, ob_loc);
2733                 /* convert shift to local space and apply to vertices */
2734                 mul_mat3_m4_v3(ob->imat, sds->obj_shift_f);
2735                 /* apply */
2736                 for (i = 0; i < num_verts; i++) {
2737                         add_v3_v3(mverts[i].co, sds->obj_shift_f);
2738                 }
2739         }
2740
2741         BKE_mesh_calc_edges(result, false, false);
2742         result->runtime.cd_dirty_vert |= CD_MASK_NORMAL;
2743         return result;
2744 }
2745
2746 static void smokeModifier_process(
2747         SmokeModifierData *smd, Depsgraph *depsgraph, Scene *scene, Object *ob, Mesh *me)
2748 {
2749         const int scene_framenr = (int)DEG_get_ctime(depsgraph);
2750
2751         if ((smd->type & MOD_SMOKE_TYPE_FLOW))
2752         {
2753                 if (scene_framenr >= smd->time)
2754                         smokeModifier_init(smd, ob, scene_framenr, me);
2755
2756                 if (smd->flow->mesh) BKE_id_free(NULL, smd->flow->mesh);
2757                 smd->flow->mesh = BKE_mesh_copy_for_eval(me, false);
2758
2759                 if (scene_framenr > smd->time)
2760                 {
2761                         smd->time = scene_framenr;
2762                 }
2763                 else if (scene_framenr < smd->time)
2764                 {
2765                         smd->time = scene_framenr;
2766                         smokeModifier_reset_ex(smd, false);
2767                 }
2768         }
2769         else if (smd->type & MOD_SMOKE_TYPE_COLL)
2770         {
2771                 if (scene_framenr >= smd->time)
2772                         smokeModifier_init(smd, ob, scene_framenr, me);
2773
2774                 if (smd->coll)
2775                 {
2776                         if (smd->coll->mesh)