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