6.4 Standard Functions
3Delight supports all the standard Shading Language (SL) built-in shadeops and constructs. The complete set of standard shadeops is listed below. Descriptions are kept brief, if any, since shadeops are already described in great details in the RenderMan specifications. Shadeops marked with (*) contain specific extensions and those marked with (**) are not part of the current standard. It is also possible to link shaders with C or C++ code to add new shadeops, see DSO Shadeops.
3Delight supports all predefined shader variables. It doesn't follow strictly the 3.2 RenderMan Interface specification though: some shaders have access to more variables.
6.4.1 Mathematics
- float radians ( float degrees )
- float degrees ( float radians )
- float sin ( float radians )
- float asin ( float a )
- float cos ( float radians )
- float acos ( float a )
- float tan ( float radians )
- float atan ( float a )
- float atan ( float y, float x )
- float sqrt ( float x )
Returns the square root of x. The domain is [0..infinity]. If x<0 this shadeop will return 0.
- float inversesqrt ( float x )
Returns 1.0/sqrt(x). The domain of this function is [0..infinity[. If x<0 this shadeop will return infinity(35).
- float log ( float x [, base] )
Returns the natural logarithm of x. If the optional base is specified, returns the logarithm of x in the specified base. The domain of this function is [0..infinity[. If x<0 this shadeop will return -infinity.
- float mod ( float x, y )
Returns x modulus y. More formally, returns a value in the range [0..y], for which mod(x, y) = x - n*y, for some integer n.
- type min ( type x, y, ... )
- type max ( type x, y, ... )
- type clamp ( type x, min, max )
min()andmax()take two or more arguments of the same type and return the minimum and maximum values, respectively.clamp()will return min if x is smaller than min, max if x is greater thanmaxand x otherwise. type can be a float or a 3-tuple. When running on 3-tuples, these shadeops will consider one component at time point (eg.min(point(1,2,3), point(4,3,2))will returnpoint(1,2,2));
- float step ( float min, value )
- float smoothstep ( float min, max, value )
step()returns 0 if value is less than min; otherwise it returns 1.smoothstep()returns 0 if value is less than min, 1 if value is greater than or equal to max, and returns a Hermite interpolation between 0 and 1 when value is in the range [min..max[.
- type mix ( type x, y, alpha )
Returns x*(1-alpha) + y*alpha. For multi-component types (color, point, ...), the operation is performed for each component.
- float filterstep ( float edge, value, ... )
- float filterstep ( float edge, value1, value2, ... )
Similar to
step()but the return value is filtered over the area of the micropolygon being shaded. Useful for shader anti-aliasing. Filtering kernel is selected using the "filter" optional parameter. Recognized filters are `gaussian', `box', `triangle' and `catmull-rom'. Default is `catmull-rom'. If two values are provided, return value is filtered in the range [value1..value2].
- type spline ( [string basis ;] float value; type begin, p1, ..., pn, end)
- type spline ( [string basis ;] float value; type p[])
Interpolates a point on a curve defined by begin, p1 to pn, and end control points. value should lie between 0 and 1, otherwise the return value will be clamped to either p1 or pn. The default basis is the `catmull-rom' spline(36). Other possible splines are `bezier', `bspline', `hermite' and `linear'. Any unknown spline is assumed to be `linear'. Any recognized spline may be prefixed by `solve', such as `solvecatmull-rom'. In such a case, the shadeop becomes a root solver and may be used as an invert function.
- type Du ( type x )
- type Dv ( type x )
- type Deriv ( type num; float denom )
Du()andDv()compute the parametric derivative of the given expressions with respect to the u and the v parameters of the underlying surface (37).
6.4.2 Noise and Random
- type noise ( float x )
- type noise ( float x, y )
- type noise ( point Pt )
- type noise ( point Pt; float w )
1D, 2D, 3D and 4D noise function. type can be
float,color,pointorvector.
- type pnoise ( float x, period )
- type pnoise ( float x, y, xperiod, yperiod )
- type pnoise ( point Pt, Ptperiod )
- type pnoise ( point Pt; float w; point Ptperiod; float wperiod )
Same as noise but has periodicity period. Maximum period is 256.
- type cellnoise ( float x )
- type cellnoise ( float x, y )
- type cellnoise ( point Pt )
- type cellnoise ( point Pt, float w )
Cellular noise functions (1D, 2D, 3D and 4D).
- type random ( )
Returns a random
float,colororpoint. Returned range is [0..1]. Can returnuniformorvaryingvalues. Here is a trick to put a random color in each grid of micropolygons:uniform float red = random(); uniform float green = random(); uniform float blue = random(); Ci = color( red, green, blue );
6.4.3 Geometry, Matrices and Colors
- float xcomp ( point Pt )
- float ycomp ( point Pt )
- float zcomp ( point Pt )
- void setxcomp ( output point Pt; float x )
- void setycomp ( output point Pt; float y )
- void setzcomp ( output point Pt; float z )
Gets or sets the x, y, or z component of a point (or vector).
- float comp ( color c; float i )
- void setcomp ( output color c, float i, x )
Returns or sets the "ith" component of the given color.
- point transform ( string [fromspace,] tospace; point Pt )
- point transform ( [string fromspace;] matrix M; point Pt )
- point transform ( string [fromspace,] tospace; vector V )
- point transform ( [string fromspace;] matrix M; vector V )
- point transform ( string [fromspace,] tospace; normal N )
- point transform ( [string fromspace;] matrix M; normal N )
Transforms a
point,vectorornormalfrom a given space (fromspace) to another space (tospace). If the optional fromspace is not given, it is assumed to be the `current' space. Refer to Table 6.3 for the complete list of valid space names.
- vector vtransform ( string [fromspace,] tospace; vector V )
- vector vtransform ( [string fromspace;] matrix M; vector V )
- normal ntransform ( string [fromspace,] tospace; normal Nr )
- normal ntransform ( [string fromspace;] matrix M; normal Nr )
Same as
transform()above but specifically selects a transform on normals or vectors (no polymorphism).NOTE
One should use
transform()instead since that shadeop will correctly select the appropriate transform depending on the parameter type.
- color ctransform ( string [fromspace,] tospace; color src_color )
Transforms color src_color from color space fromspace to color space tospace. If the optional fromspace is not specified, it is assumed to be `rgb'. 3Delight recognizes the following color spaces: RGB, HSV, HSL, YIQ and XYZ(38). If an unknown color space is given, 3Delight returns src_color.
- float distance ( point Pt1, Pt2 )
- float length ( vector V )
- vector normalize ( vector V )
distance()returns the distance between two points.length()returns the length (norm) of the given vector.normalize()divides the given vector by its length (making it of unit length). All three operations involve a square root.
- float ptlined ( point Pt1, Pt2, Q )
Returns minimum distance between a point Q and a segment defined by Pt1 and Pt2.
- point rotate ( point Q; float angle; point Pt1, Pt2 )
Rotates a point Q around the line defined by Pt1 and Pt2, by a given angle. New point position is returned. Note that angle is assumed to be in radians.
- float area ( point Pt [; string strategy] )
Returns
length(Du(Pt)^Dv(Pt)), which is approximately the area of one micro-polygon on the surface defined by Pt. The strategy variable can take two values:- ` shading'
- Compute area of the micro-polygon based on surface derivatives. This will produce smoothly varying areas if smooth derivatives are enabled (see section Other Attributes).
- ` dicing'
- Compute area of micro-polygons using their geometry, regardless of smooth derivatives.
If no strategy is supplied, `shading' will be assumed.
- vector faceforward ( vector N, I[, Nref] )
Flips N, if needed, so it faces in the direction opposite to I. Nref gives the element surface normal; if not provided, NRef is set to Ng.
- vector reflect ( vector I, N )
Returns the vector which is the reflection of I around N. Note that N must be of unit length.
- vector refract ( vector I, Nr; float eta )
Returns the refracted vector for the incoming vector I, surface normal Nr and index of refraction ratio eta. Nr must be of unit length.
- float depth ( point Pt )
Returns the normalized z coordinate of Pt in camera space. Return value is in the range [0..1] (0=near clipping plane, 1=far clipping plane). Pt is assumed to be defined in `current' space.
- normal calculatenormal ( point Pt )
Computes the normal of a surface defined by Pt. Often used after a displacement operation on Pt. Equivalent to
Du(Pt)^Dv(Pt), but faster.
- float determinant ( matrix M )
- matrix inverse ( matrix M )
- matrix translate ( matrix M; point Tr )
- matrix rotate ( matrix M; float angle; vector axis )
- matrix scale ( matrix M; point Sc )
Basic matrix operations. The angle parameter passed to
rotate()is assumed to be in radians.
6.4.4 Lighting
- color ambient ( )
Returns the contribution from ambient lights. A light is considered ambient if it does not contain an
illuminate()orsolar()statement. It is not available in lightsource shaders.
- color diffuse ( vector Nr )
Computes the diffuse light contribution. Lights placed behind the surface element being shaded are not considered. Nr is assumed to be of unit length. Light shaders that contain a parameter named
uniform float __nondiffuseare evaluated only if the parameter is set to 0. Not available in lightsource shaders (see section Predefined Shader Parameters).
- color specular ( vector Nr, V; float roughness ) *
Computes the specular light contribution. Lights placed behind the object are not considered. Nr and V are assumed to be of unit length. Light shaders that contain a parameter named
uniform float __nonspecularare evaluated only if the parameter is set to 0. Not available in lightsource shaders (see section Predefined Shader Parameters).
- color specularbrdf ( vector L, Nr, V; float roughness )
Computes the specular light contribution. Similar to
specular()but receives a L variable (incoming light vector) enabling it to run in customilluminance()loops.
- color specularstd ( normal N; vector V; float roughness)
This is the standard specular model described in all graphic books since 3Delight implements its own specular model in
specular.color specularstd( normal N; vector V; float roughness ) { extern point P; color C = 0; point Nn = normalize(N); point Vn = normalize(V); illuminance(P, Nn, PI/2) { extern vector L; extern color Cl; vector H = normalize(normalize(L)+Vn); C += Cl * pow(max(0.0, Nn.H), 1/roughness); } return C; }Listing 6.6: specularstd()implementation.
- color phong ( vector Nr, V; float size )
Computes specular light contribution using the Phong illumination model. Nr and V are assumed to be of unit length. As in
specular(), this function is also sensitive to the__nonspecularlight shader parameter. Not available in lightsource shaders.
- void fresnel ( vector I, N; float eta; output float Kr, Kt [; output vector R, T] )
Uses the Fresnel formula to compute the reflection coefficient Kr and refraction (or transmission) coefficient Kt given and incident direction I, the surface normal N and the relative index of refraction eta. Note that eta is the ratio of the index of refraction in the volume containing the incident vector to that of the volume being entered: a ray entering a water volume from a void volume would need an eta of approximately 1.0/1.3. Here is a noteworthy quotation from "The RenderMan Companion":
In most cases, a ray striking a refractive material is partly reflected and partly refracted. The function
fresnel()calculates the respective fractions. It may also return the reflected and refracted direction vectors, so that is subsumesrefract().If R and T are supplied, they are set to the direction vector of the reflected and the transmitted (refracted) ray, respectively.
6.4.5 Ray Tracing
All the ray tracing shadeops can receive a number of common optional parameters, these are described in Table 6.10. Specific optional parameters are described with each shadeop individually.
|
- color trace ( point Pt; vector R [; output float dist]; ... ) *
Returns the color of light arriving to Pt from direction R. This is accomplished by tracing a ray from Pt in the direction specified by R. Only objects tagged as visible to reflection rays are considered during the operation. If the optional output parameter dist is specified, it will contain the distance to the nearest intersection point or a very large number (> 1e30) when no intersections are found. Note that Pt and R must lie in `current' space. Optional parameters to
trace()are summarized in below.uniform float maxdist- Specifies a distance after which no intersections are checked. The default value is 1e38 which means that there is nothing
varying float samplecone- Specifies an angle in radians that, together with
trace()'s starting point Pt, describes a cone in which rays will be sampled. Larger cones means softer results. This is the same angle as specified to the transmission shadeop. The default value is 0. uniform float samples- Specifies the number of samples to use to. Higher sample counts are needed if:
- Anti-aliasing is to be performed. Even if `samplecone' is set to 0.
- `samplecone' is greater than 0 and more samples are needed to achieve a smoother result.
output varying color transmission- Returns the transmission in the traced direction. If returned transmission is equal to (1, 1, 1) then no objects have been intersected, if it is (0,0,0) then no lights is coming from direction R. Intermediate values describe a varying degree of coverage. The resulting transmission will correctly accounts for translucent objects and can be used to composite the result returned by
tracewith an environment map as shown in Listing 7.2. There is no speed penalty to get the transmission fromtrace()IMPORTANT
The returned value is exactly the same as what would have been returned by the transmission shadeop with the important difference that
transmission()intersects objects that are visible to transmission rays whiletrace()honors reflection rays.
EXAMPLE
/* Trace a ray, only considering intersections closer than 10 units. Intersection distance is stored in ``dist'' and intersection color in ``c''. If no intersection, dist will be left at 1e36 */ float dist = 1e36; color c = trace( P, Nf, dist, "maxdist", 10 );
- float trace ( point Pt; vector R )
Returns the distance to the nearest intersection, when looking from Pt in the direction specified by the unit vector R. This function may be substantially faster than the color version of
trace()since it might avoid costly shading operations. Pt and R must lie in `current' space. This function intersects objects that are visible to reflection rays.
- color transmission ( point Pt1, Pt2, ... )
Determines the visibility between Pt1 and Pt2 using ray tracing. Returns
color 1if un-occluded andcolor 0if totally occluded. In-between values indicate the presence of a translucent surface between Pt1 and Pt2. Only objects tagged as visible to transmission rays are considered during the operation (usingAttribute "visibility" "transmission", Attributes). Pt1 and Pt2 must lie in `current' space. When tracing area light shadows, it is usually better for performance to trace from the surface to the light. In addition to standard ray tracing optional parameters (see Table 6.10), this shadeop also accepts:varying float samplecone- Same as for the trace shadeop.
uniform float samples- Same as for the trace shadeop.
- float occlusion ( point Pt; vector R; [float samples;] ... ) *
Computes the amount of occlusion, using ray tracing, as seen from Pt in direction R and solid angle 2*PI (hemisphere). Returns 1.0 if all rays hit some geometry (totally occluded) and 0.0 if there are no hits (totally un-occluded).
- Pt and R must lie in `current' space and R must be of unit length.
- The optional samples parameter specifies the number of rays to trace to compute occlusion; if absent or set to 0, the value is taken from
Attribute "irradiance" "nsamples"(see section Attributes). - This shadeop accepts many optional token/value pairs. These are explained in Table 6.11.
- More on ambient occlusion in Ambient Occlusion and Point-Based Occlusion and Color Bleeding.
EXAMPLE
/* Returns the amount of occlusion using default number of samples */ float hemi_occ = occlusion( P, Ng ); /* Returns the amount of occlusion for the hemisphere surrounding P, uses a rough approximation with 8 samples */ hemi_occ = occlusion( P, Ng, 8 ); /* Same as above, but only consider objects closer than 10 units and in a solid angle of Pi/4 */ hemi_occ = occlusion( P, Ng, 8, "maxdist", 10, "coneangle", PI/4 ); /* Same as above, but only consider light coming from a hemisphere oriented toward (0,1,0) */ uniform vector sky = vector (0, 1, 0); hemi_occ = occlusion( P, Ng, 8, "maxdist", 10, "coneangle", PI/2, "axis", sky );
- color indirectdiffuse ( point Pt; vector R; [float samples;] ... ) *
-
Computes diffuse illumination due to diffuse-to-diffuse indirect light transport by sampling a hemisphere around a point Pt and direction R. Use this shadeop to render color bleeding effects.
- Pt and R must lie in `current' space and R must be of unit length.
- This function makes it possible to lookup into an HDR image when sampled rays do not hit any geometry; the map is specified using the
"environmentmap"parameter as shown in Table 6.11. - Computing the occlusion while calling this function is also possible (through the
occlusionparameter), with the following restriction:indirectdiffuse()only sees geometry tagged as visible to reflections, as opposed toocclusion()which sees geometry visible to shadows. For more informations about visibility attributes refer to Attributes.
Note
This shadeop will automatically perform "final gathering" if there is a photon map attached to geometry. Using photon maps will speed up global illumination computations tremendously using this shadeop, more about photons maps and final gathering in Photon Mapping and Final Gathering.
- color indirectdiffuse ( string envmap; vector dir ) *
Returns the irradiance coming from an environment and a given direction (dir must be of unit length). The environment can be described in three different formats:
- A cube environment map.
- A latitude/longitude environment map.
- A light probe.
Environment maps have to be generated by
tdlmakewith the `-envcube' or `-latlong' parameter. Probes are images generated by software such asHDRShopand are usually stored asRadiancefiles (with an `.hdr' extension). These must be converted bytdlmaketo a normal TIFF texture. It is perfectly correct (and recommended) to provide high dynamic range images to this shadeop. Refer to Image Based Lighting for more information.
occlusion() and indirectdiffuse() optional parameters. |
Additionally, for point-cloud based occlusion and color bleeding, the following parameters are recognized:
|
- float gather ( string category; point P; vector dir; float angle; float samples, ... )
statement[else statement] gatheris considered as a language construct and is detailed in The Gather Construct.
- color subsurface ( point Pt; ... )
Returns subsurface lighting at the given point Pt. Subsurface light transport is automatically computed in a separate pass. More about subsurface scattering in Subsurface Scattering.
subsurface() optional parameters. |
- float photonmap ( string mapname; point P; vector N; ...)
This shadeop performs a lookup in the photonmap specified by mapname at the surface location described by (P, N). This shadeop accepts the following additional parameters:
"float estimator"- An integer specifying the number of photons to use for the lookup. More photons will give smoother results. The default is 50.
"string lookuptype"-
Can take one of the following values:
- ` irradiance'
- Returns the irradiance at the specified location.
- ` radiance'
-
Returns the radiance at the specified location. Note that 3DELIGHT stores a coarse estimation of the radiance which is not meant for direct visualization. It is mainly useful for the
indirectdiffuse()shadeop when performing final gathering as explained in Final Gathering.
"float mindepth"- When performing irradiance lookups, specifies the minimum number of bounces for a photon to be considered in irradiance computation. For example, setting a mindepth of `1' will avoid photons that come directly from the light sources (meaning that the call will return only indirect light contribution).
EXAMPLE
/* Perform an irradiance lookup using 100 photons */ color res = photonmap( "gloabal.map", P, Nf, "estimator", 100 );
Refer to Photon Mapping for more details about photon maps.
- float caustic ( point P; vector N )
This shadeop performs a lookup in the caustic photon map that belongs to the surface being shaded at the surface location described by (P, N). This shadeop can be written using the
photonmap()shadeop:color caustic( point P, normal N ) { uniform float estimator = 50; uniform string causticmap = ""; attribute( "photon:causticmap", causticmap ); attribute( "photon:estimator", estimator ); color c = 0; if( causticmap!="" ) { c = photonmap( causticmap, P, N, "lookuptype", "irradiance", "estimator", estimator ); } return c; }Table 6.14: caustic()shadeop implementation using thephotonmap()shadeop.
6.4.6 Texture Mapping
- type texture ( string texturename[float channel]; ... )
- type texture ( string texturename[float channel]; float s, t; ... )
- type texture ( string texturename[float channel]; float s1, t1, s2, t2, s3, t3, s4, t4; ... )
Returns a filtered texture value, at the specified texture coordinates.
typecan be either afloator acolor. If no texture coordinates are provided, s and t are used. An optional channel can be specified to select a starting channel in the texture. This can be useful when a texture contains more than three channels. Usetdlmaketo prepare textures for improved performance and memory usage (see section Using the Texture Optimizer -tdlmake).texture()accepts a list of optional parameters as summarized in Table 6.15. EXAMPLE/* Sharper result (width<1) */ color c = texture( "grid.tdl", s, t, "width", 0.8 ); /* Returns the green component */ float green = texture( "grid.tdl"[1] ); /* Returns the alpha channel, or 1.0 (opaque) if no alpha channel is present */ float alpha = texture( "grid.tdl"[3], "fill", 1.0 ); /* Returns an _unfiltered_ color from the texture */ color unfiltered = texture( "grid.tdl", s, t, s, t, s, t, s, t );
Note that this shadeop will return proper linear-space colors if the texture has a gamma specification. Refer to Texture Mapping in Linear Space for details.
- type environment ( string texturename[channel]; vector V; ... )
- type environment ( string texturename[channel]; vector V1, V2, V3, V4; ... )
Returns a filtered texture value from an environment map, for a specified direction. As in
texture(), an optional channel can be specified to select a starting channel when performing texture lookups. Usetdlmaketo prepare cubic and long-lat envmaps. If an unprepared TIFF is given toenvironment(), it is considered as a lat-long environment map.environement()recognizes the same list of optional parameters astexture(). If the given file name is "raytrace", environment uses ray tracing instead of texture lookups, which of course is more expensive. Only geometry tagged as visible to "trace" rays is considered (Attribute "visibility" "trace" 1). Optional parameters accepted by this shadeop are listed in Table 6.15. When using ray tracing, thisenvironment()also accepts the same optional parameters astrace(see trace shadeop). EXAMPLE/* Do an env lookup */ vector Nf = faceforward( N, I ); color c = environment( "env.tdl", vtransform("world", Nf) ); /* Only fetch the alpha channel, if no alpha present, returns 1 */ float red_comp = environment( "env.tdl"[3], Nf, "fill", 1 );Note that this shadeop will return proper linear-space colors if the texture has a gamma specification. Refer to Texture Mapping in Linear Space for details.
texture() shadow() and environment() optional parameters. |
- type shadow ( string shadowmap[float channel]; point Pt; ... ) *
- type shadow ( string shadowmap[float channel]; point Pt1, Pt2, Pt3, Pt4; ... ) *
Computes occlusion at a point in space using a shadow map or a deep shadow map. Shadow lookups are automatically anti-aliased. When using deep shadow maps, colored shadows and motion blur are correctly computed. If the file name passed to
shadow()is"raytrace"then ray tracing is used to compute shadows. Note that if ray tracing is used, only objects tagged as visible to shadows are considered (usingAttribute "visibility" "transmission"). Optional parameters toshadow()are described in Table 6.15. Additional information for both shadow maps and deep shadow maps are found in Shadows.
- void bake ( string bakefile; float s, t; type value )
-
This shadeop writes the given value (of type float, point or color) to a file named bakefile. This file can then be converted to a texture map using
tdlmake(see section Using the Texture Optimizer -tdlmake) or a call toRiMakeTexture. We recommend using the `.bake' extension for files containing such "baked" data.By defaul, data is saved in a human-readable ASCII format for easy inspection but saving in binary format is also possible. To do so one can concatenate the
"&binary"string to the file name, as shown in Listing 6.7.surface bake2d( string bakefile = ""; float binary = 0; ) { Ci = noise(s*32, t*16); if( binary == 1 ) bake( concat(bakefile,"&binary"), s, t, Ci ); else bake( bakefile, s, t, Ci ); }Listing 6.7: Baking into a binary file.
Note that baking in 2D space is only appropriate when the underlying surface has a well-behaved 2D parametrisation (which is often the case in most models that had undergone some UV unwrapping). More about baking in Baking.
- float bake3d ( string bakefile; string channels; point P, normal N, ... )
This shadeops records a set of values to the file bakefile for the given position and normal. Values to record are supplied as named parameter pairs. For example:
float occlusion = occlusion( P, N, samples, "maxdist", 3 ); bake3d( texturename, "", P, N, "surface_color", Ci, "occlusion", occlusion );
Note that the channels parameter is ignored in the current implementation. The files created by the
bake3d()are unfiltered point clouds which can be used directly or converted to brick maps as explained in Brick Maps; in both cases data is directly accessible throughtexture3d()(see texture3d shadeop).bake3d()returns 1 if the write is successful and 0 otherwise. It takes various optional parameters listed in Table 6.16.Name Type Default Description "coordsystem" string"world" Specifies the coordinate system into which the values are written. "radius" varying floatbased on grid Specifies the radius of the disk (or sphere if N is 0) covered by each baked sample. "radiusscale" float1.0 Allows scaling of the radius value without overriding it. In point cloud files, the size of a disk affects the importance of its orientation for lookups with texture3d. Larger disks are less likely to be picked if the normals do not match. They are more strongly oriented."interpolate" float0.0 When set to 1.0, saves the centers of the micro-polygons instead of its corners. This is primarly usefule for point-based occlusion and color bleeding (see section Point-Based Imaging Pipeline). Table 6.16: bake3d()optional parameters.
Additionally, there is two channel names that are reserved for use with point-based occlusion and color bleeding (see section Point-Based Occlusion and Color Bleeding):
- ` float _area'
- Specifies the area of the given point. It is not necessary to specify this channel if it is not different from the actual micro-polygon area.
- ` color _radiosity'
- Specifies the radiosity at the given point. This is used for point-based color bleeding.
- float texture3d ( string bakefile; point P, normal N, ... )
This shadeop is used to perform lookups in files created by
bake3d()(see bake3d shadeop). Its syntax is indeed very similar tobake3d():
float occlusion; texture3d( texturename, P, N, "surface_color", Ci, "occlusion", occlusion );
texture3d()returns 1 if the lookup was successful and 0 otherwise. It takes various optional parameters listed in Table 6.17.Name Type Default Description "coordsystem" string"world" Specifies the coordinate system from which the values are written. "filterradius" float- Specifies the radius of the lookup filter. If none is given, the renderer computes one that is faithful to the shaded element derivatives. "filterscale" float1 A multiplier on the radius of the lookup filter. It is not necessary to specify `filterradius' to use this parameter. "maxdepth" float- Sets a maximum depth for lookups. If not specified, maximum depth is used. Works for both point clouds and brick maps. Table 6.17: texture3d()optional parameters.
6.4.7 String Manipulation
- string format ( string pattern; val1, ..., valn ) *
Similar to the C
sprintffunction. pattern is a string containing conversion characters. Recognized conversion characters are:%f- Formats a float using the style [-]ddd.ddd. Number of fractional digits depends on the precision used (see example).
%e- Formats a float using the style [-]d.ddde dd (that is, exponential notation). This is the recommended conversion for floats when precision matters.
%g- The floating point is converted to style
%for%e. If a precision specifier is used,%fis applied. Otherwise, the format which uses the least characters to represent the number is used. %d- Equivalent to
%.0f, useful to format integers. %p- Formats a point-like type (
point,vector,normal) using the style[%f %f %f]. %c- Same as
%p, but for colors. %m- Formats a matrix using the style
[%f %f %f %f, %f %f %f %f, %f %f %f %f, %f %f %f %f]if a precision specifier is used. Otherwise, each element is formatted to full precision as with%g. %s- Formats a string.
Note that all conversion characters recognize the precision specifier.
EXAMPLE
/* Formats a float using exponential notation */ string expo = format( "%e", sqrt(27) ); /* Formats a float, with 5 decimals in the fractional part */ point p = sqrt(5); string precision5 = format( "p = %.5p", p ); /* Aligns text */ string aligned = format( "%20s", "align me please" );
- void printf ( string pattern; val1, ..., valn ) *
Same as
format()but prints the formatted string to `stdout' instead of returning a string.
- float match ( string pattern, subject )
Does a string pattern match on subject. Returns 1 if pattern exists anywhere within subject, 0 otherwise. The pattern can be any standard
regex(40) expression.
6.4.8 Message Passing and Information
- float textureinfo ( string texturename, fieldname; output uniform type variable )
Returns information about a particular texture, environment or shadow map. fieldname specifies the name of the information as listed in Table 6.18. If fieldname is known, and variable is of the correct type,
textureinfo()returns 1.0. Otherwise, 0.0 is returned.EXAMPLE
/* mapres[0] gets map resolution in x, mapres[1] gets map resolution in y */ uniform float mapres[2]; textureinfo( "grid.tdl", "resolution", mapres ); /* Get current to camera matrix used to create the shadow map */ uniform matrix Nl; if( textureinfo( "main-spot.tdl", "viewingmatrix", Nl )!= 1.0 ) { Nl = 1; }
Additionally, a special call to
textureinfo()is provided to test texture existence:
color C; if( textureinfo(texturename, "exists", 0) ) C = texture(texturename); else C = errorcolor;
The existence check also checks for validity so if the file exists on disk but is not a valid texture, this function will return 0. An error message will still be output if the texture doesn't exist.
textureinfo() field names. |
- float atmosphere ( string paramname; output type variable )
- float displacement ( string paramname; output type variable )
- float incident ( string paramname; output type variable )
- float opposite ( string paramname; output type variable )
- float lightsource ( string paramname; output type variable )
- float surface ( string paramname; output type variable )
Functions to access a parameter in one of the shaders attached to the geometric primitive being shaded. The operation succeeds if the shader exists, the parameter is present and the type is compatible, in which case 1.0 is returned. Otherwise, 0.0 is returned and variable is unchanged. Note that assigning a
varyingshader parameter to auniformvariable fails. Also,lightsource()is only available inside anilluminance()block and refers to the light source being examined.
- float attribute ( string dataname; output type variable )
Returns the value of the data that is part of the primitive's attribute state. The operation succeeds if dataname is known and the type is correct, in which case 1.0 is returned. Otherwise, 0.0 is returned and variable is unchanged. The supported data names are listed in Table 6.19. User defined attributes are also accessible.
EXAMPLE
uniform float self_illuminated = 0; attribute( "user:self_illuminated", self_illuminated ); if( self_illuminated == 1 ) { .. do some magic here ... }It is possible to query the attributes of a light source from a surface shader. To do so, use the
attribute()shadeop inside an illuminance loop and prefix the attribute name with"light:".EXAMPLE
illuminance( P ) { string name; if( 1 == attribute( "light:identifier:name", name ) ) printf( "light name: %s\n", name ); }
attribute() field names. |
- float option ( string dataname; output type variable )
Returns the data that is part of the renderer's global option state. The operation succeeds if dataname is known and the type is correct, in which case 1.0 is returned. Otherwise, 0.0 is returned and variable is unchanged. The supported data names are listed in Table 6.20. User defined options (as specified by
RiOption, see User Options) are also accessible:EXAMPLE
uniform float shadow_pass = 0; option( "user:shadow_pass", shadow_pass ); if( shadow_pass == 1 ) { ... }
option() field names. |
rendererinfo() field names. |
- uniform float rendererinfo ( string dataname; output type result )
Returns information about the renderer. The operation succeeds if dataname is known and the type is correct, in which case 1.0 is returned. Otherwise, 0.0 is returned and result is unchanged. The supported data names are listed in Table 6.21.
- float rayinfo ( uniform string keyword; output type result )
Provides informations about the current ray. Returns 1.0 if keyword is known and result is of the correct type. Returns 0.0 on failure.
EXAMPLE
/* Choose the number of rays to trace depending on current ray depth. */ uniform float ray_depth; rayinfo( "depth", ray_depth ) samples = max(1, samples / pow(2, ray_depth) ); trace_color = trace( P, Nr, "samples", samples );
rayinfo() field names. |
- float raylevel ( )
- float isindirectray ( )
- float isshadowray ( )
Deprecated functions. Their functionalities can be reproduced using the
rayinfo()shadeop. See rayinfo shadeop.
- float isoutput ( var )
Returns true if var is output to a display driver. This is true if:
- The variable is declared as
outputin shaders' parameters. - The variable is specified in at least one display driver.
This function is useful to optimize shaders that have to calculate many AOVs: it is wasteful to compute an AOV if there is no display driver that uses it.
IMPORTANT
This shadeop doesn't work with compiled shaders (shaders compiled with the `-dso' option).
- The variable is declared as
6.4.9 Co-Shader Access
- shader[] getshader ( shader shader_name )
Get the shader with the specified name and active in the current attribute scope.
- shader getlight ( string light_handle )
Returns the co-shader for the light source with handle light_handle.
- shader[] getlights ( ["category"; string category_name] )
Returns all active lights in the current attribute scope, filtering them using an optional category name. This method can be used to build custom illuminance loops. For example,
vector L; color Cl, C=0; shader lights[] = getlights( "category", "diffuse" ); uniform float num_lights = arraylength( lights ), i; for (i = 0; i < num_lights; i += 1) { lights[i]->light( L, Cl ); C += Cl * (Nn . normalize(-L)); }Note that the L vector is automatically inverted by
illumiance()but in this case one has the responsibility to invert it manually. Refer to The Illuminance Construct for a more explanation about the mechanics ofilluminance()and refer to Light Categories and Predefined Shader Parameters for more about light categories.
- float getvar ( shader coshader, string name, [output type variable] )
A function to access member variables in a specified co-shaders. Refer to
Co-Shadersfor more detail.
3Delight 8.5. Copyright 2000-2009 The 3Delight Team. All Rights Reserved.