More F-Modifier Tweaks:
[blender.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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_math.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                         mul_m4_v3(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                         // copy_m4_m4(smd->flow->mat, ob->obmat);
266                         // copy_m4_m4(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                         copy_m4_m4(scs->mat, ob->obmat);
287                         copy_m4_m4(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->getFaceArray(dm), dm->getNumFaces(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->getFaceArray(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->getNumFaces(dm); i++)
314         {
315                 if(mface[i].v4)
316                         quads++;
317         }
318
319         calcTriangleDivs(ob, mvert, dm->getNumVerts(dm), mface,  dm->getNumFaces(dm), dm->getNumFaces(dm) + quads, &tridivs, cell_len);
320
321         // count triangle divisions
322         for(i = 0; i < dm->getNumFaces(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                 mul_m4_v3(ob->obmat, tmpvec);
336                 VECCOPY(&scs->points[i * 3], tmpvec);
337         }
338         
339         for(i = 0, facecounter = 0; i < dm->getNumFaces(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                         cross_v3_v3v3(trinormorg, side1, side2);
362                         normalize_v3(trinormorg);
363                         VECCOPY(trinorm, trinormorg);
364                         mul_v3_fl(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                                         mul_v3_fl(p1, (1.0-uf-vf));
394                                         mul_v3_fl(p2, uf);
395                                         mul_v3_fl(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                                         mul_m4_v3(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                                         mul_m4_v3(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                 mul_m4_v3(ob->obmat, p0);
470                 VECCOPY(p1, verts[faces[i].v2].co);
471                 mul_m4_v3(ob->obmat, p1);
472                 VECCOPY(p2, verts[faces[i].v3].co);
473                 mul_m4_v3(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_v3(side1);
482                         divs1 = (int)ceil(tmp/fsTri); 
483                 }
484                 if(INPR(side2, side2) > fsTri*fsTri) 
485                 { 
486                         float tmp = normalize_v3(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                         mul_m4_v3(ob->obmat, p0);
509                         VECCOPY(p1, verts[faces[i].v4].co);
510                         mul_m4_v3(ob->obmat, p1);
511                         VECCOPY(p2, verts[faces[i].v1].co);
512                         mul_m4_v3(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_v3(side1);
521                                 divs1 = (int)ceil(tmp/fsTri); 
522                         }
523                         if(INPR(side2, side2) > fsTri*fsTri) 
524                         { 
525                                 float tmp = normalize_v3(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 && 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                                                         // mul_m4_v3(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                                                                 // Uses particle velocity as initial velocity for smoke
877                                                                 if(smd->domain->flags & MOD_SMOKE_INITVELOCITY) {
878                                                                 velocity_x[index] = pa->state.vel[0];
879                                                                 velocity_y[index] = pa->state.vel[1];
880                                                                 velocity_z[index] = pa->state.vel[2];                                                                           
881                                                                 }                                                                               
882                                                                 
883                                                                 // obstacle[index] |= 2;
884                                                                 // we need different handling for the high-res feature
885                                                                 if(bigdensity)
886                                                                 {
887                                                                         // init all surrounding cells according to amplification, too
888                                                                         int i, j, k;
889
890                                                                         smoke_turbulence_get_res(smd->domain->wt, bigres);
891
892                                                                         for(i = 0; i < smd->domain->amplify + 1; i++)
893                                                                                 for(j = 0; j < smd->domain->amplify + 1; j++)
894                                                                                         for(k = 0; k < smd->domain->amplify + 1; k++)                                                                                                   
895                                                                                         {                                                                                                               
896                                                                                                 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);                                                                                                               
897                                                                                                 bigdensity[index] = sfs->density;                                                                                                       
898                                                                                         }                                                                               
899                                                                 }                                                                       
900                                                         }                                                                       
901                                                         else if(sfs->type & MOD_SMOKE_FLOW_TYPE_OUTFLOW) // outflow                                                                     
902                                                         {                                                                               
903                                                                 heat[index] = 0.f;                                                                              
904                                                                 density[index] = 0.f;                                                                           
905                                                                 velocity_x[index] = 0.f;                                                                                
906                                                                 velocity_y[index] = 0.f;                                                                                
907                                                                 velocity_z[index] = 0.f;
908                                                                 // we need different handling for the high-res feature
909                                                                 if(bigdensity)
910                                                                 {
911                                                                         // init all surrounding cells according to amplification, too                                                                                   
912                                                                         int i, j, k;
913                                                                         smoke_turbulence_get_res(smd->domain->wt, bigres);
914
915                                                                         for(i = 0; i < smd->domain->amplify + 1; i++)
916                                                                                 for(j = 0; j < smd->domain->amplify + 1; j++)
917                                                                                         for(k = 0; k < smd->domain->amplify + 1; k++)
918                                                                                         {                                                                                                               
919                                                                                                 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);                                                                                                               
920                                                                                                 bigdensity[index] = 0.f;                                                                                                        
921                                                                                         }                                                                               
922                                                                 }                                                                       
923                                                         }       // particles loop                                                       
924                                         }                                                       
925                                 }                                                       
926                                 else                                                    
927                                 {                                                               
928                                         /*                                                              
929                                         for()                                                           
930                                         {                                                                       
931                                                 // no psys                                                                      
932                                                 BVHTreeNearest nearest;
933                                                 nearest.index = -1;
934                                                 nearest.dist = FLT_MAX;
935
936                                                 BLI_bvhtree_find_nearest(sfs->bvh->tree, pco, &nearest, sfs->bvh->nearest_callback, sfs->bvh);
937                                         }*/                                                     
938                                 }                                               
939                         }                                               
940                 }
941                         if(sds->fluid_group)
942                                 go = go->next;
943                         else
944                                 base= base->next;
945                 }
946         }
947
948         // do effectors
949         {
950                 ListBase *effectors = pdInitEffectors(scene, ob, NULL, sds->effector_weights);
951
952                 if(effectors)
953                 {
954                         float *density = smoke_get_density(sds->fluid);
955                         float *force_x = smoke_get_force_x(sds->fluid);
956                         float *force_y = smoke_get_force_y(sds->fluid);
957                         float *force_z = smoke_get_force_z(sds->fluid);
958                         float *velocity_x = smoke_get_velocity_x(sds->fluid);
959                         float *velocity_y = smoke_get_velocity_y(sds->fluid);
960                         float *velocity_z = smoke_get_velocity_z(sds->fluid);
961                         int x, y, z;
962
963                         // precalculate wind forces
964                         for(x = 0; x < sds->res[0]; x++)
965                                 for(y = 0; y < sds->res[1]; y++)
966                                         for(z = 0; z < sds->res[2]; z++)
967                         {       
968                                 EffectedPoint epoint;
969                                 float voxelCenter[3] = {0,0,0} , vel[3] = {0,0,0} , retvel[3] = {0,0,0};
970                                 unsigned int index = smoke_get_index(x, sds->res[0], y, sds->res[1], z);
971
972                                 if(density[index] < FLT_EPSILON)                                        
973                                         continue;       
974
975                                 vel[0] = velocity_x[index];
976                                 vel[1] = velocity_y[index];
977                                 vel[2] = velocity_z[index];
978
979                                 voxelCenter[0] = sds->p0[0] + sds->dx *  x + sds->dx * 0.5;
980                                 voxelCenter[1] = sds->p0[1] + sds->dx *  y + sds->dx * 0.5;
981                                 voxelCenter[2] = sds->p0[2] + sds->dx *  z + sds->dx * 0.5;
982
983                                 pd_point_from_loc(scene, voxelCenter, vel, index, &epoint);
984                                 pdDoEffectors(effectors, NULL, sds->effector_weights, &epoint, retvel, NULL);
985
986                                 // TODO dg - do in force!
987                                 force_x[index] = MIN2(MAX2(-1.0, retvel[0] * 0.2), 1.0); 
988                                 force_y[index] = MIN2(MAX2(-1.0, retvel[1] * 0.2), 1.0); 
989                                 force_z[index] = MIN2(MAX2(-1.0, retvel[2] * 0.2), 1.0);
990                         }
991                 }
992
993                 pdEndEffectors(&effectors);
994         }
995
996         // do collisions        
997         if(1)
998         {
999                 Object *otherobj = NULL;
1000                 ModifierData *md = NULL;
1001
1002                 if(sds->coll_group) // we use groups since we have 2 domains
1003                         go = sds->coll_group->gobject.first;
1004                 else
1005                         base = scene->base.first;
1006
1007                 while(base || go)
1008                 {
1009                         otherobj = NULL;
1010                         if(sds->coll_group) 
1011                         {                                               
1012                                 if(go->ob)                                                      
1013                                         otherobj = go->ob;                                      
1014                         }                                       
1015                         else                                            
1016                                 otherobj = base->object;                                        
1017                         if(!otherobj)                                   
1018                         {                                               
1019                                 if(sds->coll_group)                                                     
1020                                         go = go->next;                                          
1021                                 else                                                    
1022                                         base= base->next;                                               
1023                                 continue;                                       
1024                         }                       
1025                         md = modifiers_findByType(otherobj, eModifierType_Smoke);
1026                         
1027                         // check for active smoke modifier
1028                         if(md && md->mode & (eModifierMode_Realtime | eModifierMode_Render))                                    
1029                         {
1030                                 SmokeModifierData *smd2 = (SmokeModifierData *)md;
1031
1032                                 if((smd2->type & MOD_SMOKE_TYPE_COLL) && smd2->coll && smd2->coll->points)
1033                                 {
1034                                         // we got nice collision object
1035                                         SmokeCollSettings *scs = smd2->coll;
1036                                         size_t i, j;
1037                                         unsigned char *obstacles = smoke_get_obstacle(smd->domain->fluid);
1038
1039                                         for(i = 0; i < scs->numpoints; i++)
1040                                         {
1041                                                 int badcell = 0;
1042                                                 size_t index = 0;
1043                                                 int cell[3];
1044
1045                                                 // 1. get corresponding cell
1046                                                 get_cell(smd->domain->p0, smd->domain->res, smd->domain->dx, &scs->points[3 * i], cell, 0);
1047                                         
1048                                                 // check if cell is valid (in the domain boundary)
1049                                                 for(j = 0; j < 3; j++)
1050                                                         if((cell[j] > sds->res[j] - 1) || (cell[j] < 0))
1051                                                         {
1052                                                                 badcell = 1;
1053                                                                 break;
1054                                                         }
1055                                                                                                                                 
1056                                                         if(badcell)                                                                     
1057                                                                 continue;
1058                                                 // 2. set cell values (heat, density and velocity)
1059                                                 index = smoke_get_index(cell[0], sds->res[0], cell[1], sds->res[1], cell[2]);
1060                                                                                                                 
1061                                                 // printf("cell[0]: %d, cell[1]: %d, cell[2]: %d\n", cell[0], cell[1], cell[2]);                                                                
1062                                                 // printf("res[0]: %d, res[1]: %d, res[2]: %d, index: %d\n\n", sds->res[0], sds->res[1], sds->res[2], index);                                                                                                                                   
1063                                                 obstacles[index] = 1;
1064                                                 // for moving gobstacles                                                                
1065                                                 /*
1066                                                 const LbmFloat maxVelVal = 0.1666;
1067                                                 const LbmFloat maxusqr = maxVelVal*maxVelVal*3. *1.5;
1068
1069                                                 LbmVec objvel = vec2L((mMOIVertices[n]-mMOIVerticesOld[n]) /dvec); 
1070                                                 {                                                               
1071                                                 const LbmFloat usqr = (objvel[0]*objvel[0]+objvel[1]*objvel[1]+objvel[2]*objvel[2])*1.5;                                                                
1072                                                 USQRMAXCHECK(usqr, objvel[0],objvel[1],objvel[2], mMaxVlen, mMxvx,mMxvy,mMxvz);                                                                 
1073                                                 if(usqr>maxusqr) {                                                                      
1074                                                 // cutoff at maxVelVal                                                                  
1075                                                 for(int jj=0; jj<3; jj++) {                                                                             
1076                                                 if(objvel[jj]>0.) objvel[jj] =  maxVelVal;                                                                              
1077                                                 if(objvel[jj]<0.) objvel[jj] = -maxVelVal;                                                                      
1078                                                 }                                                               
1079                                                 } 
1080                                                 }                                                               
1081                                                 const LbmFloat dp=dot(objvel, vec2L((*pNormals)[n]) );                                                          
1082                                                 const LbmVec oldov=objvel; // debug                                                             
1083                                                 objvel = vec2L((*pNormals)[n]) *dp;                                                             
1084                                                 */
1085                                         }
1086                                 }
1087                         }
1088
1089                         if(sds->coll_group)
1090                                 go = go->next;
1091                         else
1092                                 base= base->next;
1093                 }
1094         }
1095 }
1096 void smokeModifier_do(SmokeModifierData *smd, Scene *scene, Object *ob, DerivedMesh *dm, int useRenderParams, int isFinalCalc)
1097 {       
1098         if((smd->type & MOD_SMOKE_TYPE_FLOW))
1099         {
1100                 if(scene->r.cfra >= smd->time)
1101                         smokeModifier_init(smd, ob, scene, dm);
1102
1103                 if(scene->r.cfra > smd->time)
1104                 {
1105                         // XXX TODO
1106                         smd->time = scene->r.cfra;
1107
1108                         // rigid movement support
1109                         /*
1110                         copy_m4_m4(smd->flow->mat_old, smd->flow->mat);
1111                         copy_m4_m4(smd->flow->mat, ob->obmat);
1112                         */
1113                 }
1114                 else if(scene->r.cfra < smd->time)
1115                 {
1116                         smd->time = scene->r.cfra;
1117                         smokeModifier_reset(smd);
1118                 }
1119         }
1120         else if(smd->type & MOD_SMOKE_TYPE_COLL)
1121         {
1122                 if(scene->r.cfra >= smd->time)
1123                         smokeModifier_init(smd, ob, scene, dm);
1124
1125                 if(scene->r.cfra > smd->time)
1126                 {
1127                         // XXX TODO
1128                         smd->time = scene->r.cfra;
1129                         
1130                         if(smd->coll->dm)
1131                                 smd->coll->dm->release(smd->coll->dm);
1132
1133                         smd->coll->dm = CDDM_copy(dm);
1134
1135                         // rigid movement support
1136                         copy_m4_m4(smd->coll->mat_old, smd->coll->mat);
1137                         copy_m4_m4(smd->coll->mat, ob->obmat);
1138                 }
1139                 else if(scene->r.cfra < smd->time)
1140                 {
1141                         smd->time = scene->r.cfra;
1142                         smokeModifier_reset(smd);
1143                 }
1144         }
1145         else if(smd->type & MOD_SMOKE_TYPE_DOMAIN)
1146         {
1147                 SmokeDomainSettings *sds = smd->domain;
1148                 float light[3]; 
1149                 PointCache *cache = NULL;
1150                 PTCacheID pid;
1151                 PointCache *cache_wt = NULL;
1152                 PTCacheID pid_wt;
1153                 int startframe, endframe, framenr;
1154                 float timescale;
1155                 int cache_result = 0, cache_result_wt = 0;
1156
1157                 framenr = scene->r.cfra;
1158
1159                 // printf("time: %d\n", scene->r.cfra);
1160
1161                 if(framenr == smd->time)
1162                         return;
1163
1164                 cache = sds->point_cache[0];
1165                 BKE_ptcache_id_from_smoke(&pid, ob, smd);
1166                 BKE_ptcache_id_time(&pid, scene, framenr, &startframe, &endframe, &timescale);
1167
1168                 cache_wt = sds->point_cache[1];
1169                 BKE_ptcache_id_from_smoke_turbulence(&pid_wt, ob, smd);
1170
1171                 if(!smd->domain->fluid)
1172                 {
1173                         BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
1174                         BKE_ptcache_id_reset(scene, &pid_wt, PTCACHE_RESET_OUTDATED);
1175                 }
1176
1177                 if(framenr < startframe)
1178                         return;
1179
1180                 if(framenr > endframe)
1181                         return;
1182
1183                 if(!smd->domain->fluid && (framenr != startframe))
1184                         return;
1185
1186                 // printf("startframe: %d, framenr: %d\n", startframe, framenr);
1187
1188                 if(!smokeModifier_init(smd, ob, scene, dm))
1189                 {
1190                         printf("bad smokeModifier_init\n");
1191                         return;
1192                 }
1193
1194                 /* try to read from cache */
1195                 cache_result =  BKE_ptcache_read_cache(&pid, (float)framenr, scene->r.frs_sec);
1196                 // printf("cache_result: %d\n", cache_result);
1197
1198                 if(cache_result == PTCACHE_READ_EXACT) 
1199                 {
1200                         cache->flag |= PTCACHE_SIMULATION_VALID;
1201                         cache->simframe= framenr;
1202
1203                         if(sds->wt)
1204                         {
1205                                 cache_result_wt = BKE_ptcache_read_cache(&pid_wt, (float)framenr, scene->r.frs_sec);
1206                                 
1207                                 if(cache_result_wt == PTCACHE_READ_EXACT) 
1208                                 {
1209                                         cache_wt->flag |= PTCACHE_SIMULATION_VALID;
1210                                         cache_wt->simframe= framenr;
1211                                 }
1212                         }
1213                         return;
1214                 }
1215
1216                 tstart();
1217
1218                 smoke_calc_domain(scene, ob, smd);
1219                 
1220                 // set new time
1221                 smd->time = scene->r.cfra;
1222
1223                 /* do simulation */
1224
1225                 // low res
1226                 cache->flag |= PTCACHE_SIMULATION_VALID;
1227                 cache->simframe= framenr;
1228
1229                 // simulate the actual smoke (c++ code in intern/smoke)
1230                 // DG: interesting commenting this line + deactivating loading of noise files
1231                 if(framenr!=startframe)
1232                 {
1233                         if(sds->flags & MOD_SMOKE_DISSOLVE)
1234                                 smoke_dissolve(sds->fluid, sds->diss_speed, sds->flags & MOD_SMOKE_DISSOLVE_LOG);
1235                         smoke_step(sds->fluid, smd->time);
1236                 }
1237
1238                 // create shadows before writing cache so we get nice shadows for sstartframe, too
1239                 if(get_lamp(scene, light))
1240                         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);
1241         
1242                 BKE_ptcache_write_cache(&pid, framenr);
1243
1244                 if(sds->wt)
1245                 {
1246                         if(framenr!=startframe)
1247                         {
1248                                 if(sds->flags & MOD_SMOKE_DISSOLVE)
1249                                         smoke_dissolve_wavelet(sds->wt, sds->diss_speed, sds->flags & MOD_SMOKE_DISSOLVE_LOG);
1250                                 smoke_turbulence_step(sds->wt, sds->fluid);
1251                         }
1252
1253                         cache_wt->flag |= PTCACHE_SIMULATION_VALID;
1254                         cache_wt->simframe= framenr;
1255                         BKE_ptcache_write_cache(&pid_wt, framenr);
1256                 }
1257
1258                 tend();
1259                 printf ( "Frame: %d, Time: %f\n", (int)smd->time, ( float ) tval() );
1260         }
1261 }
1262
1263 static float calc_voxel_transp(float *result, float *input, int res[3], int *pixel, float *tRay, float correct)
1264 {
1265         const size_t index = smoke_get_index(pixel[0], res[0], pixel[1], res[1], pixel[2]);
1266
1267         // T_ray *= T_vox
1268         *tRay *= exp(input[index]*correct);
1269         
1270         if(result[index] < 0.0f)        
1271         {
1272 #pragma omp critical            
1273                 result[index] = *tRay;  
1274         }       
1275
1276         return *tRay;
1277 }
1278
1279 long long smoke_get_mem_req(int xres, int yres, int zres, int amplify)
1280 {
1281           int totalCells = xres * yres * zres;
1282           int amplifiedCells = totalCells * amplify * amplify * amplify;
1283
1284           // print out memory requirements
1285           long long int coarseSize = sizeof(float) * totalCells * 22 +
1286                            sizeof(unsigned char) * totalCells;
1287
1288           long long int fineSize = sizeof(float) * amplifiedCells * 7 + // big grids
1289                          sizeof(float) * totalCells * 8 +     // small grids
1290                          sizeof(float) * 128 * 128 * 128;     // noise tile
1291
1292           long long int totalMB = (coarseSize + fineSize) / (1024 * 1024);
1293
1294           return totalMB;
1295 }
1296
1297 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)
1298 {
1299     int dx, dy, dz, i, l, m, n, x_inc, y_inc, z_inc, err_1, err_2, dx2, dy2, dz2;
1300     int pixel[3];
1301
1302     pixel[0] = x1;
1303     pixel[1] = y1;
1304     pixel[2] = z1;
1305
1306     dx = x2 - x1;
1307     dy = y2 - y1;
1308     dz = z2 - z1;
1309
1310     x_inc = (dx < 0) ? -1 : 1;
1311     l = abs(dx);
1312     y_inc = (dy < 0) ? -1 : 1;
1313     m = abs(dy);
1314     z_inc = (dz < 0) ? -1 : 1;
1315     n = abs(dz);
1316     dx2 = l << 1;
1317     dy2 = m << 1;
1318     dz2 = n << 1;
1319
1320     if ((l >= m) && (l >= n)) {
1321         err_1 = dy2 - l;
1322         err_2 = dz2 - l;
1323         for (i = 0; i < l; i++) {
1324                 if(cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON)
1325                         break;
1326             if (err_1 > 0) {
1327                 pixel[1] += y_inc;
1328                 err_1 -= dx2;
1329             }
1330             if (err_2 > 0) {
1331                 pixel[2] += z_inc;
1332                 err_2 -= dx2;
1333             }
1334             err_1 += dy2;
1335             err_2 += dz2;
1336             pixel[0] += x_inc;
1337         }
1338     } else if ((m >= l) && (m >= n)) {
1339         err_1 = dx2 - m;
1340         err_2 = dz2 - m;
1341         for (i = 0; i < m; i++) {
1342                 if(cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON)
1343                         break;
1344             if (err_1 > 0) {
1345                 pixel[0] += x_inc;
1346                 err_1 -= dy2;
1347             }
1348             if (err_2 > 0) {
1349                 pixel[2] += z_inc;
1350                 err_2 -= dy2;
1351             }
1352             err_1 += dx2;
1353             err_2 += dz2;
1354             pixel[1] += y_inc;
1355         }
1356     } else {
1357         err_1 = dy2 - n;
1358         err_2 = dx2 - n;
1359         for (i = 0; i < n; i++) {
1360                 if(cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON)
1361                         break;
1362             if (err_1 > 0) {
1363                 pixel[1] += y_inc;
1364                 err_1 -= dz2;
1365             }
1366             if (err_2 > 0) {
1367                 pixel[0] += x_inc;
1368                 err_2 -= dz2;
1369             }
1370             err_1 += dy2;
1371             err_2 += dx2;
1372             pixel[2] += z_inc;
1373         }
1374     }
1375     cb(result, input, res, pixel, tRay, correct);
1376 }
1377
1378 static void get_cell(float *p0, int res[3], float dx, float *pos, int *cell, int correct)
1379 {
1380         float tmp[3];
1381
1382         VECSUB(tmp, pos, p0);
1383         mul_v3_fl(tmp, 1.0 / dx);
1384
1385         if(correct)
1386         {
1387                 cell[0] = MIN2(res[0] - 1, MAX2(0, (int)floor(tmp[0])));
1388                 cell[1] = MIN2(res[1] - 1, MAX2(0, (int)floor(tmp[1])));
1389                 cell[2] = MIN2(res[2] - 1, MAX2(0, (int)floor(tmp[2])));
1390         }
1391         else
1392         {
1393                 cell[0] = (int)floor(tmp[0]);
1394                 cell[1] = (int)floor(tmp[1]);
1395                 cell[2] = (int)floor(tmp[2]);
1396         }
1397 }
1398
1399 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)
1400 {
1401         float bv[6];
1402         int a, z, slabsize=res[0]*res[1], size= res[0]*res[1]*res[2];
1403
1404         for(a=0; a<size; a++)
1405                 result[a]= -1.0f;
1406
1407         bv[0] = p0[0];
1408         bv[1] = p1[0];
1409         // y
1410         bv[2] = p0[1];
1411         bv[3] = p1[1];
1412         // z
1413         bv[4] = p0[2];
1414         bv[5] = p1[2];
1415
1416 #pragma omp parallel for schedule(static,1)
1417         for(z = 0; z < res[2]; z++)
1418         {
1419                 size_t index = z*slabsize;
1420                 int x,y;
1421
1422                 for(y = 0; y < res[1]; y++)
1423                         for(x = 0; x < res[0]; x++, index++)
1424                         {
1425                                 float voxelCenter[3];
1426                                 float pos[3];
1427                                 int cell[3];
1428                                 float tRay = 1.0;
1429
1430                                 if(result[index] >= 0.0f)                                       
1431                                         continue;                                                               
1432                                 voxelCenter[0] = p0[0] + dx *  x + dx * 0.5;
1433                                 voxelCenter[1] = p0[1] + dx *  y + dx * 0.5;
1434                                 voxelCenter[2] = p0[2] + dx *  z + dx * 0.5;
1435
1436                                 // get starting position (in voxel coords)
1437                                 if(BLI_bvhtree_bb_raycast(bv, light, voxelCenter, pos) > FLT_EPSILON)
1438                                 {
1439                                         // we're ouside
1440                                         get_cell(p0, res, dx, pos, cell, 1);
1441                                 }
1442                                 else
1443                                 {
1444                                         // we're inside
1445                                         get_cell(p0, res, dx, light, cell, 1);
1446                                 }
1447
1448                                 bresenham_linie_3D(cell[0], cell[1], cell[2], x, y, z, &tRay, cb, result, input, res, correct);
1449
1450                                 // convention -> from a RGBA float array, use G value for tRay
1451 // #pragma omp critical
1452                                 result[index] = tRay;                   
1453                         }
1454         }
1455 }
1456