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
1314                 /* prepare curvemapping tables */
1315                 if ((psys->part->child_flag & PART_CHILD_USE_CLUMP_CURVE) && psys->part->clumpcurve)
1316                         curvemapping_changed_all(psys->part->clumpcurve);
1317                 if ((psys->part->child_flag & PART_CHILD_USE_ROUGH_CURVE) && psys->part->roughcurve)
1318                         curvemapping_changed_all(psys->part->roughcurve);
1319                 if ((psys->part->child_flag & PART_CHILD_USE_TWIST_CURVE) && psys->part->twistcurve)
1320                         curvemapping_changed_all(psys->part->twistcurve);
1321
1322                 /* initialize particle cache */
1323                 if (psys->part->type == PART_HAIR) {
1324                         // TODO: PART_HAIR not supported whatsoever
1325                         totchild = 0;
1326                 }
1327                 else {
1328                         totchild = psys->totchild * psys->part->disp / 100;
1329                 }
1330
1331                 particle_pos = MEM_callocN(sizeof(float) * (totpart + totchild) * 3, "smoke_flow_particles");
1332                 particle_vel = MEM_callocN(sizeof(float) * (totpart + totchild) * 3, "smoke_flow_particles");
1333
1334                 /* setup particle radius emission if enabled */
1335                 if (sfs->flags & MOD_SMOKE_FLOW_USE_PART_SIZE) {
1336                         tree = BLI_kdtree_new(psys->totpart + psys->totchild);
1337
1338                         /* check need for high resolution map */
1339                         if ((sds->flags & MOD_SMOKE_HIGHRES) && (sds->highres_sampling == SM_HRES_FULLSAMPLE)) {
1340                                 hires_multiplier = sds->amplify + 1;
1341                         }
1342
1343                         bounds_margin = (int)ceil(solid + smooth);
1344                 }
1345
1346                 /* calculate local position for each particle */
1347                 for (p = 0; p < totpart + totchild; p++)
1348                 {
1349                         ParticleKey state;
1350                         float *pos;
1351                         if (p < totpart) {
1352                                 if (psys->particles[p].flag & (PARS_NO_DISP | PARS_UNEXIST))
1353                                         continue;
1354                         }
1355                         else {
1356                                 /* handle child particle */
1357                                 ChildParticle *cpa = &psys->child[p - totpart];
1358                                 if (psys->particles[cpa->parent].flag & (PARS_NO_DISP | PARS_UNEXIST))
1359                                         continue;
1360                         }
1361
1362                         state.time = DEG_get_ctime(depsgraph); /* use depsgraph time */
1363                         if (psys_get_particle_state(&sim, p, &state, 0) == 0)
1364                                 continue;
1365
1366                         /* location */
1367                         pos = &particle_pos[valid_particles * 3];
1368                         copy_v3_v3(pos, state.co);
1369                         smoke_pos_to_cell(sds, pos);
1370
1371                         /* velocity */
1372                         copy_v3_v3(&particle_vel[valid_particles * 3], state.vel);
1373                         mul_mat3_m4_v3(sds->imat, &particle_vel[valid_particles * 3]);
1374
1375                         if (sfs->flags & MOD_SMOKE_FLOW_USE_PART_SIZE) {
1376                                 BLI_kdtree_insert(tree, valid_particles, pos);
1377                         }
1378
1379                         /* calculate emission map bounds */
1380                         em_boundInsert(em, pos);
1381                         valid_particles++;
1382                 }
1383
1384                 /* set emission map */
1385                 clampBoundsInDomain(sds, em->min, em->max, NULL, NULL, bounds_margin, dt);
1386                 em_allocateData(em, sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY, hires_multiplier);
1387
1388                 if (!(sfs->flags & MOD_SMOKE_FLOW_USE_PART_SIZE)) {
1389                         for (p = 0; p < valid_particles; p++)
1390                         {
1391                                 int cell[3];
1392                                 size_t i = 0;
1393                                 size_t index = 0;
1394                                 int badcell = 0;
1395
1396                                 /* 1. get corresponding cell */
1397                                 cell[0] = floor(particle_pos[p * 3]) - em->min[0];
1398                                 cell[1] = floor(particle_pos[p * 3 + 1]) - em->min[1];
1399                                 cell[2] = floor(particle_pos[p * 3 + 2]) - em->min[2];
1400                                 /* check if cell is valid (in the domain boundary) */
1401                                 for (i = 0; i < 3; i++) {
1402                                         if ((cell[i] > em->res[i] - 1) || (cell[i] < 0)) {
1403                                                 badcell = 1;
1404                                                 break;
1405                                         }
1406                                 }
1407                                 if (badcell)
1408                                         continue;
1409                                 /* get cell index */
1410                                 index = smoke_get_index(cell[0], em->res[0], cell[1], em->res[1], cell[2]);
1411                                 /* Add influence to emission map */
1412                                 em->influence[index] = 1.0f;
1413                                 /* Uses particle velocity as initial velocity for smoke */
1414                                 if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY && (psys->part->phystype != PART_PHYS_NO))
1415                                 {
1416                                         VECADDFAC(&em->velocity[index * 3], &em->velocity[index * 3], &particle_vel[p * 3], sfs->vel_multi);
1417                                 }
1418                         }   // particles loop
1419                 }
1420                 else if (valid_particles > 0) { // MOD_SMOKE_FLOW_USE_PART_SIZE
1421                         int min[3], max[3], res[3];
1422                         const float hr = 1.0f / ((float)hires_multiplier);
1423                         /* slightly adjust high res antialias smoothness based on number of divisions
1424                          * to allow smaller details but yet not differing too much from the low res size */
1425                         const float hr_smooth = smooth * powf(hr, 1.0f / 3.0f);
1426
1427                         /* setup loop bounds */
1428                         for (int i = 0; i < 3; i++) {
1429                                 min[i] = em->min[i] * hires_multiplier;
1430                                 max[i] = em->max[i] * hires_multiplier;
1431                                 res[i] = em->res[i] * hires_multiplier;
1432                         }
1433
1434                         BLI_kdtree_balance(tree);
1435
1436                         EmitFromParticlesData data = {
1437                                 .sfs = sfs, .tree = tree, .hires_multiplier = hires_multiplier, .hr = hr,
1438                             .em = em, .particle_vel = particle_vel, .min = min, .max = max, .res = res,
1439                             .solid = solid, .smooth = smooth, .hr_smooth = hr_smooth,
1440                         };
1441
1442                         ParallelRangeSettings settings;
1443                         BLI_parallel_range_settings_defaults(&settings);
1444                         settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC;
1445                         BLI_task_parallel_range(min[2], max[2],
1446                                                 &data,
1447                                                 emit_from_particles_task_cb,
1448                                                 &settings);
1449                 }
1450
1451                 if (sfs->flags & MOD_SMOKE_FLOW_USE_PART_SIZE) {
1452                         BLI_kdtree_free(tree);
1453                 }
1454
1455                 /* free data */
1456                 if (particle_pos)
1457                         MEM_freeN(particle_pos);
1458                 if (particle_vel)
1459                         MEM_freeN(particle_vel);
1460         }
1461 }
1462
1463 static void sample_mesh(
1464         SmokeFlowSettings *sfs,
1465         const MVert *mvert, const MLoop *mloop, const MLoopTri *mlooptri, const MLoopUV *mloopuv,
1466         float *influence_map, float *velocity_map, int index, const int base_res[3], float flow_center[3],
1467         BVHTreeFromMesh *treeData, const float ray_start[3], const float *vert_vel,
1468         bool has_velocity, int defgrp_index, MDeformVert *dvert,
1469         float x, float y, float z)
1470 {
1471         float ray_dir[3] = {1.0f, 0.0f, 0.0f};
1472         BVHTreeRayHit hit = {0};
1473         BVHTreeNearest nearest = {0};
1474
1475         float volume_factor = 0.0f;
1476         float sample_str = 0.0f;
1477
1478         hit.index = -1;
1479         hit.dist = 9999;
1480         nearest.index = -1;
1481         nearest.dist_sq = sfs->surface_distance * sfs->surface_distance; /* find_nearest uses squared distance */
1482
1483         /* Check volume collision */
1484         if (sfs->volume_density) {
1485                 if (BLI_bvhtree_ray_cast(treeData->tree, ray_start, ray_dir, 0.0f, &hit, treeData->raycast_callback, treeData) != -1) {
1486                         float dot = ray_dir[0] * hit.no[0] + ray_dir[1] * hit.no[1] + ray_dir[2] * hit.no[2];
1487                         /* If ray and hit face normal are facing same direction
1488                          * hit point is inside a closed mesh. */
1489                         if (dot >= 0) {
1490                                 /* Also cast a ray in opposite direction to make sure
1491                                  * point is at least surrounded by two faces */
1492                                 negate_v3(ray_dir);
1493                                 hit.index = -1;
1494                                 hit.dist = 9999;
1495
1496                                 BLI_bvhtree_ray_cast(treeData->tree, ray_start, ray_dir, 0.0f, &hit, treeData->raycast_callback, treeData);
1497                                 if (hit.index != -1) {
1498                                         volume_factor = sfs->volume_density;
1499                                 }
1500                         }
1501                 }
1502         }
1503
1504         /* find the nearest point on the mesh */
1505         if (BLI_bvhtree_find_nearest(treeData->tree, ray_start, &nearest, treeData->nearest_callback, treeData) != -1) {
1506                 float weights[3];
1507                 int v1, v2, v3, f_index = nearest.index;
1508                 float n1[3], n2[3], n3[3], hit_normal[3];
1509
1510                 /* emit from surface based on distance */
1511                 if (sfs->surface_distance) {
1512                         sample_str = sqrtf(nearest.dist_sq) / sfs->surface_distance;
1513                         CLAMP(sample_str, 0.0f, 1.0f);
1514                         sample_str = pow(1.0f - sample_str, 0.5f);
1515                 }
1516                 else
1517                         sample_str = 0.0f;
1518
1519                 /* calculate barycentric weights for nearest point */
1520                 v1 = mloop[mlooptri[f_index].tri[0]].v;
1521                 v2 = mloop[mlooptri[f_index].tri[1]].v;
1522                 v3 = mloop[mlooptri[f_index].tri[2]].v;
1523                 interp_weights_tri_v3(weights, mvert[v1].co, mvert[v2].co, mvert[v3].co, nearest.co);
1524
1525                 if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY && velocity_map) {
1526                         /* apply normal directional velocity */
1527                         if (sfs->vel_normal) {
1528                                 /* interpolate vertex normal vectors to get nearest point normal */
1529                                 normal_short_to_float_v3(n1, mvert[v1].no);
1530                                 normal_short_to_float_v3(n2, mvert[v2].no);
1531                                 normal_short_to_float_v3(n3, mvert[v3].no);
1532                                 interp_v3_v3v3v3(hit_normal, n1, n2, n3, weights);
1533                                 normalize_v3(hit_normal);
1534                                 /* apply normal directional and random velocity
1535                                  * - TODO: random disabled for now since it doesn't really work well as pressure calc smoothens it out... */
1536                                 velocity_map[index * 3]   += hit_normal[0] * sfs->vel_normal * 0.25f;
1537                                 velocity_map[index * 3 + 1] += hit_normal[1] * sfs->vel_normal * 0.25f;
1538                                 velocity_map[index * 3 + 2] += hit_normal[2] * sfs->vel_normal * 0.25f;
1539                                 /* TODO: for fire emitted from mesh surface we can use
1540                                  * Vf = Vs + (Ps/Pf - 1)*S to model gaseous expansion from solid to fuel */
1541                         }
1542                         /* apply object velocity */
1543                         if (has_velocity && sfs->vel_multi) {
1544                                 float hit_vel[3];
1545                                 interp_v3_v3v3v3(hit_vel, &vert_vel[v1 * 3], &vert_vel[v2 * 3], &vert_vel[v3 * 3], weights);
1546                                 velocity_map[index * 3]   += hit_vel[0] * sfs->vel_multi;
1547                                 velocity_map[index * 3 + 1] += hit_vel[1] * sfs->vel_multi;
1548                                 velocity_map[index * 3 + 2] += hit_vel[2] * sfs->vel_multi;
1549                         }
1550                 }
1551
1552                 /* apply vertex group influence if used */
1553                 if (defgrp_index != -1 && dvert) {
1554                         float weight_mask = defvert_find_weight(&dvert[v1], defgrp_index) * weights[0] +
1555                                             defvert_find_weight(&dvert[v2], defgrp_index) * weights[1] +
1556                                             defvert_find_weight(&dvert[v3], defgrp_index) * weights[2];
1557                         sample_str *= weight_mask;
1558                 }
1559
1560                 /* apply emission texture */
1561                 if ((sfs->flags & MOD_SMOKE_FLOW_TEXTUREEMIT) && sfs->noise_texture) {
1562                         float tex_co[3] = {0};
1563                         TexResult texres;
1564
1565                         if (sfs->texture_type == MOD_SMOKE_FLOW_TEXTURE_MAP_AUTO) {
1566                                 tex_co[0] = ((x - flow_center[0]) / base_res[0]) / sfs->texture_size;
1567                                 tex_co[1] = ((y - flow_center[1]) / base_res[1]) / sfs->texture_size;
1568                                 tex_co[2] = ((z - flow_center[2]) / base_res[2] - sfs->texture_offset) / sfs->texture_size;
1569                         }
1570                         else if (mloopuv) {
1571                                 const float *uv[3];
1572                                 uv[0] = mloopuv[mlooptri[f_index].tri[0]].uv;
1573                                 uv[1] = mloopuv[mlooptri[f_index].tri[1]].uv;
1574                                 uv[2] = mloopuv[mlooptri[f_index].tri[2]].uv;
1575
1576                                 interp_v2_v2v2v2(tex_co, UNPACK3(uv), weights);
1577
1578                                 /* map between -1.0f and 1.0f */
1579                                 tex_co[0] = tex_co[0] * 2.0f - 1.0f;
1580                                 tex_co[1] = tex_co[1] * 2.0f - 1.0f;
1581                                 tex_co[2] = sfs->texture_offset;
1582                         }
1583                         texres.nor = NULL;
1584                         BKE_texture_get_value(NULL, sfs->noise_texture, tex_co, &texres, false);
1585                         sample_str *= texres.tin;
1586                 }
1587         }
1588
1589         /* multiply initial velocity by emitter influence */
1590         if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY && velocity_map) {
1591                 mul_v3_fl(&velocity_map[index * 3], sample_str);
1592         }
1593
1594         /* apply final influence based on volume factor */
1595         influence_map[index] = MAX2(volume_factor, sample_str);
1596 }
1597
1598 typedef struct EmitFromDMData {
1599         SmokeDomainSettings *sds;
1600         SmokeFlowSettings *sfs;
1601         const MVert *mvert;
1602         const MLoop *mloop;
1603         const MLoopTri *mlooptri;
1604         const MLoopUV *mloopuv;
1605         MDeformVert *dvert;
1606         int defgrp_index;
1607
1608         BVHTreeFromMesh *tree;
1609         int hires_multiplier;
1610         float hr;
1611
1612         EmissionMap *em;
1613         bool has_velocity;
1614         float *vert_vel;
1615
1616         float *flow_center;
1617         int *min, *max, *res;
1618 } EmitFromDMData;
1619
1620 static void emit_from_mesh_task_cb(
1621         void *__restrict userdata,
1622         const int z,
1623         const ParallelRangeTLS *__restrict UNUSED(tls))
1624 {
1625         EmitFromDMData *data = userdata;
1626         EmissionMap *em = data->em;
1627         const int hires_multiplier = data->hires_multiplier;
1628
1629         for (int x = data->min[0]; x < data->max[0]; x++) {
1630                 for (int y = data->min[1]; y < data->max[1]; y++) {
1631                         /* take low res samples where possible */
1632                         if (hires_multiplier <= 1 || !(x % hires_multiplier || y % hires_multiplier || z % hires_multiplier)) {
1633                                 /* get low res space coordinates */
1634                                 const int lx = x / hires_multiplier;
1635                                 const int ly = y / hires_multiplier;
1636                                 const int lz = z / hires_multiplier;
1637
1638                                 const int index = smoke_get_index(
1639                                                       lx - em->min[0], em->res[0], ly - em->min[1], em->res[1], lz - em->min[2]);
1640                                 const float ray_start[3] = {((float)lx) + 0.5f, ((float)ly) + 0.5f, ((float)lz) + 0.5f};
1641
1642                                 sample_mesh(
1643                                         data->sfs, data->mvert, data->mloop, data->mlooptri, data->mloopuv,
1644                                         em->influence, em->velocity, index, data->sds->base_res, data->flow_center,
1645                                         data->tree, ray_start, data->vert_vel, data->has_velocity, data->defgrp_index, data->dvert,
1646                                         (float)lx, (float)ly, (float)lz);
1647                         }
1648
1649                         /* take high res samples if required */
1650                         if (hires_multiplier > 1) {
1651                                 /* get low res space coordinates */
1652                                 const float lx = ((float)x) * data->hr;
1653                                 const float ly = ((float)y) * data->hr;
1654                                 const float lz = ((float)z) * data->hr;
1655
1656                                 const int index = smoke_get_index(
1657                                                       x - data->min[0], data->res[0], y - data->min[1], data->res[1], z - data->min[2]);
1658                                 const float ray_start[3] = {lx + 0.5f * data->hr, ly + 0.5f * data->hr, lz + 0.5f * data->hr};
1659
1660                                 sample_mesh(
1661                                         data->sfs, data->mvert, data->mloop, data->mlooptri, data->mloopuv,
1662                                         em->influence_high, NULL, index, data->sds->base_res, data->flow_center,
1663                                         data->tree, ray_start, data->vert_vel, data->has_velocity, data->defgrp_index, data->dvert,
1664                                         /* x,y,z needs to be always lowres */
1665                                         lx, ly, lz);
1666                         }
1667                 }
1668         }
1669 }
1670
1671 static void emit_from_mesh(Object *flow_ob, SmokeDomainSettings *sds, SmokeFlowSettings *sfs, EmissionMap *em, float dt)
1672 {
1673         if (sfs->mesh) {
1674                 Mesh *me;
1675                 int defgrp_index = sfs->vgroup_density - 1;
1676                 MDeformVert *dvert = NULL;
1677                 MVert *mvert = NULL;
1678                 const MLoopTri *mlooptri = NULL;
1679                 const MLoopUV *mloopuv = NULL;
1680                 const MLoop *mloop = NULL;
1681                 BVHTreeFromMesh treeData = {NULL};
1682                 int numOfVerts, i;
1683                 float flow_center[3] = {0};
1684
1685                 float *vert_vel = NULL;
1686                 int has_velocity = 0;
1687                 int min[3], max[3], res[3];
1688                 int hires_multiplier = 1;
1689
1690                 /* copy mesh for thread safety because we modify it,
1691                  * main issue is its VertArray being modified, then replaced and freed
1692                  */
1693                 me = BKE_mesh_copy_for_eval(sfs->mesh, true);
1694
1695                 /* Duplicate vertices to modify. */
1696                 if (me->mvert) {
1697                         me->mvert = MEM_dupallocN(me->mvert);
1698                         CustomData_set_layer(&me->vdata, CD_MVERT, me->mvert);
1699                 }
1700
1701                 BKE_mesh_ensure_normals(me);
1702                 mvert = me->mvert;
1703                 numOfVerts = me->totvert;
1704                 dvert = CustomData_get_layer(&me->vdata, CD_MDEFORMVERT);
1705                 mloopuv = CustomData_get_layer_named(&me->ldata, CD_MLOOPUV, sfs->uvlayer_name);
1706                 mloop = me->mloop;
1707                 mlooptri = BKE_mesh_runtime_looptri_ensure(me);
1708
1709                 if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY) {
1710                         vert_vel = MEM_callocN(sizeof(float) * numOfVerts * 3, "smoke_flow_velocity");
1711
1712                         if (sfs->numverts != numOfVerts || !sfs->verts_old) {
1713                                 if (sfs->verts_old) MEM_freeN(sfs->verts_old);
1714                                 sfs->verts_old = MEM_callocN(sizeof(float) * numOfVerts * 3, "smoke_flow_verts_old");
1715                                 sfs->numverts = numOfVerts;
1716                         }
1717                         else {
1718                                 has_velocity = 1;
1719                         }
1720                 }
1721
1722                 /*      Transform mesh vertices to
1723                  *   domain grid space for fast lookups */
1724                 for (i = 0; i < numOfVerts; i++) {
1725                         float n[3];
1726                         /* vert pos */
1727                         mul_m4_v3(flow_ob->obmat, mvert[i].co);
1728                         smoke_pos_to_cell(sds, mvert[i].co);
1729                         /* vert normal */
1730                         normal_short_to_float_v3(n, mvert[i].no);
1731                         mul_mat3_m4_v3(flow_ob->obmat, n);
1732                         mul_mat3_m4_v3(sds->imat, n);
1733                         normalize_v3(n);
1734                         normal_float_to_short_v3(mvert[i].no, n);
1735                         /* vert velocity */
1736                         if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY) {
1737                                 float co[3];
1738                                 VECADD(co, mvert[i].co, sds->shift);
1739                                 if (has_velocity) {
1740                                         sub_v3_v3v3(&vert_vel[i * 3], co, &sfs->verts_old[i * 3]);
1741                                         mul_v3_fl(&vert_vel[i * 3], sds->dx / dt);
1742                                 }
1743                                 copy_v3_v3(&sfs->verts_old[i * 3], co);
1744                         }
1745
1746                         /* calculate emission map bounds */
1747                         em_boundInsert(em, mvert[i].co);
1748                 }
1749                 mul_m4_v3(flow_ob->obmat, flow_center);
1750                 smoke_pos_to_cell(sds, flow_center);
1751
1752                 /* check need for high resolution map */
1753                 if ((sds->flags & MOD_SMOKE_HIGHRES) && (sds->highres_sampling == SM_HRES_FULLSAMPLE)) {
1754                         hires_multiplier = sds->amplify + 1;
1755                 }
1756
1757                 /* set emission map */
1758                 clampBoundsInDomain(sds, em->min, em->max, NULL, NULL, (int)ceil(sfs->surface_distance), dt);
1759                 em_allocateData(em, sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY, hires_multiplier);
1760
1761                 /* setup loop bounds */
1762                 for (i = 0; i < 3; i++) {
1763                         min[i] = em->min[i] * hires_multiplier;
1764                         max[i] = em->max[i] * hires_multiplier;
1765                         res[i] = em->res[i] * hires_multiplier;
1766                 }
1767
1768                 if (BKE_bvhtree_from_mesh_get(&treeData, me, BVHTREE_FROM_LOOPTRI, 4)) {
1769                         const float hr = 1.0f / ((float)hires_multiplier);
1770
1771                         EmitFromDMData data = {
1772                                 .sds = sds, .sfs = sfs,
1773                             .mvert = mvert, .mloop = mloop, .mlooptri = mlooptri, .mloopuv = mloopuv,
1774                             .dvert = dvert, .defgrp_index = defgrp_index,
1775                             .tree = &treeData, .hires_multiplier = hires_multiplier, .hr = hr,
1776                             .em = em, .has_velocity = has_velocity, .vert_vel = vert_vel,
1777                             .flow_center = flow_center, .min = min, .max = max, .res = res,
1778                         };
1779
1780                         ParallelRangeSettings settings;
1781                         BLI_parallel_range_settings_defaults(&settings);
1782                         settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC;
1783                         BLI_task_parallel_range(min[2], max[2],
1784                                                 &data,
1785                                                 emit_from_mesh_task_cb,
1786                                                 &settings);
1787                 }
1788                 /* free bvh tree */
1789                 free_bvhtree_from_mesh(&treeData);
1790
1791                 if (vert_vel) {
1792                         MEM_freeN(vert_vel);
1793                 }
1794
1795                 if (me->mvert) {
1796                         MEM_freeN(me->mvert);
1797                 }
1798                 BKE_id_free(NULL, me);
1799         }
1800 }
1801
1802 /**********************************************************
1803  *  Smoke step
1804  **********************************************************/
1805
1806 static void adjustDomainResolution(SmokeDomainSettings *sds, int new_shift[3], EmissionMap *emaps, unsigned int numflowobj, float dt)
1807 {
1808         const int block_size = sds->amplify + 1;
1809         int min[3] = {32767, 32767, 32767}, max[3] = {-32767, -32767, -32767}, res[3];
1810         int total_cells = 1, res_changed = 0, shift_changed = 0;
1811         float min_vel[3], max_vel[3];
1812         int x, y, z;
1813         float *density = smoke_get_density(sds->fluid);
1814         float *fuel = smoke_get_fuel(sds->fluid);
1815         float *bigdensity = smoke_turbulence_get_density(sds->wt);
1816         float *bigfuel = smoke_turbulence_get_fuel(sds->wt);
1817         float *vx = smoke_get_velocity_x(sds->fluid);
1818         float *vy = smoke_get_velocity_y(sds->fluid);
1819         float *vz = smoke_get_velocity_z(sds->fluid);
1820         int wt_res[3];
1821
1822         if (sds->flags & MOD_SMOKE_HIGHRES && sds->wt) {
1823                 smoke_turbulence_get_res(sds->wt, wt_res);
1824         }
1825
1826         INIT_MINMAX(min_vel, max_vel);
1827
1828         /* Calculate bounds for current domain content */
1829         for (x = sds->res_min[0]; x <  sds->res_max[0]; x++)
1830                 for (y =  sds->res_min[1]; y <  sds->res_max[1]; y++)
1831                         for (z =  sds->res_min[2]; z <  sds->res_max[2]; z++)
1832                         {
1833                                 int xn = x - new_shift[0];
1834                                 int yn = y - new_shift[1];
1835                                 int zn = z - new_shift[2];
1836                                 int index;
1837                                 float max_den;
1838
1839                                 /* skip if cell already belongs to new area */
1840                                 if (xn >= min[0] && xn <= max[0] && yn >= min[1] && yn <= max[1] && zn >= min[2] && zn <= max[2])
1841                                         continue;
1842
1843                                 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]);
1844                                 max_den = (fuel) ? MAX2(density[index], fuel[index]) : density[index];
1845
1846                                 /* check high resolution bounds if max density isnt already high enough */
1847                                 if (max_den < sds->adapt_threshold && sds->flags & MOD_SMOKE_HIGHRES && sds->wt) {
1848                                         int i, j, k;
1849                                         /* high res grid index */
1850                                         int xx = (x - sds->res_min[0]) * block_size;
1851                                         int yy = (y - sds->res_min[1]) * block_size;
1852                                         int zz = (z - sds->res_min[2]) * block_size;
1853
1854                                         for (i = 0; i < block_size; i++)
1855                                                 for (j = 0; j < block_size; j++)
1856                                                         for (k = 0; k < block_size; k++)
1857                                                         {
1858                                                                 int big_index = smoke_get_index(xx + i, wt_res[0], yy + j, wt_res[1], zz + k);
1859                                                                 float den = (bigfuel) ? MAX2(bigdensity[big_index], bigfuel[big_index]) : bigdensity[big_index];
1860                                                                 if (den > max_den) {
1861                                                                         max_den = den;
1862                                                                 }
1863                                                         }
1864                                 }
1865
1866                                 /* content bounds (use shifted coordinates) */
1867                                 if (max_den >= sds->adapt_threshold) {
1868                                         if (min[0] > xn) min[0] = xn;
1869                                         if (min[1] > yn) min[1] = yn;
1870                                         if (min[2] > zn) min[2] = zn;
1871                                         if (max[0] < xn) max[0] = xn;
1872                                         if (max[1] < yn) max[1] = yn;
1873                                         if (max[2] < zn) max[2] = zn;
1874                                 }
1875
1876                                 /* velocity bounds */
1877                                 if (min_vel[0] > vx[index]) min_vel[0] = vx[index];
1878                                 if (min_vel[1] > vy[index]) min_vel[1] = vy[index];
1879                                 if (min_vel[2] > vz[index]) min_vel[2] = vz[index];
1880                                 if (max_vel[0] < vx[index]) max_vel[0] = vx[index];
1881                                 if (max_vel[1] < vy[index]) max_vel[1] = vy[index];
1882                                 if (max_vel[2] < vz[index]) max_vel[2] = vz[index];
1883                         }
1884
1885         /* also apply emission maps */
1886         for (int i = 0; i < numflowobj; i++) {
1887                 EmissionMap *em = &emaps[i];
1888
1889                 for (x = em->min[0]; x < em->max[0]; x++)
1890                         for (y = em->min[1]; y < em->max[1]; y++)
1891                                 for (z = em->min[2]; z < em->max[2]; z++)
1892                                 {
1893                                         int index = smoke_get_index(x - em->min[0], em->res[0], y - em->min[1], em->res[1], z - em->min[2]);
1894                                         float max_den = em->influence[index];
1895
1896                                         /* density bounds */
1897                                         if (max_den >= sds->adapt_threshold) {
1898                                                 if (min[0] > x) min[0] = x;
1899                                                 if (min[1] > y) min[1] = y;
1900                                                 if (min[2] > z) min[2] = z;
1901                                                 if (max[0] < x) max[0] = x;
1902                                                 if (max[1] < y) max[1] = y;
1903                                                 if (max[2] < z) max[2] = z;
1904                                         }
1905                                 }
1906         }
1907
1908         /* calculate new bounds based on these values */
1909         mul_v3_fl(min_vel, 1.0f / sds->dx);
1910         mul_v3_fl(max_vel, 1.0f / sds->dx);
1911         clampBoundsInDomain(sds, min, max, min_vel, max_vel, sds->adapt_margin + 1, dt);
1912
1913         for (int i = 0; i < 3; i++) {
1914                 /* calculate new resolution */
1915                 res[i] = max[i] - min[i];
1916                 total_cells *= res[i];
1917
1918                 if (new_shift[i])
1919                         shift_changed = 1;
1920
1921                 /* if no content set minimum dimensions */
1922                 if (res[i] <= 0) {
1923                         int j;
1924                         for (j = 0; j < 3; j++) {
1925                                 min[j] = 0;
1926                                 max[j] = 1;
1927                                 res[j] = 1;
1928                         }
1929                         res_changed = 1;
1930                         total_cells = 1;
1931                         break;
1932                 }
1933                 if (min[i] != sds->res_min[i] || max[i] != sds->res_max[i])
1934                         res_changed = 1;
1935         }
1936
1937         if (res_changed || shift_changed) {
1938                 struct FLUID_3D *fluid_old = sds->fluid;
1939                 struct WTURBULENCE *turb_old = sds->wt;
1940                 /* allocate new fluid data */
1941                 smoke_reallocate_fluid(sds, sds->dx, res, 0);
1942                 if (sds->flags & MOD_SMOKE_HIGHRES) {
1943                         smoke_reallocate_highres_fluid(sds, sds->dx, res, 0);
1944                 }
1945
1946                 /* copy values from old fluid to new */
1947                 if (sds->total_cells > 1 && total_cells > 1) {
1948                         /* low res smoke */
1949                         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;
1950                         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;
1951                         float dummy;
1952                         unsigned char *dummy_p;
1953                         /* high res smoke */
1954                         int wt_res_old[3];
1955                         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;
1956                         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;
1957
1958                         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);
1959                         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);
1960
1961                         if (sds->flags & MOD_SMOKE_HIGHRES) {
1962                                 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);
1963                                 smoke_turbulence_get_res(turb_old, wt_res_old);
1964                                 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);
1965                         }
1966
1967
1968                         for (x = sds->res_min[0]; x < sds->res_max[0]; x++)
1969                                 for (y = sds->res_min[1]; y < sds->res_max[1]; y++)
1970                                         for (z = sds->res_min[2]; z < sds->res_max[2]; z++)
1971                                         {
1972                                                 /* old grid index */
1973                                                 int xo = x - sds->res_min[0];
1974                                                 int yo = y - sds->res_min[1];
1975                                                 int zo = z - sds->res_min[2];
1976                                                 int index_old = smoke_get_index(xo, sds->res[0], yo, sds->res[1], zo);
1977                                                 /* new grid index */
1978                                                 int xn = x - min[0] - new_shift[0];
1979                                                 int yn = y - min[1] - new_shift[1];
1980                                                 int zn = z - min[2] - new_shift[2];
1981                                                 int index_new = smoke_get_index(xn, res[0], yn, res[1], zn);
1982
1983                                                 /* skip if outside new domain */
1984                                                 if (xn < 0 || xn >= res[0] ||
1985                                                     yn < 0 || yn >= res[1] ||
1986                                                     zn < 0 || zn >= res[2])
1987                                                         continue;
1988
1989                                                 /* copy data */
1990                                                 n_dens[index_new] = o_dens[index_old];
1991                                                 /* heat */
1992                                                 if (n_heat && o_heat) {
1993                                                         n_heat[index_new] = o_heat[index_old];
1994                                                         n_heatold[index_new] = o_heatold[index_old];
1995                                                 }
1996                                                 /* fuel */
1997                                                 if (n_fuel && o_fuel) {
1998                                                         n_flame[index_new] = o_flame[index_old];
1999                                                         n_fuel[index_new] = o_fuel[index_old];
2000                                                         n_react[index_new] = o_react[index_old];
2001                                                 }
2002                                                 /* color */
2003                                                 if (o_r && n_r) {
2004                                                         n_r[index_new] = o_r[index_old];
2005                                                         n_g[index_new] = o_g[index_old];
2006                                                         n_b[index_new] = o_b[index_old];
2007                                                 }
2008                                                 n_vx[index_new] = o_vx[index_old];
2009                                                 n_vy[index_new] = o_vy[index_old];
2010                                                 n_vz[index_new] = o_vz[index_old];
2011
2012                                                 if (sds->flags & MOD_SMOKE_HIGHRES && turb_old) {
2013                                                         int i, j, k;
2014                                                         /* old grid index */
2015                                                         int xx_o = xo * block_size;
2016                                                         int yy_o = yo * block_size;
2017                                                         int zz_o = zo * block_size;
2018                                                         /* new grid index */
2019                                                         int xx_n = xn * block_size;
2020                                                         int yy_n = yn * block_size;
2021                                                         int zz_n = zn * block_size;
2022
2023                                                         n_wt_tcu[index_new] = o_wt_tcu[index_old];
2024                                                         n_wt_tcv[index_new] = o_wt_tcv[index_old];
2025                                                         n_wt_tcw[index_new] = o_wt_tcw[index_old];
2026
2027                                                         for (i = 0; i < block_size; i++)
2028                                                                 for (j = 0; j < block_size; j++)
2029                                                                         for (k = 0; k < block_size; k++)
2030                                                                         {
2031                                                                                 int big_index_old = smoke_get_index(xx_o + i, wt_res_old[0], yy_o + j, wt_res_old[1], zz_o + k);
2032                                                                                 int big_index_new = smoke_get_index(xx_n + i, sds->res_wt[0], yy_n + j, sds->res_wt[1], zz_n + k);
2033                                                                                 /* copy data */
2034                                                                                 n_wt_dens[big_index_new] = o_wt_dens[big_index_old];
2035                                                                                 if (n_wt_flame && o_wt_flame) {
2036                                                                                         n_wt_flame[big_index_new] = o_wt_flame[big_index_old];
2037                                                                                         n_wt_fuel[big_index_new] = o_wt_fuel[big_index_old];
2038                                                                                         n_wt_react[big_index_new] = o_wt_react[big_index_old];
2039                                                                                 }
2040                                                                                 if (n_wt_r && o_wt_r) {
2041                                                                                         n_wt_r[big_index_new] = o_wt_r[big_index_old];
2042                                                                                         n_wt_g[big_index_new] = o_wt_g[big_index_old];
2043                                                                                         n_wt_b[big_index_new] = o_wt_b[big_index_old];
2044                                                                                 }
2045                                                                         }
2046                                                 }
2047                                         }
2048                 }
2049                 smoke_free(fluid_old);
2050                 if (turb_old)
2051                         smoke_turbulence_free(turb_old);
2052
2053                 /* set new domain dimensions */
2054                 VECCOPY(sds->res_min, min);
2055                 VECCOPY(sds->res_max, max);
2056                 VECCOPY(sds->res, res);
2057                 sds->total_cells = total_cells;
2058         }
2059 }
2060
2061 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)
2062 {
2063         density[index] = 0.f;
2064         if (heat) {
2065                 heat[index] = 0.f;
2066         }
2067         if (fuel) {
2068                 fuel[index] = 0.f;
2069                 react[index] = 0.f;
2070         }
2071         if (color_r) {
2072                 color_r[index] = 0.f;
2073                 color_g[index] = 0.f;
2074                 color_b[index] = 0.f;
2075         }
2076 }
2077
2078 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)
2079 {
2080         int absolute_flow = (sfs->flags & MOD_SMOKE_FLOW_ABSOLUTE);
2081         float dens_old = density[index];
2082         // float fuel_old = (fuel) ? fuel[index] : 0.0f;  /* UNUSED */
2083         float dens_flow = (sfs->type == MOD_SMOKE_FLOW_TYPE_FIRE) ? 0.0f : emission_value * sfs->density;
2084         float fuel_flow = emission_value * sfs->fuel_amount;
2085         /* add heat */
2086         if (heat && emission_value > 0.0f) {
2087                 heat[index] = ADD_IF_LOWER(heat[index], sfs->temp);
2088         }
2089         /* absolute */
2090         if (absolute_flow) {
2091                 if (sfs->type != MOD_SMOKE_FLOW_TYPE_FIRE) {
2092                         if (dens_flow > density[index])
2093                                 density[index] = dens_flow;
2094                 }
2095                 if (sfs->type != MOD_SMOKE_FLOW_TYPE_SMOKE && fuel && fuel_flow) {
2096                         if (fuel_flow > fuel[index])
2097                                 fuel[index] = fuel_flow;
2098                 }
2099         }
2100         /* additive */
2101         else {
2102                 if (sfs->type != MOD_SMOKE_FLOW_TYPE_FIRE) {
2103                         density[index] += dens_flow;
2104                         CLAMP(density[index], 0.0f, 1.0f);
2105                 }
2106                 if (sfs->type != MOD_SMOKE_FLOW_TYPE_SMOKE && fuel && sfs->fuel_amount) {
2107                         fuel[index] += fuel_flow;
2108                         CLAMP(fuel[index], 0.0f, 10.0f);
2109                 }
2110         }
2111
2112         /* set color */
2113         if (color_r && dens_flow) {
2114                 float total_dens = density[index] / (dens_old + dens_flow);
2115                 color_r[index] = (color_r[index] + sfs->color[0] * dens_flow) * total_dens;
2116                 color_g[index] = (color_g[index] + sfs->color[1] * dens_flow) * total_dens;
2117                 color_b[index] = (color_b[index] + sfs->color[2] * dens_flow) * total_dens;
2118         }
2119
2120         /* set fire reaction coordinate */
2121         if (fuel && fuel[index] > FLT_EPSILON) {
2122                 /* instead of using 1.0 for all new fuel add slight falloff
2123                  * to reduce flow blockiness */
2124                 float value = 1.0f - pow2f(1.0f - emission_value);
2125
2126                 if (value > react[index]) {
2127                         float f = fuel_flow / fuel[index];
2128                         react[index] = value * f + (1.0f - f) * react[index];
2129                         CLAMP(react[index], 0.0f, value);
2130                 }
2131         }
2132 }
2133
2134 static void update_flowsfluids(
2135         Depsgraph *depsgraph, Scene *scene, Object *ob, SmokeDomainSettings *sds, float dt)
2136 {
2137         Object **flowobjs = NULL;
2138         EmissionMap *emaps = NULL;
2139         unsigned int numflowobj = 0;
2140         unsigned int flowIndex;
2141         int new_shift[3] = {0};
2142         int active_fields = sds->active_fields;
2143
2144         /* calculate domain shift for current frame if using adaptive domain */
2145         if (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) {
2146                 int total_shift[3];
2147                 float frame_shift_f[3];
2148                 float ob_loc[3] = {0};
2149
2150                 mul_m4_v3(ob->obmat, ob_loc);
2151
2152                 VECSUB(frame_shift_f, ob_loc, sds->prev_loc);
2153                 copy_v3_v3(sds->prev_loc, ob_loc);
2154                 /* convert global space shift to local "cell" space */
2155                 mul_mat3_m4_v3(sds->imat, frame_shift_f);
2156                 frame_shift_f[0] = frame_shift_f[0] / sds->cell_size[0];
2157                 frame_shift_f[1] = frame_shift_f[1] / sds->cell_size[1];
2158                 frame_shift_f[2] = frame_shift_f[2] / sds->cell_size[2];
2159                 /* add to total shift */
2160                 VECADD(sds->shift_f, sds->shift_f, frame_shift_f);
2161                 /* convert to integer */
2162                 total_shift[0] = floor(sds->shift_f[0]);
2163                 total_shift[1] = floor(sds->shift_f[1]);
2164                 total_shift[2] = floor(sds->shift_f[2]);
2165                 VECSUB(new_shift, total_shift, sds->shift);
2166                 copy_v3_v3_int(sds->shift, total_shift);
2167
2168                 /* calculate new domain boundary points so that smoke doesn't slide on sub-cell movement */
2169                 sds->p0[0] = sds->dp0[0] - sds->cell_size[0] * (sds->shift_f[0] - total_shift[0] - 0.5f);
2170                 sds->p0[1] = sds->dp0[1] - sds->cell_size[1] * (sds->shift_f[1] - total_shift[1] - 0.5f);
2171                 sds->p0[2] = sds->dp0[2] - sds->cell_size[2] * (sds->shift_f[2] - total_shift[2] - 0.5f);
2172                 sds->p1[0] = sds->p0[0] + sds->cell_size[0] * sds->base_res[0];
2173                 sds->p1[1] = sds->p0[1] + sds->cell_size[1] * sds->base_res[1];
2174                 sds->p1[2] = sds->p0[2] + sds->cell_size[2] * sds->base_res[2];
2175         }
2176
2177         flowobjs = BKE_collision_objects_create(depsgraph, ob, sds->fluid_group, &numflowobj, eModifierType_Smoke);
2178
2179         /* init emission maps for each flow */
2180         emaps = MEM_callocN(sizeof(struct EmissionMap) * numflowobj, "smoke_flow_maps");
2181
2182         /* Prepare flow emission maps */
2183         for (flowIndex = 0; flowIndex < numflowobj; flowIndex++)
2184         {
2185                 Object *collob = flowobjs[flowIndex];
2186                 SmokeModifierData *smd2 = (SmokeModifierData *)modifiers_findByType(collob, eModifierType_Smoke);
2187
2188                 // check for initialized smoke object
2189                 if ((smd2->type & MOD_SMOKE_TYPE_FLOW) && smd2->flow)
2190                 {
2191                         // we got nice flow object
2192                         SmokeFlowSettings *sfs = smd2->flow;
2193                         int subframes = sfs->subframes;
2194                         EmissionMap *em = &emaps[flowIndex];
2195
2196                         /* just sample flow directly to emission map if no subframes */
2197                         if (!subframes) {
2198                                 if (sfs->source == MOD_SMOKE_FLOW_SOURCE_PARTICLES) {
2199                                         emit_from_particles(collob, sds, sfs, em, depsgraph, scene, dt);
2200                                 }
2201                                 else {
2202                                         emit_from_mesh(collob, sds, sfs, em, dt);
2203                                 }
2204                         }
2205                         /* sample subframes */
2206                         else {
2207 #if 0
2208                                 int scene_frame = (int)DEG_get_ctime(depsgraph);
2209 #endif
2210                                 // float scene_subframe = scene->r.subframe;  // UNUSED
2211                                 int subframe;
2212                                 for (subframe = 0; subframe <= subframes; subframe++) {
2213                                         EmissionMap em_temp = {NULL};
2214                                         float sample_size = 1.0f / (float)(subframes+1);
2215 #if 0
2216                                         float prev_frame_pos = sample_size * (float)(subframe+1);
2217 #endif
2218                                         float sdt = dt * sample_size;
2219                                         int hires_multiplier = 1;
2220
2221                                         if ((sds->flags & MOD_SMOKE_HIGHRES) && (sds->highres_sampling == SM_HRES_FULLSAMPLE)) {
2222                                                 hires_multiplier = sds->amplify + 1;
2223                                         }
2224
2225                                         /* TODO: setting the scene frame no longer works with the new depsgraph. */
2226 #if 0
2227                                         /* set scene frame to match previous frame + subframe
2228                                          * or use current frame for last sample */
2229                                         if (subframe < subframes) {
2230                                                 scene->r.cfra = scene_frame - 1;
2231                                                 scene->r.subframe = prev_frame_pos;
2232                                         }
2233                                         else {
2234                                                 scene->r.cfra = scene_frame;
2235                                                 scene->r.subframe = 0.0f;
2236                                         }
2237 #endif
2238
2239                                         if (sfs->source == MOD_SMOKE_FLOW_SOURCE_PARTICLES) {
2240                                                 /* emit_from_particles() updates timestep internally */
2241                                                 emit_from_particles(collob, sds, sfs, &em_temp, depsgraph, scene, sdt);
2242                                                 if (!(sfs->flags & MOD_SMOKE_FLOW_USE_PART_SIZE)) {
2243                                                         hires_multiplier = 1;
2244                                                 }
2245                                         }
2246                                         else { /* MOD_SMOKE_FLOW_SOURCE_MESH */
2247                                                 /* update flow object frame */
2248                                                 BLI_mutex_lock(&object_update_lock);
2249                                                 BKE_object_modifier_update_subframe(depsgraph, scene, collob, true, 5, DEG_get_ctime(depsgraph), eModifierType_Smoke);
2250                                                 BLI_mutex_unlock(&object_update_lock);
2251
2252                                                 /* apply flow */
2253                                                 emit_from_mesh(collob, sds, sfs, &em_temp, sdt);
2254                                         }
2255
2256                                         /* combine emission maps */
2257                                         em_combineMaps(em, &em_temp, hires_multiplier, !(sfs->flags & MOD_SMOKE_FLOW_ABSOLUTE), sample_size);
2258                                         em_freeData(&em_temp);
2259                                 }
2260                         }
2261
2262                         /* update required data fields */
2263                         if (em->total_cells && sfs->type != MOD_SMOKE_FLOW_TYPE_OUTFLOW) {
2264                                 /* activate heat field if flow produces any heat */
2265                                 if (sfs->temp) {
2266                                         active_fields |= SM_ACTIVE_HEAT;
2267                                 }
2268                                 /* activate fuel field if flow adds any fuel */
2269                                 if (sfs->type != MOD_SMOKE_FLOW_TYPE_SMOKE && sfs->fuel_amount) {
2270                                         active_fields |= SM_ACTIVE_FIRE;
2271                                 }
2272                                 /* activate color field if flows add smoke with varying colors */
2273                                 if (sfs->type != MOD_SMOKE_FLOW_TYPE_FIRE && sfs->density) {
2274                                         if (!(active_fields & SM_ACTIVE_COLOR_SET)) {
2275                                                 copy_v3_v3(sds->active_color, sfs->color);
2276                                                 active_fields |= SM_ACTIVE_COLOR_SET;
2277                                         }
2278                                         else if (!equals_v3v3(sds->active_color, sfs->color)) {
2279                                                 copy_v3_v3(sds->active_color, sfs->color);
2280                                                 active_fields |= SM_ACTIVE_COLORS;
2281                                         }
2282                                 }
2283                         }
2284                 }
2285         }
2286
2287         /* monitor active fields based on domain settings */
2288         /* if domain has fire, activate new fields if required */
2289         if (active_fields & SM_ACTIVE_FIRE) {
2290                 /* heat is always needed for fire */
2291                 active_fields |= SM_ACTIVE_HEAT;
2292                 /* also activate colors if domain smoke color differs from active color */
2293                 if (!(active_fields & SM_ACTIVE_COLOR_SET)) {
2294                         copy_v3_v3(sds->active_color, sds->flame_smoke_color);
2295                         active_fields |= SM_ACTIVE_COLOR_SET;
2296                 }
2297                 else if (!equals_v3v3(sds->active_color, sds->flame_smoke_color)) {
2298                         copy_v3_v3(sds->active_color, sds->flame_smoke_color);
2299                         active_fields |= SM_ACTIVE_COLORS;
2300                 }
2301         }
2302
2303         /* Adjust domain size if needed */
2304         if (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) {
2305                 adjustDomainResolution(sds, new_shift, emaps, numflowobj, dt);
2306         }
2307
2308         /* Initialize new data fields if any */
2309         if (active_fields & SM_ACTIVE_HEAT) {
2310                 smoke_ensure_heat(sds->fluid);
2311         }
2312         if (active_fields & SM_ACTIVE_FIRE) {
2313                 smoke_ensure_fire(sds->fluid, sds->wt);
2314         }
2315         if (active_fields & SM_ACTIVE_COLORS) {
2316                 /* initialize all smoke with "active_color" */
2317                 smoke_ensure_colors(sds->fluid, sds->wt, sds->active_color[0], sds->active_color[1], sds->active_color[2]);
2318         }
2319         sds->active_fields = active_fields;
2320
2321         /* Apply emission data */
2322         if (sds->fluid) {
2323                 for (flowIndex = 0; flowIndex < numflowobj; flowIndex++)
2324                 {
2325                         Object *collob = flowobjs[flowIndex];
2326                         SmokeModifierData *smd2 = (SmokeModifierData *)modifiers_findByType(collob, eModifierType_Smoke);
2327
2328                         // check for initialized smoke object
2329                         if ((smd2->type & MOD_SMOKE_TYPE_FLOW) && smd2->flow)
2330                         {
2331                                 // we got nice flow object
2332                                 SmokeFlowSettings *sfs = smd2->flow;
2333                                 EmissionMap *em = &emaps[flowIndex];
2334
2335                                 float *density = smoke_get_density(sds->fluid);
2336                                 float *color_r = smoke_get_color_r(sds->fluid);
2337                                 float *color_g = smoke_get_color_g(sds->fluid);
2338                                 float *color_b = smoke_get_color_b(sds->fluid);
2339                                 float *fuel = smoke_get_fuel(sds->fluid);
2340                                 float *react = smoke_get_react(sds->fluid);
2341                                 float *bigdensity = smoke_turbulence_get_density(sds->wt);
2342                                 float *bigfuel = smoke_turbulence_get_fuel(sds->wt);
2343                                 float *bigreact = smoke_turbulence_get_react(sds->wt);
2344                                 float *bigcolor_r = smoke_turbulence_get_color_r(sds->wt);
2345                                 float *bigcolor_g = smoke_turbulence_get_color_g(sds->wt);
2346                                 float *bigcolor_b = smoke_turbulence_get_color_b(sds->wt);
2347                                 float *heat = smoke_get_heat(sds->fluid);
2348                                 float *velocity_x = smoke_get_velocity_x(sds->fluid);
2349                                 float *velocity_y = smoke_get_velocity_y(sds->fluid);
2350                                 float *velocity_z = smoke_get_velocity_z(sds->fluid);
2351                                 //unsigned char *obstacle = smoke_get_obstacle(sds->fluid);
2352                                 // DG TODO UNUSED unsigned char *obstacleAnim = smoke_get_obstacle_anim(sds->fluid);
2353                                 int bigres[3];
2354                                 float *velocity_map = em->velocity;
2355                                 float *emission_map = em->influence;
2356                                 float *emission_map_high = em->influence_high;
2357
2358                                 int ii, jj, kk, gx, gy, gz, ex, ey, ez, dx, dy, dz, block_size;
2359                                 size_t e_index, d_index, index_big;
2360
2361                                 // loop through every emission map cell
2362                                 for (gx = em->min[0]; gx < em->max[0]; gx++)
2363                                         for (gy = em->min[1]; gy < em->max[1]; gy++)
2364                                                 for (gz = em->min[2]; gz < em->max[2]; gz++)
2365                                                 {
2366                                                         /* get emission map index */
2367                                                         ex = gx - em->min[0];
2368                                                         ey = gy - em->min[1];
2369                                                         ez = gz - em->min[2];
2370                                                         e_index = smoke_get_index(ex, em->res[0], ey, em->res[1], ez);
2371
2372                                                         /* get domain index */
2373                                                         dx = gx - sds->res_min[0];
2374                                                         dy = gy - sds->res_min[1];
2375                                                         dz = gz - sds->res_min[2];
2376                                                         d_index = smoke_get_index(dx, sds->res[0], dy, sds->res[1], dz);
2377                                                         /* make sure emission cell is inside the new domain boundary */
2378                                                         if (dx < 0 || dy < 0 || dz < 0 || dx >= sds->res[0] || dy >= sds->res[1] || dz >= sds->res[2]) continue;
2379
2380                                                         if (sfs->type == MOD_SMOKE_FLOW_TYPE_OUTFLOW) { // outflow
2381                                                                 apply_outflow_fields(d_index, density, heat, fuel, react, color_r, color_g, color_b);
2382                                                         }
2383                                                         else { // inflow
2384                                                                 apply_inflow_fields(sfs, emission_map[e_index], d_index, density, heat, fuel, react, color_r, color_g, color_b);
2385
2386                                                                 /* initial velocity */
2387                                                                 if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY) {
2388                                                                         velocity_x[d_index] = ADD_IF_LOWER(velocity_x[d_index], velocity_map[e_index * 3]);
2389                                                                         velocity_y[d_index] = ADD_IF_LOWER(velocity_y[d_index], velocity_map[e_index * 3 + 1]);
2390                                                                         velocity_z[d_index] = ADD_IF_LOWER(velocity_z[d_index], velocity_map[e_index * 3 + 2]);
2391                                                                 }
2392                                                         }
2393
2394                                                         /* loop through high res blocks if high res enabled */
2395                                                         if (bigdensity) {
2396                                                                 // neighbor cell emission densities (for high resolution smoke smooth interpolation)
2397                                                                 float c000, c001, c010, c011,  c100, c101, c110, c111;
2398
2399                                                                 smoke_turbulence_get_res(sds->wt, bigres);
2400                                                                 block_size = sds->amplify + 1;  // high res block size
2401
2402                                                                 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;
2403                                                                 c001 = (ex > 0 && ey > 0) ? emission_map[smoke_get_index(ex - 1, em->res[0], ey - 1, em->res[1], ez)] : 0;
2404                                                                 c010 = (ex > 0 && ez > 0) ? emission_map[smoke_get_index(ex - 1, em->res[0], ey, em->res[1], ez - 1)] : 0;
2405                                                                 c011 = (ex > 0) ? emission_map[smoke_get_index(ex - 1, em->res[0], ey, em->res[1], ez)] : 0;
2406
2407                                                                 c100 = (ey > 0 && ez > 0) ? emission_map[smoke_get_index(ex, em->res[0], ey - 1, em->res[1], ez - 1)] : 0;
2408                                                                 c101 = (ey > 0) ? emission_map[smoke_get_index(ex, em->res[0], ey - 1, em->res[1], ez)] : 0;
2409                                                                 c110 = (ez > 0) ? emission_map[smoke_get_index(ex, em->res[0], ey, em->res[1], ez - 1)] : 0;
2410                                                                 c111 = emission_map[smoke_get_index(ex, em->res[0], ey, em->res[1], ez)]; // this cell
2411
2412                                                                 for (ii = 0; ii < block_size; ii++)
2413                                                                         for (jj = 0; jj < block_size; jj++)
2414                                                                                 for (kk = 0; kk < block_size; kk++)
2415                                                                                 {
2416
2417                                                                                         float fx, fy, fz, interpolated_value;
2418                                                                                         int shift_x = 0, shift_y = 0, shift_z = 0;
2419
2420
2421                                                                                         /* Use full sample emission map if enabled and available */
2422                                                                                         if ((sds->highres_sampling == SM_HRES_FULLSAMPLE) && emission_map_high) {
2423                                                                                                 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
2424                                                                                         }
2425                                                                                         else if (sds->highres_sampling == SM_HRES_NEAREST) {
2426                                                                                                 /* without interpolation use same low resolution
2427                                                                                                  * block value for all hi-res blocks */
2428                                                                                                 interpolated_value = c111;
2429                                                                                         }
2430                                                                                         /* Fall back to interpolated */
2431                                                                                         else
2432                                                                                         {
2433                                                                                                 /* get relative block position
2434                                                                                                  * for interpolation smoothing */
2435                                                                                                 fx = (float)ii / block_size + 0.5f / block_size;
2436                                                                                                 fy = (float)jj / block_size + 0.5f / block_size;
2437                                                                                                 fz = (float)kk / block_size + 0.5f / block_size;
2438
2439                                                                                                 /* calculate trilinear interpolation */
2440                                                                                                 interpolated_value = c000 * (1 - fx) * (1 - fy) * (1 - fz) +
2441                                                                                                                      c100 * fx * (1 - fy) * (1 - fz) +
2442                                                                                                                      c010 * (1 - fx) * fy * (1 - fz) +
2443                                                                                                                      c001 * (1 - fx) * (1 - fy) * fz +
2444                                                                                                                      c101 * fx * (1 - fy) * fz +
2445                                                                                                                      c011 * (1 - fx) * fy * fz +
2446                                                                                                                      c110 * fx * fy * (1 - fz) +
2447                                                                                                                      c111 * fx * fy * fz;
2448
2449
2450                                                                                                 /* add some contrast / sharpness
2451                                                                                                  * depending on hi-res block size */
2452                                                                                                 interpolated_value = (interpolated_value - 0.4f) * (block_size / 2) + 0.4f;
2453                                                                                                 CLAMP(interpolated_value, 0.0f, 1.0f);
2454
2455                                                                                                 /* shift smoke block index
2456                                                                                                  * (because pixel center is actually
2457                                                                                                  * in halfway of the low res block) */
2458                                                                                                 shift_x = (dx < 1) ? 0 : block_size / 2;
2459                                                                                                 shift_y = (dy < 1) ? 0 : block_size / 2;
2460                                                                                                 shift_z = (dz < 1) ? 0 : block_size / 2;
2461                                                                                         }
2462
2463                                                                                         /* get shifted index for current high resolution block */
2464                                                                                         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);
2465
2466                                                                                         if (sfs->type == MOD_SMOKE_FLOW_TYPE_OUTFLOW) { // outflow
2467                                                                                                 if (interpolated_value) {
2468                                                                                                         apply_outflow_fields(index_big, bigdensity, NULL, bigfuel, bigreact, bigcolor_r, bigcolor_g, bigcolor_b);
2469                                                                                                 }
2470                                                                                         }
2471                                                                                         else { // inflow
2472                                                                                                 apply_inflow_fields(sfs, interpolated_value, index_big, bigdensity, NULL, bigfuel, bigreact, bigcolor_r, bigcolor_g, bigcolor_b);
2473                                                                                         }
2474                                                                                 } // hires loop
2475                                                         }  // bigdensity
2476                                                 } // low res loop
2477
2478                                 // free emission maps
2479                                 em_freeData(em);
2480
2481                         } // end emission
2482                 }
2483         }
2484
2485         BKE_collision_objects_free(flowobjs);
2486         if (emaps)
2487                 MEM_freeN(emaps);
2488 }
2489
2490 typedef struct UpdateEffectorsData {
2491         Scene *scene;
2492         SmokeDomainSettings *sds;
2493         ListBase *effectors;
2494
2495         float *density;
2496         float *fuel;
2497         float *force_x;
2498         float *force_y;
2499         float *force_z;
2500         float *velocity_x;
2501         float *velocity_y;
2502         float *velocity_z;
2503         unsigned char *obstacle;
2504 } UpdateEffectorsData;
2505
2506 static void update_effectors_task_cb(
2507         void *__restrict userdata,
2508         const int x,
2509         const ParallelRangeTLS *__restrict UNUSED(tls))
2510 {
2511         UpdateEffectorsData *data = userdata;
2512         SmokeDomainSettings *sds = data->sds;
2513
2514         for (int y = 0; y < sds->res[1]; y++) {
2515                 for (int z = 0; z < sds->res[2]; z++)
2516                 {
2517                         EffectedPoint epoint;
2518                         float mag;
2519                         float voxelCenter[3] = {0, 0, 0}, vel[3] = {0, 0, 0}, retvel[3] = {0, 0, 0};
2520                         const unsigned int index = smoke_get_index(x, sds->res[0], y, sds->res[1], z);
2521
2522                         if (((data->fuel ? MAX2(data->density[index], data->fuel[index]) : data->density[index]) < FLT_EPSILON) ||
2523                             data->obstacle[index])
2524                         {
2525                                 continue;
2526                         }
2527
2528                         vel[0] = data->velocity_x[index];
2529                         vel[1] = data->velocity_y[index];
2530                         vel[2] = data->velocity_z[index];
2531
2532                         /* convert vel to global space */
2533                         mag = len_v3(vel);
2534                         mul_mat3_m4_v3(sds->obmat, vel);
2535                         normalize_v3(vel);
2536                         mul_v3_fl(vel, mag);
2537
2538                         voxelCenter[0] = sds->p0[0] + sds->cell_size[0] * ((float)(x + sds->res_min[0]) + 0.5f);
2539                         voxelCenter[1] = sds->p0[1] + sds->cell_size[1] * ((float)(y + sds->res_min[1]) + 0.5f);
2540                         voxelCenter[2] = sds->p0[2] + sds->cell_size[2] * ((float)(z + sds->res_min[2]) + 0.5f);
2541                         mul_m4_v3(sds->obmat, voxelCenter);
2542
2543                         pd_point_from_loc(data->scene, voxelCenter, vel, index, &epoint);
2544                         BKE_effectors_apply(data->effectors, NULL, sds->effector_weights, &epoint, retvel, NULL);
2545
2546                         /* convert retvel to local space */
2547                         mag = len_v3(retvel);
2548                         mul_mat3_m4_v3(sds->imat, retvel);
2549                         normalize_v3(retvel);
2550                         mul_v3_fl(retvel, mag);
2551
2552                         // TODO dg - do in force!
2553                         data->force_x[index] = min_ff(max_ff(-1.0f, retvel[0] * 0.2f), 1.0f);
2554                         data->force_y[index] = min_ff(max_ff(-1.0f, retvel[1] * 0.2f), 1.0f);
2555                         data->force_z[index] = min_ff(max_ff(-1.0f, retvel[2] * 0.2f), 1.0f);
2556                 }
2557         }
2558 }
2559
2560 static void update_effectors(Depsgraph *depsgraph, Scene *scene, Object *ob, SmokeDomainSettings *sds, float UNUSED(dt))
2561 {
2562         ListBase *effectors;
2563         /* make sure smoke flow influence is 0.0f */
2564         sds->effector_weights->weight[PFIELD_SMOKEFLOW] = 0.0f;
2565         effectors = BKE_effectors_create(depsgraph, ob, NULL, sds->effector_weights);
2566
2567         if (effectors) {
2568                 // precalculate wind forces
2569                 UpdateEffectorsData data;
2570                 data.scene = scene;
2571                 data.sds = sds;
2572                 data.effectors = effectors;
2573                 data.density = smoke_get_density(sds->fluid);
2574                 data.fuel = smoke_get_fuel(sds->fluid);
2575                 data.force_x = smoke_get_force_x(sds->fluid);
2576                 data.force_y = smoke_get_force_y(sds->fluid);
2577                 data.force_z = smoke_get_force_z(sds->fluid);
2578                 data.velocity_x = smoke_get_velocity_x(sds->fluid);
2579                 data.velocity_y = smoke_get_velocity_y(sds->fluid);
2580                 data.velocity_z = smoke_get_velocity_z(sds->fluid);
2581                 data.obstacle = smoke_get_obstacle(sds->fluid);
2582
2583                 ParallelRangeSettings settings;
2584                 BLI_parallel_range_settings_defaults(&settings);
2585                 settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC;
2586                 BLI_task_parallel_range(0, sds->res[0],
2587                                         &data,
2588                                         update_effectors_task_cb,
2589                                         &settings);
2590         }
2591
2592         BKE_effectors_free(effectors);
2593 }
2594
2595 static void step(
2596         Depsgraph *depsgraph,
2597         Scene *scene, Object *ob, SmokeModifierData *smd, Mesh *domain_me, float fps)
2598 {
2599         SmokeDomainSettings *sds = smd->domain;
2600         /* stability values copied from wturbulence.cpp */
2601         const int maxSubSteps = 25;
2602         float maxVel;
2603         // maxVel should be 1.5 (1.5 cell max movement) * dx (cell size)
2604
2605         float dt;
2606         float maxVelMag = 0.0f;
2607         int totalSubsteps;
2608         int substep = 0;
2609         float dtSubdiv;
2610         float gravity[3] = {0.0f, 0.0f, -1.0f};
2611         float gravity_mag;
2612
2613         /* update object state */
2614         invert_m4_m4(sds->imat, ob->obmat);
2615         copy_m4_m4(sds->obmat, ob->obmat);
2616         smoke_set_domain_from_mesh(sds, ob, domain_me, (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) != 0);
2617
2618         /* use global gravity if enabled */
2619         if (scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) {
2620                 copy_v3_v3(gravity, scene->physics_settings.gravity);
2621                 /* map default value to 1.0 */
2622                 mul_v3_fl(gravity, 1.0f / 9.810f);
2623         }
2624         /* convert gravity to domain space */
2625         gravity_mag = len_v3(gravity);
2626         mul_mat3_m4_v3(sds->imat, gravity);
2627         normalize_v3(gravity);
2628         mul_v3_fl(gravity, gravity_mag);
2629
2630         /* adapt timestep for different framerates, dt = 0.1 is at 25fps */
2631         dt = DT_DEFAULT * (25.0f / fps);
2632         // maximum timestep/"CFL" constraint: dt < 5.0 *dx / maxVel
2633         maxVel = (sds->dx * 5.0f);
2634
2635         maxVelMag = sqrtf(maxVelMag) * dt * sds->time_scale;
2636         totalSubsteps = (int)((maxVelMag / maxVel) + 1.0f); /* always round up */
2637         totalSubsteps = (totalSubsteps < 1) ? 1 : totalSubsteps;
2638         totalSubsteps = (totalSubsteps > maxSubSteps) ? maxSubSteps : totalSubsteps;
2639
2640         /* Disable substeps for now, since it results in numerical instability */
2641         totalSubsteps = 1.0f;
2642
2643         dtSubdiv = (float)dt / (float)totalSubsteps;
2644
2645         // printf("totalSubsteps: %d, maxVelMag: %f, dt: %f\n", totalSubsteps, maxVelMag, dt);
2646
2647         for (substep = 0; substep < totalSubsteps; substep++)
2648         {
2649                 // calc animated obstacle velocities
2650                 update_flowsfluids(depsgraph, scene, ob, sds, dtSubdiv);
2651                 update_obstacles(depsgraph, ob, sds, dtSubdiv, substep, totalSubsteps);
2652
2653                 if (sds->total_cells > 1) {
2654                         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
2655                         smoke_step(sds->fluid, gravity, dtSubdiv);
2656                 }
2657         }
2658 }
2659
2660 static Mesh *createDomainGeometry(SmokeDomainSettings *sds, Object *ob)
2661 {
2662         Mesh *result;
2663         MVert *mverts;
2664         MPoly *mpolys;
2665         MLoop *mloops;
2666         float min[3];
2667         float max[3];
2668         float *co;
2669         MPoly *mp;
2670         MLoop *ml;
2671
2672         int num_verts = 8;
2673         int num_faces = 6;
2674         int i;
2675         float ob_loc[3] = {0};
2676         float ob_cache_loc[3] = {0};
2677
2678         /* dont generate any mesh if there isnt any content */
2679         if (sds->total_cells <= 1) {
2680                 num_verts = 0;
2681                 num_faces = 0;
2682         }
2683
2684         result = BKE_mesh_new_nomain(num_verts, 0, 0, num_faces * 4, num_faces);
2685         mverts = result->mvert;
2686         mpolys = result->mpoly;
2687         mloops = result->mloop;
2688
2689         if (num_verts) {
2690                 /* volume bounds */
2691                 VECMADD(min, sds->p0, sds->cell_size, sds->res_min);
2692                 VECMADD(max, sds->p0, sds->cell_size, sds->res_max);
2693
2694                 /* set vertices */
2695                 /* top slab */
2696                 co = mverts[0].co; co[0] = min[0]; co[1] = min[1]; co[2] = max[2];
2697                 co = mverts[1].co; co[0] = max[0]; co[1] = min[1]; co[2] = max[2];
2698                 co = mverts[2].co; co[0] = max[0]; co[1] = max[1]; co[2] = max[2];
2699                 co = mverts[3].co; co[0] = min[0]; co[1] = max[1]; co[2] = max[2];
2700                 /* bottom slab */
2701                 co = mverts[4].co; co[0] = min[0]; co[1] = min[1]; co[2] = min[2];
2702                 co = mverts[5].co; co[0] = max[0]; co[1] = min[1]; co[2] = min[2];
2703                 co = mverts[6].co; co[0] = max[0]; co[1] = max[1]; co[2] = min[2];
2704                 co = mverts[7].co; co[0] = min[0]; co[1] = max[1]; co[2] = min[2];
2705
2706                 /* create faces */
2707                 /* top */
2708                 mp = &mpolys[0]; ml = &mloops[0 * 4]; mp->loopstart = 0 * 4; mp->totloop = 4;
2709                 ml[0].v = 0; ml[1].v = 1; ml[2].v = 2; ml[3].v = 3;
2710                 /* right */
2711                 mp = &mpolys[1]; ml = &mloops[1 * 4]; mp->loopstart = 1 * 4; mp->totloop = 4;
2712                 ml[0].v = 2; ml[1].v = 1; ml[2].v = 5; ml[3].v = 6;
2713                 /* bottom */
2714                 mp = &mpolys[2]; ml = &mloops[2 * 4]; mp->loopstart = 2 * 4; mp->totloop = 4;
2715                 ml[0].v = 7; ml[1].v = 6; ml[2].v = 5; ml[3].v = 4;
2716                 /* left */
2717                 mp = &mpolys[3]; ml = &mloops[3 * 4]; mp->loopstart = 3 * 4; mp->totloop = 4;
2718                 ml[0].v = 0; ml[1].v = 3; ml[2].v = 7; ml[3].v = 4;
2719                 /* front */
2720                 mp = &mpolys[4]; ml = &mloops[4 * 4]; mp->loopstart = 4 * 4; mp->totloop = 4;
2721                 ml[0].v = 3; ml[1].v = 2; ml[2].v = 6; ml[3].v = 7;
2722                 /* back */
2723                 mp = &mpolys[5]; ml = &mloops[5 * 4]; mp->loopstart = 5 * 4; mp->totloop = 4;
2724                 ml[0].v = 1; ml[1].v = 0; ml[2].v = 4; ml[3].v = 5;
2725
2726                 /* calculate required shift to match domain's global position
2727                  * it was originally simulated at (if object moves without smoke step) */
2728                 invert_m4_m4(ob->imat, ob->obmat);
2729                 mul_m4_v3(ob->obmat, ob_loc);
2730                 mul_m4_v3(sds->obmat, ob_cache_loc);
2731                 VECSUB(sds->obj_shift_f, ob_cache_loc, ob_loc);
2732                 /* convert shift to local space and apply to vertices */
2733                 mul_mat3_m4_v3(ob->imat, sds->obj_shift_f);
2734                 /* apply */
2735                 for (i = 0; i < num_verts; i++) {
2736                         add_v3_v3(mverts[i].co, sds->obj_shift_f);
2737                 }
2738         }
2739
2740         BKE_mesh_calc_edges(result, false, false);
2741         result->runtime.cd_dirty_vert |= CD_MASK_NORMAL;
2742         return result;
2743 }
2744
2745 static void smokeModifier_process(
2746         SmokeModifierData *smd, Depsgraph *depsgraph, Scene *scene, Object *ob, Mesh *me)
2747 {
2748         const int scene_framenr = (int)DEG_get_ctime(depsgraph);
2749
2750         if ((smd->type & MOD_SMOKE_TYPE_FLOW))
2751         {
2752                 if (scene_framenr >= smd->time)
2753                         smokeModifier_init(smd, ob, scene_framenr, me);
2754
2755                 if (smd->flow->mesh) BKE_id_free(NULL, smd->flow->mesh);
2756                 smd->flow->mesh = BKE_mesh_copy_for_eval(me, false);
2757
2758                 if (scene_framenr > smd->time)
2759                 {
2760                         smd->time = scene_framenr;
2761                 }
2762                 else if (scene_framenr < smd->time)
2763                 {
2764                         smd->time = scene_framenr;
2765                         smokeModifier_reset_ex(smd, false);
2766                 }
2767         }
2768         else if (smd->type & MOD_SMOKE_TYPE_COLL)
2769         {
2770                 if (scene_framenr >= smd->time)
2771                         smokeModifier_init(smd, ob, scene_framenr, me);
2772
2773                 if (smd->coll)
2774                 {
2775                         if (smd->coll->mesh)
2776                                 BKE_id_free(NULL, smd->coll->mesh);