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