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