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 RSL Plug-ins.
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 thanmax
and x otherwise. type can be a float or a 3-tuple. When running on 3-tuples, these shadeops will consider one component at a time (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
,point
orvector
.
- 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
,color
orpoint
. Returned range is [0..1]. Can returnuniform
orvarying
values. 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
,vector
ornormal
from 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 __nondiffuse
are 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 __nonspecular
are 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__nonspecular
light shader parameter. Not available in lightsource shaders.
- color bsdf ( vector L; normal N; ... )
- color[] bsdf ( vector L; normal N; ... )
Evalutes one of the built-in BSDF available in 3Delight. L is the incoming light direction and N the surface normal. The optional parameters are the distribution-related ones from The trace Shadeop.
- 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
6.4.5.1 Common Parameters | ||
6.4.5.2 The trace Shadeop | ||
6.4.5.3 Other Ray Tracing Shadeops |
6.4.5.1 Common Parameters
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.
|
6.4.5.2 The trace Shadeop
- color trace ( point Pt; vector R [; output float dist]; ... )
- color[] trace ( point Pt; vector R [; output float dist]; ... )
The trace shadeop is a general tool for collecting incoming light at point Pt on the surface. In its simplest form, it will collect light from direction R.
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 all parameters must be in "current" space. trace()
accepts several optional named parameters which are explained below.
float samples
- Specifies the number of samples to use. Higher sample counts will improve quality, at the cost of performance.
float maxdist
- Specifies a distance after which no intersections are checked. The default value is 1e38 which in practice means that there is no maximum distance for intersections.
string distribution
- This parameter specifies which BRDF
trace()
will use to gather light from the scene. The possible values areuniform
,cosine
,oren-nayar
,blinn
,ashikhmin-shirley
,cook-torrance
,ward
,glass-ggx
andhair
. The default value isuniform
. Each distribution requires some specific additional parameters listed below. See also the bsdf shadeop which allows the same distributions to be used in an illuminance loop with direct light.float samplecone
- Specifies an angle in radians which, together with Pt and R, describes a cone in which
trace()
will gather light. The angle specified is the cone's half angle, meaning PI/2 will sample a hemisphere. This applies to theuniform
andcosine
distributions. The default value is 0. vector wo
- This vector specifies the viewer direction for the
oren-nayar
,blinn
,ashikhmin-shirley
,cook-torrance
,ward
,glass-ggx
andhair
distributions. This is typically -I. Note that when this parameter is needed, theR
parameter is expected to be the surface normal, except for thehair
distribution where it is a vector pointing toward the tip of the fiber. vector horizon
- This optional vector specifies the normal of a horizon plane which cuts off the requested distribution. This would usually be the geometric normal when it is different from the shading normal.
float roughness
- Specifies the roughness of the surface for the
oren-nayar
,blinn
,ashikhmin-shirley
,cook-torrance
,ward
andglass-ggx
distributions. The valid range is between 0 and 1, except fororen-nayar
which has no upper limit (in practice, there is little difference above PI/2). For theblinn
andashikhmin-shirley
distributions, roughness is converted to an exponent using this formula: pow( roughness, -3.5 ) - 1 float roughnessv
- Specifies the roughness in the second axis for the anisotropic
ashikhmin-shirley
,glass-ggx
andward
distributions. vector udir
- Specifies the orientation of the u direction for the anisotropic
ashikhmin-shirley
,glass-ggx
andward
distributions. This is the directon whereroughness
applies.roughnessv
is applied in a perpendicular direction on the surface. Theudir
vector does not need to be strictly tangent to the surface as 3Delight will project it on the surface itself. With thehair
brdf, this parameter is used to specify hair fiber orientation and eccentricity. See Using the hair BSDF. color[] eta
- Specifies an index of refraction to compute a fresnel effect for the
blinn
,ashikhmin-shirley
andcook-torrance
distributions. This is optional and not specifying it is equivalent to using 0, providing full reflection. If a color is provided, the fresnel equations are computed separately for each channel. If an array of two colors is provided, the second value is taken to be the extinction coefficient for conductors (metals). Note that giving a float or color value can be done without using an array. For theglass-ggx
distribution, this is the index of refraction of the glass, with a default value of 1.5. For thehair
distribution, this is the index of refraction of the hair fiber and the default value is 1.55. color absorption
- Specifies the absorption coefficient of the hair fiber for the
hair
distribution. This affects the color and intensity of all lobes but the first one. float[] lobeparameters
- Specifies per lobe BRDF parameters for the
hair
distribution. Each lobe requires 4 parameters and up to 4 lobes are supported. See Using the hair BSDF. For theglass-ggx
distribution, this specifies reflection and refraction weights which allow adjusting the relative contribution of each part.
uniform string environmentmap
- Specifies an environment map to use as incoming light in directions where there is no geometry.
uniform string environmentspace
- Specifies a coordinate system to orient the environment map.
color environmenttint
- Specifies a multiplicative factor for the content of the environment map.
output varying color transmission
- Returns the transmission in the traced direction. This takes into account both coverage (if sampling a cone) and the opacity of the surfaces hit by rays. It is not influenced by the specified environment map. There is no speed penalty to get the transmission from
trace()
IMPORTANT
The returned value is exactly the same as what would have been returned by the transmission shadeop with the important difference that
transmission()
defaults to intersecting objects visible to transmission rays whiletrace()
uses specular rays. output varying color environmentcontribution
- Returns the contribution of the environment map to the output of trace.
output varying color unshadowedenvironment
- Returns the contribution that the environment map would have to the output of trace if no regular geometry was hit in any direction. If area lights area being sampled, they will still block the environment map contribution to this output.
uniform float samplearealights
- Setting this to 1 means this
trace()
call will sample area lights which are set to the"trace"
sampling strategy (see The light samplingstrategy attribute). The default is 0 which means area lights are not seen by the trace shadeop. output varying color arealightcontribution
- Returns the contribution of area lights to the output of trace. Note that using only this output of trace can be faster as 3Delight will know that some surfaces do not need to be shaded. Tracing rays can also be skipped entirely if there are no area lights in the scene.
output varying color unshadowedarealight
- Returns the contribution that area lights would have to the output of trace if no regular geometry was blocking any of them.
The second version of trace which returns an array of colors can be used with some distributions to get separate results for their components. In that case, arrays of colors are also output by the environmentcontribution
, unshadowedenvironment
, arealightcontribution
and unshadowedarealight
output parameters. This is supported by the following distributions:
glass-ggx
- The array must be of length two. There is one value for reflected rays and one for refracted rays.
hair
- The array must be one fourth the length of the
lobeparameters
parameter array.
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 very large. */ float dist; color c = trace( P, Nf, dist, "maxdist", 10 );
Using the hair BSDF
The hair
BSDF is a fairly complex function which simulates several effects observed on real hair fibers. It supports a variable number of major lobes, usually named R, TT, TRT, etc which are numbered according to the number of times the light crosses the hair fiber. Here is an example which retrieves the contribution of each lobe separately:
float lobeparams[12] = { 1, tilt, roughness[0], roughness_azimuthal[0], 1, tilt, roughness[1], roughness_azimuthal[1], 1, tilt, roughness[2], roughness_azimuthal[2] }; vector orient = eccentricity * rotate( normalize(dPdu), random_hair_orient * 2 * PI, 0, point(dPdv) ); color lobes[3]; lobes = trace( P, dPdv, "distribution", "hair", "wo", normalize(-I), "samplearealights", 1, "samples", 300, "eta", 1.55, "udir", orient, "absorption", absorption, "lobeparameters", lobeparams ); Ci = lobes[0] + lobes[1] + lobes[2];
The lobeparameters
array contains 4 values for each lobe to be computed. They are, in order:
weight
- This scales the contribution of each lobe. Note that with values greater than 1, internal normalization might be done in order to avoid energy amplification by the bsdf. This means changing these weights can change the look of the hair but will generally not make it brighter overall.
scales tilt
- The angle of the scales which form the surface of the hair fiber, in radians. It affects the position of the highlight. This will typically be in the range of -0.05 to -0.1 radians for human hair (negative to tilt towards the root). Note that the final position is computed from this angle differently for each lobe so using the same value for all lobes will produce distinct highlights.
longitudinal roughness
- This will change the size of the lobe along the length of the hair. It behaves just like roughness for other bsdfs.
azimuthal roughness
- This will change the size of the lobe across the hair fiber. As the simulated hair is cylindrical, this parameter has little effect on the R and TT lobes. Its effect is most visible on the sharpness of the TRT lobe (glints).
6.4.5.3 Other Ray Tracing Shadeops
- float trace ( point Pt; vector R )
This is an obsolete form which returns the distance to the nearest intersection, when looking from Pt in the direction specified by the unit vector R. Pt and R must lie in `current' space. This function intersects objects that are visible to transmission rays and is strictly equivalent to:
float distance; trace( P, dir, distance, "type", "tranmission" );
- color transmission ( point Pt1, Pt2, ... )
Determines the visibility between Pt1 and Pt2 using ray tracing. Returns
color 1
if un-occluded andcolor 0
if 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
occlusion
parameter), 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 either an environment map or a light probe. Environment maps have to be generated by
tdlmake
with the `-envcube' or `-envlatl' parameter. All other textures are interpreted as light probes. Probe images generated by software such asHDRShop
and stored in other formats (such asRadiance
files with an `.hdr' extension) must be converted bytdlmake
to 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
] gather
is 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.
type
can be either afloat
or 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. Usetdlmake
to 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.16. 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.
The texture() shadeop also includes support for MARI's UDIM tile mapping. Simply provide a file name with the string
UDIM
in it and that will be replaced by the 4 digit tile number before looking for the texture.
- type ptexture ( string texturename; uniform float channel; float faceindex; ... )
- type ptexture ( string texturename; uniform float channel; float faceindex; float s, t; ... )
- type ptexture ( string texturename; uniform float channel; float faceindex; float s1, t1, s2, t2, s3, t3, s4, t4; ... )
Same as
texture
but acts on "ptextures".ptexture()
accepts a list of optional parameters as summerized in Table 6.15.
ptexture() optional parameters. |
- 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. Usetdlmake
to 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.16. 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.16. 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.17.Name Type Default Description "coordsystem" string
"world" Specifies the coordinate system into which the values are written. "radius" varying float
based on grid Specifies the radius of the disk (or sphere if N is 0) covered by each baked sample. "radiusscale" float
1.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" float
0.0 When set to 1.0, saves the centers of the micro-polygons instead of its corners. This is primarily useful for point-based occlusion and color bleeding (see section Point-Based Imaging Pipeline). Table 6.17: 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.18.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" float
1 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.18: texture3d()
optional parameters.
6.4.7 String Manipulation
- string format ( string pattern; val1, ..., valn ) *
Similar to the C
sprintf
function. 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
%f
or%e
. If a precision specifier is used,%f
is 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.
%h
- Formats a shader handle. Light shaders and co-shaders will use the handle of their declaration. The null shader object is output as
<null>
. Surface, Displacement, etc become<surface>
,<displacement>
, etc.
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
(42) expression.
- float stringhash ( string str )
- color stringhash ( string str )
Takes a string as input and returns a hash in form of a float or a color. Provided to output such AOVs as object and material identifiers for further masking and compositing.
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.19. 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 only be output if the file is present but invalid.
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
varying
shader parameter to auniform
variable 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.20. User defined attributes are also accessible as in:
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:"
.illuminance( P ) { string name; if( 1 == attribute( "light:identifier:name", name ) ) printf( "light name: %s\n", name ); }
The list of recognized uniform attributes is are listed in Table 6.20.
"Ri:ShadingRate" "Ri:Sides" "Ri:Color" "Ri:Opacity" "Ri:Matte" "Ri:DetailRange" "Ri:TextureCoordinates" "Ri:Orientation" "Ri:Transformation" "Ri:CoordinateSystem:space" "GeometricApproximation:motionfactor" "displacementbound:sphere" "displacementbound:coordinatesystem" "shaderdisplacementbound:sphere" "shaderdisplacementbound:coordinatesystem" "geometry:backfacing" "geometry:frontfacing" "geometry:geometricnormal" "grouping:membership" "identifier:name" "trace:bias" "trace:displacements" "trace:maxspeculardepth" "trace:maxdiffusedepth" "photon:shadingmodel" "photon:causticmap" "photon:globalmap" "photon:estimator" "sides:doubleshaded" "visibility:camera" "visibility:diffuse" "visibility:specular" "visibility:trace" "visibility:transmission" "visibility:photon" "dice:hair" "dice:rasterorient" "cull:backfacing" "cull:hidden" "derivatives:smooth" "derivatives:centered" "subsurface:groupname" "subsurface:scale" "subsurface:refractionindex" "subsurface:shadingrate" "subsurface:absorption" "subsurface:scattering" "subsurface:meanfreepath" "subsurface:reflectance" "subsurface:samples" "attribute:light:samples" "attribute:light:samplingstrategy" "attribute:light:emitphotons" "irradiance:shadingrate", "irradiance:nsamples" "hider:composite" "user:attributename" Table 6.20: attribute()
field names.
The type of each attribute is directly related to its declaration when declating the corresponding attribute in the Ri stream (with the exception of integer attributes becoming floating point values in the shader since there is no integer type in SL).
Two entries in the table require slightly more information:
shaderdisplacementbound:sphere
- This returns the displacement bound as specified by the
__displacementbound_sphere
shader parameter. If both displacement and surface shader has such parameters, their will simply be added together meaning that they should be declared in the same space. Refer to shader declared displacementbound. shaderdisplacementbound:coordinatesystem
- Will return the __displacementbound_coordinatesystem. Surface shader parameter will be returned if displacement shader has no such parameter. Again, it is imperative to have the same space in both shaders.
- 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.21. 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.22.
- 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 1 if var is output to a display driver. This is true if:
- The variable is declared as
output
in 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.
surface shader1( output varying float noisy = 0 ) { if( isoutput( noisy ) ) { noisy = noise( P ); } }
- The variable is declared as
- float isoutput ( string varname )
Returns 1 if the variable with the given name is output to a display driver. This is the same function as the other form above but by name instead of directly giving the variable to test. This form can also query individual array components:
surface shader1( output varying float outputs[3] = {} ) { if( isoutput( "outputs[1]" ) ) { outputs[1] = foo(); } }
- void outputchannel ( uniform string channelname; value )
This function allows output variables to be dynamically added to a shader. For example, these two shaders would produce equivalent behavior:
surface shader1( output varying color myoutput = 0 ) { myoutput = Cs; } surface shader2(); { outputchannel( "myoutput", Cs ); }
If the variable channelname already exists, it is simply assigned to. If there is some incompatibility in the type of detail of the existing variable then nothing is done. value may be of any type except string. Output variables should still be declared whenever possible as it is more efficient.
Note that if
outputchannel()
is called from a light shader or a coshader, the output is added to the main shader by default (usually the surface) so it will be visible to the display system. To override this behavior, prefix the variable name with "light:" or "local:".
- void gridmin ( varying float value )
- void gridmax ( varying float value )
These special functions take a varying floating point parameter as input and find out the minimum and maximum values over the entire grid (in REYES) or shading point set (ray-tracing). These functions are useful to take decisions for an entire set of shading samples. For example, if it is known that some parameter is less than X for the entire grid then one might skip some particular code branch. Not to be confused with min and max shadeops.
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[] getshaders ( ["category"; string category_name] )
Get all co-shaders declared in the current attribute scope, filtering them using an optional category name.
- 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 (see section Co-Shaders). Another use of this function is giving it the null shader handle to make it search for the variable directly on the geometric primitive, bypassing all shaders. This is likely to be slower to compute than getting a similar variable from another shader.
6.4.10 Operations on Arrays
- void resize ( output type A[], uniform float length )
Resizes the array to the specified length.
- Increase array length will leave the new elements uninitialized.
- length is always uniform.
- If length is set to 0, the memory held by the array is released
- void reserve ( output type A[], uniform float length )
Increase array's capacity if necessary without affecting it's length.
- void push ( output type A[], type value )
Increase the array length by one and initializes the last element to value.
- type pop ( output type A[] )
Returns the last element of A and decreases array's length by one. The capacity of the array is not decreased.
3Delight 10.0. Copyright 2000-2011 The 3Delight Team. All Rights Reserved.