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