diff options
author | Matt Ebb <matt@mke3.net> | 2009-08-13 09:21:25 +0400 |
---|---|---|
committer | Matt Ebb <matt@mke3.net> | 2009-08-13 09:21:25 +0400 |
commit | 5a21bc578cc392b9f21ee5355f4062075f45f907 (patch) | |
tree | 3e05ca77ef3d1be07b22433275df09cad6f4a405 /source/blender/render | |
parent | 44ca632ce77edbbb0a85f5ca8dde26c68f9efbd1 (diff) | |
parent | 7da0d1a71efee9b360eb344e7bfaa9b5f0f4ece5 (diff) |
* First commit merging 2.4-based sim_physics in to volume25 branch.
Integration is still very rough around the edges and WIP, but it works, and can render smoke (using new Smoke format in Voxel Data texture) --> http://vimeo.com/6030983
More to come, but this makes things much easier to work on for me :)
Diffstat (limited to 'source/blender/render')
19 files changed, 2823 insertions, 20 deletions
diff --git a/source/blender/render/CMakeLists.txt b/source/blender/render/CMakeLists.txt index 411bd61c3ff..4eb750262ec 100644 --- a/source/blender/render/CMakeLists.txt +++ b/source/blender/render/CMakeLists.txt @@ -30,6 +30,7 @@ SET(INC intern/include ../../../intern/guardedalloc ../blenlib ../makesdna extern/include ../blenkernel ../radiosity/extern/include ../imbuf ../quicktime ../include ../../kernel/gen_messaging ../blenloader + ../../../intern/smoke/extern ../makesrna ) diff --git a/source/blender/render/extern/include/RE_shader_ext.h b/source/blender/render/extern/include/RE_shader_ext.h index 0ad48fe97a9..36613588ff3 100644 --- a/source/blender/render/extern/include/RE_shader_ext.h +++ b/source/blender/render/extern/include/RE_shader_ext.h @@ -113,7 +113,7 @@ typedef struct ShadeInput /* internal face coordinates */ float u, v, dx_u, dx_v, dy_u, dy_v; - float co[3], view[3]; + float co[3], view[3], camera_co[3]; /* copy from material, keep synced so we can do memcopy */ /* current size: 23*4 */ @@ -161,6 +161,7 @@ typedef struct ShadeInput int samplenr; /* sample counter, to detect if we should do shadow again */ int depth; /* 1 or larger on raytrace shading */ + int volume_depth; /* number of intersections through volumes */ /* stored copy of original face normal (facenor) * before flipping. Used in Front/back output on geometry node */ diff --git a/source/blender/render/intern/include/pointdensity.h b/source/blender/render/intern/include/pointdensity.h new file mode 100644 index 00000000000..93cdef3b14e --- /dev/null +++ b/source/blender/render/intern/include/pointdensity.h @@ -0,0 +1,44 @@ +/* + * + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. + * All rights reserved. + * + * The Original Code is: all of this file. + * + * Contributor(s): Matt Ebb + * + * ***** END GPL LICENSE BLOCK ***** + */ + +#ifndef POINTDENSITY_H +#define POINTDENSITY_H + +/** + * Make point density kd-trees for all point density textures in the scene + */ + +struct Render; +struct TexResult; + +void make_pointdensities(struct Render *re); +void free_pointdensities(struct Render *re); +int pointdensitytex(struct Tex *tex, float *texvec, struct TexResult *texres); + +#endif /* POINTDENSITY_H */ + diff --git a/source/blender/render/intern/include/render_types.h b/source/blender/render/intern/include/render_types.h index ab3758781ce..c4910f7733d 100644 --- a/source/blender/render/intern/include/render_types.h +++ b/source/blender/render/intern/include/render_types.h @@ -201,6 +201,9 @@ struct Render ListBase customdata_names; struct Object *excludeob; + ListBase render_volumes_inside; + ListBase volumes; + ListBase volume_precache_parts; /* arena for allocating data for use during render, for * example dynamic TFaces to go in the VlakRen structure. @@ -292,7 +295,9 @@ typedef struct ObjectInstanceRen { float dupliorco[3], dupliuv[2]; float (*duplitexmat)[4]; - + + struct VolumePrecache *volume_precache; + float *vectors; int totvector; } ObjectInstanceRen; @@ -402,6 +407,45 @@ typedef struct StrandRen { float orco[3]; } StrandRen; +/* ------------------------------------------------------------------------- */ + +typedef struct VolumeOb +{ + struct VolumeOb *next, *prev; + struct Material *ma; + struct ObjectRen *obr; +} VolumeOb; + +typedef struct MatInside { + struct MatInside *next, *prev; + struct Material *ma; +} MatInside; + +typedef struct VolPrecachePart +{ + struct VolPrecachePart *next, *prev; + struct RayTree *tree; + struct ShadeInput *shi; + struct ObjectInstanceRen *obi; + int num; + int minx, maxx; + int miny, maxy; + int minz, maxz; + int res[3]; + float bbmin[3]; + float voxel[3]; + int working, done; +} VolPrecachePart; + +typedef struct VolumePrecache +{ + int res[3]; + float *data_r; + float *data_g; + float *data_b; +} VolumePrecache; + +/* ------------------------------------------------------------------------- */ struct LampRen; struct MTex; diff --git a/source/blender/render/intern/include/shading.h b/source/blender/render/intern/include/shading.h index d195f32d5ef..95bccd2be1e 100644 --- a/source/blender/render/intern/include/shading.h +++ b/source/blender/render/intern/include/shading.h @@ -33,6 +33,7 @@ struct VlakRen; struct StrandSegment; struct StrandPoint; struct ObjectInstanceRen obi; +struct Isect; /* shadeinput.c */ @@ -52,6 +53,7 @@ typedef struct ShadeSample { /* also the node shader callback */ void shade_material_loop(struct ShadeInput *shi, struct ShadeResult *shr); +void shade_volume_loop(struct ShadeInput *shi, struct ShadeResult *shr); void shade_input_set_triangle_i(struct ShadeInput *shi, struct ObjectInstanceRen *obi, struct VlakRen *vlr, short i1, short i2, short i3); void shade_input_set_triangle(struct ShadeInput *shi, volatile int obi, volatile int facenr, int normal_flip); @@ -87,7 +89,11 @@ void shade_color(struct ShadeInput *shi, ShadeResult *shr); void ambient_occlusion_to_diffuse(struct ShadeInput *shi, float *diff); void ambient_occlusion(struct ShadeInput *shi); +ListBase *get_lights(struct ShadeInput *shi); float lamp_get_visibility(struct LampRen *lar, float *co, float *lv, float *dist); void lamp_get_shadow(struct LampRen *lar, ShadeInput *shi, float inp, float *shadfac, int do_real); float fresnel_fac(float *view, float *vn, float fresnel, float fac); + +/* rayshade.c */ +extern void shade_ray(struct Isect *is, struct ShadeInput *shi, struct ShadeResult *shr); diff --git a/source/blender/render/intern/include/volume_precache.h b/source/blender/render/intern/include/volume_precache.h new file mode 100644 index 00000000000..d8a94c2d560 --- /dev/null +++ b/source/blender/render/intern/include/volume_precache.h @@ -0,0 +1,34 @@ +/** + * + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. + * All rights reserved. + * + * The Original Code is: all of this file. + * + * Contributor(s): Matt Ebb. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +void volume_precache(Render *re); +void free_volume_precache(Render *re); +int point_inside_volume_objectinstance(ObjectInstanceRen *obi, float *co); +int using_lightcache(Material *ma); + +#define VOL_MS_TIMESTEP 0.1f
\ No newline at end of file diff --git a/source/blender/render/intern/include/volumetric.h b/source/blender/render/intern/include/volumetric.h new file mode 100644 index 00000000000..40d79e8d173 --- /dev/null +++ b/source/blender/render/intern/include/volumetric.h @@ -0,0 +1,47 @@ +/** + * + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. + * All rights reserved. + * + * The Original Code is: all of this file. + * + * Contributor(s): Matt Ebb. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +float vol_get_stepsize(struct ShadeInput *shi, int context); +float vol_get_density(struct ShadeInput *shi, float *co); +void vol_get_scattering(ShadeInput *shi, float *scatter, float *co, float stepsize, float density); + +void shade_volume_outside(ShadeInput *shi, ShadeResult *shr); +void shade_volume_inside(ShadeInput *shi, ShadeResult *shr); +void shade_volume_shadow(struct ShadeInput *shi, struct ShadeResult *shr, struct Isect *last_is); + +#define STEPSIZE_VIEW 0 +#define STEPSIZE_SHADE 1 + +#define VOL_IS_BACKFACE 1 +#define VOL_IS_SAMEMATERIAL 2 + +#define VOL_BOUNDS_DEPTH 0 +#define VOL_BOUNDS_SS 1 + +#define VOL_SHADE_OUTSIDE 0 +#define VOL_SHADE_INSIDE 1
\ No newline at end of file diff --git a/source/blender/render/intern/include/voxeldata.h b/source/blender/render/intern/include/voxeldata.h new file mode 100644 index 00000000000..b291bdc096d --- /dev/null +++ b/source/blender/render/intern/include/voxeldata.h @@ -0,0 +1,45 @@ +/** + * + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. + * All rights reserved. + * + * The Original Code is: all of this file. + * + * Contributor(s): Raul Fernandez Hernandez (Farsthary), Matt Ebb. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +#ifndef VOXELDATA_H +#define VOXELDATA_H + +struct Render; +struct TexResult; + +typedef struct VoxelDataHeader +{ + int resolX, resolY, resolZ; + int frames; +} VoxelDataHeader; + +void make_voxeldata(struct Render *re); +void free_voxeldata(struct Render *re); +int voxeldatatex(struct Tex *tex, float *texvec, struct TexResult *texres); + +#endif /* VOXELDATA_H */ diff --git a/source/blender/render/intern/source/convertblender.c b/source/blender/render/intern/source/convertblender.c index 2b06f164c12..9f054caf7d9 100644 --- a/source/blender/render/intern/source/convertblender.c +++ b/source/blender/render/intern/source/convertblender.c @@ -100,6 +100,8 @@ #include "envmap.h" #include "occlusion.h" +#include "pointdensity.h" +#include "voxeldata.h" #include "render_types.h" #include "rendercore.h" #include "renderdatabase.h" @@ -108,6 +110,7 @@ #include "shading.h" #include "strand.h" #include "texture.h" +#include "volume_precache.h" #include "sss.h" #include "strand.h" #include "zbuf.h" @@ -2976,6 +2979,53 @@ static void use_mesh_edge_lookup(ObjectRen *obr, DerivedMesh *dm, MEdge *medge, } } +static void free_camera_inside_volumes(Render *re) +{ + BLI_freelistN(&re->render_volumes_inside); +} + +static void init_camera_inside_volumes(Render *re) +{ + ObjectInstanceRen *obi; + VolumeOb *vo; + float co[3] = {0.f, 0.f, 0.f}; + + for(vo= re->volumes.first; vo; vo= vo->next) { + for(obi= re->instancetable.first; obi; obi= obi->next) { + if (obi->obr == vo->obr) { + if (point_inside_volume_objectinstance(obi, co)) { + MatInside *mi; + + mi = MEM_mallocN(sizeof(MatInside), "camera inside material"); + mi->ma = vo->ma; + + BLI_addtail(&(re->render_volumes_inside), mi); + } + } + } + } + + { + MatInside *m; + for (m=re->render_volumes_inside.first; m; m=m->next) { + printf("matinside: ma: %s \n", m->ma->id.name+2); + } + + } +} + +static void add_volume(Render *re, ObjectRen *obr, Material *ma) +{ + struct VolumeOb *vo; + + vo = MEM_mallocN(sizeof(VolumeOb), "volume object"); + + vo->ma = ma; + vo->obr = obr; + + BLI_addtail(&re->volumes, vo); +} + static void init_render_mesh(Render *re, ObjectRen *obr, int timeoffset) { Object *ob= obr->ob; @@ -3030,6 +3080,9 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int timeoffset) if(re->r.mode & R_RADIO) if(ma->mode & MA_RADIO) do_autosmooth= 1; + + if (ma->material_type == MA_TYPE_VOLUME) + add_volume(re, obr, ma); } } @@ -4338,6 +4391,8 @@ void RE_Database_Free(Render *re) curvemapping_free(lar->curfalloff); } + free_volume_precache(re); + BLI_freelistN(&re->lampren); BLI_freelistN(&re->lights); @@ -4364,6 +4419,11 @@ void RE_Database_Free(Render *re) end_render_materials(); end_render_textures(); + free_pointdensities(re); + free_voxeldata(re); + + free_camera_inside_volumes(re); + if(re->wrld.aosphere) { MEM_freeN(re->wrld.aosphere); re->wrld.aosphere= NULL; @@ -4756,6 +4816,8 @@ void RE_Database_FromScene(Render *re, Scene *scene, int use_camera_view) /* MAKE RENDER DATA */ database_init_objects(re, lay, 0, 0, 0, 0); + + init_camera_inside_volumes(re); if(!re->test_break(re->tbh)) { int tothalo; @@ -4804,6 +4866,13 @@ void RE_Database_FromScene(Render *re, Scene *scene, int use_camera_view) /* ENVIRONMENT MAPS */ if(!re->test_break(re->tbh)) make_envmaps(re); + + /* point density texture */ + if(!re->test_break(re->tbh)) + make_pointdensities(re); + /* voxel data texture */ + if(!re->test_break(re->tbh)) + make_voxeldata(re); } if(!re->test_break(re->tbh)) @@ -4820,6 +4889,11 @@ void RE_Database_FromScene(Render *re, Scene *scene, int use_camera_view) if((re->r.mode & R_SSS) && !re->test_break(re->tbh)) if(re->r.renderer==R_INTERN) make_sss_tree(re); + + if(!re->test_break(re->tbh)) + if(re->r.mode & R_RAYTRACE) + volume_precache(re); + } if(re->test_break(re->tbh)) diff --git a/source/blender/render/intern/source/occlusion.c b/source/blender/render/intern/source/occlusion.c index feef3dd424a..a24454a38c4 100644 --- a/source/blender/render/intern/source/occlusion.c +++ b/source/blender/render/intern/source/occlusion.c @@ -630,7 +630,7 @@ static OcclusionTree *occ_tree_build(Render *re) if((a & 255)==0) vlr= obr->vlaknodes[a>>8].vlak; else vlr++; - if(vlr->mat->mode & MA_TRACEBLE) + if((vlr->mat->mode & MA_TRACEBLE) && (vlr->mat->material_type == MA_TYPE_SURFACE)) totface++; } } diff --git a/source/blender/render/intern/source/pointdensity.c b/source/blender/render/intern/source/pointdensity.c new file mode 100644 index 00000000000..fb7ec4dadc2 --- /dev/null +++ b/source/blender/render/intern/source/pointdensity.c @@ -0,0 +1,492 @@ +/* + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. + * All rights reserved. + * + * Contributors: Matt Ebb + * + * ***** END GPL LICENSE BLOCK ***** + */ + +#include <math.h> +#include <stdlib.h> +#include <stdio.h> + +#include "MEM_guardedalloc.h" + +#include "BLI_arithb.h" +#include "BLI_blenlib.h" +#include "BLI_kdopbvh.h" + +#include "BKE_DerivedMesh.h" +#include "BKE_global.h" +#include "BKE_lattice.h" +#include "BKE_main.h" +#include "BKE_object.h" +#include "BKE_particle.h" +#include "BKE_texture.h" + +#include "DNA_texture_types.h" +#include "DNA_particle_types.h" + +#include "render_types.h" +#include "renderdatabase.h" +#include "texture.h" + +/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ +/* defined in pipeline.c, is hardcopy of active dynamic allocated Render */ +/* only to be used here in this file, it's for speed */ +extern struct Render R; +/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ + + +static int point_data_used(PointDensity *pd) +{ + int pd_bitflag = 0; + + if ((pd->noise_influence == TEX_PD_NOISE_VEL) || (pd->color_source == TEX_PD_COLOR_PARTVEL) || (pd->color_source == TEX_PD_COLOR_PARTSPEED)) + pd_bitflag |= POINT_DATA_VEL; + if ((pd->noise_influence == TEX_PD_NOISE_AGE) || (pd->color_source == TEX_PD_COLOR_PARTAGE)) + pd_bitflag |= POINT_DATA_LIFE; + + return pd_bitflag; +} + + +/* additional data stored alongside the point density BVH, + * accessible by point index number to retrieve other information + * such as particle velocity or lifetime */ +static void alloc_point_data(PointDensity *pd, int total_particles, int point_data_used) +{ + int data_size = 0; + + if (point_data_used & POINT_DATA_VEL) { + /* store 3 channels of velocity data */ + data_size += 3; + } + if (point_data_used & POINT_DATA_LIFE) { + /* store 1 channel of lifetime data */ + data_size += 1; + } + + if (data_size) + pd->point_data = MEM_mallocN(sizeof(float)*data_size*total_particles, "particle point data"); +} + +static void pointdensity_cache_psys(Render *re, PointDensity *pd, Object *ob, ParticleSystem *psys) +{ + DerivedMesh* dm; + ParticleKey state; + ParticleData *pa=NULL; + float cfra = bsystem_time(re->scene, ob, (float)re->scene->r.cfra, 0.0); + int i, childexists; + int total_particles, offset=0; + int data_used = point_data_used(pd); + float partco[3]; + float obview[4][4]; + + + /* init everything */ + if (!psys || !ob || !pd) return; + + Mat4MulMat4(obview, re->viewinv, ob->obmat); + + /* Just to create a valid rendering context for particles */ + psys_render_set(ob, psys, re->viewmat, re->winmat, re->winx, re->winy, 0); + + dm = mesh_create_derived_render(re->scene, ob,CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL); + + if ( !psys_check_enabled(ob, psys)) { + psys_render_restore(ob, psys); + return; + } + + /* in case ob->imat isn't up-to-date */ + Mat4Invert(ob->imat, ob->obmat); + + total_particles = psys->totpart+psys->totchild; + psys->lattice=psys_get_lattice(re->scene,ob,psys); + + pd->point_tree = BLI_bvhtree_new(total_particles, 0.0, 4, 6); + alloc_point_data(pd, total_particles, data_used); + pd->totpoints = total_particles; + if (data_used & POINT_DATA_VEL) offset = pd->totpoints*3; + + if (psys->totchild > 0 && !(psys->part->draw & PART_DRAW_PARENT)) + childexists = 1; + + for (i=0, pa=psys->particles; i < total_particles; i++, pa++) { + + state.time = cfra; + if(psys_get_particle_state(re->scene, ob, psys, i, &state, 0)) { + + VECCOPY(partco, state.co); + + if (pd->psys_cache_space == TEX_PD_OBJECTSPACE) + Mat4MulVecfl(ob->imat, partco); + else if (pd->psys_cache_space == TEX_PD_OBJECTLOC) { + float obloc[3]; + VECCOPY(obloc, ob->loc); + VecSubf(partco, partco, obloc); + } else { + /* TEX_PD_WORLDSPACE */ + } + + BLI_bvhtree_insert(pd->point_tree, i, partco, 1); + + if (data_used & POINT_DATA_VEL) { + pd->point_data[i*3 + 0] = state.vel[0]; + pd->point_data[i*3 + 1] = state.vel[1]; + pd->point_data[i*3 + 2] = state.vel[2]; + } + if (data_used & POINT_DATA_LIFE) { + float pa_time; + + if (i < psys->totpart) { + pa_time = (cfra - pa->time)/pa->lifetime; + } else { + ChildParticle *cpa= (psys->child + i) - psys->totpart; + float pa_birthtime, pa_dietime; + + pa_time = psys_get_child_time(psys, cpa, cfra, &pa_birthtime, &pa_dietime); + } + + pd->point_data[offset + i] = pa_time; + } + } + } + + BLI_bvhtree_balance(pd->point_tree); + dm->release(dm); + + if(psys->lattice){ + end_latt_deform(psys->lattice); + psys->lattice=0; + } + + psys_render_restore(ob, psys); +} + + +static void pointdensity_cache_object(Render *re, PointDensity *pd, ObjectRen *obr) +{ + int i; + + if (!obr || !pd) return; + if(!obr->vertnodes) return; + + /* in case ob->imat isn't up-to-date */ + Mat4Invert(obr->ob->imat, obr->ob->obmat); + + pd->point_tree = BLI_bvhtree_new(obr->totvert, 0.0, 4, 6); + pd->totpoints = obr->totvert; + + for(i=0; i<obr->totvert; i++) { + float ver_co[3]; + VertRen *ver= RE_findOrAddVert(obr, i); + + VECCOPY(ver_co, ver->co); + Mat4MulVecfl(re->viewinv, ver_co); + + if (pd->ob_cache_space == TEX_PD_OBJECTSPACE) { + Mat4MulVecfl(obr->ob->imat, ver_co); + } else if (pd->psys_cache_space == TEX_PD_OBJECTLOC) { + VecSubf(ver_co, ver_co, obr->ob->loc); + } else { + /* TEX_PD_WORLDSPACE */ + } + + BLI_bvhtree_insert(pd->point_tree, i, ver_co, 1); + } + + BLI_bvhtree_balance(pd->point_tree); + +} +static void cache_pointdensity(Render *re, Tex *tex) +{ + PointDensity *pd = tex->pd; + + if (pd->point_tree) { + BLI_bvhtree_free(pd->point_tree); + pd->point_tree = NULL; + } + + if (pd->source == TEX_PD_PSYS) { + ParticleSystem *psys; + Object *ob = pd->object; + int i; + + if (!ob) return; + if (BLI_countlist(&ob->particlesystem) == 0) return; + + + for(psys=ob->particlesystem.first, i=0; i< pd->psysindex-1; i++) + psys= psys->next; + + if (!psys) return; + + pointdensity_cache_psys(re, pd, ob, psys); + } + else if (pd->source == TEX_PD_OBJECT) { + Object *ob = pd->object; + ObjectRen *obr; + int found=0; + + /* find the obren that corresponds to the object */ + for (obr=re->objecttable.first; obr; obr=obr->next) { + if (obr->ob == ob) { + found=1; + break; + } + } + if (!found) return; + + pointdensity_cache_object(re, pd, obr); + } +} + +static void free_pointdensity(Render *re, Tex *tex) +{ + PointDensity *pd = tex->pd; + + if (!pd) return; + + if (pd->point_tree) { + BLI_bvhtree_free(pd->point_tree); + pd->point_tree = NULL; + } + + if (pd->point_data) { + MEM_freeN(pd->point_data); + pd->point_data = NULL; + } + pd->totpoints = 0; +} + + + +void make_pointdensities(Render *re) +{ + Tex *tex; + + if(re->scene->r.scemode & R_PREVIEWBUTS) + return; + + re->i.infostr= "Caching Point Densities"; + re->stats_draw(re->sdh, &re->i); + + for (tex= G.main->tex.first; tex; tex= tex->id.next) { + if(tex->id.us && tex->type==TEX_POINTDENSITY) { + cache_pointdensity(re, tex); + } + } + + re->i.infostr= NULL; + re->stats_draw(re->sdh, &re->i); +} + +void free_pointdensities(Render *re) +{ + Tex *tex; + + if(re->scene->r.scemode & R_PREVIEWBUTS) + return; + + for (tex= G.main->tex.first; tex; tex= tex->id.next) { + if(tex->id.us && tex->type==TEX_POINTDENSITY) { + free_pointdensity(re, tex); + } + } +} + +typedef struct PointDensityRangeData +{ + float *density; + float squared_radius; + float *point_data; + float *vec; + float softness; + short falloff_type; + short noise_influence; + float *age; + int point_data_used; + int offset; +} PointDensityRangeData; + +void accum_density(void *userdata, int index, float squared_dist) +{ + PointDensityRangeData *pdr = (PointDensityRangeData *)userdata; + const float dist = (pdr->squared_radius - squared_dist) / pdr->squared_radius * 0.5f; + float density; + + if (pdr->falloff_type == TEX_PD_FALLOFF_STD) + density = dist; + else if (pdr->falloff_type == TEX_PD_FALLOFF_SMOOTH) + density = 3.0f*dist*dist - 2.0f*dist*dist*dist; + else if (pdr->falloff_type == TEX_PD_FALLOFF_SOFT) + density = pow(dist, pdr->softness); + else if (pdr->falloff_type == TEX_PD_FALLOFF_CONSTANT) + density = pdr->squared_radius; + else if (pdr->falloff_type == TEX_PD_FALLOFF_ROOT) + density = sqrt(dist); + + if (pdr->point_data_used & POINT_DATA_VEL) { + pdr->vec[0] += pdr->point_data[index*3 + 0]; //* density; + pdr->vec[1] += pdr->point_data[index*3 + 1]; //* density; + pdr->vec[2] += pdr->point_data[index*3 + 2]; //* density; + } + if (pdr->point_data_used & POINT_DATA_LIFE) { + *pdr->age += pdr->point_data[pdr->offset + index]; // * density; + } + + *pdr->density += density; +} + + +static void init_pointdensityrangedata(PointDensity *pd, PointDensityRangeData *pdr, float *density, float *vec, float *age) +{ + pdr->squared_radius = pd->radius*pd->radius; + pdr->density = density; + pdr->point_data = pd->point_data; + pdr->falloff_type = pd->falloff_type; + pdr->vec = vec; + pdr->age = age; + pdr->softness = pd->falloff_softness; + pdr->noise_influence = pd->noise_influence; + pdr->point_data_used = point_data_used(pd); + pdr->offset = (pdr->point_data_used & POINT_DATA_VEL)?pd->totpoints*3:0; +} + + +int pointdensitytex(Tex *tex, float *texvec, TexResult *texres) +{ + int retval = TEX_INT; + PointDensity *pd = tex->pd; + PointDensityRangeData pdr; + float density=0.0f, age=0.0f, time=0.0f; + float vec[3] = {0.0f, 0.0f, 0.0f}, co[3]; + float col[4]; + float turb, noise_fac; + int num=0; + + texres->tin = 0.0f; + + if ((!pd) || (!pd->point_tree)) + return 0; + + init_pointdensityrangedata(pd, &pdr, &density, vec, &age); + noise_fac = pd->noise_fac * 0.5f; /* better default */ + + VECCOPY(co, texvec); + + if (point_data_used(pd)) { + /* does a BVH lookup to find accumulated density and additional point data * + * stores particle velocity vector in 'vec', and particle lifetime in 'time' */ + num = BLI_bvhtree_range_query(pd->point_tree, co, pd->radius, accum_density, &pdr); + if (num > 0) { + age /= num; + VecMulf(vec, 1.0f/num); + } + + /* reset */ + density = vec[0] = vec[1] = vec[2] = 0.0f; + } + + if (pd->flag & TEX_PD_TURBULENCE) { + + if (pd->noise_influence == TEX_PD_NOISE_AGE) { + turb = BLI_gTurbulence(pd->noise_size, texvec[0]+age, texvec[1]+age, texvec[2]+age, pd->noise_depth, 0, pd->noise_basis); + } + else if (pd->noise_influence == TEX_PD_NOISE_TIME) { + time = R.cfra / (float)R.r.efra; + turb = BLI_gTurbulence(pd->noise_size, texvec[0]+time, texvec[1]+time, texvec[2]+time, pd->noise_depth, 0, pd->noise_basis); + //turb = BLI_turbulence(pd->noise_size, texvec[0]+time, texvec[1]+time, texvec[2]+time, pd->noise_depth); + } + else { + turb = BLI_gTurbulence(pd->noise_size, texvec[0]+vec[0], texvec[1]+vec[1], texvec[2]+vec[2], pd->noise_depth, 0, pd->noise_basis); + } + + turb -= 0.5f; /* re-center 0.0-1.0 range around 0 to prevent offsetting result */ + + /* now we have an offset coordinate to use for the density lookup */ + co[0] = texvec[0] + noise_fac * turb; + co[1] = texvec[1] + noise_fac * turb; + co[2] = texvec[2] + noise_fac * turb; + } + + /* BVH query with the potentially perturbed coordinates */ + num = BLI_bvhtree_range_query(pd->point_tree, co, pd->radius, accum_density, &pdr); + if (num > 0) { + age /= num; + VecMulf(vec, 1.0f/num); + } + + texres->tin = density; + BRICONT; + + if (pd->color_source == TEX_PD_COLOR_CONSTANT) + return retval; + + retval |= TEX_RGB; + + switch (pd->color_source) { + case TEX_PD_COLOR_PARTAGE: + if (pd->coba) { + if (do_colorband(pd->coba, age, col)) { + texres->talpha= 1; + VECCOPY(&texres->tr, col); + texres->tin *= col[3]; + texres->ta = texres->tin; + } + } + break; + case TEX_PD_COLOR_PARTSPEED: + { + float speed = VecLength(vec) * pd->speed_scale; + + if (pd->coba) { + if (do_colorband(pd->coba, speed, col)) { + texres->talpha= 1; + VECCOPY(&texres->tr, col); + texres->tin *= col[3]; + texres->ta = texres->tin; + } + } + break; + } + case TEX_PD_COLOR_PARTVEL: + texres->talpha= 1; + VecMulf(vec, pd->speed_scale); + VECCOPY(&texres->tr, vec); + texres->ta = texres->tin; + break; + case TEX_PD_COLOR_CONSTANT: + default: + texres->tr = texres->tg = texres->tb = texres->ta = 1.0f; + break; + } + BRICONTRGB; + + return retval; + + /* + if (texres->nor!=NULL) { + texres->nor[0] = texres->nor[1] = texres->nor[2] = 0.0f; + } + */ +} diff --git a/source/blender/render/intern/source/rayshade.c b/source/blender/render/intern/source/rayshade.c index 010930fcb85..b5071de12f2 100644 --- a/source/blender/render/intern/source/rayshade.c +++ b/source/blender/render/intern/source/rayshade.c @@ -54,6 +54,7 @@ #include "pixelshading.h" #include "shading.h" #include "texture.h" +#include "volumetric.h" #include "RE_raytrace.h" @@ -95,6 +96,17 @@ static int vlr_check_intersect(Isect *is, int ob, RayFace *face) return (is->lay & obi->lay); } +static int vlr_check_intersect_solid(Isect *is, int ob, RayFace *face) +{ + VlakRen *vlr = (VlakRen*)face; + + /* solid material types only */ + if (vlr->mat->material_type == MA_TYPE_SURFACE) + return 1; + else + return 0; +} + static float *vlr_get_transform(void *userdata, int i) { ObjectInstanceRen *obi= RAY_OBJECT_GET((Render*)userdata, i); @@ -205,7 +217,7 @@ void makeraytree(Render *re) re->stats_draw(re->sdh, &re->i); } -static void shade_ray(Isect *is, ShadeInput *shi, ShadeResult *shr) +void shade_ray(Isect *is, ShadeInput *shi, ShadeResult *shr) { VlakRen *vlr= (VlakRen*)is->face; ObjectInstanceRen *obi= RAY_OBJECT_GET(&R, is->ob); @@ -260,8 +272,14 @@ static void shade_ray(Isect *is, ShadeInput *shi, ShadeResult *shr) shade_input_flip_normals(shi); shade_input_set_shade_texco(shi); - - if(is->mode==RE_RAY_SHADOW_TRA) { + if (shi->mat->material_type == MA_TYPE_VOLUME) { + if(ELEM(is->mode, RE_RAY_SHADOW, RE_RAY_SHADOW_TRA)) { + shade_volume_shadow(shi, shr, is); + } else { + shade_volume_outside(shi, shr); + } + } + else if(is->mode==RE_RAY_SHADOW_TRA) { /* temp hack to prevent recursion */ if(shi->nodes==0 && shi->mat->nodetree && shi->mat->use_nodes) { ntreeShaderExecTree(shi->mat->nodetree, shi, shr); @@ -275,9 +293,20 @@ static void shade_ray(Isect *is, ShadeInput *shi, ShadeResult *shr) ntreeShaderExecTree(shi->mat->nodetree, shi, shr); shi->mat= vlr->mat; /* shi->mat is being set in nodetree */ } - else - shade_material_loop(shi, shr); - + else { + int tempdepth; + /* XXX dodgy business here, set ray depth to -1 + * to ignore raytrace in shade_material_loop() + * this could really use a refactor --Matt */ + if (shi->volume_depth == 0) { + tempdepth = shi->depth; + shi->depth = -1; + shade_material_loop(shi, shr); + shi->depth = tempdepth; + } else { + shade_material_loop(shi, shr); + } + } /* raytrace likes to separate the spec color */ VECSUB(shr->diff, shr->combined, shr->spec); } @@ -1302,11 +1331,15 @@ static void ray_trace_shadow_tra(Isect *is, ShadeInput *origshi, int depth, int shi.nodes= origshi->nodes; shade_ray(is, &shi, &shr); - if (traflag & RAY_TRA) - d= shade_by_transmission(is, &shi, &shr); - - /* mix colors based on shadfac (rgb + amount of light factor) */ - addAlphaLight(is->col, shr.diff, shr.alpha, d*shi.mat->filter); + if (shi.mat->material_type == MA_TYPE_SURFACE) { + if (traflag & RAY_TRA) + d= shade_by_transmission(is, &shi, &shr); + + /* mix colors based on shadfac (rgb + amount of light factor) */ + addAlphaLight(is->col, shr.diff, shr.alpha, d*shi.mat->filter); + } else if (shi.mat->material_type == MA_TYPE_VOLUME) { + addAlphaLight(is->col, shr.combined, shr.alpha, 1.0f); + } if(depth>0 && is->col[3]>0.0f) { @@ -1607,7 +1640,7 @@ static void ray_ao_qmc(ShadeInput *shi, float *shadfac) prev = fac; - if(RE_ray_tree_intersect(R.raytree, &isec)) { + if(RE_ray_tree_intersect_check(R.raytree, &isec, vlr_check_intersect_solid)) { if (R.wrld.aomode & WO_AODIST) fac+= exp(-isec.labda*R.wrld.aodistfac); else fac+= 1.0f; } @@ -1732,7 +1765,7 @@ static void ray_ao_spheresamp(ShadeInput *shi, float *shadfac) isec.end[2] = shi->co[2] - maxdist*vec[2]; /* do the trace */ - if(RE_ray_tree_intersect(R.raytree, &isec)) { + if(RE_ray_tree_intersect_check(R.raytree, &isec, vlr_check_intersect_solid)) { if (R.wrld.aomode & WO_AODIST) sh+= exp(-isec.labda*R.wrld.aodistfac); else sh+= 1.0f; } diff --git a/source/blender/render/intern/source/raytrace.c b/source/blender/render/intern/source/raytrace.c index 09d3711885a..b34fe6a7039 100644 --- a/source/blender/render/intern/source/raytrace.c +++ b/source/blender/render/intern/source/raytrace.c @@ -931,7 +931,7 @@ int RE_ray_face_intersection(Isect *is, RayObjectTransformFunc transformfunc, Ra intersection to be detected in its neighbour face */ if(is->facecontr && is->faceisect); // optimizing, the tests below are not needed - else if(is->labda< .1) { + else if(is->labda< .1 && is->faceorig) { RayFace *face= is->faceorig; float *origv1, *origv2, *origv3, *origv4; short de= 0; diff --git a/source/blender/render/intern/source/shadeinput.c b/source/blender/render/intern/source/shadeinput.c index c860e9ac5d1..3f503a4b5fd 100644 --- a/source/blender/render/intern/source/shadeinput.c +++ b/source/blender/render/intern/source/shadeinput.c @@ -52,6 +52,7 @@ #include "shading.h" #include "strand.h" #include "texture.h" +#include "volumetric.h" #include "zbuf.h" /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ @@ -166,6 +167,10 @@ void shade_material_loop(ShadeInput *shi, ShadeResult *shr) if((shi->layflag & SCE_LAY_SKY) && (R.r.alphamode==R_ADDSKY)) shr->alpha= 1.0f; } + + if(R.r.mode & R_RAYTRACE) { + shade_volume_inside(shi, shr); + } } @@ -183,7 +188,12 @@ void shade_input_do_shade(ShadeInput *shi, ShadeResult *shr) /* copy all relevant material vars, note, keep this synced with render_types.h */ shade_input_init_material(shi); - shade_material_loop(shi, shr); + if (shi->mat->material_type == MA_TYPE_SURFACE) { + shade_material_loop(shi, shr); + } else if (shi->mat->material_type == MA_TYPE_VOLUME) { + if(R.r.mode & R_RAYTRACE) + shade_volume_outside(shi, shr); + } } /* copy additional passes */ @@ -705,6 +715,10 @@ void shade_input_calc_viewco(ShadeInput *shi, float x, float y, float z, float * } } + /* set camera coords - for scanline, it's always 0.0,0.0,0.0 (render is in camera space) + * however for raytrace it can be different - the position of the last intersection */ + shi->camera_co[0] = shi->camera_co[1] = shi->camera_co[2] = 0.0f; + /* cannot normalize earlier, code above needs it at viewplane level */ Normalize(view); } diff --git a/source/blender/render/intern/source/shadeoutput.c b/source/blender/render/intern/source/shadeoutput.c index 2fbd93df0ce..744dffa7d9d 100644 --- a/source/blender/render/intern/source/shadeoutput.c +++ b/source/blender/render/intern/source/shadeoutput.c @@ -58,7 +58,7 @@ extern struct Render R; /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ -static ListBase *get_lights(ShadeInput *shi) +ListBase *get_lights(ShadeInput *shi) { if(R.r.scemode & R_PREVIEWBUTS) diff --git a/source/blender/render/intern/source/texture.c b/source/blender/render/intern/source/texture.c index bb491efdaba..27cf698aabe 100644 --- a/source/blender/render/intern/source/texture.c +++ b/source/blender/render/intern/source/texture.c @@ -65,6 +65,8 @@ #include "BKE_ipo.h" #include "envmap.h" +#include "pointdensity.h" +#include "voxeldata.h" #include "renderpipeline.h" #include "render_types.h" #include "rendercore.h" @@ -1262,6 +1264,13 @@ static int multitex(Tex *tex, float *texvec, float *dxt, float *dyt, int osatex, retval= mg_distNoiseTex(tex, tmpvec, texres); break; + case TEX_POINTDENSITY: + retval= pointdensitytex(tex, texvec, texres); + break; + case TEX_VOXELDATA: + retval= voxeldatatex(tex, texvec, texres); + break; + } if (tex->flag & TEX_COLORBAND) { @@ -1272,7 +1281,7 @@ static int multitex(Tex *tex, float *texvec, float *dxt, float *dyt, int osatex, texres->tg= col[1]; texres->tb= col[2]; texres->ta= col[3]; - retval |= 1; + retval |= TEX_RGB; } } return retval; @@ -2248,6 +2257,175 @@ void do_material_tex(ShadeInput *shi) } } + +void do_volume_tex(ShadeInput *shi, float *xyz, int mapto_flag, float *col, float *val) +{ + MTex *mtex; + Tex *tex; + TexResult texres= {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0, NULL}; + int tex_nr, rgbnor= 0; + float co[3], texvec[3]; + float fact, stencilTin=1.0; + + if (R.r.scemode & R_NO_TEX) return; + /* here: test flag if there's a tex (todo) */ + + for(tex_nr=0; tex_nr<MAX_MTEX; tex_nr++) { + /* separate tex switching */ + if(shi->mat->septex & (1<<tex_nr)) continue; + + if(shi->mat->mtex[tex_nr]) { + mtex= shi->mat->mtex[tex_nr]; + tex= mtex->tex; + if(tex==0) continue; + + /* only process if this texture is mapped + * to one that we're interested in */ + if (!(mtex->mapto & mapto_flag)) continue; + + /* which coords */ + if(mtex->texco==TEXCO_OBJECT) { + Object *ob= mtex->object; + ob= mtex->object; + if(ob) { + VECCOPY(co, xyz); + if(mtex->texflag & MTEX_OB_DUPLI_ORIG) { + if(shi->obi && shi->obi->duplitexmat) + MTC_Mat4MulVecfl(shi->obi->duplitexmat, co); + } + MTC_Mat4MulVecfl(ob->imat, co); + } + } + /* not really orco, but 'local' */ + else if(mtex->texco==TEXCO_ORCO) { + + if(mtex->texflag & MTEX_DUPLI_MAPTO) { + VECCOPY(co, shi->duplilo); + } + else { + Object *ob= shi->obi->ob; + VECCOPY(co, xyz); + MTC_Mat4MulVecfl(ob->imat, co); + } + } + else if(mtex->texco==TEXCO_GLOB) { + VECCOPY(co, xyz); + MTC_Mat4MulVecfl(R.viewinv, co); + } + else continue; // can happen when texco defines disappear and it renders old files + + texres.nor= NULL; + + if(tex->type==TEX_IMAGE) { + continue; /* not supported yet */ + //do_2d_mapping(mtex, texvec, NULL, NULL, dxt, dyt); + } + else { + /* placement */ + if(mtex->projx) texvec[0]= mtex->size[0]*(co[mtex->projx-1]+mtex->ofs[0]); + else texvec[0]= mtex->size[0]*(mtex->ofs[0]); + + if(mtex->projy) texvec[1]= mtex->size[1]*(co[mtex->projy-1]+mtex->ofs[1]); + else texvec[1]= mtex->size[1]*(mtex->ofs[1]); + + if(mtex->projz) texvec[2]= mtex->size[2]*(co[mtex->projz-1]+mtex->ofs[2]); + else texvec[2]= mtex->size[2]*(mtex->ofs[2]); + } + + rgbnor= multitex(tex, texvec, NULL, NULL, 0, &texres, 0, mtex->which_output); /* NULL = dxt/dyt, 0 = shi->osatex - not supported */ + + /* texture output */ + + if( (rgbnor & TEX_RGB) && (mtex->texflag & MTEX_RGBTOINT)) { + texres.tin= (0.35*texres.tr+0.45*texres.tg+0.2*texres.tb); + rgbnor-= TEX_RGB; + } + if(mtex->texflag & MTEX_NEGATIVE) { + if(rgbnor & TEX_RGB) { + texres.tr= 1.0-texres.tr; + texres.tg= 1.0-texres.tg; + texres.tb= 1.0-texres.tb; + } + texres.tin= 1.0-texres.tin; + } + if(mtex->texflag & MTEX_STENCIL) { + if(rgbnor & TEX_RGB) { + fact= texres.ta; + texres.ta*= stencilTin; + stencilTin*= fact; + } + else { + fact= texres.tin; + texres.tin*= stencilTin; + stencilTin*= fact; + } + } + + + if((mapto_flag & (MAP_COL+MAP_COLMIR)) && (mtex->mapto & (MAP_COL+MAP_COLMIR))) { + float tcol[3], colfac; + + /* stencil maps on the texture control slider, not texture intensity value */ + colfac= mtex->colfac*stencilTin; + + if((rgbnor & TEX_RGB)==0) { + tcol[0]= mtex->r; + tcol[1]= mtex->g; + tcol[2]= mtex->b; + } else { + tcol[0]=texres.tr; + tcol[1]=texres.tg; + tcol[2]=texres.tb; + if(texres.talpha) + texres.tin= texres.ta; + } + + /* inverse gamma correction */ + if (R.r.color_mgt_flag & R_COLOR_MANAGEMENT) { + color_manage_linearize(tcol, tcol); + } + + /* used for emit */ + if((mapto_flag & MAP_COL) && (mtex->mapto & MAP_COL)) { + texture_rgb_blend(col, tcol, col, texres.tin, colfac, mtex->blendtype); + } + + /* MAP_COLMIR is abused for absorption colour at the moment */ + if((mapto_flag & MAP_COLMIR) && (mtex->mapto & MAP_COLMIR)) { + texture_rgb_blend(col, tcol, col, texres.tin, colfac, mtex->blendtype); + } + } + + if((mapto_flag & MAP_VARS) && (mtex->mapto & MAP_VARS)) { + /* stencil maps on the texture control slider, not texture intensity value */ + float varfac= mtex->varfac*stencilTin; + + /* convert RGB to intensity if intensity info isn't provided */ + if (!(rgbnor & TEX_INT)) { + if (rgbnor & TEX_RGB) { + if(texres.talpha) texres.tin= texres.ta; + else texres.tin= (0.35*texres.tr+0.45*texres.tg+0.2*texres.tb); + } + } + + if((mapto_flag & MAP_EMIT) && (mtex->mapto & MAP_EMIT)) { + int flip= mtex->maptoneg & MAP_EMIT; + + *val = texture_value_blend(mtex->def_var, *val, texres.tin, varfac, mtex->blendtype, flip); + if(*val<0.0) *val= 0.0; + } + if((mapto_flag & MAP_ALPHA) && (mtex->mapto & MAP_ALPHA)) { + int flip= mtex->maptoneg & MAP_ALPHA; + + *val = texture_value_blend(mtex->def_var, *val, texres.tin, varfac, mtex->blendtype, flip); + CLAMP(*val, 0.0, 1.0); + } + } + } + } +} + + /* ------------------------------------------------------------------------- */ void do_halo_tex(HaloRen *har, float xn, float yn, float *colf) diff --git a/source/blender/render/intern/source/volume_precache.c b/source/blender/render/intern/source/volume_precache.c new file mode 100644 index 00000000000..0b81d775649 --- /dev/null +++ b/source/blender/render/intern/source/volume_precache.c @@ -0,0 +1,736 @@ +/** + * + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. + * All rights reserved. + * + * The Original Code is: all of this file. + * + * Contributor(s): Matt Ebb. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +#include <math.h> +#include <stdlib.h> +#include <string.h> +#include <float.h> + +#include "MEM_guardedalloc.h" + +#include "BLI_blenlib.h" +#include "BLI_arithb.h" +#include "BLI_threads.h" +#include "BLI_voxel.h" + +#include "PIL_time.h" + +#include "RE_shader_ext.h" +#include "RE_raytrace.h" + +#include "DNA_material_types.h" + +#include "render_types.h" +#include "renderdatabase.h" +#include "volumetric.h" +#include "volume_precache.h" + +#if defined( _MSC_VER ) && !defined( __cplusplus ) +# define inline __inline +#endif // defined( _MSC_VER ) && !defined( __cplusplus ) + +#include "BKE_global.h" + +/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ +/* defined in pipeline.c, is hardcopy of active dynamic allocated Render */ +/* only to be used here in this file, it's for speed */ +extern struct Render R; +/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ + +/* *** utility code to set up an individual raytree for objectinstance, for checking inside/outside *** */ + +/* Recursive test for intersections, from a point inside the mesh, to outside + * Number of intersections (depth) determine if a point is inside or outside the mesh */ +int intersect_outside_volume(RayTree *tree, Isect *isect, float *offset, int limit, int depth) +{ + if (limit == 0) return depth; + + if (RE_ray_tree_intersect(tree, isect)) { + float hitco[3]; + + hitco[0] = isect->start[0] + isect->labda*isect->vec[0]; + hitco[1] = isect->start[1] + isect->labda*isect->vec[1]; + hitco[2] = isect->start[2] + isect->labda*isect->vec[2]; + VecAddf(isect->start, hitco, offset); + + return intersect_outside_volume(tree, isect, offset, limit-1, depth+1); + } else { + return depth; + } +} + +/* Uses ray tracing to check if a point is inside or outside an ObjectInstanceRen */ +int point_inside_obi(RayTree *tree, ObjectInstanceRen *obi, float *co) +{ + float maxsize = RE_ray_tree_max_size(tree); + Isect isect; + float vec[3] = {0.0f,0.0f,1.0f}; + int final_depth=0, depth=0, limit=20; + + /* set up the isect */ + memset(&isect, 0, sizeof(isect)); + VECCOPY(isect.start, co); + isect.end[0] = co[0] + vec[0] * maxsize; + isect.end[1] = co[1] + vec[1] * maxsize; + isect.end[2] = co[2] + vec[2] * maxsize; + + /* and give it a little offset to prevent self-intersections */ + VecMulf(vec, 1e-5); + VecAddf(isect.start, isect.start, vec); + + isect.mode= RE_RAY_MIRROR; + isect.face_last= NULL; + isect.lay= -1; + + final_depth = intersect_outside_volume(tree, &isect, vec, limit, depth); + + /* even number of intersections: point is outside + * odd number: point is inside */ + if (final_depth % 2 == 0) return 0; + else return 1; +} + +static int inside_check_func(Isect *is, int ob, RayFace *face) +{ + return 1; +} +static void vlr_face_coords(RayFace *face, float **v1, float **v2, float **v3, float **v4) +{ + VlakRen *vlr= (VlakRen*)face; + + *v1 = (vlr->v1)? vlr->v1->co: NULL; + *v2 = (vlr->v2)? vlr->v2->co: NULL; + *v3 = (vlr->v3)? vlr->v3->co: NULL; + *v4 = (vlr->v4)? vlr->v4->co: NULL; +} + +RayTree *create_raytree_obi(ObjectInstanceRen *obi, float *bbmin, float *bbmax) +{ + int v; + VlakRen *vlr= NULL; + + /* create empty raytree */ + RayTree *tree = RE_ray_tree_create(64, obi->obr->totvlak, bbmin, bbmax, + vlr_face_coords, inside_check_func, NULL, NULL); + + /* fill it with faces */ + for(v=0; v<obi->obr->totvlak; v++) { + if((v & 255)==0) + vlr= obi->obr->vlaknodes[v>>8].vlak; + else + vlr++; + + RE_ray_tree_add_face(tree, 0, vlr); + } + + RE_ray_tree_done(tree); + + return tree; +} + +/* *** light cache filtering *** */ + +static float get_avg_surrounds(float *cache, int *res, int xx, int yy, int zz) +{ + int x, y, z, x_, y_, z_; + int added=0; + float tot=0.0f; + + for (z=-1; z <= 1; z++) { + z_ = zz+z; + if (z_ >= 0 && z_ <= res[2]-1) { + + for (y=-1; y <= 1; y++) { + y_ = yy+y; + if (y_ >= 0 && y_ <= res[1]-1) { + + for (x=-1; x <= 1; x++) { + x_ = xx+x; + if (x_ >= 0 && x_ <= res[0]-1) { + + if (cache[ V_I(x_, y_, z_, res) ] > 0.0f) { + tot += cache[ V_I(x_, y_, z_, res) ]; + added++; + } + + } + } + } + } + } + } + + tot /= added; + + return ((added>0)?tot:0.0f); +} + +/* function to filter the edges of the light cache, where there was no volume originally. + * For each voxel which was originally external to the mesh, it finds the average values of + * the surrounding internal voxels and sets the original external voxel to that average amount. + * Works almost a bit like a 'dilate' filter */ +static void lightcache_filter(VolumePrecache *vp) +{ + int x, y, z; + + for (z=0; z < vp->res[2]; z++) { + for (y=0; y < vp->res[1]; y++) { + for (x=0; x < vp->res[0]; x++) { + /* trigger for outside mesh */ + if (vp->data_r[ V_I(x, y, z, vp->res) ] < -0.5f) + vp->data_r[ V_I(x, y, z, vp->res) ] = get_avg_surrounds(vp->data_r, vp->res, x, y, z); + if (vp->data_g[ V_I(x, y, z, vp->res) ] < -0.5f) + vp->data_g[ V_I(x, y, z, vp->res) ] = get_avg_surrounds(vp->data_g, vp->res, x, y, z); + if (vp->data_b[ V_I(x, y, z, vp->res) ] < -0.5f) + vp->data_b[ V_I(x, y, z, vp->res) ] = get_avg_surrounds(vp->data_b, vp->res, x, y, z); + } + } + } +} + +static inline int ms_I(int x, int y, int z, int *n) //has a pad of 1 voxel surrounding the core for boundary simulation +{ + return z*(n[1]+2)*(n[0]+2) + y*(n[0]+2) + x; +} + + +/* *** multiple scattering approximation *** */ + +/* get the total amount of light energy in the light cache. used to normalise after multiple scattering */ +static float total_ss_energy(VolumePrecache *vp) +{ + int x, y, z; + int *res = vp->res; + float energy=0.f; + + for (z=0; z < res[2]; z++) { + for (y=0; y < res[1]; y++) { + for (x=0; x < res[0]; x++) { + if (vp->data_r[ V_I(x, y, z, res) ] > 0.f) energy += vp->data_r[ V_I(x, y, z, res) ]; + if (vp->data_g[ V_I(x, y, z, res) ] > 0.f) energy += vp->data_g[ V_I(x, y, z, res) ]; + if (vp->data_b[ V_I(x, y, z, res) ] > 0.f) energy += vp->data_b[ V_I(x, y, z, res) ]; + } + } + } + + return energy; +} + +static float total_ms_energy(float *sr, float *sg, float *sb, int *res) +{ + int x, y, z, i; + float energy=0.f; + + for (z=1;z<=res[2];z++) { + for (y=1;y<=res[1];y++) { + for (x=1;x<=res[0];x++) { + + i = ms_I(x,y,z,res); + if (sr[i] > 0.f) energy += sr[i]; + if (sg[i] > 0.f) energy += sg[i]; + if (sb[i] > 0.f) energy += sb[i]; + } + } + } + + return energy; +} + +static void ms_diffuse(int b, float* x0, float* x, float diff, int *n) +{ + int i, j, k, l; + const float dt = VOL_MS_TIMESTEP; + const float a = dt*diff*n[0]*n[1]*n[2]; + + for (l=0; l<20; l++) + { + for (k=1; k<=n[2]; k++) + { + for (j=1; j<=n[1]; j++) + { + for (i=1; i<=n[0]; i++) + { + x[ms_I(i,j,k,n)] = (x0[ms_I(i,j,k,n)] + a*( + x[ms_I(i-1,j,k,n)]+x[ms_I(i+1,j,k,n)]+ + x[ms_I(i,j-1,k,n)]+x[ms_I(i,j+1,k,n)]+ + x[ms_I(i,j,k-1,n)]+x[ms_I(i,j,k+1,n)]))/(1+6*a); + } + } + } + } +} + +void multiple_scattering_diffusion(Render *re, VolumePrecache *vp, Material *ma) +{ + const float diff = ma->vol.ms_diff * 0.001f; /* compensate for scaling for a nicer UI range */ + const float simframes = ma->vol.ms_steps; + const int shade_type = ma->vol.shade_type; + float fac = ma->vol.ms_intensity; + + int x, y, z, m; + int *n = vp->res; + const int size = (n[0]+2)*(n[1]+2)*(n[2]+2); + double time, lasttime= PIL_check_seconds_timer(); + float total; + float c=1.0f; + int i; + float origf; /* factor for blending in original light cache */ + float energy_ss, energy_ms; + + float *sr0=(float *)MEM_callocN(size*sizeof(float), "temporary multiple scattering buffer"); + float *sr=(float *)MEM_callocN(size*sizeof(float), "temporary multiple scattering buffer"); + float *sg0=(float *)MEM_callocN(size*sizeof(float), "temporary multiple scattering buffer"); + float *sg=(float *)MEM_callocN(size*sizeof(float), "temporary multiple scattering buffer"); + float *sb0=(float *)MEM_callocN(size*sizeof(float), "temporary multiple scattering buffer"); + float *sb=(float *)MEM_callocN(size*sizeof(float), "temporary multiple scattering buffer"); + + total = (float)(n[0]*n[1]*n[2]*simframes); + + energy_ss = total_ss_energy(vp); + + /* Scattering as diffusion pass */ + for (m=0; m<simframes; m++) + { + /* add sources */ + for (z=1; z<=n[2]; z++) + { + for (y=1; y<=n[1]; y++) + { + for (x=1; x<=n[0]; x++) + { + i = V_I((x-1), (y-1), (z-1), n); + time= PIL_check_seconds_timer(); + c++; + + if (vp->data_r[i] > 0.f) + sr[ms_I(x,y,z,n)] += vp->data_r[i]; + if (vp->data_g[i] > 0.f) + sg[ms_I(x,y,z,n)] += vp->data_g[i]; + if (vp->data_b[i] > 0.f) + sb[ms_I(x,y,z,n)] += vp->data_b[i]; + + /* Displays progress every second */ + if(time-lasttime>1.0f) { + char str[64]; + sprintf(str, "Simulating multiple scattering: %d%%", (int) + (100.0f * (c / total))); + re->i.infostr= str; + re->stats_draw(re->sdh, &re->i); + re->i.infostr= NULL; + lasttime= time; + } + } + } + } + SWAP(float *, sr, sr0); + SWAP(float *, sg, sg0); + SWAP(float *, sb, sb0); + + /* main diffusion simulation */ + ms_diffuse(0, sr0, sr, diff, n); + ms_diffuse(0, sg0, sg, diff, n); + ms_diffuse(0, sb0, sb, diff, n); + + if (re->test_break(re->tbh)) break; + } + + /* normalisation factor to conserve energy */ + energy_ms = total_ms_energy(sr, sg, sb, n); + fac *= (energy_ss / energy_ms); + + /* blend multiple scattering back in the light cache */ + if (shade_type == MA_VOL_SHADE_SINGLEPLUSMULTIPLE) { + /* conserve energy - half single, half multiple */ + origf = 0.5f; + fac *= 0.5f; + } else { + origf = 0.0f; + } + + for (z=1;z<=n[2];z++) + { + for (y=1;y<=n[1];y++) + { + for (x=1;x<=n[0];x++) + { + int index=(x-1)*n[1]*n[2] + (y-1)*n[2] + z-1; + vp->data_r[index] = origf * vp->data_r[index] + fac * sr[ms_I(x,y,z,n)]; + vp->data_g[index] = origf * vp->data_g[index] + fac * sg[ms_I(x,y,z,n)]; + vp->data_b[index] = origf * vp->data_b[index] + fac * sb[ms_I(x,y,z,n)]; + } + } + } + + MEM_freeN(sr0); + MEM_freeN(sr); + MEM_freeN(sg0); + MEM_freeN(sg); + MEM_freeN(sb0); + MEM_freeN(sb); +} + + + +#if 0 // debug stuff +static void *vol_precache_part_test(void *data) +{ + VolPrecachePart *pa = data; + + printf("part number: %d \n", pa->num); + printf("done: %d \n", pa->done); + printf("x min: %d x max: %d \n", pa->minx, pa->maxx); + printf("y min: %d y max: %d \n", pa->miny, pa->maxy); + printf("z min: %d z max: %d \n", pa->minz, pa->maxz); + + return NULL; +} +#endif + +/* Iterate over the 3d voxel grid, and fill the voxels with scattering information + * + * It's stored in memory as 3 big float grids next to each other, one for each RGB channel. + * I'm guessing the memory alignment may work out better this way for the purposes + * of doing linear interpolation, but I haven't actually tested this theory! :) + */ +static void *vol_precache_part(void *data) +{ + VolPrecachePart *pa = (VolPrecachePart *)data; + ObjectInstanceRen *obi = pa->obi; + RayTree *tree = pa->tree; + ShadeInput *shi = pa->shi; + float density, scatter_col[3] = {0.f, 0.f, 0.f}; + float co[3]; + int x, y, z; + const int res[3]= {pa->res[0], pa->res[1], pa->res[2]}; + const float stepsize = vol_get_stepsize(shi, STEPSIZE_VIEW); + + for (z= pa->minz; z < pa->maxz; z++) { + co[2] = pa->bbmin[2] + (pa->voxel[2] * z); + + for (y= pa->miny; y < pa->maxy; y++) { + co[1] = pa->bbmin[1] + (pa->voxel[1] * y); + + for (x=pa->minx; x < pa->maxx; x++) { + co[0] = pa->bbmin[0] + (pa->voxel[0] * x); + + // don't bother if the point is not inside the volume mesh + if (!point_inside_obi(tree, obi, co)) { + obi->volume_precache->data_r[ V_I(x, y, z, res) ] = -1.0f; + obi->volume_precache->data_g[ V_I(x, y, z, res) ] = -1.0f; + obi->volume_precache->data_b[ V_I(x, y, z, res) ] = -1.0f; + continue; + } + + VecCopyf(shi->view, co); + Normalize(shi->view); + density = vol_get_density(shi, co); + vol_get_scattering(shi, scatter_col, co, stepsize, density); + + obi->volume_precache->data_r[ V_I(x, y, z, res) ] = scatter_col[0]; + obi->volume_precache->data_g[ V_I(x, y, z, res) ] = scatter_col[1]; + obi->volume_precache->data_b[ V_I(x, y, z, res) ] = scatter_col[2]; + } + } + } + + pa->done = 1; + + return 0; +} + + +static void precache_setup_shadeinput(Render *re, ObjectInstanceRen *obi, Material *ma, ShadeInput *shi) +{ + memset(shi, 0, sizeof(ShadeInput)); + shi->depth= 1; + shi->mask= 1; + shi->mat = ma; + shi->vlr = NULL; + memcpy(&shi->r, &shi->mat->r, 23*sizeof(float)); // note, keep this synced with render_types.h + shi->har= shi->mat->har; + shi->obi= obi; + shi->obr= obi->obr; + shi->lay = re->scene->lay; +} + +static void precache_init_parts(Render *re, RayTree *tree, ShadeInput *shi, ObjectInstanceRen *obi, int totthread, int *parts) +{ + VolumePrecache *vp = obi->volume_precache; + int i=0, x, y, z; + float voxel[3]; + int sizex, sizey, sizez; + float *bbmin=obi->obr->boundbox[0], *bbmax=obi->obr->boundbox[1]; + int *res; + int minx, maxx; + int miny, maxy; + int minz, maxz; + + if (!vp) return; + + BLI_freelistN(&re->volume_precache_parts); + + /* currently we just subdivide the box, number of threads per side */ + parts[0] = parts[1] = parts[2] = totthread; + res = vp->res; + + VecSubf(voxel, bbmax, bbmin); + if ((voxel[0] < FLT_EPSILON) || (voxel[1] < FLT_EPSILON) || (voxel[2] < FLT_EPSILON)) + return; + voxel[0] /= res[0]; + voxel[1] /= res[1]; + voxel[2] /= res[2]; + + for (x=0; x < parts[0]; x++) { + sizex = ceil(res[0] / (float)parts[0]); + minx = x * sizex; + maxx = minx + sizex; + maxx = (maxx>res[0])?res[0]:maxx; + + for (y=0; y < parts[1]; y++) { + sizey = ceil(res[1] / (float)parts[1]); + miny = y * sizey; + maxy = miny + sizey; + maxy = (maxy>res[1])?res[1]:maxy; + + for (z=0; z < parts[2]; z++) { + VolPrecachePart *pa= MEM_callocN(sizeof(VolPrecachePart), "new precache part"); + + sizez = ceil(res[2] / (float)parts[2]); + minz = z * sizez; + maxz = minz + sizez; + maxz = (maxz>res[2])?res[2]:maxz; + + pa->done = 0; + pa->working = 0; + + pa->num = i; + pa->tree = tree; + pa->shi = shi; + pa->obi = obi; + VECCOPY(pa->bbmin, bbmin); + VECCOPY(pa->voxel, voxel); + VECCOPY(pa->res, res); + + pa->minx = minx; pa->maxx = maxx; + pa->miny = miny; pa->maxy = maxy; + pa->minz = minz; pa->maxz = maxz; + + + BLI_addtail(&re->volume_precache_parts, pa); + + i++; + } + } + } +} + +static VolPrecachePart *precache_get_new_part(Render *re) +{ + VolPrecachePart *pa, *nextpa=NULL; + + for (pa = re->volume_precache_parts.first; pa; pa=pa->next) + { + if (pa->done==0 && pa->working==0) { + nextpa = pa; + break; + } + } + + return nextpa; +} + +static void precache_resolution(VolumePrecache *vp, float *bbmin, float *bbmax, int res) +{ + float dim[3], div; + + VecSubf(dim, bbmax, bbmin); + + div = MAX3(dim[0], dim[1], dim[2]); + dim[0] /= div; + dim[1] /= div; + dim[2] /= div; + + vp->res[0] = dim[0] * (float)res; + vp->res[1] = dim[1] * (float)res; + vp->res[2] = dim[2] * (float)res; +} + +/* Precache a volume into a 3D voxel grid. + * The voxel grid is stored in the ObjectInstanceRen, + * in camera space, aligned with the ObjectRen's bounding box. + * Resolution is defined by the user. + */ +void vol_precache_objectinstance_threads(Render *re, ObjectInstanceRen *obi, Material *ma) +{ + VolumePrecache *vp; + VolPrecachePart *nextpa, *pa; + RayTree *tree; + ShadeInput shi; + ListBase threads; + float *bbmin=obi->obr->boundbox[0], *bbmax=obi->obr->boundbox[1]; + int parts[3], totparts; + + int caching=1, counter=0; + int totthread = re->r.threads; + + double time, lasttime= PIL_check_seconds_timer(); + + R = *re; + + /* create a raytree with just the faces of the instanced ObjectRen, + * used for checking if the cached point is inside or outside. */ + tree = create_raytree_obi(obi, bbmin, bbmax); + if (!tree) return; + + vp = MEM_callocN(sizeof(VolumePrecache), "volume light cache"); + precache_resolution(vp, bbmin, bbmax, ma->vol.precache_resolution); + + vp->data_r = MEM_callocN(sizeof(float)*vp->res[0]*vp->res[1]*vp->res[2], "volume light cache data red channel"); + vp->data_g = MEM_callocN(sizeof(float)*vp->res[0]*vp->res[1]*vp->res[2], "volume light cache data green channel"); + vp->data_b = MEM_callocN(sizeof(float)*vp->res[0]*vp->res[1]*vp->res[2], "volume light cache data blue channel"); + obi->volume_precache = vp; + + /* Need a shadeinput to calculate scattering */ + precache_setup_shadeinput(re, obi, ma, &shi); + + precache_init_parts(re, tree, &shi, obi, totthread, parts); + totparts = parts[0] * parts[1] * parts[2]; + + BLI_init_threads(&threads, vol_precache_part, totthread); + + while(caching) { + + if(BLI_available_threads(&threads) && !(re->test_break(re->tbh))) { + nextpa = precache_get_new_part(re); + if (nextpa) { + nextpa->working = 1; + BLI_insert_thread(&threads, nextpa); + } + } + else PIL_sleep_ms(50); + + caching=0; + counter=0; + for(pa= re->volume_precache_parts.first; pa; pa= pa->next) { + + if(pa->done) { + counter++; + BLI_remove_thread(&threads, pa); + } else + caching = 1; + } + + if (re->test_break(re->tbh) && BLI_available_threads(&threads)==totthread) + caching=0; + + time= PIL_check_seconds_timer(); + if(time-lasttime>1.0f) { + char str[64]; + sprintf(str, "Precaching volume: %d%%", (int)(100.0f * ((float)counter / (float)totparts))); + re->i.infostr= str; + re->stats_draw(re->sdh, &re->i); + re->i.infostr= NULL; + lasttime= time; + } + } + + BLI_end_threads(&threads); + BLI_freelistN(&re->volume_precache_parts); + + if(tree) { + RE_ray_tree_free(tree); + tree= NULL; + } + + lightcache_filter(obi->volume_precache); + + if (ELEM(ma->vol.shade_type, MA_VOL_SHADE_MULTIPLE, MA_VOL_SHADE_SINGLEPLUSMULTIPLE)) + { + multiple_scattering_diffusion(re, vp, ma); + } +} + +int using_lightcache(Material *ma) +{ + return (((ma->vol.shadeflag & MA_VOL_PRECACHESHADING) && (ma->vol.shade_type == MA_VOL_SHADE_SINGLE)) + || (ELEM(ma->vol.shade_type, MA_VOL_SHADE_MULTIPLE, MA_VOL_SHADE_SINGLEPLUSMULTIPLE))); +} + +/* loop through all objects (and their associated materials) + * marked for pre-caching in convertblender.c, and pre-cache them */ +void volume_precache(Render *re) +{ + ObjectInstanceRen *obi; + VolumeOb *vo; + + for(vo= re->volumes.first; vo; vo= vo->next) { + if (using_lightcache(vo->ma)) { + for(obi= re->instancetable.first; obi; obi= obi->next) { + if (obi->obr == vo->obr) { + vol_precache_objectinstance_threads(re, obi, vo->ma); + } + } + } + } + + re->i.infostr= NULL; + re->stats_draw(re->sdh, &re->i); +} + +void free_volume_precache(Render *re) +{ + ObjectInstanceRen *obi; + + for(obi= re->instancetable.first; obi; obi= obi->next) { + if (obi->volume_precache != NULL) { + MEM_freeN(obi->volume_precache); + MEM_freeN(obi->volume_precache->data_r); + MEM_freeN(obi->volume_precache->data_g); + MEM_freeN(obi->volume_precache->data_b); + } + } + + BLI_freelistN(&re->volumes); +} + +int point_inside_volume_objectinstance(ObjectInstanceRen *obi, float *co) +{ + RayTree *tree; + int inside=0; + + tree = create_raytree_obi(obi, obi->obr->boundbox[0], obi->obr->boundbox[1]); + if (!tree) return 0; + + inside = point_inside_obi(tree, obi, co); + + RE_ray_tree_free(tree); + tree= NULL; + + return inside; +} + diff --git a/source/blender/render/intern/source/volumetric.c b/source/blender/render/intern/source/volumetric.c new file mode 100644 index 00000000000..04eb1b5e3bf --- /dev/null +++ b/source/blender/render/intern/source/volumetric.c @@ -0,0 +1,714 @@ +/** + * + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. + * All rights reserved. + * + * The Original Code is: all of this file. + * + * Contributor(s): Matt Ebb, Raul Fernandez Hernandez (Farsthary) + * + * ***** END GPL LICENSE BLOCK ***** + */ + +#include <math.h> +#include <stdlib.h> +#include <string.h> +#include <float.h> + +#include "MEM_guardedalloc.h" + +#include "BLI_blenlib.h" +#include "BLI_arithb.h" +#include "BLI_rand.h" +#include "BLI_voxel.h" + +#include "RE_shader_ext.h" +#include "RE_raytrace.h" + +#include "DNA_material_types.h" +#include "DNA_group_types.h" +#include "DNA_lamp_types.h" + +#include "BKE_global.h" + +#include "render_types.h" +#include "pixelshading.h" +#include "shading.h" +#include "texture.h" +#include "volumetric.h" + +#if defined( _MSC_VER ) && !defined( __cplusplus ) +# define inline __inline +#endif // defined( _MSC_VER ) && !defined( __cplusplus ) + +/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ +/* defined in pipeline.c, is hardcopy of active dynamic allocated Render */ +/* only to be used here in this file, it's for speed */ +extern struct Render R; +/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ + +static int vol_backface_intersect_check(Isect *is, int ob, RayFace *face) +{ + VlakRen *vlr = (VlakRen *)face; + + /* only consider faces away, so overlapping layers + * of foward facing geometry don't cause the ray to stop */ + return (INPR(is->vec, vlr->n) < 0.0f); +} + +/* TODO: Box or sphere intersection types could speed things up */ +static int vol_get_bounds(ShadeInput *shi, float *co, float *vec, float *hitco, Isect *isect, int intersect_type, int checkfunc) +{ + float maxsize = RE_ray_tree_max_size(R.raytree); + int intersected=0; + + /* TODO: use object's bounding box to calculate max size */ + VECCOPY(isect->start, co); + isect->end[0] = co[0] + vec[0] * maxsize; + isect->end[1] = co[1] + vec[1] * maxsize; + isect->end[2] = co[2] + vec[2] * maxsize; + + isect->mode= RE_RAY_MIRROR; + isect->oborig= RAY_OBJECT_SET(&R, shi->obi); + isect->face_last= NULL; + isect->ob_last= 0; + isect->lay= -1; + + if (intersect_type == VOL_BOUNDS_DEPTH) isect->faceorig= (RayFace*)shi->vlr; + else if (intersect_type == VOL_BOUNDS_SS) isect->faceorig= NULL; + + if (checkfunc==VOL_IS_BACKFACE) + intersected = RE_ray_tree_intersect_check(R.raytree, isect, vol_backface_intersect_check); + else + intersected = RE_ray_tree_intersect(R.raytree, isect); + + if(intersected) + { + float isvec[3]; + + VECCOPY(isvec, isect->vec); + hitco[0] = isect->start[0] + isect->labda*isvec[0]; + hitco[1] = isect->start[1] + isect->labda*isvec[1]; + hitco[2] = isect->start[2] + isect->labda*isvec[2]; + + return 1; + } else { + return 0; + } +} + +float vol_get_stepsize(struct ShadeInput *shi, int context) +{ + if (shi->mat->vol.stepsize_type == MA_VOL_STEP_RANDOMIZED) { + /* range between 0.75 and 1.25 */ + const float rnd = 0.5f * BLI_thread_frand(shi->thread) + 0.75f; + + if (context == STEPSIZE_VIEW) + return shi->mat->vol.stepsize * rnd; + else if (context == STEPSIZE_SHADE) + return shi->mat->vol.shade_stepsize * rnd; + } + else { // MA_VOL_STEP_CONSTANT + + if (context == STEPSIZE_VIEW) + return shi->mat->vol.stepsize; + else if (context == STEPSIZE_SHADE) + return shi->mat->vol.shade_stepsize; + } + + return shi->mat->vol.stepsize; +} + +static float vol_get_depth_cutoff(struct ShadeInput *shi) +{ + return shi->mat->vol.depth_cutoff; +} + +/* trilinear interpolation */ +static void vol_get_precached_scattering(ShadeInput *shi, float *scatter_col, float *co) +{ + VolumePrecache *vp = shi->obi->volume_precache; + float bbmin[3], bbmax[3], dim[3]; + float sample_co[3]; + + if (!vp) return; + + /* convert input coords to 0.0, 1.0 */ + VECCOPY(bbmin, shi->obi->obr->boundbox[0]); + VECCOPY(bbmax, shi->obi->obr->boundbox[1]); + VecSubf(dim, bbmax, bbmin); + + sample_co[0] = ((co[0] - bbmin[0]) / dim[0]); + sample_co[1] = ((co[1] - bbmin[1]) / dim[1]); + sample_co[2] = ((co[2] - bbmin[2]) / dim[2]); + + scatter_col[0] = voxel_sample_trilinear(vp->data_r, vp->res, sample_co); + scatter_col[1] = voxel_sample_trilinear(vp->data_g, vp->res, sample_co); + scatter_col[2] = voxel_sample_trilinear(vp->data_b, vp->res, sample_co); +} + +float vol_get_density(struct ShadeInput *shi, float *co) +{ + float density = shi->mat->alpha; + float density_scale = shi->mat->vol.density_scale; + float col[3] = {0.0, 0.0, 0.0}; + + do_volume_tex(shi, co, MAP_ALPHA, col, &density); + + return density * density_scale; +} + +/* compute emission component, amount of radiance to add per segment + * can be textured with 'emit' */ +void vol_get_emission(ShadeInput *shi, float *em, float *co, float density) +{ + float emission = shi->mat->emit; + float col[3] = {0.0, 0.0, 0.0}; + + VECCOPY(col, &shi->mat->r); + + do_volume_tex(shi, co, MAP_EMIT+MAP_COL, col, &emission); + + em[0] = em[1] = em[2] = emission * density; + VecMulVecf(em, em, col); +} + +/* scattering multiplier, values above 1.0 are non-physical, + * but can be useful to tweak lighting */ +void vol_get_scattering_fac(ShadeInput *shi, float *scatter_fac, float *co, float density) +{ + *scatter_fac = shi->mat->vol.scattering; +} + +/* phase function - determines in which directions the light + * is scattered in the volume relative to incoming direction + * and view direction */ +float vol_get_phasefunc(ShadeInput *shi, short phasefunc_type, float g, float *w, float *wp) +{ + const float costheta = Inpf(w, wp); + + if (phasefunc_type == MA_VOL_PH_ISOTROPIC) { + return 1.f / (4.f * M_PI); + } + else if (phasefunc_type == MA_VOL_PH_MIEHAZY) { + return (0.5f + 4.5f * powf(0.5 * (1.f + costheta), 8.f)) / (4.f*M_PI); + } + else if (phasefunc_type == MA_VOL_PH_MIEMURKY) { + return (0.5f + 16.5f * powf(0.5 * (1.f + costheta), 32.f)) / (4.f*M_PI); + } + else if (phasefunc_type == MA_VOL_PH_RAYLEIGH) { + return 3.f/(16.f*M_PI) * (1 + costheta * costheta); + } + else if (phasefunc_type == MA_VOL_PH_HG) { + return 1.f / (4.f * M_PI) * (1.f - g*g) / powf(1.f + g*g - 2.f * g * costheta, 1.5f); + } + else if (phasefunc_type == MA_VOL_PH_SCHLICK) { + const float k = 1.55f * g - .55f * g * g * g; + const float kcostheta = k * costheta; + return 1.f / (4.f * M_PI) * (1.f - k*k) / ((1.f - kcostheta) * (1.f - kcostheta)); + } else { + return 1.0f; + } +} + +void vol_get_absorption(ShadeInput *shi, float *absorb_col, float *co) +{ + float dummy = 1.0f; + const float absorption = shi->mat->vol.absorption; + + VECCOPY(absorb_col, shi->mat->vol.absorption_col); + + do_volume_tex(shi, co, MAP_COLMIR, absorb_col, &dummy); + + absorb_col[0] = (1.0f - absorb_col[0]) * absorption; + absorb_col[1] = (1.0f - absorb_col[1]) * absorption; + absorb_col[2] = (1.0f - absorb_col[2]) * absorption; +} + +/* Compute attenuation, otherwise known as 'optical thickness', extinction, or tau. + * Used in the relationship Transmittance = e^(-attenuation) + */ +void vol_get_attenuation(ShadeInput *shi, float *tau, float *co, float *endco, float density, float stepsize) +{ + /* input density = density at co */ + float absorb_col[3]; + int s, nsteps; + float step_vec[3], step_sta[3], step_end[3]; + const float dist = VecLenf(co, endco); + + vol_get_absorption(shi, absorb_col, co); + + nsteps = (int)((dist / stepsize) + 0.5); + + /* trigger for recalculating density */ + if (density < -0.001f) density = vol_get_density(shi, co); + + if (nsteps == 1) { + /* homogenous volume within the sampled distance */ + tau[0] = tau[1] = tau[2] = dist * density; + + VecMulVecf(tau, tau, absorb_col); + return; + } else { + tau[0] = tau[1] = tau[2] = 0.0; + } + + VecSubf(step_vec, endco, co); + VecMulf(step_vec, 1.0f / nsteps); + + VecCopyf(step_sta, co); + VecAddf(step_end, step_sta, step_vec); + + for (s = 0; s < nsteps; s++) { + if (s > 0) + density = vol_get_density(shi, step_sta); + + tau[0] += stepsize * density; + tau[1] += stepsize * density; + tau[2] += stepsize * density; + + if (s < nsteps-1) { + VECCOPY(step_sta, step_end); + VecAddf(step_end, step_end, step_vec); + } + } + VecMulVecf(tau, tau, absorb_col); +} + +void vol_shade_one_lamp(struct ShadeInput *shi, float *co, LampRen *lar, float *lacol, float stepsize, float density) +{ + float visifac, lv[3], lampdist; + float tau[3], tr[3]={1.0,1.0,1.0}; + float hitco[3], *atten_co; + float p; + float scatter_fac; + float shade_stepsize = vol_get_stepsize(shi, STEPSIZE_SHADE); + + if (lar->mode & LA_LAYER) if((lar->lay & shi->obi->lay)==0) return; + if ((lar->lay & shi->lay)==0) return; + if (lar->energy == 0.0) return; + + visifac= lamp_get_visibility(lar, co, lv, &lampdist); + if(visifac==0.0f) return; + + lacol[0] = lar->r; + lacol[1] = lar->g; + lacol[2] = lar->b; + + if(lar->mode & LA_TEXTURE) { + shi->osatex= 0; + do_lamp_tex(lar, lv, shi, lacol, LA_TEXTURE); + } + + VecMulf(lacol, visifac*lar->energy); + + if (ELEM(lar->type, LA_SUN, LA_HEMI)) + VECCOPY(lv, lar->vec); + VecMulf(lv, -1.0f); + + p = vol_get_phasefunc(shi, shi->mat->vol.phasefunc_type, shi->mat->vol.phasefunc_g, shi->view, lv); + VecMulf(lacol, p); + + if (shi->mat->vol.shade_type != MA_VOL_SHADE_NONE) { + Isect is; + + /* find minimum of volume bounds, or lamp coord */ + if (vol_get_bounds(shi, co, lv, hitco, &is, VOL_BOUNDS_SS, 0)) { + float dist = VecLenf(co, hitco); + VlakRen *vlr = (VlakRen *)is.face; + + /* simple internal shadowing */ + if (vlr->mat->material_type == MA_TYPE_SURFACE) { + lacol[0] = lacol[1] = lacol[2] = 0.0f; + return; + } + + if (ELEM(lar->type, LA_SUN, LA_HEMI)) + atten_co = hitco; + else if ( lampdist < dist ) { + atten_co = lar->co; + } else + atten_co = hitco; + + vol_get_attenuation(shi, tau, co, atten_co, density, shade_stepsize); + tr[0] = exp(-tau[0]); + tr[1] = exp(-tau[1]); + tr[2] = exp(-tau[2]); + + VecMulVecf(lacol, lacol, tr); + } + else { + /* Point is on the outside edge of the volume, + * therefore no attenuation, full transmission. + * Radiance from lamp remains unchanged */ + } + } + + vol_get_scattering_fac(shi, &scatter_fac, co, density); + VecMulf(lacol, scatter_fac); +} + +/* single scattering only for now */ +void vol_get_scattering(ShadeInput *shi, float *scatter, float *co, float stepsize, float density) +{ + ListBase *lights; + GroupObject *go; + LampRen *lar; + float col[3] = {0.f, 0.f, 0.f}; + int i=0; + + lights= get_lights(shi); + for(go=lights->first; go; go= go->next) + { + float lacol[3] = {0.f, 0.f, 0.f}; + + i++; + + lar= go->lampren; + if (lar) { + vol_shade_one_lamp(shi, co, lar, lacol, stepsize, density); + VecAddf(col, col, lacol); + } + } + + VECCOPY(scatter, col); +} + + +/* +The main volumetric integrator, using an emission/absorption/scattering model. + +Incoming radiance = + +outgoing radiance from behind surface * beam transmittance/attenuation ++ added radiance from all points along the ray due to participating media + --> radiance for each segment = + (radiance added by scattering + radiance added by emission) * beam transmittance/attenuation + +-- To find transmittance: + compute optical thickness with tau (perhaps involving monte carlo integration) + transmittance = exp(-tau) + +-- To find radiance from segments along the way: + find radiance for one step: + - loop over lights and weight by phase function +*/ +static void volumeintegrate(struct ShadeInput *shi, float *col, float *co, float *endco) +{ + float tr[3] = {1.0f, 1.0f, 1.0f}; + float radiance[3] = {0.f, 0.f, 0.f}, d_radiance[3] = {0.f, 0.f, 0.f}; + float stepsize = vol_get_stepsize(shi, STEPSIZE_VIEW); + int nsteps, s; + float tau[3], emit_col[3], scatter_col[3] = {0.0, 0.0, 0.0}; + float stepvec[3], step_sta[3], step_end[3], step_mid[3]; + float density = vol_get_density(shi, co); + const float depth_cutoff = vol_get_depth_cutoff(shi); + + /* multiply col_behind with beam transmittance over entire distance */ + vol_get_attenuation(shi, tau, co, endco, density, stepsize); + tr[0] *= exp(-tau[0]); + tr[1] *= exp(-tau[1]); + tr[2] *= exp(-tau[2]); + VecMulVecf(radiance, tr, col); + tr[0] = tr[1] = tr[2] = 1.0f; + + /* ray marching */ + nsteps = (int)((VecLenf(co, endco) / stepsize) + 0.5); + + VecSubf(stepvec, endco, co); + VecMulf(stepvec, 1.0f / nsteps); + VecCopyf(step_sta, co); + VecAddf(step_end, step_sta, stepvec); + + /* get radiance from all points along the ray due to participating media */ + for (s = 0; s < nsteps; s++) { + + if (s > 0) density = vol_get_density(shi, step_sta); + + /* there's only any use in shading here if there's actually some density to shade! */ + if (density > 0.01f) { + + /* transmittance component (alpha) */ + vol_get_attenuation(shi, tau, step_sta, step_end, density, stepsize); + tr[0] *= exp(-tau[0]); + tr[1] *= exp(-tau[1]); + tr[2] *= exp(-tau[2]); + + step_mid[0] = step_sta[0] + (stepvec[0] * 0.5); + step_mid[1] = step_sta[1] + (stepvec[1] * 0.5); + step_mid[2] = step_sta[2] + (stepvec[2] * 0.5); + + /* incoming light via emission or scattering (additive) */ + vol_get_emission(shi, emit_col, step_mid, density); + + if (using_lightcache(shi->mat)) { + vol_get_precached_scattering(shi, scatter_col, step_mid); + } else + vol_get_scattering(shi, scatter_col, step_mid, stepsize, density); + + VecMulf(scatter_col, density); + VecAddf(d_radiance, emit_col, scatter_col); + + /* Lv += Tr * (Lve() + Ld) */ + VecMulVecf(d_radiance, tr, d_radiance); + VecMulf(d_radiance, stepsize); + + VecAddf(radiance, radiance, d_radiance); + } + + VecCopyf(step_sta, step_end); + VecAddf(step_end, step_end, stepvec); + + /* luminance rec. 709 */ + if ((0.2126*tr[0] + 0.7152*tr[1] + 0.0722*tr[2]) < depth_cutoff) break; + } + + VecCopyf(col, radiance); + col[3] = 1.0f -(tr[0] + tr[1] + tr[2]) * 0.333f; +} + +static void shade_intersection(ShadeInput *shi, float *col, Isect *is) +{ + ShadeInput shi_new; + ShadeResult shr_new; + + memset(&shi_new, 0, sizeof(ShadeInput)); + + shi_new.mask= shi->mask; + shi_new.osatex= shi->osatex; + shi_new.thread= shi->thread; + shi_new.depth = shi->depth + 1; + shi_new.volume_depth= shi->volume_depth + 1; + shi_new.xs= shi->xs; + shi_new.ys= shi->ys; + shi_new.lay= shi->lay; + shi_new.passflag= SCE_PASS_COMBINED; /* result of tracing needs no pass info */ + shi_new.combinedflag= 0xFFFFFF; /* ray trace does all options */ + shi_new.light_override= shi->light_override; + shi_new.mat_override= shi->mat_override; + + VECCOPY(shi_new.camera_co, is->start); + + memset(&shr_new, 0, sizeof(ShadeResult)); + + /* hardcoded limit of 100 for now - prevents problems in weird geometry */ + if (shi->volume_depth < 100) { + shade_ray(is, &shi_new, &shr_new); + } + + col[0] = shr_new.combined[0]; + col[1] = shr_new.combined[1]; + col[2] = shr_new.combined[2]; + col[3] = shr_new.alpha; +} + +static void vol_trace_behind(ShadeInput *shi, VlakRen *vlr, float *co, float *col) +{ + Isect isect; + float maxsize = RE_ray_tree_max_size(R.raytree); + + VECCOPY(isect.start, co); + isect.end[0] = isect.start[0] + shi->view[0] * maxsize; + isect.end[1] = isect.start[1] + shi->view[1] * maxsize; + isect.end[2] = isect.start[2] + shi->view[2] * maxsize; + + isect.faceorig= (RayFace *)vlr; + + isect.mode= RE_RAY_MIRROR; + isect.oborig= RAY_OBJECT_SET(&R, shi->obi); + isect.face_last= NULL; + isect.ob_last= 0; + isect.lay= -1; + + /* check to see if there's anything behind the volume, otherwise shade the sky */ + if(RE_ray_tree_intersect(R.raytree, &isect)) { + shade_intersection(shi, col, &isect); + } else { + shadeSkyView(col, co, shi->view, NULL, shi->thread); + shadeSunView(col, shi->view); + } +} + +/* the main entry point for volume shading */ +static void volume_trace(struct ShadeInput *shi, struct ShadeResult *shr, int inside_volume) +{ + float hitco[3], col[4] = {0.f,0.f,0.f,0.f}; + int trace_behind = 1; + Isect is; + + /* check for shading an internal face a volume object directly */ + if (inside_volume == VOL_SHADE_INSIDE) { + trace_behind = 0; + } + if (inside_volume == VOL_SHADE_OUTSIDE) { + if (shi->flippednor) + inside_volume = VOL_SHADE_INSIDE; + } + + if (inside_volume == VOL_SHADE_INSIDE) { + + if (trace_behind) { + /* trace behind the volume object */ + vol_trace_behind(shi, shi->vlr, shi->co, col); + } else { + /* we're tracing through the volume between the camera + * and a solid surface, so use that pre-shaded radiance */ + QUATCOPY(col, shr->combined); + } + + /* shade volume from 'camera' to 1st hit point */ + volumeintegrate(shi, col, shi->camera_co, shi->co); + + shr->combined[0] = col[0]; + shr->combined[1] = col[1]; + shr->combined[2] = col[2]; + + if (shi->mat->vol.shadeflag & MA_VOL_USEALPHA) { + if (col[3] > 1.0f) + col[3] = 1.0f; + } + else + col[3] = 1.0f; + shr->combined[3] = col[3]; + shr->alpha = col[3]; + + VECCOPY(shr->diff, shr->combined); + } + /* trace to find a backface, the other side bounds of the volume */ + /* (ray intersect ignores front faces here) */ + else if (vol_get_bounds(shi, shi->co, shi->view, hitco, &is, VOL_BOUNDS_DEPTH, 0)) { + VlakRen *vlr = (VlakRen *)is.face; + + /* if it's another face in the same material */ + if (vlr->mat == shi->mat) { + /* trace behind the 2nd (raytrace) hit point */ + vol_trace_behind(shi, (VlakRen *)is.face, hitco, col); + } else { + shade_intersection(shi, col, &is); + } + + /* shade volume from 1st hit point to 2nd hit point */ + volumeintegrate(shi, col, shi->co, hitco); + + shr->combined[0] = col[0]; + shr->combined[1] = col[1]; + shr->combined[2] = col[2]; + + if (shi->mat->vol.shadeflag & MA_VOL_USEALPHA) { + if (col[3] > 1.0f) + col[3] = 1.0f; + } + else + col[3] = 1.0f; + shr->combined[3] = col[3]; + shr->alpha = col[3]; + + VECCOPY(shr->diff, shr->combined); + } + else { + shr->combined[0] = 0.0f; + shr->combined[1] = 0.0f; + shr->combined[2] = 0.0f; + shr->combined[3] = shr->alpha = 1.0f; + } +} + +/* Traces a shadow through the object, + * pretty much gets the transmission over a ray path */ +void shade_volume_shadow(struct ShadeInput *shi, struct ShadeResult *shr, struct Isect *last_is) +{ + float hitco[3]; + float tr[3] = {1.0,1.0,1.0}; + float tau[3] = {0.0,0.0,0.0}; + Isect is; + float shade_stepsize = vol_get_stepsize(shi, STEPSIZE_SHADE); + + memset(shr, 0, sizeof(ShadeResult)); + + /* if 1st hit normal is facing away from the camera, + * then we're inside the volume already. */ + if (shi->flippednor) { + + vol_get_attenuation(shi, tau, last_is->start, shi->co, -1.0f, shade_stepsize); + tr[0] = exp(-tau[0]); + tr[1] = exp(-tau[1]); + tr[2] = exp(-tau[2]); + + shr->combined[0] = tr[0]; + shr->combined[1] = tr[1]; + shr->combined[2] = tr[2]; + + shr->combined[3] = 1.0f -(tr[0] + tr[1] + tr[2]) * 0.333f; + shr->alpha = shr->combined[3]; + } + /* trace to find a backface, the other side bounds of the volume */ + /* (ray intersect ignores front faces here) */ + else if (vol_get_bounds(shi, shi->co, shi->view, hitco, &is, VOL_BOUNDS_DEPTH, 0)) { + + vol_get_attenuation(shi, tau, shi->co, hitco, -1.0f, shade_stepsize); + tr[0] = exp(-tau[0]); + tr[1] = exp(-tau[1]); + tr[2] = exp(-tau[2]); + + shr->combined[0] = tr[0]; + shr->combined[1] = tr[1]; + shr->combined[2] = tr[2]; + + shr->combined[3] = 1.0f -(tr[0] + tr[1] + tr[2]) * 0.333f; + shr->alpha = shr->combined[3]; + + } + else { + shr->combined[0] = 0.0f; + shr->combined[1] = 0.0f; + shr->combined[2] = 0.0f; + shr->combined[3] = shr->alpha = 0.0f; + } +} + + +/* delivers a fully filled in ShadeResult, for all passes */ +void shade_volume_outside(ShadeInput *shi, ShadeResult *shr) +{ + memset(shr, 0, sizeof(ShadeResult)); + + volume_trace(shi, shr, VOL_SHADE_OUTSIDE); +} + + +void shade_volume_inside(ShadeInput *shi, ShadeResult *shr) +{ + MatInside *m; + Material *mat_backup; + + if (BLI_countlist(&R.render_volumes_inside) == 0) return; + + mat_backup = shi->mat; + +// for (m=R.render_volumes_inside.first; m; m=m->next) { +// printf("matinside: ma: %s \n", m->ma->id.name+2); +// } + + m = R.render_volumes_inside.first; + shi->mat = m->ma; + + volume_trace(shi, shr, VOL_SHADE_INSIDE); + + shi->mat = mat_backup; +}
\ No newline at end of file diff --git a/source/blender/render/intern/source/voxeldata.c b/source/blender/render/intern/source/voxeldata.c new file mode 100644 index 00000000000..81fd1a408e1 --- /dev/null +++ b/source/blender/render/intern/source/voxeldata.c @@ -0,0 +1,340 @@ +/** + * + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. + * All rights reserved. + * + * The Original Code is: all of this file. + * + * Contributor(s): Raul Fernandez Hernandez (Farsthary), Matt Ebb. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +#include <math.h> +#include <stdlib.h> +#include <stdio.h> + +#include "MEM_guardedalloc.h" + +#include "BLI_arithb.h" +#include "BLI_blenlib.h" +#include "BLI_voxel.h" + +#include "IMB_imbuf.h" +#include "IMB_imbuf_types.h" + +#include "BKE_global.h" +#include "BKE_image.h" +#include "BKE_main.h" + +#include "smoke_API.h" + +#include "DNA_texture_types.h" +#include "DNA_object_types.h" +#include "DNA_modifier_types.h" +#include "DNA_smoke_types.h" + + +#include "render_types.h" +#include "renderdatabase.h" +#include "texture.h" +#include "voxeldata.h" + +void load_frame_blendervoxel(FILE *fp, float *F, int size, int frame, int offset) +{ + fseek(fp,frame*size*sizeof(float)+offset,0); + fread(F,sizeof(float),size,fp); +} + +void load_frame_raw8(FILE *fp, float *F, int size, int frame) +{ + char *tmp; + int i; + + tmp = (char *)MEM_mallocN(sizeof(char)*size, "temporary voxel file reading storage"); + + fseek(fp,(frame-1)*size*sizeof(char),0); + fread(tmp, sizeof(char), size, fp); + + for (i=0; i<size; i++) { + F[i] = (float)tmp[i] / 256.f; + } + MEM_freeN(tmp); +} + +void load_frame_image_sequence(Render *re, VoxelData *vd, Tex *tex) +{ + ImBuf *ibuf; + Image *ima = tex->ima; + ImageUser *iuser = &tex->iuser; + int x=0, y=0, z=0; + float *rf; + + if (!ima || !iuser) return; + + ima->source = IMA_SRC_SEQUENCE; + iuser->framenr = 1 + iuser->offset; + + /* find the first valid ibuf and use it to initialise the resolution of the data set */ + /* need to do this in advance so we know how much memory to allocate */ + ibuf= BKE_image_get_ibuf(ima, iuser); + while (!ibuf && (iuser->framenr < iuser->frames)) { + iuser->framenr++; + ibuf= BKE_image_get_ibuf(ima, iuser); + } + if (!ibuf) return; + if (!ibuf->rect_float) IMB_float_from_rect(ibuf); + + vd->flag |= TEX_VD_STILL; + vd->resol[0] = ibuf->x; + vd->resol[1] = ibuf->y; + vd->resol[2] = iuser->frames; + vd->dataset = MEM_mapallocN(sizeof(float)*(vd->resol[0])*(vd->resol[1])*(vd->resol[2]), "voxel dataset"); + + for (z=0; z < iuser->frames; z++) + { + /* get a new ibuf for each frame */ + if (z > 0) { + iuser->framenr++; + ibuf= BKE_image_get_ibuf(ima, iuser); + if (!ibuf) break; + if (!ibuf->rect_float) IMB_float_from_rect(ibuf); + } + rf = ibuf->rect_float; + + for (y=0; y < ibuf->y; y++) + { + for (x=0; x < ibuf->x; x++) + { + /* currently converted to monchrome */ + vd->dataset[ V_I(x, y, z, vd->resol) ] = (rf[0] + rf[1] + rf[2])*0.333f; + rf +=4; + } + } + + BKE_image_free_anim_ibufs(ima, iuser->framenr); + } +} + +void write_voxeldata_header(struct VoxelDataHeader *h, FILE *fp) +{ + fwrite(h,sizeof(struct VoxelDataHeader),1,fp); +} + +void read_voxeldata_header(FILE *fp, struct VoxelData *vd) +{ + VoxelDataHeader *h=(VoxelDataHeader *)MEM_mallocN(sizeof(VoxelDataHeader), "voxel data header"); + + rewind(fp); + fread(h,sizeof(VoxelDataHeader),1,fp); + + vd->resol[0]=h->resolX; + vd->resol[1]=h->resolY; + vd->resol[2]=h->resolZ; + + MEM_freeN(h); +} + +void init_frame_smoke(Render *re, VoxelData *vd, Tex *tex) +{ + Object *ob; + ModifierData *md; + + vd->dataset = NULL; + if (vd->object == NULL) return; + ob= vd->object; + + /* draw code for smoke */ + if(md = (ModifierData *)modifiers_findByType(ob, eModifierType_Smoke)) + { + SmokeModifierData *smd = (SmokeModifierData *)md; + + if(smd->domain && smd->domain->fluid) { + int big = (smd->domain->flags & MOD_SMOKE_HIGHRES); + + if (big) { + smoke_turbulence_get_res(smd->domain->wt, vd->resol); + vd->dataset = smoke_turbulence_get_density(smd->domain->wt); + } else { + VECCOPY(vd->resol, smd->domain->res); + vd->dataset = smoke_get_density(smd->domain->fluid); + } + } + } +} + +void cache_voxeldata(struct Render *re,Tex *tex) +{ + VoxelData *vd = tex->vd; + FILE *fp; + int size; + int curframe; + + if (!vd) return; + + /* image sequence gets special treatment */ + if (vd->file_format == TEX_VD_IMAGE_SEQUENCE) { + load_frame_image_sequence(re, vd, tex); + return; + } else if (vd->file_format == TEX_VD_SMOKE) { + init_frame_smoke(re, vd, tex); + return; + } + + if (!BLI_exists(vd->source_path)) return; + fp = fopen(vd->source_path,"rb"); + if (!fp) return; + + if (vd->file_format == TEX_VD_BLENDERVOXEL) + read_voxeldata_header(fp, vd); + + size = (vd->resol[0])*(vd->resol[1])*(vd->resol[2]); + vd->dataset = MEM_mapallocN(sizeof(float)*size, "voxel dataset"); + + if (vd->flag & TEX_VD_STILL) curframe = vd->still_frame; + else curframe = re->r.cfra; + + switch(vd->file_format) { + case TEX_VD_BLENDERVOXEL: + load_frame_blendervoxel(fp, vd->dataset, size, curframe-1, sizeof(VoxelDataHeader)); + break; + case TEX_VD_RAW_8BIT: + load_frame_raw8(fp, vd->dataset, size, curframe); + break; + } + + fclose(fp); +} + +void make_voxeldata(struct Render *re) +{ + Tex *tex; + + if(re->scene->r.scemode & R_PREVIEWBUTS) + return; + + re->i.infostr= "Loading voxel datasets"; + re->stats_draw(re->sdh, &re->i); + + /* XXX: should be doing only textures used in this render */ + for (tex= G.main->tex.first; tex; tex= tex->id.next) { + if(tex->id.us && tex->type==TEX_VOXELDATA) { + cache_voxeldata(re, tex); + } + } + + re->i.infostr= NULL; + re->stats_draw(re->sdh, &re->i); + +} + +static void free_voxeldata_one(Render *re, Tex *tex) +{ + VoxelData *vd = tex->vd; + + if (vd->dataset) { + MEM_freeN(vd->dataset); + vd->dataset = NULL; + } +} + + +void free_voxeldata(Render *re) +{ + Tex *tex; + + if(re->scene->r.scemode & R_PREVIEWBUTS) + return; + + for (tex= G.main->tex.first; tex; tex= tex->id.next) { + if(tex->id.us && tex->type==TEX_VOXELDATA) { + free_voxeldata_one(re, tex); + } + } +} + +int voxeldatatex(struct Tex *tex, float *texvec, struct TexResult *texres) +{ + int retval = TEX_INT; + VoxelData *vd = tex->vd; + float co[3], offset[3] = {0.5, 0.5, 0.5}; + + if ((!vd) || (vd->dataset==NULL)) { + texres->tin = 0.0f; + return 0; + } + + /* scale lookup from 0.0-1.0 (original location) to -1.0, 1.0, consistent with image texture tex coords */ + /* in implementation this works backwards, bringing sample locations from -1.0, 1.0 + * to the range 0.0, 1.0, before looking up in the voxel structure. */ + VecCopyf(co, texvec); + VecMulf(co, 0.5f); + VecAddf(co, co, offset); + + /* co is now in the range 0.0, 1.0 */ + switch (tex->extend) { + case TEX_CLIP: + { + if ((co[0] < 0.f || co[0] > 1.f) || (co[1] < 0.f || co[1] > 1.f) || (co[2] < 0.f || co[2] > 1.f)) { + texres->tin = 0.f; + return retval; + } + break; + } + case TEX_REPEAT: + { + co[0] = co[0] - floor(co[0]); + co[1] = co[1] - floor(co[1]); + co[2] = co[2] - floor(co[2]); + break; + } + case TEX_EXTEND: + { + CLAMP(co[0], 0.f, 1.f); + CLAMP(co[1], 0.f, 1.f); + CLAMP(co[2], 0.f, 1.f); + break; + } + } + + switch (vd->interp_type) { + case TEX_VD_NEARESTNEIGHBOR: + texres->tin = voxel_sample_nearest(vd->dataset, vd->resol, co); + break; + case TEX_VD_LINEAR: + texres->tin = voxel_sample_trilinear(vd->dataset, vd->resol, co); + break; + case TEX_VD_TRICUBIC: + texres->tin = voxel_sample_tricubic(vd->dataset, vd->resol, co); + break; + } + + texres->tin *= vd->int_multiplier; + BRICONT; + + texres->tr = texres->tin; + texres->tg = texres->tin; + texres->tb = texres->tin; + texres->ta = texres->tin; + BRICONTRGB; + + return retval; +} + + |