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