more macro --> bli math lib replacements.
[blender.git] / source / blender / blenkernel / intern / smoke.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Daniel Genrich
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/smoke.c
29  *  \ingroup bke
30  */
31
32
33 /* Part of the code copied from elbeem fluid library, copyright by Nils Thuerey */
34
35 #include <GL/glew.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include <float.h>
40 #include <math.h>
41 #include <stdio.h>
42 #include <string.h> /* memset */
43
44 #include "BLI_linklist.h"
45 #include "BLI_rand.h"
46 #include "BLI_jitter.h"
47 #include "BLI_blenlib.h"
48 #include "BLI_math.h"
49 #include "BLI_edgehash.h"
50 #include "BLI_kdtree.h"
51 #include "BLI_kdopbvh.h"
52 #include "BLI_utildefines.h"
53
54 #include "BKE_bvhutils.h"
55 #include "BKE_cdderivedmesh.h"
56 #include "BKE_customdata.h"
57 #include "BKE_DerivedMesh.h"
58 #include "BKE_effect.h"
59 #include "BKE_modifier.h"
60 #include "BKE_particle.h"
61 #include "BKE_pointcache.h"
62 #include "BKE_smoke.h"
63
64
65 #include "DNA_customdata_types.h"
66 #include "DNA_group_types.h"
67 #include "DNA_lamp_types.h"
68 #include "DNA_mesh_types.h"
69 #include "DNA_meshdata_types.h"
70 #include "DNA_modifier_types.h"
71 #include "DNA_object_types.h"
72 #include "DNA_particle_types.h"
73 #include "DNA_scene_types.h"
74 #include "DNA_smoke_types.h"
75
76 #include "smoke_API.h"
77
78 #include "BKE_smoke.h"
79
80 #ifdef WITH_SMOKE
81
82 #ifdef _WIN32
83 #include <time.h>
84 #include <stdio.h>
85 #include <conio.h>
86 #include <windows.h>
87
88 static LARGE_INTEGER liFrequency;
89 static LARGE_INTEGER liStartTime;
90 static LARGE_INTEGER liCurrentTime;
91
92 static void tstart ( void )
93 {
94         QueryPerformanceFrequency ( &liFrequency );
95         QueryPerformanceCounter ( &liStartTime );
96 }
97 static void tend ( void )
98 {
99         QueryPerformanceCounter ( &liCurrentTime );
100 }
101 static double tval( void )
102 {
103         return ((double)( (liCurrentTime.QuadPart - liStartTime.QuadPart)* (double)1000.0/(double)liFrequency.QuadPart ));
104 }
105 #else
106 #include <sys/time.h>
107 static struct timeval _tstart, _tend;
108 static struct timezone tz;
109 static void tstart ( void )
110 {
111         gettimeofday ( &_tstart, &tz );
112 }
113 static void tend ( void )
114 {
115         gettimeofday ( &_tend,&tz );
116 }
117
118 #if 0 // unused
119 static double tval()
120 {
121         double t1, t2;
122         t1 = ( double ) _tstart.tv_sec*1000 + ( double ) _tstart.tv_usec/ ( 1000 );
123         t2 = ( double ) _tend.tv_sec*1000 + ( double ) _tend.tv_usec/ ( 1000 );
124         return t2-t1;
125 }
126 #endif
127 #endif
128
129 struct Object;
130 struct Scene;
131 struct DerivedMesh;
132 struct SmokeModifierData;
133
134 #define TRI_UVOFFSET (1./4.)
135
136 /* forward declerations */
137 static void calcTriangleDivs(Object *ob, MVert *verts, int numverts, MFace *tris, int numfaces, int numtris, int **tridivs, float cell_len);
138 static void get_cell(float *p0, int res[3], float dx, float *pos, int *cell, int correct);
139 static void fill_scs_points(Object *ob, DerivedMesh *dm, SmokeCollSettings *scs);
140
141 #else /* WITH_SMOKE */
142
143 /* Stubs to use when smoke is disabled */
144 struct WTURBULENCE *smoke_turbulence_init(int *UNUSED(res), int UNUSED(amplify), int UNUSED(noisetype)) { return NULL; }
145 struct FLUID_3D *smoke_init(int *UNUSED(res), float *UNUSED(p0)) { return NULL; }
146 void smoke_free(struct FLUID_3D *UNUSED(fluid)) {}
147 void smoke_turbulence_free(struct WTURBULENCE *UNUSED(wt)) {}
148 void smoke_initWaveletBlenderRNA(struct WTURBULENCE *UNUSED(wt), float *UNUSED(strength)) {}
149 void smoke_initBlenderRNA(struct FLUID_3D *UNUSED(fluid), float *UNUSED(alpha), float *UNUSED(beta), float *UNUSED(dt_factor), float *UNUSED(vorticity), int *UNUSED(border_colli)) {}
150 long long smoke_get_mem_req(int UNUSED(xres), int UNUSED(yres), int UNUSED(zres), int UNUSED(amplify)) { return 0; }
151 void smokeModifier_do(SmokeModifierData *UNUSED(smd), Scene *UNUSED(scene), Object *UNUSED(ob), DerivedMesh *UNUSED(dm)) {}
152
153 #endif /* WITH_SMOKE */
154
155 #ifdef WITH_SMOKE
156
157 static int smokeModifier_init (SmokeModifierData *smd, Object *ob, Scene *scene, DerivedMesh *dm)
158 {
159         if((smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain && !smd->domain->fluid)
160         {
161                 size_t i;
162                 float min[3] = {FLT_MAX, FLT_MAX, FLT_MAX}, max[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX};
163                 float size[3];
164                 MVert *verts = dm->getVertArray(dm);
165                 float scale = 0.0;
166                 int res;                
167
168                 res = smd->domain->maxres;
169
170                 // get BB of domain
171                 for(i = 0; i < dm->getNumVerts(dm); i++)
172                 {
173                         float tmp[3];
174
175                         copy_v3_v3(tmp, verts[i].co);
176                         mul_m4_v3(ob->obmat, tmp);
177
178                         // min BB
179                         min[0] = MIN2(min[0], tmp[0]);
180                         min[1] = MIN2(min[1], tmp[1]);
181                         min[2] = MIN2(min[2], tmp[2]);
182
183                         // max BB
184                         max[0] = MAX2(max[0], tmp[0]);
185                         max[1] = MAX2(max[1], tmp[1]);
186                         max[2] = MAX2(max[2], tmp[2]);
187                 }
188
189                 copy_v3_v3(smd->domain->p0, min);
190                 copy_v3_v3(smd->domain->p1, max);
191
192                 // calc other res with max_res provided
193                 sub_v3_v3v3(size, max, min);
194
195                 // printf("size: %f, %f, %f\n", size[0], size[1], size[2]);
196
197                 // prevent crash when initializing a plane as domain
198                 if((size[0] < FLT_EPSILON) || (size[1] < FLT_EPSILON) || (size[2] < FLT_EPSILON))
199                         return 0;
200
201                 if(size[0] > size[1])
202                 {
203                         if(size[0] > size[2])
204                         {
205                                 scale = res / size[0];
206                                 smd->domain->dx = size[0] / res;
207                                 smd->domain->res[0] = res;
208                                 smd->domain->res[1] = (int)(size[1] * scale + 0.5);
209                                 smd->domain->res[2] = (int)(size[2] * scale + 0.5);
210                         }
211                         else
212                         {
213                                 scale = res / size[2];
214                                 smd->domain->dx = size[2] / res;
215                                 smd->domain->res[2] = res;
216                                 smd->domain->res[0] = (int)(size[0] * scale + 0.5);
217                                 smd->domain->res[1] = (int)(size[1] * scale + 0.5);
218                         }
219                 }
220                 else
221                 {
222                         if(size[1] > size[2])
223                         {
224                                 scale = res / size[1];
225                                 smd->domain->dx = size[1] / res;
226                                 smd->domain->res[1] = res;
227                                 smd->domain->res[0] = (int)(size[0] * scale + 0.5);
228                                 smd->domain->res[2] = (int)(size[2] * scale + 0.5);
229                         }
230                         else
231                         {
232                                 scale = res / size[2];
233                                 smd->domain->dx = size[2] / res;
234                                 smd->domain->res[2] = res;
235                                 smd->domain->res[0] = (int)(size[0] * scale + 0.5);
236                                 smd->domain->res[1] = (int)(size[1] * scale + 0.5);
237                         }
238                 }
239
240                 // printf("smd->domain->dx: %f\n", smd->domain->dx);
241
242                 // TODO: put in failsafe if res<=0 - dg
243
244                 // printf("res[0]: %d, res[1]: %d, res[2]: %d\n", smd->domain->res[0], smd->domain->res[1], smd->domain->res[2]);
245                 // dt max is 0.1
246                 smd->domain->fluid = smoke_init(smd->domain->res, smd->domain->p0);
247                 smd->time = scene->r.cfra;
248
249                 if(smd->domain->flags & MOD_SMOKE_HIGHRES)
250                 {
251                         smd->domain->wt = smoke_turbulence_init(smd->domain->res, smd->domain->amplify + 1, smd->domain->noise);
252                         smd->domain->res_wt[0] = smd->domain->res[0] * (smd->domain->amplify + 1);
253                         smd->domain->res_wt[1] = smd->domain->res[1] * (smd->domain->amplify + 1);                      
254                         smd->domain->res_wt[2] = smd->domain->res[2] * (smd->domain->amplify + 1);                      
255                         smd->domain->dx_wt = smd->domain->dx / (smd->domain->amplify + 1);              
256                         // printf("smd->domain->amplify: %d\n",  smd->domain->amplify);
257                         // printf("(smd->domain->flags & MOD_SMOKE_HIGHRES)\n");
258                 }
259
260                 if(!smd->domain->shadow)
261                         smd->domain->shadow = MEM_callocN(sizeof(float) * smd->domain->res[0] * smd->domain->res[1] * smd->domain->res[2], "SmokeDomainShadow");
262
263                 smoke_initBlenderRNA(smd->domain->fluid, &(smd->domain->alpha), &(smd->domain->beta), &(smd->domain->time_scale), &(smd->domain->vorticity), &(smd->domain->border_collisions));
264
265                 if(smd->domain->wt)     
266                 {
267                         smoke_initWaveletBlenderRNA(smd->domain->wt, &(smd->domain->strength));
268                         // printf("smoke_initWaveletBlenderRNA\n");
269                 }
270                 return 1;
271         }
272         else if((smd->type & MOD_SMOKE_TYPE_FLOW) && smd->flow)
273         {
274                 // handle flow object here
275                 // XXX TODO
276
277                 smd->time = scene->r.cfra;
278
279                 // update particle lifetime to be one frame
280                 // smd->flow->psys->part->lifetime = scene->r.efra + 1;
281 /*
282                 if(!smd->flow->bvh)
283                 {
284                         // smd->flow->bvh = MEM_callocN(sizeof(BVHTreeFromMesh), "smoke_bvhfromfaces");
285                         // bvhtree_from_mesh_faces(smd->flow->bvh, dm, 0.0, 2, 6);
286
287                         // copy obmat
288                         // copy_m4_m4(smd->flow->mat, ob->obmat);
289                         // copy_m4_m4(smd->flow->mat_old, ob->obmat);
290                 }
291 */
292
293                 return 1;
294         }
295         else if((smd->type & MOD_SMOKE_TYPE_COLL))
296         {
297                 smd->time = scene->r.cfra;
298
299                 // todo: delete this when loading colls work -dg
300                 if(!smd->coll)
301                         smokeModifier_createType(smd);
302
303                 if(!smd->coll->points)
304                 {
305                         // init collision points
306                         SmokeCollSettings *scs = smd->coll;
307
308                         // copy obmat
309                         copy_m4_m4(scs->mat, ob->obmat);
310                         copy_m4_m4(scs->mat_old, ob->obmat);
311
312                         fill_scs_points(ob, dm, scs);
313                 }
314
315                 if(!smd->coll->bvhtree)
316                 {
317                         smd->coll->bvhtree = NULL; // bvhtree_build_from_smoke ( ob->obmat, dm->getFaceArray(dm), dm->getNumFaces(dm), dm->getVertArray(dm), dm->getNumVerts(dm), 0.0 );
318                 }
319                 return 1;
320         }
321
322         return 2;
323 }
324
325 static void fill_scs_points(Object *ob, DerivedMesh *dm, SmokeCollSettings *scs)
326 {
327         MVert *mvert = dm->getVertArray(dm);
328         MFace *mface = dm->getFaceArray(dm);
329         int i = 0, divs = 0;
330         int *tridivs = NULL;
331         float cell_len = 1.0 / 50.0; // for res = 50
332         int newdivs = 0;
333         int quads = 0, facecounter = 0;
334
335         // count quads
336         for(i = 0; i < dm->getNumFaces(dm); i++)
337         {
338                 if(mface[i].v4)
339                         quads++;
340         }
341
342         calcTriangleDivs(ob, mvert, dm->getNumVerts(dm), mface,  dm->getNumFaces(dm), dm->getNumFaces(dm) + quads, &tridivs, cell_len);
343
344         // count triangle divisions
345         for(i = 0; i < dm->getNumFaces(dm) + quads; i++)
346         {
347                 divs += (tridivs[3 * i] + 1) * (tridivs[3 * i + 1] + 1) * (tridivs[3 * i + 2] + 1);
348         }
349
350         // printf("divs: %d\n", divs);
351
352         scs->points = MEM_callocN(sizeof(float) * (dm->getNumVerts(dm) + divs) * 3, "SmokeCollPoints");
353
354         for(i = 0; i < dm->getNumVerts(dm); i++)
355         {
356                 float tmpvec[3];
357                 copy_v3_v3(tmpvec, mvert[i].co);
358                 mul_m4_v3(ob->obmat, tmpvec);
359                 copy_v3_v3(&scs->points[i * 3], tmpvec);
360         }
361         
362         for(i = 0, facecounter = 0; i < dm->getNumFaces(dm); i++)
363         {
364                 int again = 0;
365                 do
366                 {
367                         int j, k;
368                         int divs1 = tridivs[3 * facecounter + 0];
369                         int divs2 = tridivs[3 * facecounter + 1];
370                         //int divs3 = tridivs[3 * facecounter + 2];
371                         float side1[3], side2[3], trinormorg[3], trinorm[3];
372                         
373                         if(again == 1 && mface[i].v4)
374                         {
375                                 sub_v3_v3v3(side1,  mvert[ mface[i].v3 ].co, mvert[ mface[i].v1 ].co);
376                                 sub_v3_v3v3(side2,  mvert[ mface[i].v4 ].co, mvert[ mface[i].v1 ].co);
377                         }
378                         else
379                         {
380                                 sub_v3_v3v3(side1,  mvert[ mface[i].v2 ].co, mvert[ mface[i].v1 ].co);
381                                 sub_v3_v3v3(side2,  mvert[ mface[i].v3 ].co, mvert[ mface[i].v1 ].co);
382                         }
383
384                         cross_v3_v3v3(trinormorg, side1, side2);
385                         normalize_v3(trinormorg);
386                         copy_v3_v3(trinorm, trinormorg);
387                         mul_v3_fl(trinorm, 0.25 * cell_len);
388
389                         for(j = 0; j <= divs1; j++)
390                         {
391                                 for(k = 0; k <= divs2; k++)
392                                 {
393                                         float p1[3], p2[3], p3[3], p[3]={0,0,0}; 
394                                         const float uf = (float)(j + TRI_UVOFFSET) / (float)(divs1 + 0.0);
395                                         const float vf = (float)(k + TRI_UVOFFSET) / (float)(divs2 + 0.0);
396                                         float tmpvec[3];
397                                         
398                                         if(uf+vf > 1.0) 
399                                         {
400                                                 // printf("bigger - divs1: %d, divs2: %d\n", divs1, divs2);
401                                                 continue;
402                                         }
403
404                                         copy_v3_v3(p1, mvert[ mface[i].v1 ].co);
405                                         if(again == 1 && mface[i].v4)
406                                         {
407                                                 copy_v3_v3(p2, mvert[ mface[i].v3 ].co);
408                                                 copy_v3_v3(p3, mvert[ mface[i].v4 ].co);
409                                         }
410                                         else
411                                         {
412                                                 copy_v3_v3(p2, mvert[ mface[i].v2 ].co);
413                                                 copy_v3_v3(p3, mvert[ mface[i].v3 ].co);
414                                         }
415
416                                         mul_v3_fl(p1, (1.0-uf-vf));
417                                         mul_v3_fl(p2, uf);
418                                         mul_v3_fl(p3, vf);
419                                         
420                                         add_v3_v3v3(p, p1, p2);
421                                         add_v3_v3(p, p3);
422
423                                         if(newdivs > divs)
424                                                 printf("mem problem\n");
425
426                                         // mMovPoints.push_back(p + trinorm);
427                                         add_v3_v3v3(tmpvec, p, trinorm);
428                                         mul_m4_v3(ob->obmat, tmpvec);
429                                         copy_v3_v3(&scs->points[3 * (dm->getNumVerts(dm) + newdivs)], tmpvec);
430                                         newdivs++;
431
432                                         if(newdivs > divs)
433                                                 printf("mem problem\n");
434
435                                         // mMovPoints.push_back(p - trinorm);
436                                         copy_v3_v3(tmpvec, p);
437                                         sub_v3_v3(tmpvec, trinorm);
438                                         mul_m4_v3(ob->obmat, tmpvec);
439                                         copy_v3_v3(&scs->points[3 * (dm->getNumVerts(dm) + newdivs)], tmpvec);
440                                         newdivs++;
441                                 }
442                         }
443
444                         if(again == 0 && mface[i].v4)
445                                 again++;
446                         else
447                                 again = 0;
448
449                         facecounter++;
450
451                 } while(again!=0);
452         }
453
454         scs->numpoints = dm->getNumVerts(dm) + newdivs;
455
456         MEM_freeN(tridivs);
457 }
458
459 /*! init triangle divisions */
460 static void calcTriangleDivs(Object *ob, MVert *verts, int UNUSED(numverts), MFace *faces, int numfaces, int numtris, int **tridivs, float cell_len)
461 {
462         // mTriangleDivs1.resize( faces.size() );
463         // mTriangleDivs2.resize( faces.size() );
464         // mTriangleDivs3.resize( faces.size() );
465
466         size_t i = 0, facecounter = 0;
467         float maxscale[3] = {1,1,1}; // = channelFindMaxVf(mcScale);
468         float maxpart = ABS(maxscale[0]);
469         float scaleFac = 0;
470         float fsTri = 0;
471         if(ABS(maxscale[1])>maxpart) maxpart = ABS(maxscale[1]);
472         if(ABS(maxscale[2])>maxpart) maxpart = ABS(maxscale[2]);
473         scaleFac = 1.0 / maxpart;
474         // featureSize = mLevel[mMaxRefine].nodeSize
475         fsTri = cell_len * 0.5 * scaleFac;
476
477         if(*tridivs)
478                 MEM_freeN(*tridivs);
479
480         *tridivs = MEM_callocN(sizeof(int) * numtris * 3, "Smoke_Tridivs");
481
482         for(i = 0, facecounter = 0; i < numfaces; i++) 
483         {
484                 float p0[3], p1[3], p2[3];
485                 float side1[3];
486                 float side2[3];
487                 float side3[3];
488                 int divs1=0, divs2=0, divs3=0;
489
490                 copy_v3_v3(p0, verts[faces[i].v1].co);
491                 mul_m4_v3(ob->obmat, p0);
492                 copy_v3_v3(p1, verts[faces[i].v2].co);
493                 mul_m4_v3(ob->obmat, p1);
494                 copy_v3_v3(p2, verts[faces[i].v3].co);
495                 mul_m4_v3(ob->obmat, p2);
496
497                 sub_v3_v3v3(side1, p1, p0);
498                 sub_v3_v3v3(side2, p2, p0);
499                 sub_v3_v3v3(side3, p1, p2);
500
501                 if(dot_v3v3(side1, side1) > fsTri*fsTri)
502                 { 
503                         float tmp = normalize_v3(side1);
504                         divs1 = (int)ceil(tmp/fsTri); 
505                 }
506                 if(dot_v3v3(side2, side2) > fsTri*fsTri)
507                 { 
508                         float tmp = normalize_v3(side2);
509                         divs2 = (int)ceil(tmp/fsTri); 
510                         
511                         /*
512                         // debug
513                         if(i==0)
514                                 printf("b tmp: %f, fsTri: %f, divs2: %d\n", tmp, fsTri, divs2);
515                         */
516                 }
517
518                 (*tridivs)[3 * facecounter + 0] = divs1;
519                 (*tridivs)[3 * facecounter + 1] = divs2;
520                 (*tridivs)[3 * facecounter + 2] = divs3;
521
522                 // TODO quad case
523                 if(faces[i].v4)
524                 {
525                         divs1=0, divs2=0, divs3=0;
526
527                         facecounter++;
528                         
529                         copy_v3_v3(p0, verts[faces[i].v3].co);
530                         mul_m4_v3(ob->obmat, p0);
531                         copy_v3_v3(p1, verts[faces[i].v4].co);
532                         mul_m4_v3(ob->obmat, p1);
533                         copy_v3_v3(p2, verts[faces[i].v1].co);
534                         mul_m4_v3(ob->obmat, p2);
535
536                         sub_v3_v3v3(side1, p1, p0);
537                         sub_v3_v3v3(side2, p2, p0);
538                         sub_v3_v3v3(side3, p1, p2);
539
540                         if(dot_v3v3(side1, side1) > fsTri*fsTri)
541                         { 
542                                 float tmp = normalize_v3(side1);
543                                 divs1 = (int)ceil(tmp/fsTri); 
544                         }
545                         if(dot_v3v3(side2, side2) > fsTri*fsTri)
546                         { 
547                                 float tmp = normalize_v3(side2);
548                                 divs2 = (int)ceil(tmp/fsTri); 
549                         }
550
551                         (*tridivs)[3 * facecounter + 0] = divs1;
552                         (*tridivs)[3 * facecounter + 1] = divs2;
553                         (*tridivs)[3 * facecounter + 2] = divs3;
554                 }
555                 facecounter++;
556         }
557 }
558
559 #endif /* WITH_SMOKE */
560
561 static void smokeModifier_freeDomain(SmokeModifierData *smd)
562 {
563         if(smd->domain)
564         {
565                 if(smd->domain->shadow)
566                                 MEM_freeN(smd->domain->shadow);
567                         smd->domain->shadow = NULL;
568
569                 if(smd->domain->fluid)
570                         smoke_free(smd->domain->fluid);
571
572                 if(smd->domain->wt)
573                         smoke_turbulence_free(smd->domain->wt);
574
575                 if(smd->domain->effector_weights)
576                                 MEM_freeN(smd->domain->effector_weights);
577                 smd->domain->effector_weights = NULL;
578
579                 BKE_ptcache_free_list(&(smd->domain->ptcaches[0]));
580                 smd->domain->point_cache[0] = NULL;
581
582                 MEM_freeN(smd->domain);
583                 smd->domain = NULL;
584         }
585 }
586
587 static void smokeModifier_freeFlow(SmokeModifierData *smd)
588 {
589         if(smd->flow)
590         {
591 /*
592                 if(smd->flow->bvh)
593                 {
594                         free_bvhtree_from_mesh(smd->flow->bvh);
595                         MEM_freeN(smd->flow->bvh);
596                 }
597                 smd->flow->bvh = NULL;
598 */
599                 MEM_freeN(smd->flow);
600                 smd->flow = NULL;
601         }
602 }
603
604 static void smokeModifier_freeCollision(SmokeModifierData *smd)
605 {
606         if(smd->coll)
607         {
608                 if(smd->coll->points)
609                 {
610                         MEM_freeN(smd->coll->points);
611                         smd->coll->points = NULL;
612                 }
613
614                 if(smd->coll->bvhtree)
615                 {
616                         BLI_bvhtree_free(smd->coll->bvhtree);
617                         smd->coll->bvhtree = NULL;
618                 }
619
620                 if(smd->coll->dm)
621                         smd->coll->dm->release(smd->coll->dm);
622                 smd->coll->dm = NULL;
623
624                 MEM_freeN(smd->coll);
625                 smd->coll = NULL;
626         }
627 }
628
629 void smokeModifier_reset_turbulence(struct SmokeModifierData *smd)
630 {
631         if(smd && smd->domain && smd->domain->wt)
632         {
633                 smoke_turbulence_free(smd->domain->wt);
634                 smd->domain->wt = NULL;
635         }
636 }
637
638 void smokeModifier_reset(struct SmokeModifierData *smd)
639 {
640         if(smd)
641         {
642                 if(smd->domain)
643                 {
644                         if(smd->domain->shadow)
645                                 MEM_freeN(smd->domain->shadow);
646                         smd->domain->shadow = NULL;
647
648                         if(smd->domain->fluid)
649                         {
650                                 smoke_free(smd->domain->fluid);
651                                 smd->domain->fluid = NULL;
652                         }
653
654                         smokeModifier_reset_turbulence(smd);
655
656                         smd->time = -1;
657
658                         // printf("reset domain end\n");
659                 }
660                 else if(smd->flow)
661                 {
662                         /*
663                         if(smd->flow->bvh)
664                         {
665                                 free_bvhtree_from_mesh(smd->flow->bvh);
666                                 MEM_freeN(smd->flow->bvh);
667                         }
668                         smd->flow->bvh = NULL;
669                         */
670                 }
671                 else if(smd->coll)
672                 {
673                         if(smd->coll->points)
674                         {
675                                 MEM_freeN(smd->coll->points);
676                                 smd->coll->points = NULL;
677                         }
678
679                         if(smd->coll->bvhtree)
680                         {
681                                 BLI_bvhtree_free(smd->coll->bvhtree);
682                                 smd->coll->bvhtree = NULL;
683                         }
684
685                         if(smd->coll->dm)
686                                 smd->coll->dm->release(smd->coll->dm);
687                         smd->coll->dm = NULL;
688
689                 }
690         }
691 }
692
693 void smokeModifier_free (SmokeModifierData *smd)
694 {
695         if(smd)
696         {
697                 smokeModifier_freeDomain(smd);
698                 smokeModifier_freeFlow(smd);
699                 smokeModifier_freeCollision(smd);
700         }
701 }
702
703 void smokeModifier_createType(struct SmokeModifierData *smd)
704 {
705         if(smd)
706         {
707                 if(smd->type & MOD_SMOKE_TYPE_DOMAIN)
708                 {
709                         if(smd->domain)
710                                 smokeModifier_freeDomain(smd);
711
712                         smd->domain = MEM_callocN(sizeof(SmokeDomainSettings), "SmokeDomain");
713
714                         smd->domain->smd = smd;
715
716                         smd->domain->point_cache[0] = BKE_ptcache_add(&(smd->domain->ptcaches[0]));
717                         smd->domain->point_cache[0]->flag |= PTCACHE_DISK_CACHE;
718                         smd->domain->point_cache[0]->step = 1;
719
720                         /* Deprecated */
721                         smd->domain->point_cache[1] = NULL;
722                         smd->domain->ptcaches[1].first = smd->domain->ptcaches[1].last = NULL;
723                         /* set some standard values */
724                         smd->domain->fluid = NULL;
725                         smd->domain->wt = NULL;                 
726                         smd->domain->eff_group = NULL;
727                         smd->domain->fluid_group = NULL;
728                         smd->domain->coll_group = NULL;
729                         smd->domain->maxres = 32;
730                         smd->domain->amplify = 1;                       
731                         smd->domain->omega = 1.0;                       
732                         smd->domain->alpha = -0.001;
733                         smd->domain->beta = 0.1;
734                         smd->domain->time_scale = 1.0;
735                         smd->domain->vorticity = 2.0;
736                         smd->domain->border_collisions = 1;             // vertically non-colliding
737                         smd->domain->flags = MOD_SMOKE_DISSOLVE_LOG | MOD_SMOKE_HIGH_SMOOTH;
738                         smd->domain->strength = 2.0;
739                         smd->domain->noise = MOD_SMOKE_NOISEWAVE;
740                         smd->domain->diss_speed = 5;
741                         // init 3dview buffer
742
743                         smd->domain->viewsettings = MOD_SMOKE_VIEW_SHOWBIG;
744                         smd->domain->effector_weights = BKE_add_effector_weights(NULL);
745                 }
746                 else if(smd->type & MOD_SMOKE_TYPE_FLOW)
747                 {
748                         if(smd->flow)
749                                 smokeModifier_freeFlow(smd);
750
751                         smd->flow = MEM_callocN(sizeof(SmokeFlowSettings), "SmokeFlow");
752
753                         smd->flow->smd = smd;
754
755                         /* set some standard values */
756                         smd->flow->density = 1.0;
757                         smd->flow->temp = 1.0;
758                         smd->flow->flags = MOD_SMOKE_FLOW_ABSOLUTE;
759                         smd->flow->vel_multi = 1.0;
760
761                         smd->flow->psys = NULL;
762
763                 }
764                 else if(smd->type & MOD_SMOKE_TYPE_COLL)
765                 {
766                         if(smd->coll)
767                                 smokeModifier_freeCollision(smd);
768
769                         smd->coll = MEM_callocN(sizeof(SmokeCollSettings), "SmokeColl");
770
771                         smd->coll->smd = smd;
772                         smd->coll->points = NULL;
773                         smd->coll->numpoints = 0;
774                         smd->coll->bvhtree = NULL;
775                         smd->coll->dm = NULL;
776                 }
777         }
778 }
779
780 void smokeModifier_copy(struct SmokeModifierData *smd, struct SmokeModifierData *tsmd)
781 {
782         tsmd->type = smd->type;
783         tsmd->time = smd->time;
784         
785         smokeModifier_createType(tsmd);
786
787         if (tsmd->domain) {
788                 tsmd->domain->maxres = smd->domain->maxres;
789                 tsmd->domain->amplify = smd->domain->amplify;
790                 tsmd->domain->omega = smd->domain->omega;
791                 tsmd->domain->alpha = smd->domain->alpha;
792                 tsmd->domain->beta = smd->domain->beta;
793                 tsmd->domain->flags = smd->domain->flags;
794                 tsmd->domain->strength = smd->domain->strength;
795                 tsmd->domain->noise = smd->domain->noise;
796                 tsmd->domain->diss_speed = smd->domain->diss_speed;
797                 tsmd->domain->viewsettings = smd->domain->viewsettings;
798                 tsmd->domain->fluid_group = smd->domain->fluid_group;
799                 tsmd->domain->coll_group = smd->domain->coll_group;
800                 tsmd->domain->vorticity = smd->domain->vorticity;
801                 tsmd->domain->time_scale = smd->domain->time_scale;
802                 tsmd->domain->border_collisions = smd->domain->border_collisions;
803                 
804                 MEM_freeN(tsmd->domain->effector_weights);
805                 tsmd->domain->effector_weights = MEM_dupallocN(smd->domain->effector_weights);
806         } else if (tsmd->flow) {
807                 tsmd->flow->density = smd->flow->density;
808                 tsmd->flow->temp = smd->flow->temp;
809                 tsmd->flow->psys = smd->flow->psys;
810                 tsmd->flow->type = smd->flow->type;
811                 tsmd->flow->flags = smd->flow->flags;
812                 tsmd->flow->vel_multi = smd->flow->vel_multi;
813         } else if (tsmd->coll) {
814                 ;
815                 /* leave it as initialised, collision settings is mostly caches */
816         }
817 }
818
819 #ifdef WITH_SMOKE
820
821 // forward decleration
822 static void smoke_calc_transparency(float *result, float *input, float *p0, float *p1, int res[3], float dx, float *light, bresenham_callback cb, float correct);
823 static float calc_voxel_transp(float *result, float *input, int res[3], int *pixel, float *tRay, float correct);
824
825 static int get_lamp(Scene *scene, float *light)
826 {       
827         Base *base_tmp = NULL;  
828         int found_lamp = 0;
829
830         // try to find a lamp, preferably local
831         for(base_tmp = scene->base.first; base_tmp; base_tmp= base_tmp->next) {
832                 if(base_tmp->object->type == OB_LAMP) {
833                         Lamp *la = base_tmp->object->data;
834
835                         if(la->type == LA_LOCAL) {
836                                 copy_v3_v3(light, base_tmp->object->obmat[3]);
837                                 return 1;
838                         }
839                         else if(!found_lamp) {
840                                 copy_v3_v3(light, base_tmp->object->obmat[3]);
841                                 found_lamp = 1;
842                         }
843                 }
844         }
845
846         return found_lamp;
847 }
848
849 static void smoke_calc_domain(Scene *scene, Object *ob, SmokeModifierData *smd)
850 {
851         SmokeDomainSettings *sds = smd->domain;
852         GroupObject *go = NULL;                 
853         Base *base = NULL;      
854
855         // do collisions, needs to be done before emission, so that smoke isn't emitted inside collision cells
856         if(1)
857         {
858                 Object *otherobj = NULL;
859                 ModifierData *md = NULL;
860
861                 if(sds->coll_group) // we use groups since we have 2 domains
862                         go = sds->coll_group->gobject.first;
863                 else
864                         base = scene->base.first;
865
866                 while(base || go)
867                 {
868                         otherobj = NULL;
869                         if(sds->coll_group) 
870                         {                                               
871                                 if(go->ob)                                                      
872                                         otherobj = go->ob;                                      
873                         }                                       
874                         else                                            
875                                 otherobj = base->object;                                        
876                         if(!otherobj)                                   
877                         {                                               
878                                 if(sds->coll_group)                                                     
879                                         go = go->next;                                          
880                                 else                                                    
881                                         base= base->next;                                               
882                                 continue;                                       
883                         }                       
884                         md = modifiers_findByType(otherobj, eModifierType_Smoke);
885                         
886                         // check for active smoke modifier
887                         if(md && md->mode & (eModifierMode_Realtime | eModifierMode_Render))                                    
888                         {
889                                 SmokeModifierData *smd2 = (SmokeModifierData *)md;
890
891                                 if((smd2->type & MOD_SMOKE_TYPE_COLL) && smd2->coll && smd2->coll->points)
892                                 {
893                                         // we got nice collision object
894                                         SmokeCollSettings *scs = smd2->coll;
895                                         size_t i, j;
896                                         unsigned char *obstacles = smoke_get_obstacle(smd->domain->fluid);
897
898                                         for(i = 0; i < scs->numpoints; i++)
899                                         {
900                                                 int badcell = 0;
901                                                 size_t index = 0;
902                                                 int cell[3];
903
904                                                 // 1. get corresponding cell
905                                                 get_cell(smd->domain->p0, smd->domain->res, smd->domain->dx, &scs->points[3 * i], cell, 0);
906                                         
907                                                 // check if cell is valid (in the domain boundary)
908                                                 for(j = 0; j < 3; j++)
909                                                         if((cell[j] > sds->res[j] - 1) || (cell[j] < 0))
910                                                         {
911                                                                 badcell = 1;
912                                                                 break;
913                                                         }
914                                                                                                                                 
915                                                         if(badcell)                                                                     
916                                                                 continue;
917                                                 // 2. set cell values (heat, density and velocity)
918                                                 index = smoke_get_index(cell[0], sds->res[0], cell[1], sds->res[1], cell[2]);
919                                                                                                                 
920                                                 // printf("cell[0]: %d, cell[1]: %d, cell[2]: %d\n", cell[0], cell[1], cell[2]);                                                                
921                                                 // printf("res[0]: %d, res[1]: %d, res[2]: %d, index: %d\n\n", sds->res[0], sds->res[1], sds->res[2], index);                                                                                                                                   
922                                                 obstacles[index] = 1;
923                                                 // for moving gobstacles                                                                
924                                                 /*
925                                                 const LbmFloat maxVelVal = 0.1666;
926                                                 const LbmFloat maxusqr = maxVelVal*maxVelVal*3. *1.5;
927
928                                                 LbmVec objvel = vec2L((mMOIVertices[n]-mMOIVerticesOld[n]) /dvec); 
929                                                 {                                                               
930                                                 const LbmFloat usqr = (objvel[0]*objvel[0]+objvel[1]*objvel[1]+objvel[2]*objvel[2])*1.5;                                                                
931                                                 USQRMAXCHECK(usqr, objvel[0],objvel[1],objvel[2], mMaxVlen, mMxvx,mMxvy,mMxvz);                                                                 
932                                                 if(usqr>maxusqr) {                                                                      
933                                                 // cutoff at maxVelVal                                                                  
934                                                 for(int jj=0; jj<3; jj++) {                                                                             
935                                                 if(objvel[jj]>0.) objvel[jj] =  maxVelVal;                                                                              
936                                                 if(objvel[jj]<0.) objvel[jj] = -maxVelVal;                                                                      
937                                                 }                                                               
938                                                 } 
939                                                 }                                                               
940                                                 const LbmFloat dp=dot(objvel, vec2L((*pNormals)[n]) );                                                          
941                                                 const LbmVec oldov=objvel; // debug                                                             
942                                                 objvel = vec2L((*pNormals)[n]) *dp;                                                             
943                                                 */
944                                         }
945                                 }
946                         }
947
948                         if(sds->coll_group)
949                                 go = go->next;
950                         else
951                                 base= base->next;
952                 }
953         }
954
955         // do flows and fluids
956         if(1)                   
957         {
958                 Object *otherobj = NULL;                                
959                 ModifierData *md = NULL;
960                 if(sds->fluid_group) // we use groups since we have 2 domains
961                         go = sds->fluid_group->gobject.first;                           
962                 else                                    
963                         base = scene->base.first;
964                 while(base || go)
965                 {                                       
966                         otherobj = NULL;
967                         if(sds->fluid_group) 
968                         {
969                                 if(go->ob)                                                      
970                                         otherobj = go->ob;                                      
971                         }                                       
972                         else                                            
973                                 otherobj = base->object;
974                         if(!otherobj)
975                         {
976                                 if(sds->fluid_group)
977                                         go = go->next;
978                                 else
979                                         base= base->next;
980
981                                 continue;
982                         }
983
984                         md = modifiers_findByType(otherobj, eModifierType_Smoke);
985                         
986                         // check for active smoke modifier
987                         if(md && md->mode & (eModifierMode_Realtime | eModifierMode_Render))
988                         {
989                                 SmokeModifierData *smd2 = (SmokeModifierData *)md;
990                                 
991                                 // check for initialized smoke object
992                                 if((smd2->type & MOD_SMOKE_TYPE_FLOW) && smd2->flow)                                            
993                                 {
994                                         // we got nice flow object
995                                         SmokeFlowSettings *sfs = smd2->flow;
996                                         
997                                         if(sfs && sfs->psys && sfs->psys->part && sfs->psys->part->type==PART_EMITTER) // is particle system selected
998                                         {
999                                                 ParticleSimulationData sim;
1000                                                 ParticleSystem *psys = sfs->psys;
1001                                                 int p = 0;                                                              
1002                                                 float *density = smoke_get_density(sds->fluid);                                                         
1003                                                 float *bigdensity = smoke_turbulence_get_density(sds->wt);                                                              
1004                                                 float *heat = smoke_get_heat(sds->fluid);                                                               
1005                                                 float *velocity_x = smoke_get_velocity_x(sds->fluid);                                                           
1006                                                 float *velocity_y = smoke_get_velocity_y(sds->fluid);                                                           
1007                                                 float *velocity_z = smoke_get_velocity_z(sds->fluid);                                                           
1008                                                 unsigned char *obstacle = smoke_get_obstacle(sds->fluid);                                                               
1009                                                 int bigres[3];
1010                                                 short absolute_flow = (sfs->flags & MOD_SMOKE_FLOW_ABSOLUTE);
1011                                                 short high_emission_smoothing = bigdensity ? (smd->domain->flags & MOD_SMOKE_HIGH_SMOOTH) : 0;
1012
1013                                                 /*
1014                                                 * A temporary volume map used to store whole emissive
1015                                                 * area to be added to smoke density and interpolated
1016                                                 * for high resolution smoke.
1017                                                 */
1018                                                 float *temp_emission_map = NULL;
1019
1020                                                 sim.scene = scene;
1021                                                 sim.ob = otherobj;
1022                                                 sim.psys = psys;
1023
1024                                                 // initialize temp emission map
1025                                                 if(!(sfs->type & MOD_SMOKE_FLOW_TYPE_OUTFLOW))
1026                                                 {
1027                                                         int i;
1028                                                         temp_emission_map = MEM_callocN(sizeof(float) * sds->res[0]*sds->res[1]*sds->res[2], "SmokeTempEmission");
1029                                                         // set whole volume to 0.0f
1030                                                         for (i=0; i<sds->res[0]*sds->res[1]*sds->res[2]; i++) {
1031                                                                 temp_emission_map[i] = 0.0f;
1032                                                         }
1033                                                 }
1034                                                                                                                 
1035                                                 // mostly copied from particle code                                                             
1036                                                 for(p=0; p<psys->totpart; p++)                                                          
1037                                                 {
1038                                                         int cell[3];
1039                                                         size_t i = 0;
1040                                                         size_t index = 0;
1041                                                         int badcell = 0;
1042                                                         ParticleKey state;
1043
1044                                                         if(psys->particles[p].flag & (PARS_NO_DISP|PARS_UNEXIST))
1045                                                                 continue;
1046
1047                                                         state.time = smd->time;
1048
1049                                                         if(psys_get_particle_state(&sim, p, &state, 0) == 0)
1050                                                                 continue;
1051                                                         
1052                                                         // copy_v3_v3(pos, pa->state.co);
1053                                                         // mul_m4_v3(ob->imat, pos);                                                                                                                                            
1054                                                         // 1. get corresponding cell    
1055                                                         get_cell(smd->domain->p0, smd->domain->res, smd->domain->dx, state.co, cell, 0);                                                                                                                                        
1056                                                         // check if cell is valid (in the domain boundary)                                                                      
1057                                                         for(i = 0; i < 3; i++)                                                                  
1058                                                         {                                                                               
1059                                                                 if((cell[i] > sds->res[i] - 1) || (cell[i] < 0))                                                                                
1060                                                                 {                                                                                       
1061                                                                         badcell = 1;                                                                                    
1062                                                                         break;                                                                          
1063                                                                 }                                                                       
1064                                                         }                                                                                                                                                       
1065                                                         if(badcell)                                                                             
1066                                                                 continue;                                                                                                                                               
1067                                                         // 2. set cell values (heat, density and velocity)                                                                      
1068                                                         index = smoke_get_index(cell[0], sds->res[0], cell[1], sds->res[1], cell[2]);                                                                                                                                           
1069                                                         if(!(sfs->type & MOD_SMOKE_FLOW_TYPE_OUTFLOW) && !(obstacle[index])) // this is inflow
1070                                                         {                                                                               
1071                                                                 // heat[index] += sfs->temp * 0.1;                                                                              
1072                                                                 // density[index] += sfs->density * 0.1;
1073                                                                 heat[index] = sfs->temp;
1074                                                                 
1075                                                                 // Add emitter density to temp emission map
1076                                                                 temp_emission_map[index] = sfs->density;
1077
1078                                                                 // Uses particle velocity as initial velocity for smoke
1079                                                                 if(sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY && (psys->part->phystype != PART_PHYS_NO))
1080                                                                 {
1081                                                                         velocity_x[index] = state.vel[0]*sfs->vel_multi;
1082                                                                         velocity_y[index] = state.vel[1]*sfs->vel_multi;
1083                                                                         velocity_z[index] = state.vel[2]*sfs->vel_multi;
1084                                                                 }                                                                               
1085                                                         }                                                                       
1086                                                         else if(sfs->type & MOD_SMOKE_FLOW_TYPE_OUTFLOW) // outflow                                                                     
1087                                                         {                                                                               
1088                                                                 heat[index] = 0.f;                                                                              
1089                                                                 density[index] = 0.f;                                                                           
1090                                                                 velocity_x[index] = 0.f;                                                                                
1091                                                                 velocity_y[index] = 0.f;                                                                                
1092                                                                 velocity_z[index] = 0.f;
1093                                                                 // we need different handling for the high-res feature
1094                                                                 if(bigdensity)
1095                                                                 {
1096                                                                         // init all surrounding cells according to amplification, too                                                                                   
1097                                                                         int i, j, k;
1098                                                                         smoke_turbulence_get_res(smd->domain->wt, bigres);
1099
1100                                                                         for(i = 0; i < smd->domain->amplify + 1; i++)
1101                                                                                 for(j = 0; j < smd->domain->amplify + 1; j++)
1102                                                                                         for(k = 0; k < smd->domain->amplify + 1; k++)
1103                                                                                         {                                                                                                               
1104                                                                                                 index = smoke_get_index((smd->domain->amplify + 1)* cell[0] + i, bigres[0], (smd->domain->amplify + 1)* cell[1] + j, bigres[1], (smd->domain->amplify + 1)* cell[2] + k);                                                                                                               
1105                                                                                                 bigdensity[index] = 0.f;                                                                                                        
1106                                                                                         }                                                                               
1107                                                                 }
1108                                                         }
1109                                                         }       // particles loop
1110
1111
1112                                                         // apply emission values
1113                                                         if(!(sfs->type & MOD_SMOKE_FLOW_TYPE_OUTFLOW)) {
1114
1115                                                                 // initialize variables
1116                                                                 int ii, jj, kk, x, y, z, block_size;
1117                                                                 size_t index, index_big;
1118
1119                                                                 smoke_turbulence_get_res(smd->domain->wt, bigres);
1120                                                                 block_size = smd->domain->amplify + 1;  // high res block size
1121
1122
1123                                                                         // loop through every low res cell
1124                                                                         for(x = 0; x < sds->res[0]; x++)
1125                                                                                 for(y = 0; y < sds->res[1]; y++)
1126                                                                                         for(z = 0; z < sds->res[2]; z++)                                                                                                        
1127                                                                                         {
1128
1129                                                                                                 // neighbour cell emission densities (for high resolution smoke smooth interpolation)
1130                                                                                                 float c000, c001, c010, c011,  c100, c101, c110, c111;
1131
1132                                                                                                 c000 = (x>0 && y>0 && z>0) ? temp_emission_map[smoke_get_index(x-1, sds->res[0], y-1, sds->res[1], z-1)] : 0;
1133                                                                                                 c001 = (x>0 && y>0) ? temp_emission_map[smoke_get_index(x-1, sds->res[0], y-1, sds->res[1], z)] : 0;
1134                                                                                                 c010 = (x>0 && z>0) ? temp_emission_map[smoke_get_index(x-1, sds->res[0], y, sds->res[1], z-1)] : 0;
1135                                                                                                 c011 = (x>0) ? temp_emission_map[smoke_get_index(x-1, sds->res[0], y, sds->res[1], z)] : 0;
1136
1137                                                                                                 c100 = (y>0 && z>0) ? temp_emission_map[smoke_get_index(x, sds->res[0], y-1, sds->res[1], z-1)] : 0;
1138                                                                                                 c101 = (y>0) ? temp_emission_map[smoke_get_index(x, sds->res[0], y-1, sds->res[1], z)] : 0;
1139                                                                                                 c110 = (z>0) ? temp_emission_map[smoke_get_index(x, sds->res[0], y, sds->res[1], z-1)] : 0;
1140                                                                                                 c111 = temp_emission_map[smoke_get_index(x, sds->res[0], y, sds->res[1], z)];                   // this cell
1141
1142
1143
1144                                                                                                 // get cell index
1145                                                                                                 index = smoke_get_index(x, sds->res[0], y, sds->res[1], z);
1146
1147                                                                                                 // add emission to low resolution density
1148                                                                                                 if (absolute_flow) {if (temp_emission_map[index]>0) density[index] = temp_emission_map[index];}
1149                                                                                                 else {
1150                                                                                                         density[index] += temp_emission_map[index];
1151                                                                                                         if (density[index]>1) density[index]=1.0f;
1152                                                                                                 }
1153
1154                                                                                                 smoke_turbulence_get_res(smd->domain->wt, bigres);
1155
1156
1157
1158                                                                                                 /*
1159                                                                                                 loop through high res blocks if high res enabled
1160                                                                                                 */
1161                                                                                                 if (bigdensity)
1162                                                                                                 for(ii = 0; ii < block_size; ii++)
1163                                                                                                         for(jj = 0; jj < block_size; jj++)
1164                                                                                                                 for(kk = 0; kk < block_size; kk++)                                                                                                      
1165                                                                                                                 {
1166
1167                                                                                                                 float fx,fy,fz, interpolated_value;
1168                                                                                                                 int shift_x, shift_y, shift_z;
1169
1170
1171                                                                                                                 /*
1172                                                                                                                 * Do volume interpolation if emitter smoothing
1173                                                                                                                 * is enabled
1174                                                                                                                 */
1175                                                                                                                 if (high_emission_smoothing) {
1176                                                                                                                         // convert block position to relative
1177                                                                                                                         // for interpolation smoothing
1178                                                                                                                         fx = (float)ii/block_size + 0.5f/block_size;
1179                                                                                                                         fy = (float)jj/block_size + 0.5f/block_size;
1180                                                                                                                         fz = (float)kk/block_size + 0.5f/block_size;
1181
1182                                                                                                                         // calculate trilinear interpolation
1183                                                                                                                         interpolated_value = c000 * (1-fx) * (1-fy) * (1-fz) +
1184                                                                                                                         c100 * fx * (1-fy) * (1-fz) +
1185                                                                                                                         c010 * (1-fx) * fy * (1-fz) +
1186                                                                                                                         c001 * (1-fx) * (1-fy) * fz +
1187                                                                                                                         c101 * fx * (1-fy) * fz +
1188                                                                                                                         c011 * (1-fx) * fy * fz +
1189                                                                                                                         c110 * fx * fy * (1-fz) +
1190                                                                                                                         c111 * fx * fy * fz;
1191
1192
1193                                                                                                                         // add some contrast / sharpness
1194                                                                                                                         // depending on hi-res block size
1195
1196                                                                                                                         interpolated_value = (interpolated_value-0.4f*sfs->density)*(block_size/2) + 0.4f*sfs->density;
1197                                                                                                                         if (interpolated_value<0.0f) interpolated_value = 0.0f;
1198                                                                                                                         if (interpolated_value>1.0f) interpolated_value = 1.0f;
1199
1200                                                                                                                         // shift smoke block index
1201                                                                                                                         // (because pixel center is actually
1202                                                                                                                         // in halfway of the low res block)
1203                                                                                                                         shift_x = (x < 1) ? 0 : block_size/2;
1204                                                                                                                         shift_y = (y < 1) ? 0 : block_size/2;
1205                                                                                                                         shift_z = (z < 1) ? 0 : block_size/2;
1206                                                                                                                 }
1207                                                                                                                 else {
1208                                                                                                                         // without interpolation use same low resolution
1209                                                                                                                         // block value for all hi-res blocks
1210                                                                                                                         interpolated_value = c111;
1211                                                                                                                         shift_x = 0;
1212                                                                                                                         shift_y = 0;
1213                                                                                                                         shift_z = 0;
1214                                                                                                                 }
1215
1216                                                                                                                 // get shifted index for current high resolution block
1217                                                                                                                 index_big = smoke_get_index(block_size * x + ii - shift_x, bigres[0], block_size * y + jj - shift_y, bigres[1], block_size * z + kk - shift_z);                                                                                                         
1218                                                                                                                 
1219                                                                                                                 // add emission data to high resolution density
1220                                                                                                                 if (absolute_flow) {if (interpolated_value > 0) bigdensity[index_big] = interpolated_value;}
1221                                                                                                                 else {
1222                                                                                                                         bigdensity[index_big] += interpolated_value;
1223                                                                                                                         if (bigdensity[index_big]>1) bigdensity[index_big]=1.0f;
1224                                                                                                                 }
1225
1226                                                                                                                 } // end of hires loop
1227
1228                                                                         }       // end of low res loop
1229
1230                                                                 // free temporary emission map
1231                                                         if (temp_emission_map) MEM_freeN(temp_emission_map);
1232
1233                                                         }       // end emission
1234
1235
1236                                                                                 
1237                                 }                                                       
1238                                 else                                                    
1239                                 {                                                               
1240                                         /*                                                              
1241                                         for()                                                           
1242                                         {                                                                       
1243                                                 // no psys                                                                      
1244                                                 BVHTreeNearest nearest;
1245                                                 nearest.index = -1;
1246                                                 nearest.dist = FLT_MAX;
1247
1248                                                 BLI_bvhtree_find_nearest(sfs->bvh->tree, pco, &nearest, sfs->bvh->nearest_callback, sfs->bvh);
1249                                         }*/                                                     
1250                                 }
1251                         }                                               
1252                 }
1253                         if(sds->fluid_group)
1254                                 go = go->next;
1255                         else
1256                                 base= base->next;
1257                 }
1258         }
1259
1260         // do effectors
1261         {
1262                 ListBase *effectors = pdInitEffectors(scene, ob, NULL, sds->effector_weights);
1263
1264                 if(effectors)
1265                 {
1266                         float *density = smoke_get_density(sds->fluid);
1267                         float *force_x = smoke_get_force_x(sds->fluid);
1268                         float *force_y = smoke_get_force_y(sds->fluid);
1269                         float *force_z = smoke_get_force_z(sds->fluid);
1270                         float *velocity_x = smoke_get_velocity_x(sds->fluid);
1271                         float *velocity_y = smoke_get_velocity_y(sds->fluid);
1272                         float *velocity_z = smoke_get_velocity_z(sds->fluid);
1273                         int x, y, z;
1274
1275                         // precalculate wind forces
1276                         for(x = 0; x < sds->res[0]; x++)
1277                                 for(y = 0; y < sds->res[1]; y++)
1278                                         for(z = 0; z < sds->res[2]; z++)
1279                         {       
1280                                 EffectedPoint epoint;
1281                                 float voxelCenter[3] = {0,0,0} , vel[3] = {0,0,0} , retvel[3] = {0,0,0};
1282                                 unsigned int index = smoke_get_index(x, sds->res[0], y, sds->res[1], z);
1283
1284                                 if(density[index] < FLT_EPSILON)                                        
1285                                         continue;       
1286
1287                                 vel[0] = velocity_x[index];
1288                                 vel[1] = velocity_y[index];
1289                                 vel[2] = velocity_z[index];
1290
1291                                 voxelCenter[0] = sds->p0[0] + sds->dx *  x + sds->dx * 0.5;
1292                                 voxelCenter[1] = sds->p0[1] + sds->dx *  y + sds->dx * 0.5;
1293                                 voxelCenter[2] = sds->p0[2] + sds->dx *  z + sds->dx * 0.5;
1294
1295                                 pd_point_from_loc(scene, voxelCenter, vel, index, &epoint);
1296                                 pdDoEffectors(effectors, NULL, sds->effector_weights, &epoint, retvel, NULL);
1297
1298                                 // TODO dg - do in force!
1299                                 force_x[index] = MIN2(MAX2(-1.0, retvel[0] * 0.2), 1.0); 
1300                                 force_y[index] = MIN2(MAX2(-1.0, retvel[1] * 0.2), 1.0); 
1301                                 force_z[index] = MIN2(MAX2(-1.0, retvel[2] * 0.2), 1.0);
1302                         }
1303                 }
1304
1305                 pdEndEffectors(&effectors);
1306         }
1307
1308 }
1309 void smokeModifier_do(SmokeModifierData *smd, Scene *scene, Object *ob, DerivedMesh *dm)
1310 {       
1311         if((smd->type & MOD_SMOKE_TYPE_FLOW))
1312         {
1313                 if(scene->r.cfra >= smd->time)
1314                         smokeModifier_init(smd, ob, scene, dm);
1315
1316                 if(scene->r.cfra > smd->time)
1317                 {
1318                         // XXX TODO
1319                         smd->time = scene->r.cfra;
1320
1321                         // rigid movement support
1322                         /*
1323                         copy_m4_m4(smd->flow->mat_old, smd->flow->mat);
1324                         copy_m4_m4(smd->flow->mat, ob->obmat);
1325                         */
1326                 }
1327                 else if(scene->r.cfra < smd->time)
1328                 {
1329                         smd->time = scene->r.cfra;
1330                         smokeModifier_reset(smd);
1331                 }
1332         }
1333         else if(smd->type & MOD_SMOKE_TYPE_COLL)
1334         {
1335                 if(scene->r.cfra >= smd->time)
1336                         smokeModifier_init(smd, ob, scene, dm);
1337
1338                 if(scene->r.cfra > smd->time)
1339                 {
1340                         // XXX TODO
1341                         smd->time = scene->r.cfra;
1342                         
1343                         if(smd->coll->dm)
1344                                 smd->coll->dm->release(smd->coll->dm);
1345
1346                         smd->coll->dm = CDDM_copy(dm);
1347
1348                         // rigid movement support
1349                         copy_m4_m4(smd->coll->mat_old, smd->coll->mat);
1350                         copy_m4_m4(smd->coll->mat, ob->obmat);
1351                 }
1352                 else if(scene->r.cfra < smd->time)
1353                 {
1354                         smd->time = scene->r.cfra;
1355                         smokeModifier_reset(smd);
1356                 }
1357         }
1358         else if(smd->type & MOD_SMOKE_TYPE_DOMAIN)
1359         {
1360                 SmokeDomainSettings *sds = smd->domain;
1361                 float light[3]; 
1362                 PointCache *cache = NULL;
1363                 PTCacheID pid;
1364                 int startframe, endframe, framenr;
1365                 float timescale;
1366
1367                 framenr = scene->r.cfra;
1368
1369                 //printf("time: %d\n", scene->r.cfra);
1370
1371                 cache = sds->point_cache[0];
1372                 BKE_ptcache_id_from_smoke(&pid, ob, smd);
1373                 BKE_ptcache_id_time(&pid, scene, framenr, &startframe, &endframe, &timescale);
1374
1375                 if(!smd->domain->fluid || framenr == startframe)
1376                 {
1377                         BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
1378                         BKE_ptcache_validate(cache, framenr);
1379                         cache->flag &= ~PTCACHE_REDO_NEEDED;
1380                 }
1381
1382                 if(!smd->domain->fluid && (framenr != startframe) && (smd->domain->flags & MOD_SMOKE_FILE_LOAD)==0 && (cache->flag & PTCACHE_BAKED)==0)
1383                         return;
1384
1385                 smd->domain->flags &= ~MOD_SMOKE_FILE_LOAD;
1386
1387                 CLAMP(framenr, startframe, endframe);
1388
1389                 /* If already viewing a pre/after frame, no need to reload */
1390                 if ((smd->time == framenr) && (framenr != scene->r.cfra))
1391                         return;
1392
1393                 // printf("startframe: %d, framenr: %d\n", startframe, framenr);
1394
1395                 if(smokeModifier_init(smd, ob, scene, dm)==0)
1396                 {
1397                         printf("bad smokeModifier_init\n");
1398                         return;
1399                 }
1400
1401                 /* try to read from cache */
1402                 if(BKE_ptcache_read(&pid, (float)framenr) == PTCACHE_READ_EXACT) {
1403                         BKE_ptcache_validate(cache, framenr);
1404                         smd->time = framenr;
1405                         return;
1406                 }
1407                 
1408                 /* only calculate something when we advanced a single frame */
1409                 if(framenr != (int)smd->time+1)
1410                         return;
1411
1412                 /* don't simulate if viewing start frame, but scene frame is not real start frame */
1413                 if (framenr != scene->r.cfra)
1414                         return;
1415
1416                 tstart();
1417
1418                 smoke_calc_domain(scene, ob, smd);
1419
1420                 /* if on second frame, write cache for first frame */
1421                 if((int)smd->time == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact==0)) {
1422                         // create shadows straight after domain initialization so we get nice shadows for startframe, too
1423                         if(get_lamp(scene, light))
1424                                 smoke_calc_transparency(sds->shadow, smoke_get_density(sds->fluid), sds->p0, sds->p1, sds->res, sds->dx, light, calc_voxel_transp, -7.0*sds->dx);
1425
1426                         if(sds->wt)
1427                         {
1428                                 if(sds->flags & MOD_SMOKE_DISSOLVE)
1429                                         smoke_dissolve_wavelet(sds->wt, sds->diss_speed, sds->flags & MOD_SMOKE_DISSOLVE_LOG);
1430                                 smoke_turbulence_step(sds->wt, sds->fluid);
1431                         }
1432
1433                         BKE_ptcache_write(&pid, startframe);
1434                 }
1435                 
1436                 // set new time
1437                 smd->time = scene->r.cfra;
1438
1439                 /* do simulation */
1440
1441                 // low res
1442
1443                 // simulate the actual smoke (c++ code in intern/smoke)
1444                 // DG: interesting commenting this line + deactivating loading of noise files
1445                 if(framenr!=startframe)
1446                 {
1447                         if(sds->flags & MOD_SMOKE_DISSOLVE)
1448                                 smoke_dissolve(sds->fluid, sds->diss_speed, sds->flags & MOD_SMOKE_DISSOLVE_LOG);
1449                         smoke_step(sds->fluid, smd->time, scene->r.frs_sec / scene->r.frs_sec_base);
1450                 }
1451
1452                 // create shadows before writing cache so they get stored
1453                 if(get_lamp(scene, light))
1454                         smoke_calc_transparency(sds->shadow, smoke_get_density(sds->fluid), sds->p0, sds->p1, sds->res, sds->dx, light, calc_voxel_transp, -7.0*sds->dx);
1455
1456                 if(sds->wt)
1457                 {
1458                         if(sds->flags & MOD_SMOKE_DISSOLVE)
1459                                 smoke_dissolve_wavelet(sds->wt, sds->diss_speed, sds->flags & MOD_SMOKE_DISSOLVE_LOG);
1460                         smoke_turbulence_step(sds->wt, sds->fluid);
1461                 }
1462         
1463                 BKE_ptcache_validate(cache, framenr);
1464                 if(framenr != startframe)
1465                         BKE_ptcache_write(&pid, framenr);
1466
1467                 tend();
1468                 //printf ( "Frame: %d, Time: %f\n", (int)smd->time, ( float ) tval() );
1469         }
1470 }
1471
1472 static float calc_voxel_transp(float *result, float *input, int res[3], int *pixel, float *tRay, float correct)
1473 {
1474         const size_t index = smoke_get_index(pixel[0], res[0], pixel[1], res[1], pixel[2]);
1475
1476         // T_ray *= T_vox
1477         *tRay *= exp(input[index]*correct);
1478         
1479         if(result[index] < 0.0f)        
1480         {
1481 #pragma omp critical            
1482                 result[index] = *tRay;  
1483         }       
1484
1485         return *tRay;
1486 }
1487
1488 long long smoke_get_mem_req(int xres, int yres, int zres, int amplify)
1489 {
1490         int totalCells = xres * yres * zres;
1491         int amplifiedCells = totalCells * amplify * amplify * amplify;
1492
1493         // print out memory requirements
1494         long long int coarseSize = sizeof(float) * totalCells * 22 +
1495         sizeof(unsigned char) * totalCells;
1496
1497         long long int fineSize = sizeof(float) * amplifiedCells * 7 + // big grids
1498         sizeof(float) * totalCells * 8 +     // small grids
1499         sizeof(float) * 128 * 128 * 128;     // noise tile
1500
1501         long long int totalMB = (coarseSize + fineSize) / (1024 * 1024);
1502
1503         return totalMB;
1504 }
1505
1506 static void bresenham_linie_3D(int x1, int y1, int z1, int x2, int y2, int z2, float *tRay, bresenham_callback cb, float *result, float *input, int res[3], float correct)
1507 {
1508         int dx, dy, dz, i, l, m, n, x_inc, y_inc, z_inc, err_1, err_2, dx2, dy2, dz2;
1509         int pixel[3];
1510
1511         pixel[0] = x1;
1512         pixel[1] = y1;
1513         pixel[2] = z1;
1514
1515         dx = x2 - x1;
1516         dy = y2 - y1;
1517         dz = z2 - z1;
1518
1519         x_inc = (dx < 0) ? -1 : 1;
1520         l = abs(dx);
1521         y_inc = (dy < 0) ? -1 : 1;
1522         m = abs(dy);
1523         z_inc = (dz < 0) ? -1 : 1;
1524         n = abs(dz);
1525         dx2 = l << 1;
1526         dy2 = m << 1;
1527         dz2 = n << 1;
1528
1529         if ((l >= m) && (l >= n)) {
1530                 err_1 = dy2 - l;
1531                 err_2 = dz2 - l;
1532                 for (i = 0; i < l; i++) {
1533                         if(cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON)
1534                                 break;
1535                         if (err_1 > 0) {
1536                                 pixel[1] += y_inc;
1537                                 err_1 -= dx2;
1538                         }
1539                         if (err_2 > 0) {
1540                                 pixel[2] += z_inc;
1541                                 err_2 -= dx2;
1542                         }
1543                         err_1 += dy2;
1544                         err_2 += dz2;
1545                         pixel[0] += x_inc;
1546                 }
1547         } else if ((m >= l) && (m >= n)) {
1548                 err_1 = dx2 - m;
1549                 err_2 = dz2 - m;
1550                 for (i = 0; i < m; i++) {
1551                         if(cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON)
1552                                 break;
1553                         if (err_1 > 0) {
1554                                 pixel[0] += x_inc;
1555                                 err_1 -= dy2;
1556                         }
1557                         if (err_2 > 0) {
1558                                 pixel[2] += z_inc;
1559                                 err_2 -= dy2;
1560                         }
1561                         err_1 += dx2;
1562                         err_2 += dz2;
1563                         pixel[1] += y_inc;
1564                 }
1565         } else {
1566                 err_1 = dy2 - n;
1567                 err_2 = dx2 - n;
1568                 for (i = 0; i < n; i++) {
1569                         if(cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON)
1570                                 break;
1571                         if (err_1 > 0) {
1572                                 pixel[1] += y_inc;
1573                                 err_1 -= dz2;
1574                         }
1575                         if (err_2 > 0) {
1576                                 pixel[0] += x_inc;
1577                                 err_2 -= dz2;
1578                         }
1579                         err_1 += dy2;
1580                         err_2 += dx2;
1581                         pixel[2] += z_inc;
1582                 }
1583         }
1584         cb(result, input, res, pixel, tRay, correct);
1585 }
1586
1587 static void get_cell(float *p0, int res[3], float dx, float *pos, int *cell, int correct)
1588 {
1589         float tmp[3];
1590
1591         sub_v3_v3v3(tmp, pos, p0);
1592         mul_v3_fl(tmp, 1.0 / dx);
1593
1594         if(correct)
1595         {
1596                 cell[0] = MIN2(res[0] - 1, MAX2(0, (int)floor(tmp[0])));
1597                 cell[1] = MIN2(res[1] - 1, MAX2(0, (int)floor(tmp[1])));
1598                 cell[2] = MIN2(res[2] - 1, MAX2(0, (int)floor(tmp[2])));
1599         }
1600         else
1601         {
1602                 cell[0] = (int)floor(tmp[0]);
1603                 cell[1] = (int)floor(tmp[1]);
1604                 cell[2] = (int)floor(tmp[2]);
1605         }
1606 }
1607
1608 static void smoke_calc_transparency(float *result, float *input, float *p0, float *p1, int res[3], float dx, float *light, bresenham_callback cb, float correct)
1609 {
1610         float bv[6];
1611         int a, z, slabsize=res[0]*res[1], size= res[0]*res[1]*res[2];
1612
1613         for(a=0; a<size; a++)
1614                 result[a]= -1.0f;
1615
1616         bv[0] = p0[0];
1617         bv[1] = p1[0];
1618         // y
1619         bv[2] = p0[1];
1620         bv[3] = p1[1];
1621         // z
1622         bv[4] = p0[2];
1623         bv[5] = p1[2];
1624
1625 #pragma omp parallel for schedule(static,1)
1626         for(z = 0; z < res[2]; z++)
1627         {
1628                 size_t index = z*slabsize;
1629                 int x,y;
1630
1631                 for(y = 0; y < res[1]; y++)
1632                         for(x = 0; x < res[0]; x++, index++)
1633                         {
1634                                 float voxelCenter[3];
1635                                 float pos[3];
1636                                 int cell[3];
1637                                 float tRay = 1.0;
1638
1639                                 if(result[index] >= 0.0f)                                       
1640                                         continue;                                                               
1641                                 voxelCenter[0] = p0[0] + dx *  x + dx * 0.5;
1642                                 voxelCenter[1] = p0[1] + dx *  y + dx * 0.5;
1643                                 voxelCenter[2] = p0[2] + dx *  z + dx * 0.5;
1644
1645                                 // get starting position (in voxel coords)
1646                                 if(BLI_bvhtree_bb_raycast(bv, light, voxelCenter, pos) > FLT_EPSILON)
1647                                 {
1648                                         // we're ouside
1649                                         get_cell(p0, res, dx, pos, cell, 1);
1650                                 }
1651                                 else
1652                                 {
1653                                         // we're inside
1654                                         get_cell(p0, res, dx, light, cell, 1);
1655                                 }
1656
1657                                 bresenham_linie_3D(cell[0], cell[1], cell[2], x, y, z, &tRay, cb, result, input, res, correct);
1658
1659                                 // convention -> from a RGBA float array, use G value for tRay
1660 // #pragma omp critical
1661                                 result[index] = tRay;                   
1662                         }
1663         }
1664 }
1665
1666 #endif /* WITH_SMOKE */