code cleanup: use uppercase defines and change drawFCurveFade into static function.
[blender.git] / source / blender / render / intern / source / volume_precache.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Matt Ebb, Ra˙l Fern·ndez Hern·ndez (Farsthary).
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/render/intern/source/volume_precache.c
29  *  \ingroup render
30  */
31
32
33 #include <math.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <float.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "BLI_blenlib.h"
41 #include "BLI_math.h"
42 #include "BLI_threads.h"
43 #include "BLI_voxel.h"
44 #include "BLI_utildefines.h"
45
46 #include "PIL_time.h"
47
48 #include "RE_shader_ext.h"
49
50 #include "DNA_material_types.h"
51
52 #include "rayintersection.h"
53 #include "rayobject.h"
54 #include "render_types.h"
55 #include "rendercore.h"
56 #include "renderdatabase.h"
57 #include "volumetric.h"
58 #include "volume_precache.h"
59
60 #include "BKE_global.h"
61
62 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
63 /* defined in pipeline.c, is hardcopy of active dynamic allocated Render */
64 /* only to be used here in this file, it's for speed */
65 extern struct Render R;
66 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
67
68 /* *** utility code to set up an individual raytree for objectinstance, for checking inside/outside *** */
69
70 /* Recursive test for intersections, from a point inside the mesh, to outside
71  * Number of intersections (depth) determine if a point is inside or outside the mesh */
72 static int intersect_outside_volume(RayObject *tree, Isect *isect, float *offset, int limit, int depth)
73 {
74         if (limit == 0) return depth;
75         
76         if (RE_rayobject_raycast(tree, isect)) {
77                 
78                 isect->start[0] = isect->start[0] + isect->dist*isect->dir[0];
79                 isect->start[1] = isect->start[1] + isect->dist*isect->dir[1];
80                 isect->start[2] = isect->start[2] + isect->dist*isect->dir[2];
81                 
82                 isect->dist = FLT_MAX;
83                 isect->skip = RE_SKIP_VLR_NEIGHBOUR;
84                 isect->orig.face= isect->hit.face;
85                 isect->orig.ob= isect->hit.ob;
86                 
87                 return intersect_outside_volume(tree, isect, offset, limit-1, depth+1);
88         }
89         else {
90                 return depth;
91         }
92 }
93
94 /* Uses ray tracing to check if a point is inside or outside an ObjectInstanceRen */
95 static int point_inside_obi(RayObject *tree, ObjectInstanceRen *UNUSED(obi), float *co)
96 {
97         Isect isect= {{0}};
98         float dir[3] = {0.0f,0.0f,1.0f};
99         int final_depth=0, depth=0, limit=20;
100         
101         /* set up the isect */
102         copy_v3_v3(isect.start, co);
103         copy_v3_v3(isect.dir, dir);
104         isect.mode= RE_RAY_MIRROR;
105         isect.last_hit= NULL;
106         isect.lay= -1;
107         
108         isect.dist = FLT_MAX;
109         isect.orig.face= NULL;
110         isect.orig.ob = NULL;
111
112         final_depth = intersect_outside_volume(tree, &isect, dir, limit, depth);
113         
114         /* even number of intersections: point is outside
115          * odd number: point is inside */
116         if (final_depth % 2 == 0) return 0;
117         else return 1;
118 }
119
120 /* find the bounding box of an objectinstance in global space */
121 void global_bounds_obi(Render *re, ObjectInstanceRen *obi, float *bbmin, float *bbmax)
122 {
123         ObjectRen *obr = obi->obr;
124         VolumePrecache *vp = obi->volume_precache;
125         VertRen *ver= NULL;
126         float co[3];
127         int a;
128         
129         if (vp->bbmin != NULL && vp->bbmax != NULL) {
130                 copy_v3_v3(bbmin, vp->bbmin);
131                 copy_v3_v3(bbmax, vp->bbmax);
132                 return;
133         }
134         
135         vp->bbmin = MEM_callocN(sizeof(float)*3, "volume precache min boundbox corner");
136         vp->bbmax = MEM_callocN(sizeof(float)*3, "volume precache max boundbox corner");
137         
138         INIT_MINMAX(bbmin, bbmax);
139         
140         for (a=0; a<obr->totvert; a++) {
141                 if ((a & 255)==0) ver= obr->vertnodes[a>>8].vert;
142                 else ver++;
143                 
144                 copy_v3_v3(co, ver->co);
145                 
146                 /* transformed object instance in camera space */
147                 if (obi->flag & R_TRANSFORMED)
148                         mul_m4_v3(obi->mat, co);
149                 
150                 /* convert to global space */
151                 mul_m4_v3(re->viewinv, co);
152                 
153                 DO_MINMAX(co, vp->bbmin, vp->bbmax);
154         }
155         
156         copy_v3_v3(bbmin, vp->bbmin);
157         copy_v3_v3(bbmax, vp->bbmax);
158         
159 }
160
161 /* *** light cache filtering *** */
162
163 static float get_avg_surrounds(float *cache, int *res, int xx, int yy, int zz)
164 {
165         int x, y, z, x_, y_, z_;
166         int added=0;
167         float tot=0.0f;
168         
169         for (z=-1; z <= 1; z++) {
170                 z_ = zz+z;
171                 if (z_ >= 0 && z_ <= res[2]-1) {
172                 
173                         for (y=-1; y <= 1; y++) {
174                                 y_ = yy+y;
175                                 if (y_ >= 0 && y_ <= res[1]-1) {
176                                 
177                                         for (x=-1; x <= 1; x++) {
178                                                 x_ = xx+x;
179                                                 if (x_ >= 0 && x_ <= res[0]-1) {
180                                                         const int i= V_I(x_, y_, z_, res);
181                                                         
182                                                         if (cache[i] > 0.0f) {
183                                                                 tot += cache[i];
184                                                                 added++;
185                                                         }
186                                                         
187                                                 }
188                                         }
189                                 }
190                         }
191                 }
192         }
193         
194         if (added > 0) tot /= added;
195         
196         return tot;
197 }
198
199 /* function to filter the edges of the light cache, where there was no volume originally.
200  * For each voxel which was originally external to the mesh, it finds the average values of
201  * the surrounding internal voxels and sets the original external voxel to that average amount.
202  * Works almost a bit like a 'dilate' filter */
203 static void lightcache_filter(VolumePrecache *vp)
204 {
205         int x, y, z;
206
207         for (z=0; z < vp->res[2]; z++) {
208                 for (y=0; y < vp->res[1]; y++) {
209                         for (x=0; x < vp->res[0]; x++) {
210                                 /* trigger for outside mesh */
211                                 const int i= V_I(x, y, z, vp->res);
212                                 
213                                 if (vp->data_r[i] < -0.f)
214                                         vp->data_r[i] = get_avg_surrounds(vp->data_r, vp->res, x, y, z);
215                                 if (vp->data_g[i] < -0.f)
216                                         vp->data_g[i] = get_avg_surrounds(vp->data_g, vp->res, x, y, z);
217                                 if (vp->data_b[i] < -0.f)
218                                         vp->data_b[i] = get_avg_surrounds(vp->data_b, vp->res, x, y, z);
219                         }
220                 }
221         }
222 }
223
224 #if 0
225 static void lightcache_filter2(VolumePrecache *vp)
226 {
227         int x, y, z;
228         float *new_r, *new_g, *new_b;
229         int field_size = vp->res[0]*vp->res[1]*vp->res[2]*sizeof(float);
230         
231         new_r = MEM_mallocN(field_size, "temp buffer for light cache filter r channel");
232         new_g = MEM_mallocN(field_size, "temp buffer for light cache filter g channel");
233         new_b = MEM_mallocN(field_size, "temp buffer for light cache filter b channel");
234         
235         memcpy(new_r, vp->data_r, field_size);
236         memcpy(new_g, vp->data_g, field_size);
237         memcpy(new_b, vp->data_b, field_size);
238         
239         for (z=0; z < vp->res[2]; z++) {
240                 for (y=0; y < vp->res[1]; y++) {
241                         for (x=0; x < vp->res[0]; x++) {
242                                 /* trigger for outside mesh */
243                                 const int i= V_I(x, y, z, vp->res);
244                                 if (vp->data_r[i] < -0.f)
245                                         new_r[i] = get_avg_surrounds(vp->data_r, vp->res, x, y, z);
246                                 if (vp->data_g[i] < -0.f)
247                                         new_g[i] = get_avg_surrounds(vp->data_g, vp->res, x, y, z);
248                                 if (vp->data_b[i] < -0.f)
249                                         new_b[i] = get_avg_surrounds(vp->data_b, vp->res, x, y, z);
250                         }
251                 }
252         }
253         
254         SWAP(float *, vp->data_r, new_r);
255         SWAP(float *, vp->data_g, new_g);
256         SWAP(float *, vp->data_b, new_b);
257         
258         if (new_r) { MEM_freeN(new_r); new_r=NULL; }
259         if (new_g) { MEM_freeN(new_g); new_g=NULL; }
260         if (new_b) { MEM_freeN(new_b); new_b=NULL; }
261 }
262 #endif
263
264 BLI_INLINE int ms_I(int x, int y, int z, int *n) //has a pad of 1 voxel surrounding the core for boundary simulation
265
266         /* different ordering to light cache */
267         return x*(n[1]+2)*(n[2]+2) + y*(n[2]+2) + z;    
268 }
269
270 BLI_INLINE int v_I_pad(int x, int y, int z, int *n) //has a pad of 1 voxel surrounding the core for boundary simulation
271
272         /* same ordering to light cache, with padding */
273         return z*(n[1]+2)*(n[0]+2) + y*(n[0]+2) + x;    
274 }
275
276 BLI_INLINE int lc_to_ms_I(int x, int y, int z, int *n)
277
278         /* converting light cache index to multiple scattering index */
279         return (x-1)*(n[1]*n[2]) + (y-1)*(n[2]) + z-1;
280 }
281
282 /* *** multiple scattering approximation *** */
283
284 /* get the total amount of light energy in the light cache. used to normalize after multiple scattering */
285 static float total_ss_energy(Render *re, int do_test_break, VolumePrecache *vp)
286 {
287         int x, y, z;
288         int *res = vp->res;
289         float energy=0.f;
290         
291         for (z=0; z < res[2]; z++) {
292                 for (y=0; y < res[1]; y++) {
293                         for (x=0; x < res[0]; x++) {
294                                 const int i=V_I(x, y, z, res);
295                         
296                                 if (vp->data_r[i] > 0.f) energy += vp->data_r[i];
297                                 if (vp->data_g[i] > 0.f) energy += vp->data_g[i];
298                                 if (vp->data_b[i] > 0.f) energy += vp->data_b[i];
299                         }
300                 }
301
302                 if (do_test_break && re->test_break(re->tbh)) break;
303         }
304         
305         return energy;
306 }
307
308 static float total_ms_energy(Render *re, int do_test_break, float *sr, float *sg, float *sb, int *res)
309 {
310         int x, y, z;
311         float energy=0.f;
312         
313         for (z=1;z<=res[2];z++) {
314                 for (y=1;y<=res[1];y++) {
315                         for (x=1;x<=res[0];x++) {
316                                 const int i = ms_I(x,y,z,res);
317                                 
318                                 if (sr[i] > 0.f) energy += sr[i];
319                                 if (sg[i] > 0.f) energy += sg[i];
320                                 if (sb[i] > 0.f) energy += sb[i];
321                         }
322                 }
323
324                 if (do_test_break && re->test_break(re->tbh)) break;
325         }
326         
327         return energy;
328 }
329
330 static void ms_diffuse(Render *re, int do_test_break, float *x0, float *x, float diff, int *n) //n is the unpadded resolution
331 {
332         int i, j, k, l;
333         const float dt = VOL_MS_TIMESTEP;
334         size_t size = n[0]*n[1]*n[2];
335         const float a = dt*diff*size;
336         
337         for (l=0; l<20; l++)
338         {
339                 for (k=1; k<=n[2]; k++)
340                 {
341                         for (j=1; j<=n[1]; j++)
342                         {
343                                 for (i=1; i<=n[0]; i++)
344                                 {
345                                    x[v_I_pad(i,j,k,n)] = (x0[v_I_pad(i,j,k,n)]) + a*(   x0[v_I_pad(i-1,j,k,n)]+ x0[v_I_pad(i+1,j,k,n)]+ x0[v_I_pad(i,j-1,k,n)]+
346                                                                                                                                                 x0[v_I_pad(i,j+1,k,n)]+ x0[v_I_pad(i,j,k-1,n)]+x0[v_I_pad(i,j,k+1,n)]
347                                                                                                                                                 ) / (1+6*a);
348                                 }
349                         }
350
351                         if (do_test_break && re->test_break(re->tbh)) break;
352                 }
353
354                 if (re->test_break(re->tbh)) break;
355         }
356 }
357
358 static void multiple_scattering_diffusion(Render *re, VolumePrecache *vp, Material *ma)
359 {
360         const float diff = ma->vol.ms_diff * 0.001f;    /* compensate for scaling for a nicer UI range */
361         const int simframes = (int)(ma->vol.ms_spread * (float)MAX3(vp->res[0], vp->res[1], vp->res[2]));
362         const int shade_type = ma->vol.shade_type;
363         float fac = ma->vol.ms_intensity;
364         
365         int x, y, z, m;
366         int *n = vp->res;
367         const int size = (n[0]+2)*(n[1]+2)*(n[2]+2);
368         const int do_test_break = (size > 100000);
369         double time, lasttime= PIL_check_seconds_timer();
370         float total;
371         float c=1.0f;
372         float origf;    /* factor for blending in original light cache */
373         float energy_ss, energy_ms;
374
375         float *sr0=(float *)MEM_callocN(size*sizeof(float), "temporary multiple scattering buffer");
376         float *sr=(float *)MEM_callocN(size*sizeof(float), "temporary multiple scattering buffer");
377         float *sg0=(float *)MEM_callocN(size*sizeof(float), "temporary multiple scattering buffer");
378         float *sg=(float *)MEM_callocN(size*sizeof(float), "temporary multiple scattering buffer");
379         float *sb0=(float *)MEM_callocN(size*sizeof(float), "temporary multiple scattering buffer");
380         float *sb=(float *)MEM_callocN(size*sizeof(float), "temporary multiple scattering buffer");
381
382         total = (float)(n[0]*n[1]*n[2]*simframes);
383         
384         energy_ss = total_ss_energy(re, do_test_break, vp);
385         
386         /* Scattering as diffusion pass */
387         for (m=0; m<simframes; m++)
388         {
389                 /* add sources */
390                 for (z=1; z<=n[2]; z++)
391                 {
392                         for (y=1; y<=n[1]; y++)
393                         {
394                                 for (x=1; x<=n[0]; x++)
395                                 {
396                                         const int i = lc_to_ms_I(x, y ,z, n);   //lc index                                      
397                                         const int j = ms_I(x, y, z, n);                 //ms index
398                                         
399                                         time= PIL_check_seconds_timer();
400                                         c++;                                                                            
401                                         if (vp->data_r[i] > 0.0f)
402                                                 sr[j] += vp->data_r[i];
403                                         if (vp->data_g[i] > 0.0f)
404                                                 sg[j] += vp->data_g[i];
405                                         if (vp->data_b[i] > 0.0f)
406                                                 sb[j] += vp->data_b[i];
407                                         
408                                         /* Displays progress every second */
409                                         if (time-lasttime>1.0) {
410                                                 char str[64];
411                                                 BLI_snprintf(str, sizeof(str), "Simulating multiple scattering: %d%%", (int)(100.0f * (c / total)));
412                                                 re->i.infostr= str;
413                                                 re->stats_draw(re->sdh, &re->i);
414                                                 re->i.infostr= NULL;
415                                                 lasttime= time;
416                                         }
417                                 }
418                         }
419
420                         if (do_test_break && re->test_break(re->tbh)) break;
421                 }
422
423                 if (re->test_break(re->tbh)) break;
424
425                 SWAP(float *,sr,sr0);
426                 SWAP(float *,sg,sg0);
427                 SWAP(float *,sb,sb0);
428
429                 /* main diffusion simulation */
430                 ms_diffuse(re, do_test_break, sr0, sr, diff, n);
431                 ms_diffuse(re, do_test_break, sg0, sg, diff, n);
432                 ms_diffuse(re, do_test_break, sb0, sb, diff, n);
433                 
434                 if (re->test_break(re->tbh)) break;
435         }
436         
437         /* normalization factor to conserve energy */
438         energy_ms = total_ms_energy(re, do_test_break, sr, sg, sb, n);
439         fac *= (energy_ss / energy_ms);
440         
441         /* blend multiple scattering back in the light cache */
442         if (shade_type == MA_VOL_SHADE_SHADEDPLUSMULTIPLE) {
443                 /* conserve energy - half single, half multiple */
444                 origf = 0.5f;
445                 fac *= 0.5f;
446         }
447         else {
448                 origf = 0.0f;
449         }
450
451         for (z=1;z<=n[2];z++)
452         {
453                 for (y=1;y<=n[1];y++)
454                 {
455                         for (x=1;x<=n[0];x++)
456                         {
457                                 const int i = lc_to_ms_I(x, y ,z, n);   //lc index                                      
458                                 const int j = ms_I(x, y, z, n);                 //ms index
459                                 
460                                 vp->data_r[i] = origf * vp->data_r[i] + fac * sr[j];
461                                 vp->data_g[i] = origf * vp->data_g[i] + fac * sg[j];
462                                 vp->data_b[i] = origf * vp->data_b[i] + fac * sb[j];
463                         }
464                 }
465
466                 if (do_test_break && re->test_break(re->tbh)) break;
467         }
468
469         MEM_freeN(sr0);
470         MEM_freeN(sr);
471         MEM_freeN(sg0);
472         MEM_freeN(sg);
473         MEM_freeN(sb0);
474         MEM_freeN(sb);
475 }
476
477
478
479 #if 0 // debug stuff
480 static void *vol_precache_part_test(void *data)
481 {
482         VolPrecachePart *pa = data;
483
484         printf("part number: %d\n", pa->num);
485         printf("done: %d\n", pa->done);
486         printf("x min: %d   x max: %d\n", pa->minx, pa->maxx);
487         printf("y min: %d   y max: %d\n", pa->miny, pa->maxy);
488         printf("z min: %d   z max: %d\n", pa->minz, pa->maxz);
489
490         return NULL;
491 }
492 #endif
493
494 typedef struct VolPrecacheQueue {
495         ThreadQueue *work;
496         ThreadQueue *done;
497 } VolPrecacheQueue;
498
499 /* Iterate over the 3d voxel grid, and fill the voxels with scattering information
500  *
501  * It's stored in memory as 3 big float grids next to each other, one for each RGB channel.
502  * I'm guessing the memory alignment may work out better this way for the purposes
503  * of doing linear interpolation, but I haven't actually tested this theory! :)
504  */
505 static void *vol_precache_part(void *data)
506 {
507         VolPrecacheQueue *queue = (VolPrecacheQueue*)data;
508         VolPrecachePart *pa;
509
510         while ((pa = BLI_thread_queue_pop(queue->work))) {
511                 ObjectInstanceRen *obi = pa->obi;
512                 RayObject *tree = pa->tree;
513                 ShadeInput *shi = pa->shi;
514                 float scatter_col[3] = {0.f, 0.f, 0.f};
515                 float co[3], cco[3], view[3];
516                 int x, y, z, i;
517                 int res[3];
518
519                 if (pa->re->test_break && pa->re->test_break(pa->re->tbh))
520                         break;
521
522                 res[0]= pa->res[0];
523                 res[1]= pa->res[1];
524                 res[2]= pa->res[2];
525
526                 for (z= pa->minz; z < pa->maxz; z++) {
527                         co[2] = pa->bbmin[2] + (pa->voxel[2] * (z + 0.5f));
528                         
529                         for (y= pa->miny; y < pa->maxy; y++) {
530                                 co[1] = pa->bbmin[1] + (pa->voxel[1] * (y + 0.5f));
531                                 
532                                 for (x=pa->minx; x < pa->maxx; x++) {
533                                         co[0] = pa->bbmin[0] + (pa->voxel[0] * (x + 0.5f));
534                                         
535                                         if (pa->re->test_break && pa->re->test_break(pa->re->tbh))
536                                                 break;
537                                         
538                                         /* convert from world->camera space for shading */
539                                         mul_v3_m4v3(cco, pa->viewmat, co);
540                                         
541                                         i= V_I(x, y, z, res);
542                                         
543                                         // don't bother if the point is not inside the volume mesh
544                                         if (!point_inside_obi(tree, obi, cco)) {
545                                                 obi->volume_precache->data_r[i] = -1.0f;
546                                                 obi->volume_precache->data_g[i] = -1.0f;
547                                                 obi->volume_precache->data_b[i] = -1.0f;
548                                                 continue;
549                                         }
550                                         
551                                         copy_v3_v3(view, cco);
552                                         normalize_v3(view);
553                                         vol_get_scattering(shi, scatter_col, cco, view);
554                                 
555                                         obi->volume_precache->data_r[i] = scatter_col[0];
556                                         obi->volume_precache->data_g[i] = scatter_col[1];
557                                         obi->volume_precache->data_b[i] = scatter_col[2];
558                                         
559                                 }
560                         }
561                 }
562
563                 BLI_thread_queue_push(queue->done, pa);
564         }
565         
566         return NULL;
567 }
568
569
570 static void precache_setup_shadeinput(Render *re, ObjectInstanceRen *obi, Material *ma, ShadeInput *shi)
571 {
572         memset(shi, 0, sizeof(ShadeInput)); 
573         shi->depth= 1;
574         shi->mask= 1;
575         shi->mat = ma;
576         shi->vlr = NULL;
577         memcpy(&shi->r, &shi->mat->r, 23*sizeof(float));        // note, keep this synced with render_types.h
578         shi->har= shi->mat->har;
579         shi->obi= obi;
580         shi->obr= obi->obr;
581         shi->lay = re->lay;
582 }
583
584 static void precache_init_parts(Render *re, RayObject *tree, ShadeInput *shi, ObjectInstanceRen *obi, int totthread, int *parts)
585 {
586         VolumePrecache *vp = obi->volume_precache;
587         int i=0, x, y, z;
588         float voxel[3];
589         int sizex, sizey, sizez;
590         float bbmin[3], bbmax[3];
591         int *res;
592         int minx, maxx;
593         int miny, maxy;
594         int minz, maxz;
595         
596         if (!vp) return;
597
598         BLI_freelistN(&re->volume_precache_parts);
599         
600         /* currently we just subdivide the box, number of threads per side */
601         parts[0] = parts[1] = parts[2] = totthread;
602         res = vp->res;
603         
604         /* using boundbox in worldspace */
605         global_bounds_obi(re, obi, bbmin, bbmax);
606         sub_v3_v3v3(voxel, bbmax, bbmin);
607         
608         voxel[0] /= (float)res[0];
609         voxel[1] /= (float)res[1];
610         voxel[2] /= (float)res[2];
611
612         for (x=0; x < parts[0]; x++) {
613                 sizex = ceil(res[0] / (float)parts[0]);
614                 minx = x * sizex;
615                 maxx = minx + sizex;
616                 maxx = (maxx>res[0])?res[0]:maxx;
617                 
618                 for (y=0; y < parts[1]; y++) {
619                         sizey = ceil(res[1] / (float)parts[1]);
620                         miny = y * sizey;
621                         maxy = miny + sizey;
622                         maxy = (maxy>res[1])?res[1]:maxy;
623                         
624                         for (z=0; z < parts[2]; z++) {
625                                 VolPrecachePart *pa= MEM_callocN(sizeof(VolPrecachePart), "new precache part");
626                                 
627                                 sizez = ceil(res[2] / (float)parts[2]);
628                                 minz = z * sizez;
629                                 maxz = minz + sizez;
630                                 maxz = (maxz>res[2])?res[2]:maxz;
631                                 
632                                 pa->re = re;
633                                 pa->num = i;
634                                 pa->tree = tree;
635                                 pa->shi = shi;
636                                 pa->obi = obi;
637                                 copy_m4_m4(pa->viewmat, re->viewmat);
638                                 
639                                 copy_v3_v3(pa->bbmin, bbmin);
640                                 copy_v3_v3(pa->voxel, voxel);
641                                 copy_v3_v3_int(pa->res, res);
642                                 
643                                 pa->minx = minx; pa->maxx = maxx;
644                                 pa->miny = miny; pa->maxy = maxy;
645                                 pa->minz = minz; pa->maxz = maxz;
646                                 
647                                 
648                                 BLI_addtail(&re->volume_precache_parts, pa);
649                                 
650                                 i++;
651                         }
652                 }
653         }
654 }
655
656 /* calculate resolution from bounding box in world space */
657 static int precache_resolution(Render *re, VolumePrecache *vp, ObjectInstanceRen *obi, int res)
658 {
659         float dim[3], div;
660         float bbmin[3], bbmax[3];
661         
662         /* bound box in global space */
663         global_bounds_obi(re, obi, bbmin, bbmax);
664         sub_v3_v3v3(dim, bbmax, bbmin);
665         
666         div = MAX3(dim[0], dim[1], dim[2]);
667         dim[0] /= div;
668         dim[1] /= div;
669         dim[2] /= div;
670         
671         vp->res[0] = ceil(dim[0] * res);
672         vp->res[1] = ceil(dim[1] * res);
673         vp->res[2] = ceil(dim[2] * res);
674         
675         if ((vp->res[0] < 1) || (vp->res[1] < 1) || (vp->res[2] < 1))
676                 return 0;
677         
678         return 1;
679 }
680
681 /* Precache a volume into a 3D voxel grid.
682  * The voxel grid is stored in the ObjectInstanceRen, 
683  * in camera space, aligned with the ObjectRen's bounding box.
684  * Resolution is defined by the user.
685  */
686 static void vol_precache_objectinstance_threads(Render *re, ObjectInstanceRen *obi, Material *ma)
687 {
688         VolumePrecache *vp;
689         VolPrecachePart *pa;
690         RayObject *tree;
691         ShadeInput shi;
692         ListBase threads;
693         VolPrecacheQueue queue;
694         int parts[3] = {1, 1, 1}, totparts;
695         
696         int counter=0;
697         int totthread = re->r.threads, thread;
698         
699         double time, lasttime= PIL_check_seconds_timer();
700         
701         R = *re;
702
703         /* create a raytree with just the faces of the instanced ObjectRen, 
704          * used for checking if the cached point is inside or outside. */
705         tree = makeraytree_object(&R, obi);
706         if (!tree) return;
707
708         vp = MEM_callocN(sizeof(VolumePrecache), "volume light cache");
709         obi->volume_precache = vp;
710         
711         if (!precache_resolution(re, vp, obi, ma->vol.precache_resolution)) {
712                 MEM_freeN(vp);
713                 vp = NULL;
714                 return;
715         }
716
717         vp->data_r = MEM_callocN(sizeof(float)*vp->res[0]*vp->res[1]*vp->res[2], "volume light cache data red channel");
718         vp->data_g = MEM_callocN(sizeof(float)*vp->res[0]*vp->res[1]*vp->res[2], "volume light cache data green channel");
719         vp->data_b = MEM_callocN(sizeof(float)*vp->res[0]*vp->res[1]*vp->res[2], "volume light cache data blue channel");
720         if (vp->data_r==NULL || vp->data_g==NULL || vp->data_b==NULL) {
721                 MEM_freeN(vp);
722                 return;
723         }
724
725         /* Need a shadeinput to calculate scattering */
726         precache_setup_shadeinput(re, obi, ma, &shi);
727         
728         precache_init_parts(re, tree, &shi, obi, totthread, parts);
729         totparts = parts[0] * parts[1] * parts[2];
730
731         /* setup work and done queues */
732         queue.work = BLI_thread_queue_init();
733         queue.done = BLI_thread_queue_init();
734         BLI_thread_queue_nowait(queue.work);
735
736         for (pa= re->volume_precache_parts.first; pa; pa= pa->next)
737                 BLI_thread_queue_push(queue.work, pa);
738         
739         /* launch threads */
740         BLI_init_threads(&threads, vol_precache_part, totthread);
741
742         for (thread= 0; thread<totthread; thread++)
743                 BLI_insert_thread(&threads, &queue);
744         
745         /* loop waiting for work to be done */
746         while (counter < totparts) {
747                 if (re->test_break && re->test_break(re->tbh))
748                         break;
749
750                 if (BLI_thread_queue_pop_timeout(queue.done, 50))
751                         counter++;
752
753                 time= PIL_check_seconds_timer();
754                 if (time-lasttime>1.0) {
755                         char str[64];
756                         BLI_snprintf(str, sizeof(str), "Precaching volume: %d%%", (int)(100.0f * ((float)counter / (float)totparts)));
757                         re->i.infostr= str;
758                         re->stats_draw(re->sdh, &re->i);
759                         re->i.infostr= NULL;
760                         lasttime= time;
761                 }
762         }
763         
764         /* free */
765         BLI_end_threads(&threads);
766         BLI_thread_queue_free(queue.work);
767         BLI_thread_queue_free(queue.done);
768         BLI_freelistN(&re->volume_precache_parts);
769         
770         if (tree) {
771                 //TODO: makeraytree_object creates a tree and saves it on OBI, if we free this tree we should also clear other pointers to it
772                 //RE_rayobject_free(tree);
773                 //tree= NULL;
774         }
775         
776         if (ELEM(ma->vol.shade_type, MA_VOL_SHADE_MULTIPLE, MA_VOL_SHADE_SHADEDPLUSMULTIPLE)) {
777                 /* this should be before the filtering */
778                 multiple_scattering_diffusion(re, obi->volume_precache, ma);
779         }
780                 
781         lightcache_filter(obi->volume_precache);
782 }
783
784 static int using_lightcache(Material *ma)
785 {
786         return (((ma->vol.shadeflag & MA_VOL_PRECACHESHADING) && (ma->vol.shade_type == MA_VOL_SHADE_SHADED))
787                 || (ELEM(ma->vol.shade_type, MA_VOL_SHADE_MULTIPLE, MA_VOL_SHADE_SHADEDPLUSMULTIPLE)));
788 }
789
790 /* loop through all objects (and their associated materials)
791  * marked for pre-caching in convertblender.c, and pre-cache them */
792 void volume_precache(Render *re)
793 {
794         ObjectInstanceRen *obi;
795         VolumeOb *vo;
796
797         re->i.infostr= "Volume preprocessing";
798         re->stats_draw(re->sdh, &re->i);
799
800         for (vo= re->volumes.first; vo; vo= vo->next) {
801                 if (using_lightcache(vo->ma)) {
802                         for (obi= re->instancetable.first; obi; obi= obi->next) {
803                                 if (obi->obr == vo->obr) {
804                                         vol_precache_objectinstance_threads(re, obi, vo->ma);
805
806                                         if (re->test_break && re->test_break(re->tbh))
807                                                 break;
808                                 }
809                         }
810
811                         if (re->test_break && re->test_break(re->tbh))
812                                 break;
813                 }
814         }
815         
816         re->i.infostr= NULL;
817         re->stats_draw(re->sdh, &re->i);
818 }
819
820 void free_volume_precache(Render *re)
821 {
822         ObjectInstanceRen *obi;
823         
824         for (obi= re->instancetable.first; obi; obi= obi->next) {
825                 if (obi->volume_precache != NULL) {
826                         MEM_freeN(obi->volume_precache->data_r);
827                         MEM_freeN(obi->volume_precache->data_g);
828                         MEM_freeN(obi->volume_precache->data_b);
829                         MEM_freeN(obi->volume_precache->bbmin);
830                         MEM_freeN(obi->volume_precache->bbmax);
831                         MEM_freeN(obi->volume_precache);
832                         obi->volume_precache = NULL;
833                 }
834         }
835         
836         BLI_freelistN(&re->volumes);
837 }
838
839 int point_inside_volume_objectinstance(Render *re, ObjectInstanceRen *obi, float *co)
840 {
841         RayObject *tree;
842         int inside=0;
843         
844         tree = makeraytree_object(re, obi);
845         if (!tree) return 0;
846         
847         inside = point_inside_obi(tree, obi, co);
848         
849         //TODO: makeraytree_object creates a tree and saves it on OBI, if we free this tree we should also clear other pointers to it
850         //RE_rayobject_free(tree);
851         //tree= NULL;
852         
853         return inside;
854 }
855