1 ////////////////////////////////////////////////////////////////////// 2 // 3 // Pixie 4 // 5 // Copyright � 1999 - 2003, Okan Arikan 6 // 7 // Contact: okan@cs.utexas.edu 8 // 9 // This library is free software; you can redistribute it and/or 10 // modify it under the terms of the GNU Lesser General Public 11 // License as published by the Free Software Foundation; either 12 // version 2.1 of the License, or (at your option) any later version. 13 // 14 // This library is distributed in the hope that it will be useful, 15 // but WITHOUT ANY WARRANTY; without even the implied warranty of 16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 17 // Lesser General Public License for more details. 18 // 19 // You should have received a copy of the GNU Lesser General Public 20 // License along with this library; if not, write to the Free Software 21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 22 // 23 /////////////////////////////////////////////////////////////////////// 24 /////////////////////////////////////////////////////////////////////// 25 // 26 // File : shading.h 27 // Classes : CShadingContext 28 // Description : The shading context that handles sampling/shading surfaces 29 // 30 //////////////////////////////////////////////////////////////////////// 31 #ifndef SHADING_H 32 #define SHADING_H 33 34 #include "common/global.h" 35 #include "common/algebra.h" 36 #include "common/containers.h" 37 #include "shader.h" 38 #include "random.h" 39 40 // Some forward definitions 41 class CShaderInstance; 42 class CVariable; 43 class CAttributes; 44 class CXform; 45 class CShaderInstance; 46 class CRay; 47 class CObject; 48 class CRemoteChannel; 49 class CSurface; 50 class CTracable; 51 class CQuadVertex; 52 class CQuadTriangle; 53 class CQuad; 54 class CTexture3d; 55 class CVertex; 56 class CMovingVertex; 57 class CTriangle; 58 class CMovingTriangle; 59 class CMemPage; 60 class CActiveSample; 61 class CPoints; 62 class CPointCloud; 63 class CVolume; 64 class CParticipatingMedium; 65 class CVisorCache; 66 class CPl; 67 class CSphereLight; 68 struct TObjectHash; 69 class CPLLookup; 70 class CPointHierarchy; 71 class CEnvironment; 72 73 74 typedef enum { 75 SHADING_0D, // Shading points 76 SHADING_2D_GRID, // Shading a 2D grid 77 SHADING_2D // Shading a 2D surface that has been arbitraryly sampled 78 } EShadingDim; 79 80 // Predefined ray labels used during raytracing 81 extern const char *rayLabelPrimary; 82 extern const char *rayLabelTrace; 83 extern const char *rayLabelTransmission; 84 extern const char *rayLabelGather; 85 86 87 /////////////////////////////////////////////////////////////////////// 88 // Class : CConditional 89 // Description : This class is used to hold info about a conditional 90 // Comments : 91 class CConditional { 92 public: 93 int forStart; // The start IP of the conditional 94 int forContinue; // The continue IP of the conditional 95 int forEnd; // The end IP of the conditional 96 int forExecCount; // The execution count of the conditional 97 CConditional *next,*prev; // The next in the free list and the prev in the conditional stack 98 }; 99 100 101 /////////////////////////////////////////////////////////////////////// 102 // Class : CShadedLight 103 // Description : Hold a shaded light 104 // Comments : An instance of this class will be created for each execution of "solar" or "illuminate" 105 class CShadedLight { 106 public: 107 float **savedState; // the saved variables for this light 108 // savedState[0] -> L 109 // savedState[1] -> Cl 110 int *lightTags; // the runtags indicating which points this light ran on 111 CShaderInstance *instance; // points to the instance of light 112 CShadedLight *next; // Points to the next shaded light 113 }; 114 115 116 /////////////////////////////////////////////////////////////////////// 117 // Class : CShadingScratch 118 // Description : Holds all the scratch variables 119 // Comments : 120 struct CShadingScratch { 121 public: 122 123 // Texture/Environment parameters 124 struct { 125 RtFilterFunc filter; 126 float blur; 127 float width; 128 float swidth; 129 float twidth; 130 float fill; 131 float samples; } textureParams; 132 133 // Photonmap parameters 134 struct { 135 float estimator; } photonmapParams; 136 137 // texture3d/bake3d parameters 138 struct { 139 const char *coordsys; 140 float interpolate; 141 float radius; 142 float radiusScale; } texture3dParams; 143 144 // Trace/Transmission parameters 145 struct { 146 float samples; 147 float bias; // This parameter is copied from object attributes by default (unnecessary redundancy in RenderMan) 148 float coneAngle; 149 float sampleBase; 150 float maxDist; 151 const char *label; } traceParams; 152 153 // Indirectdiffuse/occlusion parameters 154 struct { 155 float maxError; // This parameter is copied from object attributes by default (unnecessary redundancy in RenderMan) 156 float pointbased; 157 float maxBrightness; 158 const char *environmentMapName; 159 const char *pointHierarchyName; 160 float maxPixelDist; 161 float maxSolidAngle; 162 int occlusion; 163 const char *cacheHandle; 164 const char *cacheMode; 165 vector environmentColor; 166 CTexture3d *pointHierarchy; 167 CEnvironment *environment; } occlusionParams; 168 169 // Gather parameters 170 struct { 171 const char *distribution; } gatherParams; 172 }; 173 174 /////////////////////////////////////////////////////////////////////// 175 // Class : CShadingState 176 // Description : Holds a shading state at a depth 177 // Comments : 178 class CShadingState { 179 public: 180 // ---> Input fields 181 CSurface *currentObject; // Current object 182 int numVertices; // The number of vertices to be shaded 183 int numUvertices,numVvertices; // The number of o/v vertices (only if rendering a regular grid) 184 EShadingDim shadingDim; // The shading dimentionality 185 // ---> Shading variables: 186 float **varying; // Varying variables 187 float *Ns; // For the light source shaders: the normal of the surface 188 const float *costheta; // For the light source shaders: the cosine of the cone of normals 189 // ---> Lighting variables 190 CShadedLight *lights; // Lights for grid 191 CShadedLight *alights; // Ambient lights for grid 192 CShadedLight *currentLight; // Within an illumination statement, this points to the current light being iterated 193 CShadedLight *freeLights; // Unused lights 194 int *lightingTags; // The tags active when the lighting was executed 195 int lightsExecuted; // FALSE if the lights have not been executed yet 196 int ambientLightsExecuted; // FALSE if the ambient lights have not been executed yet 197 int lightCategory; // The current light category 198 // ---> State and runtags 199 int *tags; // Exec stack counter 200 int numRealVertices; // Vertex count (internally used) 201 int numActive,numPassive; // The number of vertices that are active and passive respectively 202 CShaderInstance *postShader; // Shader to be executed on the surface after the atmosphere 203 204 CShaderInstance *currentShaderInstance; // The current shader instance that's executing 205 CShaderInstance *currentLightInstance; // The current light instance that's executing 206 207 float **locals[NUM_ACCESSORS]; // The local variables for each shader type 208 209 CShadingScratch scratch; // The scratch pad that holds PL data 210 211 CShadingState *next; // The next in free state list 212 }; 213 214 /////////////////////////////////////////////////////////////////////// 215 // Class : CRayBundle 216 // Description : Encapsulates a bundle of rays 217 // Comments : 218 class CRayBundle { 219 public: 220 int numRays; // The number of rays to trace 221 CRay **rays; // The array of rays to trace 222 const char *label; // The label of these rays 223 int last; // The last transparent ray 224 int depth; // The transparency depth of the bundle 225 CShaderInstance *postShader; // The shader to execute after the raytrace 226 227 virtual int postTraceAction() = 0; // The function to be called after the rays are traced 228 virtual void postShade(int,CRay **,float **) = 0; // The function that's called with the shade results 229 virtual void postShade(int,CRay **) = 0; // The function that's called with the rays that don't intersect anything 230 virtual void post() = 0; // The function that's called after each pass 231 }; 232 233 /////////////////////////////////////////////////////////////////////// 234 // Class : TObjectHash 235 // Description : Holds an object hash root 236 // Comments : 237 typedef struct TObjectHash { 238 CSurface *object; 239 CRay *rays; 240 int numRays; 241 TObjectHash *next; 242 TObjectHash *shadeNext; 243 } TObjectHash; 244 245 /////////////////////////////////////////////////////////////////////// 246 // Class : CShadingContext 247 // Description : Holds thread specific stuff 248 // Comments : 249 class CShadingContext { 250 public: 251 CShadingContext(int thread); 252 virtual ~CShadingContext(); 253 254 // This function is called to to render 255 virtual void renderingLoop() = 0; 256 257 // Delayed rendering functions 258 virtual void drawObject(CObject *) = 0; 259 260 // Primitive creation functions 261 virtual void drawGrid(CSurface *,int,int,float,float,float,float) = 0; 262 virtual void drawPoints(CSurface *,int) = 0; 263 264 // The current shading state 265 CShadingState *currentShadingState; 266 267 // Shade points on a surface 268 void shade(CSurface *,int,int,EShadingDim,unsigned int,int displaceOnly=FALSE); displace(CSurface * surface,int u,int v,EShadingDim dim,unsigned int up)269 inline void displace(CSurface *surface,int u,int v,EShadingDim dim,unsigned int up) { shade(surface,u,v,dim,up,TRUE); } displaceEstimate(CSurface * surface,int u,int v,EShadingDim dim,unsigned int up)270 inline void displaceEstimate(CSurface *surface,int u,int v,EShadingDim dim,unsigned int up) { shade(surface,u,v,dim,up,3); } 271 272 // Raytracing functions 273 void trace(CRayBundle *); // Trace and maybe shade bunch of rays 274 void traceEx(CRayBundle *); // Trace and maybe shade a bundle of rays. This version increments the shading depth 275 void trace(CRay *); // Trace a ray (no shading) 276 void traceAny(CRay *); // Trace any ray (no shading) 277 278 // Shading state management functions 279 void updateState(); // Add a variable into the shading state 280 CShadingState *newState(); // Allocate a new shading state 281 void freeState(CShadingState *); // Destroy a shading state 282 void deleteState(CShadingState *); // Delete a shading state 283 void *saveState(); // Save the shading state 284 void restoreState(void *state); // Restore a saved shading state 285 286 // Memory from which we allocate the temp thread stuff 287 CMemPage *threadMemory; 288 289 // The current bucket we're processing in this thread 290 int currentXBucket,currentYBucket; 291 292 // Thread safe random number generator for integers irand()293 inline uint32_t irand() { 294 register uint32_t y; 295 296 if(state == next) next_state(); 297 298 y = *( --next); 299 300 // Tempering 301 y ^= (y >> 11); 302 y ^= (y << 7) & 0x9d2c5680UL; 303 y ^= (y << 15) & 0xefc60000UL; 304 y ^= (y >> 18); 305 306 return y; 307 } 308 309 // Thread safe random number generator for floats urand()310 inline float urand() { 311 register uint32_t y; 312 313 if(state == next) next_state(); 314 315 y = *( --next); 316 317 // Tempering 318 y ^= (y >> 11); 319 y ^= (y << 7) & 0x9d2c5680UL; 320 y ^= (y << 15) & 0xefc60000UL; 321 y ^= (y >> 18); 322 323 y &= 0x3FFFFFFF; 324 return float(y) * (float(1.0)/float(0x3FFFFFFF)); 325 } 326 327 const int thread; // The thread number for this context 328 329 CSobol<2> random2d; // 2D random number generator 330 CSobol<3> random3d; // 3D random number generator 331 CSobol<4> random4d; // 4D random number generator 332 333 int numIndirectDiffuseRays; 334 int numIndirectDiffuseSamples; 335 int numOcclusionRays; 336 int numOcclusionSamples; 337 int numIndirectDiffusePhotonmapLookups; 338 protected: 339 // Hiders can hook into the following functions solarBegin(const float *,const float *)340 virtual void solarBegin(const float *,const float *) { } solarEnd()341 virtual void solarEnd() { } illuminateBegin(const float *,const float *,const float *)342 virtual void illuminateBegin(const float *,const float *,const float *) { } illuminateEnd()343 virtual void illuminateEnd() { } 344 345 int numShade; // Number of times shade is called 346 int numSampled; // Number of points sampled 347 int numShaded; // Number of points shaded 348 int vertexMemory; // The amount of vertex memory allocated by this context 349 int peakVertexMemory; // The maximum peak vertex memory 350 int numTracedRays; // The number of rays traced 351 int numReflectionRays; 352 int numTransmissionRays; 353 int numGatherRays; 354 private: 355 CMemPage *shaderStateMemory; // Memory from which we allocate shader instance variables 356 357 CConditional *conditionals; // Holds nested conditionals 358 int currentRayDepth; // Current shading depth 359 const char *currentRayLabel; // The current ray label 360 CShadingState *freeStates; // The list of free states 361 int inShadow; // TRUE if we're in a shadow 362 363 TObjectHash *traceObjectHash; // An object hash array for raytraced objects 364 365 void execute(CProgrammableShaderInstance *,float **); // Execute a shader 366 367 // The following functions are used in the shaders 368 void duFloat(float *,const float *); 369 void dvFloat(float *,const float *); 370 void DuFloat(float *,const float *); 371 void DvFloat(float *,const float *); 372 void duVector(float *,const float *); 373 void dvVector(float *,const float *); 374 void DuVector(float *,const float *); 375 void DvVector(float *,const float *); 376 float *rayDiff(const float *from,const float *dir,const float *to); 377 float *rayDiff(const float *from); 378 379 class CTraceLocation { 380 public: 381 float *res; // Where we will store the result 382 float t; // The average intersection distance 383 vector C; // Temp area to store the result 384 vector P,dPdu,dPdv; // The ray origin 385 vector D,dDdu,dDdv; // The direction (for reflection), the ray target (for transmission) 386 vector N; // Surface normal reference to determine interior or exterior 387 float time; // Of the sample 388 float coneAngle; // The angular spread 389 int numSamples; // The number of samples to shoot from this location 390 float bias; // The shadow bias 391 float sampleBase; // The sample base 392 float maxDist; // The maximum intersection distance 393 }; 394 395 void traceTransmission(int numRays,CTraceLocation *rays,int probeOnly); 396 void traceReflection(int numRays,CTraceLocation *rays,int probeOnly); 397 398 // The following functions are used in the shaders 399 int surfaceParameter(void *dest,const char *name,CVariable**,int*); 400 int displacementParameter(void *dest,const char *name,CVariable**,int*); 401 int atmosphereParameter(void *dest,const char *name,CVariable**,int*); 402 int incidentParameter(void *dest,const char *name,CVariable**,int*); 403 int oppositeParameter(void *dest,const char *name,CVariable**,int*); 404 int options(void *dest,const char *name,CVariable**,int*); 405 int attributes(void *dest,const char *name,CVariable**,int*); 406 int rendererInfo(void *,const char *,CVariable**,int*); 407 const char *shaderName(); 408 const char *shaderName(const char *type); 409 410 // Some misc tesselation functions (tesselate.cpp) 411 int refine2D(const CAttributes *,CQuad *); 412 int refine1D(const CAttributes *,const CQuadVertex *,const CQuadVertex *,const CQuadVertex *); 413 void displace(CSurface *,int,CQuadVertex **); 414 415 // Some misc shading functions 416 void findCoordinateSystem(const char *,const float *&,const float *&); 417 void findCoordinateSystem(const char *,const float *&,const float *&,ECoordinateSystem &); 418 419 // Some data structures for urand() 420 // 421 // implementation of Takuji Nishimura and Makoto Matsumoto's 422 // MT19937 (Mersenne Twister pseudorandom number generator) 423 // with optimizations by Shawn Cokus, Matthe Bellew. 424 // This generator is not cryptoraphically secure. 425 // 426 // M. Matsumoto and T. Nishimura, 427 // "Mersenne Twister: A 623-Dimensionally Equidistributed Uniform 428 // Pseudo-Random Number Generator", 429 // ACM Transactions on Modeling and Computer Simulation, 430 // Vol. 8, No. 1, January 1998, pp 3--30. 431 // 432 // C++ interface and further optimization by Mayur Patel 433 // 434 435 uint32_t state[624]; 436 uint32_t *next; 437 438 CPLLookup *plHash[PL_HASH_SIZE]; 439 440 void next_state(); 441 void randomInit(uint32_t u = 5489UL); 442 void randomShutdown(); 443 444 445 friend class CPhotonHider; 446 friend class CProgrammableShaderInstance; 447 friend class CSphereLight; 448 friend class CQuadLight; 449 }; 450 451 #endif 452 453