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