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