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