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