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