# RSL Functions

The shading language provides the following functions:

### Mathematical Functions

The following library of math functions is provided. This library includes most of the routines normally found in the standard C math library as well as functions for interpolation and computing derivatives.

The following mathematical functions are provided:

```float Du( float p ), Dv( float p ), Deriv( float num; float den )
color Du( color p ), Dv( color p ), Deriv( color num; float den )
point Du( point p ), Dv( point p ), Deriv( point num; float den )
vector Du( vector p ), Dv( vector p ), Deriv( vector num; float den )
```

These functions compute the derivatives of their arguments. The type returned depends on the type of the first argument. Du and Dv compute the derivatives in the u and v directions, respectively. Deriv computes the derivative of the first argument with respect to the second argument. This is done using the chain rule:

```Deriv(num,den) = Du(num)/Du(den) + Dv(num)/Dv(den);
```

The actual change in a variable is equal to its derivative with respect to a surface parameter times the change in the surface parameter. Thus, assuming forward differencing:

```function(u+du)-function(u) = Du( function(u) ) * du;
function(v+dv)-function(v) = Dv( function(v) ) * dv;
```

```float erf( float x )
float erfc( float x )
```
The erf function returns the error function of x, which is defined to be erf(x) = (2 / sqrt(PI)) * (the integral from 0 to x of e^(-t^2) dt). The erfc function returns the complementary error function of x, that is 1.0 - erf(x).

```float filterstep( float edge, s1;  [parameterlist]  )
float filterstep( float edge, s1, s2;  [parameterlist]  )
```
filterstep provides an analytically antialiased step function.  In its two argument form, it takes parameters identical to step, but returns a result that is filtered over the area of the surface element being shaded. If the optional s2 parameter is provided, the step function is filtered in the range between the two values.  This low-pass filtering is similar to that done for texture maps (for reference, see Texture Mapping Functions). The parameterlist provides control over the filter function, and may include the following parameters: "width" (a.k.a. "swidth"), the amount to "overfilter" in s; "filter", the name of the filter kernel to apply.  The filter may be any of the following: "box", "triangle", "catmull-rom", or "gaussian".  The default filter is "catmull-rom".

```float floor( float x )
float ceil( float x )
float round( float x )
```
floor returns the largest integer (expressed as a float) not greater than x. ceil returns the smallest integer (expressed as a float) not smaller than x. round returns the integer closest to x.

```float gridmin(varying float myVal)
float gridmax(varying float myVal)
```
gridmin and gridmax operate over a grid of floats and return a uniform result. These functions will find the max/min of all the values of myVal over the surface of the grid currently being shaded. The result can be varying, however the same value will be returned at all points in the varying result value.

```type min(type a, b, ... )
type max( type a, b, ... )
type clamp( type a, min, max )
```
min takes a list of two or more arguments of identical type and returns the argument with minimum value, max returns the argument with maximum value.  clamp returns min if a is less than min, max if a is greater than max, otherwise it returns a.  The type may be any of float, point, vector, normal, or color.  The variants that operate on colors or point-like objects operate on a component-by-component basis (i.e. separately for x, y, and z).

```float mix( float x, y; float alpha )
point mix( point x, y; float alpha )
vector mix( vector x, y; float alpha )
normal mix( normal z, y; float alpha )
color mix( color x, y; float alpha )
point mix( point x, y; color alpha )
vector mix( vector x, y; color alpha )
normal mix( normal z, y; color alpha )
color mix( color x, y; color alpha )
```
mix returns x * (1-alpha) + y * alpha, that is, it performs a linear blend between values x and y.  The types of x and y must be identical, but may be any of float, point, vector, normal or color.  The variants that operate on colors or point-like objects operate on a component-by-component basis (i.e. separately for x, y, and z); for these variants, either a float or a color alpha may be specified. If a float alpha is used each component is weighed by the same alpha, otherwise the appropriate channel on a component-by-component basis is used.

```float mod( float a, b )
float abs( float x )
float sign( float x )
```
mod returns a value greater than 0 and less than or equal to b such that mod(a,b) = a - n*b for some integer n. abs returns the absolute value of its argument and sign returns -1 if its argument is negative, 1 if its argument is positive, and 0 if its argument is zero.

```float noise( float v ),
noise( float u, v ),
noise( point pt ),
noise( point pt, float t )
color noise( float v ),
noise( float u, v ),
noise( point pt ),
noise( point pt, float t )
point noise( float v ),
noise( float u, v ),
noise( point pt ),
noise( point pt, float t )
vector noise( float v ),
noise( float u, v ),
noise( point pt ),
noise( point pt, float t )
```

noise returns a value that is a pseudorandom function of its arguments; its value is always between 0 and 1. The domain of this noise function can be 1D (one float), 2D (two floats), or 3D (one point), or 4D (one point and one float). These functions can return any type. The type desired is indicated by casting the function to the type desired. The following statement causes noise to return a color.

```c = 2 * color noise(P);
```

```float  cellnoise( float v ),
cellnoise( float u, v ),
cellnoise( point pt ),
cellnoise( point pt, float t )
color  cellnoise( float v ),
cellnoise( float u, v ),
cellnoise( point pt ),
cellnoise( point pt, float t )
point  cellnoise( float v ),
cellnoise( float u, v ),
cellnoise( point pt ),
cellnoise( point pt, float t )
vector  cellnoise( float v ),
cellnoise( float u, v ),
cellnoise( point pt ),
cellnoise( point pt, float t )
```
cellnoise returns a value that is a pseudorandom function of its arguments.  Its domain can be 1D (one float), 2D (two floats), 3D (one point), or 4D (one point and one float).  Its return value is uniformly distributed between 0 and 1, has constant value between integer lattice points, and is discontinuous at integer locations.  This is useful if you are dividing space into regions ("cells") and want a different (repeatable) random number for each region.  It is considerably cheaper than calling noise, and thus is preferable if you have been using noise simply to generate repeatable random sequences.  The type desired is indicated by casting the function to the type desired.

```float knoise( filterregion fr, uniform float freqWindow,
"keyword", value );
```

knoise is similar to Gabor Noise (Siggraph 2009), with many of the same properties. In particular, it is filtered and gives the user control over the frequency window, number of octaves, and amount and direction of anisotropy. Like Gabor noise it works by using a random collection of nearby points to splat values onto the lookup point. It takes a filterregion as its input, which means that it can generate 1d, 2d, and 3d noise values, filtered either over the local surface or the local volume, depending upon the underlying object.

The freqWindow parameter controls the range of frequencies that will be generated. A larger value here results in something that looks closer to white noise, while a smaller value give much more uniform frequencies and a more "structured" appearance. Useful values tend to be in the range of .5 or so to 1.2, or so.

Optional knoise() Parameters
Name Type Description
"project" uniform float project takes a float value of 0 or 1, and gives better band limiting of 3d noise on a surface by eliminating the low frequency contribution of some of the samples.
"octaves" num uniform float Controls the number of octaves that will be used. n is best kept fairly small, and doesn't have to be an integer, but does need to be above 1. It can be viewed as increasing the frequency window but decreasing the amplitude of the higher frequencies.
"anisotropy" varying float Controls the amount of anisotropy. The amount of anisotropy can be 0 ... 1; defaults to 0.
"anisotropydirection" varying vector The direction of anisotropy. Should probably be roughly normalized; a length longer than 1 will effectively shift the anisotropy amount towards totally anisotropic ("anisotropy" of 1).

```float pnoise( float v, uniform float period ),
pnoise( float u, v, uniform float uperiod, uniform float vperiod ),
pnoise( point pt, uniform point pperiod ),
pnoise( point pt, float t, uniform point pperiod, uniform float tperiod )
color pnoise( float v, uniform float period ),
pnoise( float u, v, uniform float uperiod, uniform float vperiod ),
pnoise( point pt, uniform point pperiod )
pnoise( point pt, float t, uniform point pperiod, uniform float tperiod )
point pnoise( float v, uniform float period ),
pnoise( float u, v, uniform float uperiod, uniform float vperiod ),
pnoise( point pt, uniform point pperiod ),
pnoise( point pt, float t, uniform point pperiod, uniform float tperiod )
vector pnoise( float v, uniform float period ),
pnoise( float u, v, uniform float uperiod, uniform float vperiod ),
pnoise( point pt, uniform point pperiod ),
pnoise( point pt, float t, uniform point pperiod, uniform float tperiod )
```
pnoise returns a value similar to noise with the same arguments; however, the value returned by pnoise is periodic with period, period (or pperiod, tperiod, et cetera). That is, pnoise(v, p) == pnoise(v+p, p). The period parameters must be uniform and have an integer value (if it is a float expression), or lie on the integer lattice (if it a point expression).

```float wnoise( point pt; float filterWidth; [parameterlist] )
```

wnoise produces one or more bands of noise constructed with wavelets, and is based on the 2005 SIGGRAPH paper by Cook and DeRose. Wavelet noise has a similar appearance to Perlin noise but can be band-limited more effectively for the sake of antialiasing. Unlike the noise function, which returns values between 0 and 1, wnoise by default returns values between -1 and 1. The distribution and range of these values may be changed using the parameters below, though output values are always centered around 0.

The filterwidth parameter is used to filter any frequencies that would otherwise alias and represents the width of the filter, usually calculated by approximating the width of a micropolygon:

```float fw = max(sqrt(area(P)), (2e-6));
float fn = wnoise(P, fw);
```

Optional wnoise parameters are specified as name/value pairs.

Optional wnoise() Parameters
Name Type Description
"projectvector" vec vector By default, the noise is projected along the surface normal, which greatly improves filtering characteristics. You can override the vector used for projection with this parameter. This vector need not be normalized, but it must be in a stable space such as "object" or "shader". Passing a vector with value (0,0,0) disables projection.
"frequencyrange" range uniform string Controls whether noise spectrum is "finite" and based on the point (the default), or "infinite" and always consists of visible frequencies.
"octaves" num uniform float Controls the number of octaves of noise to calculate. By default, this value is 1.
"lacunarity" lacunarity uniform float Specifies a multiplier for each successive frequency of noise. By default this is 2.
"weights" weightArray uniform float[] An array of floats representing weights for each frequency. Their effect will automatically be normalized. Ideally the length of the array matches the number of octaves. If the array is longer, only the relevant entries will be used. If the array is shorter or absent, the missing values will be set to 1.
"distribution" dist uniform string Controls the manner in which values are distributed around the center. By default, this is a "flat" distribution. With a value of "gaussian", the values will have a gaussian distribution.
"amplitude" amp uniform float Controls the amplitude of distribution about the center value. With a "flat" distribution, output values range from -amplitude to +amplitude. With a "gaussian" distribution, amplitude represents the standard deviation. In this case, a small percentage of values will exceed the bounds set by amplitude. This value defaults to 1.

```float PI = 3.14159... ;
float sin( float a )
float asin( float a )
float cos( float a )
float acos( float a )
float tan( float a )
float atan( float yoverx ), atan( float y, x )
```
The predefined float constant PI is the value of pi. The function radians converts from degrees to radians, and, conversely, the function degrees converts from radians to degrees. sin, cos, and tan are the standard trigonometric functions of radian arguments. asin returns the arc sine in the range -PI/2 to PI/2. acos returns the arc cosine in the range 0 to PI. atan with one argument returns the arc tangent in the range -PI/2 to PI/2. atan with two arguments returns the arc tangent of y/x in the range -PI to PI.

```void sincos( float a, output float sina, output float cosa )
```
The sincos() function performs both the standard trigonometric functions sine and cosine simultaneously.

```float pow( float x, y )
float exp( float x )
float sqrt( float x )
float inversesqrt( float x )
float log( float x ), log( float x, base )
```
These functions compute power and inverse power functions. pow returns x ** y, exp returns pow(e,x). sqrt returns the positive square root of x, and inversesqrt returns 1/sqrt(x). log with one argument returns the natural logarithm of x (x = log(exp(x))). log with two arguments returns the logarithm in the specified base (x = log(pow(base, x), base)).

```float random()
color random()
point random()
```
random returns a float, color, or point whose components are a random number between 0 and 1.

```float randomgrid()
color randomgrid()
```
randomgrid returns a random uniform float or color per grid.

```float spline([string basis;] float value; float f1, f2, ..., fn, fn1 )
float spline([string basis;] float value; float fvals[] )
color spline([string basis;] float value; color c1, c2, ..., cn, cn1 )
color spline([string basis;] float value; color cvals[] )
point spline([string basis;] float value; point p1, p2, ..., pn, pn1 )
point spline([string basis;] float value; point pvals[] )
vector spline([stringbasis;] float value; vector v1, v2, ..., vn, vn1 )
vector spline([string basis;] float value; vector vvals[] )
```

spline fits a spline to the control points given.  At least four control points must always be given.  If value equals 0, f2 (or c2, p2, v2) is returned; if value equals 1, fn (or cn, pn, vn) is returned.  The type of the result depends on the type of the arguments.

If the first argument to spline is a string, it is interpreted as the name of a cubic spline basis function.  The basis may be any one of "catmull-rom", "bezier", "bspline", "hermite", "monotonecubic" or "linear". If the optional basis name is not supplied, "catmull-rom" is assumed, resulting in the control points being interpolated by a Catmull-Rom spline. In the case of Bezier and Hermite spline bases, the number of spline knots must be 4+3n and 4+2n, respectively. In the case of monotone cubic, the first and last knot inform the incoming and outgoing tangents, and the remaining knots are interpolated through, increasing or decreasing monotonically between adjacent knots. In the case of linear spline basis, the first and last knot are unused but are nonetheless required to maintain consistency with the cubic bases.

For all spline types, an array of values may be used instead of a list of values to specify the control points of a spline. Additionally, each basis has an associated "solve" mode (e.g. "solvelinear") that is used to position the control points, e.g.:

```float signal = spline ( "solvecatmull-rom", s, 0, 0, .2, .8, .1, 1 );

color result = spline ( "catmull-rom", signal, (0,0,0), (0,0,0), (1,1,0),
(1,1,1), (1,1,1) );
```

```float step( float min, value )
float step( color min, value )
float smoothstep( float min, max, value )
float smoothstep( color 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 performs a smooth Hermite interpolation between 0 and 1 in the interval min to max. When using versions of these operators that work on color arguments, the operation is applied on a component-by-component basis.

### Geometric Functions

Geometric functions provide a kernel of useful geometric operations. Most of these functions are most easily described by just giving their implementation.

```float area( point P [; string measure] )
```
```{
return length( Du(P)*du ^ Dv(P)*dv);
}
```

Return the differential surface area. If measure is "shading" or isn't supplied, the areas are smoothly varying across shading grids, independent of the actual dicing rates. If measure is "dicing", the areas are the areas of micropolygons (and therefore discontinuous between shading grids with different dicing rates).

When shading a volume element, the area shadeop returns the approximate area of a circle with diameter equal to the diagonal of the voxel. This may be a poor approximation of the spot size, particularly if the voxels are highly isotropic due to depthrelativeshadingrate, and is not generally recommended for antialiasing of shaders.

```normal calculatenormal( point P )
```
```{
return Du(P) ^ Dv(P);
}
```

Return surface normal given a point on the surface. This function is usually called after a displacement. For example:

```P += displacement * N;
N = calculatenormal( P );
```

```float depth( point P )
```
Return the depth of the point P in camera coordinates. The depth is normalized to lie between 0 (at the near clipping plane) and 1 (at the far clipping plane).

```float distance( point P1, P2 )
```
```{
return length(P1-P2);
}
```

Return the distance between two points.

```vector faceforward( vector N, I [, Nref = Ng] )
```
```{
return sign(-I.Nref) * N;
}
```

Flip N so that it faces in the direction opposite to I, from the point of view of the current surface element. The surface element's point of view is the geometric normal Ng, unless Nref is supplied, in which case it is used instead.

```void fresnel( vector I, N; float eta, output float Kr, Kt
[; output vector R, T] )
```
Return the reflection coefficient Kr and refraction (or transmission) coefficient Kt given an incident direction I, the surface normal N, and the relative index of refraction eta. eta is the ratio of the index of refraction in the volume containing the incident vector to that of the volume being entered. These coefficients are computed using the Fresnel formula. Optionally, this procedure also returns the reflected (R) and transmitted (T) vectors. The transmitted vector is computed using Snell's law. The angle between I and N is supposed to be larger than 90 degrees. If the angle is less than 90 degrees, fresnel will return full reflection (Kr = 1, Kt = 0).

```float gridpattern( string pattern, float context, ... )
```

gridpattern returns a one or a zero for each shading point, according to the specified pattern and context. Like other varying functions, gridpattern returns a result which may be different at each shading point on the underlying grid; however, unlike most other functions, the output is intentionally a function of the shading grid's structure. It is typically used to produce a mask using one of the built-in pattern generators, the mask is then used in a varying conditional to apply specific operations to the on subset of points. Furthermore, some patterns can be applied iteratively, in conjunction with a preserved context, and will become successively more refine in terms of the sets of points selected, until all of the points on the grid have been visited.

The available patterns are:

Pattern Description Behavior
"gridpoint" one shading point on at a time convergent
"binaryrefinement" sparse-to-dense sampling convergent
"concentric" "rings" around the periphery of the grid [1] convergent
"checkerboard" alternating on and off points [1] non-convergent
"random" a random distribution of on and off points non-convergent
 [1] (1, 2) Some patterns have undefined results on non-rectangular internal grid types
• Note:

The internal structure and content of shading grids are inherently implementation dependent, and they are strongly affected by the input geometry types, shading rate, camera settings, and numerous other tuning parameters. There are no guarantees about the specific behavior or reproducibility of patterns.

The context variable is used to carry state between iterative calls to gridpattern; the meaning and usage of context depends on pattern. Usually context should be initialized to zero prior to first use. Each pattern will modify context differently and it should generally be assumed to be private data owned by gridpattern. Some patterns guarantee convergence in the sense that after a series of calls, all grid points will have been "visited" and further calls will return zero for all points.

The shading language supports several familiar conditional constructs which cause operations to occur on grid subsets; consider:

```if (s < 0.5) k += 1;
```

The varying variable k will only be incremented at the points which satisfy the condition. Similarly, gridpattern produces a varying float mask which is 1 for some points, 0 for others. This mask might be used directly (as a float) or used in further conditional expressions.

For example, for a shader executing on a tiny 5x5 grid:

```varying float patctx = 0;  /* initialize the context */
varying float f = gridpattern("concentric", patctx);
```

the variable f will now contain the following pattern:

```1 1 1 1 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 1 1 1 1
```

the patctx variable allows gridpattern to track a particular context through repeated calls, so a subsequent call to:

```varying float g = gridpattern("concentric", patctx);
```

would produce, in g:

```0 0 0 0 0
0 1 1 1 0
0 1 0 1 0
0 1 1 1 0
0 0 0 0 0
```

and f+g would be:

```1 1 1 1 1
1 1 1 1 1
1 1 0 1 1
1 1 1 1 1
1 1 1 1 1
```

After another iteration (in which only the center spot would be one), the pattern will have "converged," meaning that all of the gridpoints will have been visited and subsequent calls to gridpattern (with the same context variable) will return all zeros.

Another pattern type, named "binaryrefinement", tries to select a few widely spaced points for the first pass, and then more points which are less widely spaced for the second pass, etc., until all points have been visited.

• Note:

while "any" (relation)

The while loop usually has the desirable behavior that only shading points which satisfy the specified condition continue to be evaluated within the loop. When all points finally fail the condition, or have had break applied to them, then the loop is complete.

There are a few rare cases, such as with gridpattern(), where it is instead desirable for every point which was active when the loop started to remain potentially active if any shading point passes the conditional. In these situations, the addition of the "any" modifier string after while causes the success/fail state at every shading point to be reset (rather than preserved) each time through the loop.

The while "any" construct allows looping on gridpattern calls until a convergence occurs. In this mode a different set of gridpoints will be active during each iteration. So a typical convergence loop might look like this:

```while "any" (0 != gridpattern("binaryrefinement", patctx)) {
/* do things on this subset */
}
```

See the gridpattern() example for an illustration.

```float length( vector V )
```
```{
return sqrt(V.V);
}
```

Return the length of a vector.

```vector normalize( vector/normal V )
```
```{
return V/length(V);
}
```

Return a unit vector in the direction of V.

```float ptlined( point P1, P2, Q )
```
Returns the minimum perpendicular distance between the point Q and the line segment that passes from the point P1 to the point P2 (not the infinite line that passes through P1 and P2).

```vector reflect( vector I, N )
```
```{
return I - 2*(I.N)*N;
}
```

Return the reflection vector given an incident direction I and a normal vector N.

```vector refract( vector I, N; float eta )
```
```{
float IdotN = I.N;
float k = 1 - eta*eta*(1 - IdotN*IdotN);

return k < 0 ? (0,0,0) : eta*I - (eta*IdotN + sqrt(k))*N;
}
```

Return the transmitted vector given an incident direction I, the normal vector N and the relative index of refraction eta. eta is the ratio of the index of refraction in the volume containing the incident vector to that of the volume being entered. This vector is computed using Snell's law. If the returned vector has zero length, then there is no transmitted light because of total internal reflection.

```point rotate( point Q; float angle; point P1, P2 )
```
Rotate a point Q by angle radians about the axis that passes through the points P1 and P2.

```point transform( string tospace; point P );
point transform( string fromspace, tospace; point P );
point transform( matrix m; point P );
point transform( string fromspace; matrix m; point P );
vector vtransform( string tospace; vector v );
vector vtransform( string fromspace, tospace; vector v );
vector vtransform( matrix m; vector v );
vector vtransform( string fromspace; matrix m; vector v );
normal ntransform( string tospace; normal  );
normal ntransform( string fromspace, tospace; normal n );
normal ntransform( matrix m; normal n );
normal ntransform( string fromspace; matrix m; normal n );
```
The transform function transforms the point P from the coordinate system fromspace to the coordinate system tospace.  If fromspace is absent, it is assumed to be the "current" coordinate system.  A transformation matrix may be given instead of a tospace name.  The vtransform and ntransform functions perform the equivalent coordinate system transformations on vectors and normals, respectively.

```float xcomp( ptype P )
ycomp( ptype P )
zcomp( ptype P )
setxcomp( ptype P; float x )
setycomp( ptype P; float y )
setzcomp( ptype P; float z )
```
These functions get [*comp] and set [set*comp] individual components of points, vectors or normals.

### Arbitrary Output Variable and Primitive Variable Functions

```float readaov( uniform string name; type variable )
```

This function fetches a named AOV and writes it to variable, if it exists. If the variable exists, 1 is returned, otherwise 0 is returned.

The variable must be a pre-declared display channel but is not required to be in the parameter list of the shader.

```float writeaov( uniform string name; type variable )
```

This function writes the contents of variable to a named AOV. If the arbitrary output variable exists, 1 is returned, otherwise 0 is returned and no write is performed.

The variable must be a pre-declared display channel but is not required to be in the parameter list of the shader.

```float readprimvar( uniform string name; type variable )
```

This function reads a named primitive variable and writes it to variable if it exists. There are three different return codes from readprimvar:

1 means that the value came from the primitive variable.

2 means it came from the shader parameterlist.

3 means it came from an instance's primitive variable.

Otherwise, 0 is returned and no write is performed.

The variable need not be a parameter of the current shader. The detail of the variable must be varying (unless the variable is a string) so that the renderer is free to combine grids. Doing so ensures the best performance and is analogous to making a shader parameter varying to ensure good grid combining. Reading into a string variable will defeat the grid combining optimizations.

```float evalparam( uniform string name; type variable )
```
This function evaluates parameters of the shader. If a parameter is declared to be a reference to an RIS shading plugin node, the node and its associated pattern graph are evaluated and the resulting data are written to variable. Otherwise the literal value bound to the parameter is written to variable. The variable must be a parameter of the current shader.

The return codes follow those of the RixSCConnectionInfo return value from RixParameterList:::GetParamInfo

1 means the variable was found in the shader parameterlist,
but not connected to a pattern network.
2 means the variable was in the parameterlist and connected
to a pattern network.

Otherwise, -1 is returned and no write is performed.

This function is especially useful in RSL shaders used to perform displacement in an RIS render.

Optional evalparam() Parameters
Name Type Description
"reset" float If greater than zero, causes the values of P and Ng to be re-read and placed into the RIS RixShadingContext prior to evaluation of the pattern network. Allows layered displacements where each layer operates on the previously displaced points and normals.

### Color Functions

Several functions exist that operate on colors.

```float comp( color c; float index )
setcomp( color c; float index, value )
```

These functions get and set individual color components, respectively. The index values are 0-based (e.g., the green channel of an RGB triple is component 1).

```color ctransform( string tospace; color C; )
color ctransform( string fromspace, tospace; color C; )
```
Transform the color C from the color representation fromspace to the color representation tospace.  If fromspace is absent, it is assumed to be "rgb". Valid spaces include (but may not be limited to): "rgb", "hsv", "hsl", "xyz", "XYZ", and "YIQ".

### Matrix Functions

```float comp( matrix m; float row, column )
setcomp(  matrix m; float row, column, value )
```
These functions get and set individual components of a matrix, respectively. Strict runtime bounds checking will be performed on row and column to ensure that they fall into the range 0...3.

```float determinant( matrix m )
```
Returns the determinant of matrix m.

```matrix translate( matrix m; vector t )
matrix rotate( matrix m; float angle; vector axis )
matrix scale( matrix m; point s )
```
Postconcatenate simple transformations onto the matrix m. These functions are similar to the RI functions RiTranslate, RiRotate, and RiScale, except that the rotation angle in rotate() is in radians, not in degrees as with RiRotate.

### Array Functions

See the documentation on Array Types for more information on the use of arrays in RSL.

```float arraylength( type array[] )
float capacity( type array[] )
```
Returns the length or capacity of an array. The capacity of a fixed-length array is always equal to its length, but the capacity of a resizable array might be greater than its length. See the documentation on Resizable Arrays for more information.

```type pop( output type array[] )
```
Returns the last element of the array and decreases its length by one. The capacity is not decreased.

```void push( output type array[], type value )
```
Increases the length of the array by one and stores the given value as the last entry.

```void reserve( output type array[], uniform float length )
```

Increases the capacity of the array if necessary, but does not change its length. The capacity is never reduced, unless it is set to zero. Reserving storage is preferable to incrementally resizing an array, since increasing capacity generally requires copying the array contents. This is especially useful when repeatedly pushing items on an array:

```reserve(A, arraylength(A)+3);
// reallocate A before pushing.
push(A, 1);
push(A, 2);
push(A, 3);
```

```void resize( output type array[], uniform float length )
```
Changes the length of a resizable array. Note that the length is always uniform. If the length is increased, the new elements are uninitialized. An error is reported if the array has a fixed length.

### String Functions

```string concat( string a, b, ... )
```
Concatenates two or more strings into a single string.

```string format( string pattern, ... )
```
Does a formatted string creation under the control of pattern.  This function is similar to the C function sprintf().  As with the Shading Language printf function, use "%f", "%p", "%c", "%m", and "%s" to indicate float, point, color, matrix, and string, respectively.

```float match( string pattern, subject )
```
Does a string pattern match on subject.  Returns 1.0 if the pattern exists anywhere within subject, and 0.0 if the pattern does not exist within subjectpattern can be any regular expression, as described in the POSIX manual page on regex() (3X), with the following exception: the \$n notation does not work, as there are no return values from this function.  Note that the pattern does not need to start in the first character of subect, unless the pattern begins with the ^ (beginning of string) character.

```void printf( string pattern, ... )
```
Print the values of the specified variables on the standard output stream of the renderer. pattern uses "%f", "%p", "%c", "%m", and "%s" to indicate float, point, color, matrix, and string, respectively. A vector or normal may also be printed using "%p".

```ambience() stmt
```

Lights are classified at compile-time whether they will contain ambient contributions or not, thus permitting the renderer to refrain from executing certain lights when only the ambient contribution is being computed. The criteria is simple. If the light contains "solar" or "illuminate" blocks, it is considered non-ambient and will not be forced to execute by the ambient() surface shader shadeop. If the light contains neither op, it is considered ambient and is not run by diffuse(), specular(), or illuminance().

This behavior can be overridden by using an ambience() block. Any light shader that contains an ambience() block specifies a "run-it-and-check" behavior. ambience() is a simple block structure like solar(), but has no parameters. It automatically sets L to 0, so it is not necessary (nor is it advisable) to tweak L inside the block. For example:

```if (goofytest != 0) {
illuminate(from, axis, coneangle) {
Cl = lightcolor * atten;
}
} else {
ambience() {
Cl = 0.5;
}
}
```

However, it continues to be useful to set L = 0 in the case where you wish to dynamically "turn off" a non-ambient light.

```color ambient()
```
ambient returns the total amount of ambient light incident upon the surface. An ambient light source is one in which there is no directional component, that is, a light that does not have an illuminate or a solar statement.

```color caustic( point P; normal N )
```
caustic returns the total amount of caustic light incident upon the surface. Caustics come about through indirect specular-to-diffuse ray paths.  If a particular implementation doesn't support caustics, caustic will always return 0 (black).

```color diffuse( normal N )
```

diffuse returns the diffuse component of the lighting model.  N is a unit-length surface normal.

Example:

```{
color C = 0;
illuminance( P, N, PI/2 )
C += Cl * normalize(L).N;
return C;
}
```

Note that the diffuse() shadeop responds to a special parameter of the light shader. Any light shader that contains

```float __nondiffuse = 1
```

will be ignored by diffuse (note that there are two underbars). If the value of the parameter is 0.0, it is not ignored, so this behavior can be controlled both from the RIB file, or procedurally from inside the light shader, if desired. This parameter may be either uniform or varying, and can also be accessed within illuminance statements.

```emit( color, [parameterlist] )
```

The arguments to describe the emissivity of the surface to the renderer. It accepts a uniform or varying color - a uniform color describes a constant luminaire, a varying color a textured luminaire (constant values are detected automatically).

By default, the emission is a single-sided cosine lobe about N. Tighter lobes may be constructed with cosine power other than 1, which adjusts the distribution to be more concentrated about the emission direction. The emission profile is stored away and used by the system to build its lighting database.

emit() runs in a context much like that of a surface shader. That is, P represents points on the emitting surface (not a surface being illuminated). The shadeop must be present in the prelighting() method of an area light source shader. The geometry to which it is attached must not be inside a procedural.

The following optional parameters are supported:

Optional emit() Parameters
Name Type Description
"direction" varying vector defaults to N, emission direction
"cosinepower" uniform float >=1.0 specify power for cosine power. Larger values make the light emit more strongly in the direction specified - giving a focusing effect. A value of 1 is default and specifies that the light contribution is simply due to the form factor of a portion of the light, and is not further focused.
"spotcosinepower" uniform float >0 applies a cosine power like falloff to a light against the spot orientation space (shader space). It defaults to 0 and can be any number > 0; -ve disables. This is unlike "cosinepower", which can be thought of more like a 'grid' or 'snoot' on a light - it makes the rays more single-direction. Instead, "spotcosinepower" shapes the overall profile, and may be combined with "coneangle" and "penumbraangle".
"environmentmap" string specify map name for env light (environment lights only)
"filteredimportance" uniform float 0|1 perform filtered importance sampling or not (currently implemented for environment lights only)
"areanormalized" uniform float 0|1 Specifies that the emissivity should be divided by the area of the light. As a result, rescaling the light does not make the lighting in the scene brighter. Note that for large light sources the incoming light's interaction with the brdf is still in play (eg N.L for diffuse surfaces), so lighting will not be constant with differing light scales in these cases.
"pointareanormalized" uniform float 0|1 Specifies that the emissivity should be adjusted to cope with uneven dicing of the light. This corrects for increase brightness at pinch poles of spheres for example, where the dicing of the light geometry creates shading vertices much closer together than in other areas. Produces more accurate results with a small performance tradeoff.
"portal" or "portals" uniform string, uniform matrix, uniform string[], or uniform matrix[] Specifies a set of portals through which light may flow - either predefined coordinate system names are supplied, or matrices representing the space of each portal. The space is defined -1 to 1 in xy.
"blocker" or "blockers" uniform string, uniform matrix, uniform string[], or uniform matrix[] Specifies a set of blocker coordinate systems in which light contribution is modified. Either predefined coordinate system names are supplied, or matrices representing the space of each blocker. The space is defined -1 to 1 in xyz.
"blockershape" or "blockershapes" uniform vector, or uniform vector[] Specifies the shape of the blocker (e1,e2,falloffDistance). See blocker documentation for more information.
"blockermultiplier" or "blockermultipliers" uniform float, or uniform float[] Multiples the light contribution by the specified amount. This is multiplicative with the diffusecontribution and specularcontribution.
"blockerdiffusemultiplier" or "blockerdiffusemultipliers" uniform float, or uniform float[] Multiples the light diffuse contribution by the specified amount. This is multiplicative with the diffusecontribution.
"blockerspecularmultiplier" or "blockerspecularmultipliers" uniform float, or uniform float[] Multiples the light specular contribution by the specified amount. This is multiplicative with the specularcontribution.
"gobo" or "gobos" uniform string, uniform matrix, uniform string[], or uniform matrix[] Specifies a set of gobo coordinate systems for gobos. Either predefined coordinate system names are supplied, or matricies representing the space of each gobo map. The space is defined -1 to 1 in xy.
"gobomap" or "gobomaps" uniform string, uniform string[] Specifies the map name for each gobo.
"diffusecontribution" uniform float or color Specify light's contribution to the diffuse lobe
"specularcontribution" uniform float or color Specify light's contribution to the specular lobes
"iesprofile" uniform string Specifies an IES profile to be read (if not ""). The profile can also be specified via a map (see below). Note: this parameter cannot be used with environment or distant lights.
"profilemap" uniform string Specifies a latlong profile to be read (if not ""). Note: this parameter cannot be used with environment or distant lights.
"profilerange" uniform float Specifies the number of degrees the profile represents. Smaller numbers allow maps representing say 90 degrees to be used, (the default is 180 degrees). Any value > 0 is permissible; -ve values disable remapping.
"profilespace" uniform string Specifies the space which the profile map or conenangle is specified. The default is "object" space.
"coneangle" uniform float Restricts light to the specified number of degrees. In combination with the iesprofile or profilemap options, maps the specified cone to the profile.
"penumbraangle" uniform float Specifies the penumbra angle for spotlights (does not apply if an iesprofile or profilemap has been specified).
"penumbraexponent" uniform float Specifies the exponent for penumbra falloff for spotlights (does not apply if an iesprofile or profilemap has been specified).
"importance" uniform float Multiplies the internally computed importance for this light (>1 makes the light relatively more important, <1 makes it less important). This may be used to adjust relative balances between lights when it is determined that heuristics are incorrectly causing samples to be allocated to the wrong light.
"fixedsamplecount" uniform float Specifies an explicit sample count for the light which removes it from consideration by the automatic sample balancing. Available in RIS only. Integrators may choose to respect or disregard this request (which may be desirable at deeper depths in the ray tree). If the request is ignored, the light will undergo sample balancing in the usual manner.
Name Type Description
"shadowbias" uniform float Specify bias for ray-traced shadowing purposes. If the value is -1, the "trace" "emissionbias" Attribute value is used. If "emissionbias" is also -1, then the "trace" "bias" Attribute value for each object is used.
"excludesubset" string Specify tracegroup subsets to be excluded from shadowing
"samplebase" uniform float Specify samplebase to be applied when shadowing (see areashadow)
"shadowhitsides" string Specifies which side(s) of one-sided surfaces can be hit by the rays. The possible values are "front", "back", and "both". The default is "both".
"subset" uniform string Specify trace subset to be used for shadowing
"excludesubset" uniform string Specify trace subset specifying objects to be excluded for shadowing

```gather( string category, point P, vector dir, float angle, float samples, ... )
{statements} [else {statements}]
```

The gather looping construct collects information via ray tracing. It typically controls integration of a procedural reflectance model over incoming light whose source is other surfaces; that is, it collects indirect light. Direct light from light sources is collected with illuminance loops.

Rays are cast within the cone specified by P, dir and angle. The angle, in radians, is measured from dir, the central axis of the cone; an angle of zero implies that rays should only be cast in direction dir, whereas PI/2 produces sampling over a hemispherical area. Within this region, samples rays are stochastically distributed, so increasing the cone angle increases the blurriness; increasing the number of samples increases the quality. When a ray intersection occurs, the optional output variables are updated with values obtained from the hit surface. The loop statements are executed repeatedly, once for each sample pass, similar to while, for, or illuminance loops. In each pass, results from the current ray cast are available to the statement code, which typically accumulates values from all sample passes; a weighted average is then often computed outside the gather loop. Code in the first statement block will be executed when a sample ray hit occurs; code in the else block will be executed when no ray intersection is found. For example:

```float samples = 16;      /* often from a shader parameter */
Ci = 0;
if (N.I < 0) { /* only trace from points facing the eye */
vector R = reflect(normalize(I),normalize(N));
color hitcolor = 0;
gather("illuminance", P, R, blur, samples, "volume:Ci", hitcolor) {
Ci += hitcolor;
} else {
Ci += environment("skymap.env", R);
}
Ci = Ci / samples;
}
Ci *= Os;
Oi = Os;
```

Arbitrary data associated with ray hits can be collected, see msg_spec below. Since many gathered values will be unrelated to indirect illumination, the required category string(first argument to gather) allows the renderer to distinguish certain important types of gathering. There are, currently, two special categories: illuminance and samplepattern. "illuminance" is recognized as distinguishing illuminance-gathering blocks from other information-gathering uses. In particular, during photon map creation, shader analysis will select only those gather calls categorized as "illuminance" to participate in photon scattering. "samplepattern" causes gather to generate correctly stratified and distributed rays within the sample cone described by the subsequent arguments, but gather itself will not actually shoot any rays. Instead, the gather() "else" block is executed once per sample, after filling in any requests for "ray:direction", which can be useful for shaders that want to do other types of direction-based lookups but don't want to generate their own sample distributions.

Unlike illuminance blocks, in which L and Cl are preset to each light's direction and color, there are no additional predefined variables provided by gather to its code blocks. Instead, shader writers supply their own local variables to gather, which are filled in with values from the hit surface as specified with an output msg_spec. These local variables can then be referenced within the gather code block. This general interface without reserved names prevents conflicts when gather loops are nested or called within lightsource shaders (where illuminance is illegal).

Note that there can be two code blocks associated with a gather call; the first block is executed when a ray hits something, and the optional else block executes when a ray misses everything. Output msg_spec variables have undefined values in the "miss" case, and therefore should not be referenced in the else block. Output variables from the "ray:" namespace are an exception; they are valid in both hit and miss cases. Even when a ray-hit occurs it is possible that the value requested for a particular msg_spec is not available from the hit surface; this is especially true for user-defined "message passing" shader output variables, which might not be supplied by every hit surface shader. In this case the local output variable will not be updated by gather, so it is up to the shader writer to re-initialize loop variables whose spec doesn't guarantee success.

Automatic continuation of rays occurs when the hit surface is not opaque, as determined by the output Oi from the shader(s) on the surface. Rays will continue in their original direction, collecting values from hit surfaces, until the opacity threshold is reached (see othreshold in the table below).

Optional parameters to gather take the form of token-value pairs. It supports all of the common ray tracing function parameters, as well as the following:

• Note:

Some implementations may provide an additional message passing mechanism for sending arbitrary variable values with the ray, to be used as parameters in shaders on hit objects.

 gather(..., "s", v, ...) "s" - descriptor (listed below) v - local_variable A single gather call can collect multiple output values, these are values fetched from the surfaces hit by gather rays. Each output is specified with a descriptor-variable pair of parameters. The descriptor specifies the value to be fetched, and the local variable name is where that value should be stored. The local variable type and detail must match the requested value! [Note: currently, the requested value's type cannot be *string, since strings are uniform, and gather must return varying results since rays from each grid point may hit a different object.*] "shadertype:varname" retrieves the value of a graphics state variable (Ci, N, P, etc), or user-specified shader output "message passing" parameter, from the shader context on the hit primitive. The typical reflection or refraction rays should fetch "volume:Ci". The value of the named remote variable is taken from the shader context after the specified type of shader has executed. Supported shader types are volume, surface, displacement, light, and coshader. So in the volume:Ci case, the shader output color, Ci, is retrieved after any displacement, surface, and volume shaders associated with the hit surface have executed. Note that atmosphere shaders are defined for "camera rays" only and therefore are not executed in the gather "secondary ray" context. However, interior and exterior shaders are executed in ray-traced situations. "primitive:varname" retrieves the value of varname on the hit surface prior* to shader execution, for example "primitive:P" would be the point of ray-surface intersection. Outputs such as Ci that require shader execution can not be retrieved using this mode since they are only valid after shading. "attribute:name:value" retrieves an attribute from the state bound to the hit primitive, for example: ```float hitproperty = 0; gather(..., "attribute:user:myproperty", hitproperty, ...) { //... use hitproperty ... } ``` "ray:element" - "ray:origin" (point) - "ray:direction" (vector) - "ray:length" (float) retrieves details of the particular ray associated with the current sample pass. Note that the actual ray origin and direction returned here will be different from the nominal (P, dir) due to jittering and stochastic sampling of the cone region. Ray length will be large (maxdist) when no hits occur, or when hits do not reach the opacity threshold before the ray leaves the scene. "ray:sampleindex" retrieves the (uniform) index for the current sample, useful when filling arrays or indexing arrays in the body of a gather loop
In situations where values are fetched using only primitive:var, attribute:var, or ray:var descriptors, some implementations may opt to skip execution of the shaders on the hit surface entirely, as an optimization. In these cases, automatic ray continuation may not occur, since shader execution is required to determine the surface opacity, Oi.

```illuminance([string category], point position )
statement
illuminance([string category], point position, vector axis, float angle )
statement
```

The illuminance statement controls integration of a procedural reflectance model over the incoming light. Inside the illuminance block two additional variables are defined: Cl or light color, and L or light direction. The vector L points towards the light source, but may not be normalized (see the Light source shader state illustration, in the Shader Execution Environment document). The arguments to the illuminance statement specify a three-dimensional solid cone and, optionally, the effective number of samples or step size of the integral.

The first form (above) specifies that the integral extends over the entire sphere centered at position. The second form integrates over a cone whose apex is on the surface at position. This cone is specified by giving its centerline, and the angle between the side and the axis in radians. If angle is PI, the cone extends to cover the entire sphere and these forms are the same as the first form. If angle is PI/2, the cone subtends a hemisphere with the north pole in the direction axis. Finally, if angle is 0, the cone reduces to an infinitesimally thin ray.

The optional category string parameter selects which lights should execute during a particular illuminance loop. The illuminance category string is a simple pattern expression which is matched against each light's declared list of category "memberships". Light shaders can specify categories to which they belong by declaring a string parameter named __category (this name has two underscores), whose value is a comma-separated list of names. These categories are simply arbitrary names, chosen by the programmer to be useful among a set of cooperating shaders. The illuminance category parameter expressions are very limited. They consist of category "terms" separated by "&" or "|" (for AND and OR). The "terms" can be:

"name" - matches lights which include "name" in their category list

"-name" -matches lights which do not have "name" in their category list (including lights which have no category list)

"*" - matches every light with non-null category

"-*" - matches every light with no categories

"" - matches everything

"-" - matches nothing

omitted- if the category parameter is omitted, the illuminance loop will execute its body for every nonambient light source.

A Lambertian shading model is expressed simply using the illuminance statement:

```Nn = normalize(N);
illuminance( P, Nn, PI/2 )
{
Ln = normalize(L);
Ci += Cs * Cl * Ln.Nn;
}
```

This example integrates over a hemisphere centered at the point on the surface with its north pole in the direction of the normal. Since the integral extends only over the upper hemisphere, it is not necessary to use the customary max``(0,Ln.Nn)`` to exclude lights that are locally occluded by the surface element.

```illuminate( point position ) stmt
illuminate( point position, vector axis, float angle ) stmt
```
```solar( ) stmt
solar( vector axis, float angle ) stmt
```

The illuminate and solar statements are inverses of the illuminance statement. They control the casting of light in different directions. The vector variable L corresponding to a particular light direction is available inside this block. This vector points outward from the light source. The color variable Cl corresponds to the color in this direction and should be set. Like the illuminance statements, illuminate and solar statements cannot be nested.

The illuminate statement is used to specify light cast by local light sources. The arguments to the illuminate statement specify a three-dimensional solid cone. The first form (above) specifies that light is cast in all directions. The second form specifies that light is cast only inside the given cone. The length of L inside an illuminate statement is equal to the distance between the light source and the surface currently being shaded.

The solar statement is used to specify light cast by distant light sources. The arguments to the solar statement specify a three-dimensional cone. Light is cast from distant directions inside this cone. Since this cone specifies only directions, its apex need not be given. The first form (above) specifies that light is being cast from all points at infinity (e.g., an illumination map). The second form specifies that light is being cast from only directions inside a cone.

An example of the solar statement is the specification of a distant light source:

```solar( D, 0 )
Cl = intensity * lightcolor;
```

This defines a light source at infinity that sends light in the direction D. Since the angle of the cone is 0, all rays from this light are parallel.

An example of the illuminate statement is the specification of a standard point light source:

```illuminate( P )
Cl = (intensity * lightcolor) / (L.L)
```

This defines a light source at position P that casts light in all directions. The 1/L.L term indicates an inverse square law fall off.

```color indirectdiffuse( point P; normal N; float samples;  [parameterlist]  )
```

indirectdiffuse returns diffuse illumination arising from indirect illumination. Effects such as "color bleeding", which arise through diffuse-to-diffuse indirect light transport paths, are captured via the indirectdiffuse function. Note that the indirectdiffuse function can be expressed in terms of gather calls but is much more efficient due to interpolation of results. Required parameters:

P, N, samples controls sampling of the underlying indirect illumination function. The sampling region is defined to be the hemisphere centered about the surface normal N at point P. (samples is ignored for point-based calculations.) Optional parameters are specified as name/value pairs.

indirectdiffuse() supports all of the common ray tracing function parameters, as well as the following:

Optional indirectdiffuse() Parameters
Name Type Mode Description
"bias" float both a bias value for ray origins, to prevent self-intersection. If not provided, the "trace" "bias" Attribute is used.
"coneangle" float both Specifies the part of the hemisphere to be considered when performing intersection calculations. The default value is PI/2, corresponding to the entire hemisphere. (For ray-traced calculations, if coneangle is PI and the normal is (0,0,0) and distribution is "uniform" then the entire sphere is considered.)
"distribution" string both Specifies the distribution of samples across the sample region. Available distributions are "uniform" and "cosine". Use "cosine" when the results are intended to simulate diffuse reflection at a surface. Use "uniform" to ensure that all portions of the sample region are treated equally, as needed, for example, for a point in a volume. The default distribution is "cosine".
"maxdist" float both Specifies the (float) maximum distance to consider when performing intersection calculations.
"falloffmode" uniform float both Chooses between two types of distance falloff. Set to 0 (the default), the contribution of a ray hit has exponential falloff; set to 1, the contribution of a ray hit is computed as (1 - dist/maxdist)^falloff.
"falloff" float both Determines the color bleeding falloff with distance. When the "falloffmode" parameter is set to 0 (its default), indicating exponential falloff, the indirectdiffuse() function uses the "falloff" parameter to determine the rate of falloff via exp(-falloff*dist). When the "falloffmode" is set to 1, the contribution of a ray hit is computed as (1 - dist/maxdist)^falloff. In this case, "falloff" = 1 gives linear falloff. Note that the default value for "falloff" is 0, meaning no distance falloff regardless of the "falloffmode" setting.
"samplebase" float both Specifies the jittering of the hemisphere ray origins. The default value is 0 (no jittering). A value of 1 corresponds to jittering over the size of a micropolygon. This can be useful to smooth out aliased indirect illumination next to edges.
"environmentmap" string both Specifies the name of an environment map to use when rays don't hit any geometry.
"environmentspace" uniform string|matrix both Specifies the name of a coordinate system to apply when accessing the environment map, or a transformation matrix to transform N by when accessing the environment map. By default the world coordinate system is used. Passing the string "_disable" or a unit matrix turns transformation off.
"maxvariation" float both Specifies an error metric to control quality/speed tradeoff for irradiance calculations. If set to zero, the irradiance will be computed at every shading point; no attempt at interpolation will be made. The larger "maxvariation" is, the more time can be saved by interpolating nearby irradiance values. "maxvariation" specifies how much the interpolated irradiance values are allowed to deviate from the true irradiance. The default value is 0.05. For high-quality final rendering, values in the 0.01 to 0.02 range are typical; for quick preview renderings, values of 0.05 or even 0.1 can be used. "maxvariation" should always be set to 0 if "coneangle" is less than pi/4; for such narrow coneangles interpolation does not work.
"maxpixeldist" float both Specifies an error metric to control quality/speed tradeoff for irradiance calculations. If set to zero, the irradiance will be computed at every shading point; no attempt at interpolation will be made. "maxpixeldist" is used in conjunction with "maxvariation" and provides a screen-based metric to limit artifacts associated with interpolation. If not provided or if set to a negative value, the value of the "irradiance" "maxpixeldist" attribute is used.
"maxerror" float both This parameter has been superseded by the "maxvariation" parameter and will be deprecated in a future release. "maxvariation" is a better error metric than "maxerror" and should be used instead; the same quality can be obtained with fewer irradiance calculations, increasing performance, and the control is more intuitive. If "maxvariation" is not provided or is set to a negative value, "maxerror" will be used instead (at least for now).
"hitsides" string both Specifies which side of a surface can be hit by the rays. The possible values are "front", "back", and "both". The default is "both". Sets both "colorhitsides" and "occlusionhitsides".
"colorhitsides" string both Used for point-based color bleeding. Specifies which side of a surface emits light. The possible values are "front", "back", and "both". The default is "both". Best results are usually obtained with "front".
"occlusionhitsides" string both Used for point-based color bleeding. Specifies which side of a surface can block color bleeding. The possible values are "front", "back", and "both". The default is "both", which is also the recommended setting.
"pointbased" uniform float both Tells the function to use point-based irradiance and occlusion calculation instead of ray tracing.
"adaptive" float ray-traced Indicates whether the hemisphere can be adaptively sampled. The default value is 1 (on) for "samples" at least 64. Adaptive hemisphere sampling is a useful optimization in scenes with large objects with smoothly varying color. It does not help in scenes with many small objects or lots of detailed color variation due to shadows and textures: the initial sampling may miss small bright surfaces. (adaptive is ignored for point-based calculations.)
"autobias" string ray-traced controls whether ray tracing bias is automatically computed. Valid settings are "on" (the default) and "off".
"usemotionbias" string ray-traced controls application of ray origin compensation for motion when Attribute "trace" "int samplemotion" is set. This compensation offsets the ray origins by t * dPdtime for each ray. Valid settings are "auto", "on", and "off". The default is "auto" which preserves the behavior of version 16.0. This compensates only when the origin == P. Setting "on" always applies compensation, "off" never applies it.
"minsamples" float ray-traced Specifies the minimum number of samples for adaptive sampling of the hemisphere. The default value is samples/4 if samples is at least 64; otherwise it is samples (corresponding to non-adaptive sampling). (Ignored for point-based calculations.)
"hitmode" string ray-traced Specifies how the color and opacity should be computed at ray hit points. If the value is "default", the color and opacity are determined by the hit object's "shade" "diffusehitmode" attribute. If the value is "primitive", the color and opacity are copied from the object's Cs and Os vertex variables (if present) or its Color and Opacity attributes. If the value is "cache", the color and opacity are found by looking up in a point cloud or brick map, as specified with the parameters "filename", "colorchannel", and "opacitychannel", or the attributes Attribute "shade" "string diffusehitcache" "file:...", Attribute "shade" "string diffusehitcolorchannel" "...", and Attribute "shade" "string diffusehitopacitychannel" "...". The parameters, if present, take precedence over the attributes. (The default for color channel is "", which is interpreted as "any channel with name "Cs", "cs", "_Cs", or "_cs"". Similarly, the default for opacity channel is "", which is interpreted as "any channel with name "Os", "os", "_Os", or "_os"".) If the value is "shader", the shader is evaluated to get the color and opacity. In all but the "default" mode, if the opacity is less than othreshold, a continuation ray will be fired. In "default" mode, if no Attribute "shade" "diffusehitmode" is defined the opacity will be considered 1; this special case is for backwards compatibility. Note that hitmode is ignored for point-based calculations.
"othreshold" color ray-traced othreshold is used to override Option "limits" "othreshold". Continuation rays are shot from transparent and semitransparent ray hits if the accumulated opacity is less than othreshold (with othreshold either from the "othreshold" parameter or Option "limits" "othreshold").
"subset" string ray-traced A trace set to consider for ray intersections. Only objects that are members of the named groups will be visible to the traced rays. Sets are defined with Attribute "grouping" "membership".
"excludesubset" string ray-traced Objects that are members of the named groups will not be visible to the traced rays.
"type" string ray-traced Explicitly specifies the ray type for all rays spawned by this call. Valid values are "specular", "diffuse", and "transmission"; the default type is "specular". (Note that the default type for occlusion() was "diffuse" in releases prior to 17.0.)
"label" string ray-traced labels can be queried in shaders executed as the result of a ray hit.
"seed" float ray-traced

"seed" can be used to seed the random ray directions. The main use is that if seed is computed as a function of a Pref, then the sampling noise patterns will follow an object even when it moves. For example:

```float seed = abs(123 * Pref[0] +
456 * Pref[1] +
789 * Pref[2]);
```

(Less useful: if "seed" is a constant value then the ray directions from all points will be the same, leading to no noise but heavy aliasing.) If "seed" is set to -1 or not specified, the ray directions will depend on position and change when points move.

"weight" color ray-traced The weight is multiplied on the (automatically computed) importance of diffuse hemisphere and sphere rays. The default value is (1,1,1).
"photonmap" string ray-traced The name of a photon map to use for photon-guided diffuse ray tracing. If no "photonmap" parameter is given, PRMan will use the photon map given by Attribute "photon" "globalmap". If neither the parameter nor the attribute is set, photon guiding is off. Note that photon-guided diffuse is currently only implemented for non-adaptive hemisphere sampling, so passing the "photonmap" parameter (or the "globalmap" attribute) turns "adaptive" off.
"filename" string point-based Specifies the name of the point cloud file to use for point-based irradiance and occlusion. The point data must include float _area and color _radiosity. The entire point cloud will be read in if it is unorganized. If it is organized, the points and octree nodes will be read on demand and cached.
"filenames" array of strings point-based Specifies an array of point cloud file names to use for point-based irradiance and occlusion. (For more details, see "filename", above.)
"areachannel" string point-based Specifies the name of the point-cloud channel that contains area data. The default is "_area".
"radiositychannel" string point-based Specifies the name of the point-cloud channel that contains reflected direct illumination. The default is "_radiosity".
"extinctionchannel" string point-based Specifies the name of the point-cloud channel that contains volume extinction coefficients. The default is "_extinction".
"maxsolidangle" float point-based "maxsolidangle" is a quality setting for point-based calculations. Smaller values mean better quality but longer rendering time. The default value is 0.1.
"clamp" uniform float point-based by setting its value to 1, this parameter reduces "over-bleeding" (the point-based method tends to compute too much color bleeding, due to superposition).
"sortbleeding" uniform float point-based Specifies whether color bleeding colors are sorted front-to-back or just mixed. This parameter is strictly for point-based irradiance and is only used if clamp is set to 1. As of PRMan 15.1, this parameter is always on for volume color bleeding.
"rasterresolution" uniform float point-based Sets the raster resolution for point-based irradiance clamping. This parameter is only used if clamp is 1. Its default value is 12, meaning that the sphere is divided into six faces with 12x12 pixels each. Higher values gives more accurate results, but slightly longer render times.
"volume" uniform float point-based When this parameter is set to 1, points with normal (0,0,0) are treated as being in a volume: they emit and receive light from the entire sphere of directions, and attenuate light passing through them. This parameter is only used if clamp is 1. Its default value is 0. Note that point-based color bleeding requires the "sortbleeding" parameter (above) to be set to 1.
"coordsystem" uniform string|matrix point-based Specifies the name of the coordinate system that the object is in or a matrix that specifies the transformation that P and N should be subjected to. By default the world coordinate system is used. Passing the string "_disable" or a unit matrix turns transformation off. Used for point-based computations.
"shbands" uniform float point-based Specifies the number of spherical harmonic bands to be computed and then stored in the optional output parameters "dirvisshcoeffs" and "incradshcoeffs". Currently only implemented for point-based calculations (not ray-traced). The "clamp" parameter must be set to 1.
indirectdiffuse() Output Parameters
Name Type Description
"environmentcolor" color Specifies the optional output variable to fill with the color resulting from environment map lookups at ray misses. If no environment map is provided, the environment color will be black. (To get the color resulting from ray hits, just subtract the environment color from the indirectdiffuse() return value.)
"environmentdir" varying vector Specifies an optional output variable to fill with the average unoccluded direction. This direction is obtained by averaging the directions of all samples that fail to hit local geometry.
"occlusion" float Specifies an optional output variable to fill with the percentage of the samples that hit local geometry.
"dirvisshcoeffs" float array The spherical harmonic coefficients for directional visibility. Currently only implemented for point-based calculations (not ray-traced). The "clamp" parameter must be set to 1.
"incradshcoeffs" color array The spherical harmonic coefficients for incident radiance. Same restrictions as for "dirvisshcoeffs".
Implementations that don't support indirectdiffuse should return black.

```_lightingstart()
```

lightingstart is a special no-op shadeop that serves as an optimization hint for the re-rendering mode of PRMan; it marks the end of light-independent calculations (texturing and noise for example), and the beginning of light-dependent calculations (such as calls to diffuse(), illuminance(), et cetera); this allows the re-renderer to cache all shading results that occur before lighting.

The shader compiler attempts to place _lightingstart() in a reasonable part of the shaders. For complicated shaders, the result may not always be optimal and can be overridden by explicitly adding the statements to the shader sourcecode. For example:

```surface
matte( float Ka=1, Kd=1 )
{
normal Nf;

Nf = faceforward(normalize(N),I);

Oi = Os;
_lightingstart();
Ci = Os * Cs * ( Ka*ambient() + Kd*diffuse(Nf) ) ;
}
```

```float occlusion( point P; normal N; float samples;  [parameterlist]  )
```

occlusion returns a measure of ambient occlusion defined as the percentage of the hemisphere that is occluded from view by the "environment".

P, N, samples controls sampling of the underlying ambient occlusion function. The sampling region is defined to be the hemisphere centered about the surface normal N at point P. (samples is ignored for point-based calculations.) Optional parameters are specified as name/value pairs.

occlusion() supports the common ray tracing function parameters (except as noted), as well as the following:

Optional occlusion() Parameters
Name Type Mode Description
"bias" float both a bias value for ray origins, to prevent self-intersection. If not provided, the "trace" "bias" Attribute is used.
"coneangle" float both Specifies the (float) part of the hemisphere to be considered when performing intersection calculations. The default value is PI/2, corresponding to the entire hemisphere. (For ray-traced calculations, if coneangle is PI and the normal is (0,0,0) and distribution is "uniform" then the entire sphere is considered.)
"distribution" string both Specifies the distribution of samples across the sample region. Available distributions are "uniform" and "cosine". Use "cosine" when the occlusion results are intended to simulate diffuse reflection at a surface. Use "uniform" to ensure that all portions of the sample region are treated equally, as needed for example at a point in a volume. The default distribution is "cosine".
"maxdist" float both Specifies the (float) maximum distance to consider when performing intersection calculations.
"falloffmode" uniform float both Chooses between two types of distance falloff. Set to 0 (the default), the occlusion contribution of a ray hit has exponential falloff; set to 1, the occlusion contribution of a ray hit is computed as (1 - dist/maxdist)^falloff.
"falloff" float both Determines the occlusion falloff with distance. When the "falloffmode" parameter is set to 0 (its default), indicating exponential falloff, the occlusion() function uses the "falloff" parameter to determine the rate of falloff via exp(-falloff*dist). When the "falloffmode" is set to 1, the occlusion contribution of a ray hit is computed as (1 - dist/maxdist)^falloff. In this case, "falloff" = 1 gives linear falloff. Note that the default value for "falloff" is 0, meaning no distance falloff regardless of the "falloffmode" setting.
"samplebase" float both Specifies the (float) jittering of the hemisphere ray origins. The default value is 0 (no jittering). A value of 1 corresponds to jittering over the size of a micropolygon. This is useful to smooth out aliased occlusion next to edges.
"hitsides" uniform string both Specifies which side of a surface can be hit by the rays / is visible for point-based calculations. The possible values are "front", "back", and "both". The default is "both".
"environmentmap" string both Specifies the name of an environment map to use when rays don't hit any geometry / when no points block a certain direction. If the brightnesswarp parameter is on, the environment map will guide the distribution of occlusion rays. (For more details about the brightnesswarp parameter, see below.)
"environmentspace" uniform string|matrix both Specifies the name of a coordinate system to apply when accessing the environment map, or a transformation matrix to transform N by when accessing the environment map. By default the world coordinate system is used. Passing the string "_disable" or a unit matrix turns transformation off.
"maxvariation" float both Specifies an error metric to control quality/speed tradeoff for occlusion calculations. If set to zero, the occlusion will be computed at every shading point; no attempt at interpolation will be made. The larger "maxvariation" is, the more time can be saved by interpolating nearby occlusion values. "maxvariation" specifies how much the interpolated occlusion values are allowed to deviate from the true occlusion. The default value is 0.05. For high-quality final rendering, values in the 0.01 to 0.02 range are typical; for quick preview renderings, values of 0.05 or even 0.1 can be used. "maxvariation" should always be set to 0 if "coneangle" is less than pi/4; for such narrow coneangles interpolation does not work.
"maxpixeldist" float both Specifies an error metric to control quality/speed tradeoff for occlusion calculations. If set to zero, the occlusion will be computed at every shading point; no attempt at interpolation will be made. "maxpixeldist" is used in conjunction with "maxerror" or "maxvariation" and provides a screen-based metric to limit artifacts associated with interpolation.  If not provided or if set to a negative value, the value of Attribute "irradiance" "maxpixeldist" is used.
"maxerror" float both This parameter has been superseded by the "maxvariation" parameter and will be phased out in a future release. "maxvariation" is a better error metric than "maxerror" and should be used instead; the same quality can be obtained with fewer occlusion calculations (increasing performance) and the control is more intuitive. If "maxvariation" is not provided or is set to a negative value, "maxerror" will be used instead (at least for now).
"pointbased" uniform float both Use point-based occlusion calculation instead of ray-traced.
"adaptive" uniform float ray-traced Indicates whether the hemisphere can be adaptively sampled. Adaptive hemisphere sampling is a useful optimization in scenes with large objects; it does not help in scenes with many small objects. The default value is 1 (on) for "samples" at least 64. Adaptive sampling is always off for samples fewer than 64, regardless of this parameter's value.
"autobias" string ray-traced controls whether ray tracing bias is automatically computed. Valid settings are "on" (the default) and "off".
"usemotionbias" string ray-traced controls application of ray origin compensation for motion when Attribute "trace" "int samplemotion" is set. This compensation offsets the ray origins by t * dPdtime for each ray. Valid settings are "auto", "on", and "off". The default is "auto" which preserves the behavior of version 16.0. This compensates only when the origin == P. Setting "on" always applies compensation, "off" never applies it.
"minsamples" float ray-traced Specifies the (float) minimum number of samples for adaptive sampling of the hemisphere. The default value is samples/4 if samples is at least 64; otherwise it is samples (corresponding to non-adaptive sampling).
"hitmode" string ray-traced Specifies how the opacity should be computed at ray hit points. If the value is "default", the opacity is determined as specified by the hit object's hitmode attribute for the ray type (usually Attribute "shade" "transmissionhitmode"). If the value is "primitive", the opacity is copied from the object's Os vertex variable or Opacity attribute. If the value is "cache", the opacity is found by looking up in a point cloud or brick map, as specified with the parameters "filename" and "opacitychannel", or the attributes Attribute "shade" "string transmissionhitcache" "file:..." and Attribute "shade" "string transmissionhitopacitychannel" "..." (or whatever the ray type is). The parameters, if present, take precedence over the attributes. (The default for the opacity channel is "" which is interpreted as "any channel with name "Os", "os", "_Os", or "_os"".) If the value is "shader", the shader is evaluated to get the opacity. In all but the "default" mode, if the opacity is less than othreshold, a continuation ray will be fired. (In "default" mode, if no Attribute "shade" "transmissionhitmode" is defined, the opacity will be considered 1; this special case is for backwards compatibility.)
"othreshold" color ray-traced 'othreshold' is used to override Option "limits" "othreshold". Continuation rays are shot from transparent and semitransparent ray hits if the accumulated opacity is less than othreshold (with othreshold either from the "othreshold" parameter or Option "limits" "othreshold").
"subset" string ray-traced A trace set to consider for ray intersections. Only objects that are members of the named groups will be visible to the traced rays. Sets are defined with Attribute "grouping" "membership".
"excludesubset" string ray-traced Objects that are members of the named groups will not be visible to the traced rays.
"type" string ray-traced Explicitly specifies the ray type for all rays spawned by this call. Valid values are "specular", "diffuse", and "transmission"; the default type is "specular". (Note that the default type for occlusion() was "diffuse" in releases prior to 17.0.)
"label" string ray-traced labels can be queried in shaders executed as the result of a ray hit.
"brightnesswarp" uniform float ray-traced Specifies whether the environment map should be used to importance sample the hemisphere, i.e. more rays shot in directions where the environment map is bright than in directions where it is dark. This significantly reduces the noise in the computed environmentcolor, particularly if a high-dynamic range image (HDRI) is used for the environment map. The meaning of the occlusion function return value changes when an environment map is used like this: instead of being the fraction of the hemisphere that is occluded by objects, it is the brightness-weighted fraction of the hemisphere that is occluded by objects. The default for brightnesswarp is 1 (on). If there is no environment map, this parameter is ignored.
"seed" float ray-traced

"seed" can be used to seed the random ray directions. The main use is that if seed is computed as a function of a Pref, then the sampling noise patterns will follow an object even when it moves. For example:

```float seed = abs(123 * Pref[0] +
456 * Pref[1] +
789 * Pref[2]);
```

(Less useful: if "seed" is a constant value then the ray directions from all points will be the same, leading to no noise but heavy aliasing.) If "seed" is set to -1 or not specified, the ray directions will depend on position and change when points move.

"filename" string point-based Specifies the name of the point cloud file to use for point-based occlusion. The point data must include float _area. The entire point cloud will be read in if it is unorganized. If it is organized, the points and octree nodes will be read on demand and cached.
"filenames" array of strings point-based Specifies an array of point cloud file names to use for point-based occlusion. (For more details, see "filename", above.)
"areachannel" string point-based Specifies the name of the point-cloud channel that contains area data. The default is "_area".
"maxsolidangle" uniform float point-based "maxsolidangle" is a quality setting for point-based calculations. Smaller values mean better quality but longer rendering time. The default value is 0.1.
"clamp" uniform float point-based By setting its value to 1, this parameter reduces "over-bleeding" (the point-based method tends to compute too much color bleeding, due to superposition).
"rasterresolution" uniform float point-based Sets the raster resolution for point-based occlusion clamping. This parameter is only used if clamp is 1. Its default value is 12, meaning that the sphere is divided into six faces with 12x12 pixels each. Higher values gives more accurate results, but slightly longer render times. This parameter was introduced in PRMan 15.0.
"shbands" uniform float point-based Specifies the number of spherical harmonic bands to be computed and then stored in the optional "dirvisshcoeffs" output parameter. Currently only implemented for point-based calculations (not ray-traced). The "clamp" parameter must be set to 1.
"coordsystem" uniform string|matrix point-based Specifies the name of the coordinate system the object is in or a matrix that specifies the transformation that P and N should be subjected to. By default the world coordinate system is used. Passing the string "_disable" or a unit matrix turns transformation off. Used for point-based computations.
occlusion() Output Parameters
Name Type Description
"environmentcolor" color Specifies the optional output variable to fill with the color resulting from environment map lookups on unnoccluded samples.  If no environment map is provided, the environment color will be black.
"environmentdir" varying vector Specifies an optional output variable to fill with the average unoccluded direction. This direction is obtained by averaging the directions of all samples that fail to hit local geometry.
"dirvisshcoeffs" float array Specifies the spherical harmonic coefficients for directional visibility. Currently only implemented for point-based calculations (not ray-traced). The "clamp" parameter must be set to 1.
Implementations that don't support occlusion should return 0 (unoccluded).

```color phong( normal N; vector V; float size )
```

phong implements the Phong specular lighting model.

Example:

```{
color C = 0;
vector R = reflect( -normalize(V), normalize(N) );
illuminance( P, N, PI/2 ) {
vector Ln = normalize(L);
C += Cl * pow(max(0.0,R.Ln), size);
}
return C;
}
```

The phong shadeop responds to the following special parameter of a light shader:

```float __nonspecular = 1
```

Any light that contains this parameter will be ignored by both phong and specular. Please note that if the value of the parameter is 0.0, it is not ignored, so this behavior can be controlled both from the RIB file, or procedurally from inside the light shader, if desired. This parameter may be either uniform or varying, and can also be accessed within illuminance statements.

```color specular( normal N; vector V; float roughness )
```

specular returns the specular component of the lighting model using an implementation-dependent specularbrdf. N is the unit-length normal to the surface. V is a unit-length vector from a point on the surface towards the viewer. For example:

```{
color C = 0;
illuminance( P, N, PI/2 )
C += Cl * specularbrdf(normalize(L), N, V, roughness);
return C;
}
```

The specular shadeop responds to the following special parameter of a light shader:

```float __nonspecular = 1
```

Any light that contains this parameter will be ignored by both specular and phong. Please note that if the value of the parameter is 0.0, it is not ignored, so this behavior can be controlled both from the RIB file, or procedurally from inside the light shader, if desired. This parameter may be either uniform or varying, and can also be accessed within illuminance statements.

```float specularbrdf( vector L; normal N; vector V; float roughness )
color specularbrdf( vector L; normal N; vector V; float roughness )
```

Returns the specular attenuation of light coming from the direction L, reflecting toward direction V, with surface normal N and roughness, roughness.  All of L, V and N are assumed to be of unit length.  This is the same reflection model calculation found inside the illuminance loop of the specular() function.  This allows users to write an illuminance loop that reproduces the functionality of the specular() function, even if the renderer has an implementation-specific formula for built-in specular reflection.  Here is a sample implementation:

```color specularbrdf(vector L, N, V; float roughness)
{
vector H = normalize(L+V);
return pow(max(0, N.H), 1/roughness);
}
```

```color subsurface( [mode]; point P; normal N;  [parameterlist]  )
```

subsurface returns the subsurface scattering at point P, with surface normal N. (N is only used for point-based subsurface diffusion if the paramter "followtopology" is on.) Mode can be "pointbased" or "raytraced", with "pointbased" being the default. Other optional parameters are specified as name/value pairs.

subsurface() supports most of the common ray tracing function parameters (except as noted), plus the following:

Optional subsurface() Parameters
Name Type Mode Description
"bias" float both a bias value for ray origins, to prevent self-intersection. If not provided, the "trace" "bias" Attribute is used.
"type" string both Specifies the type of subsurface scattering - "ssdiffusion" (or "dipolediffusion"), "singlescatter", or "beamdiffusion". "ssdiffusion" is the default value.
"scattering" varying color both Specifies the reduced scattering coefficients of the material (sigma'_s). There is no default since albedo and diffusemeanfreepath are used if scattering and absorption aren't defined.
"absorption" varying color both Specifies the absorption coefficients of the material (sigma_a). There is no default since albedo and diffusemeanfreepath are used if scattering and absorption aren't defined.
"albedo" varying color both Specifies the albedo (diffuse color) of the material. The default albedo is (0.830 0.791 0.753), corresponding to marble.
"diffusemeanfreepath" varying color both Specifies the diffuse mean free path length of light in the material (measured in millimeters). The default value is (8.51 5.57 3.95) mm, corresponding to marble. (For ray-traced calculations, the diffusemeanfreepath is used indirectly to determine how deep below the surface the subsurface rays are shot from. If the diffusemeanfreepath for the three color bands are very different, it is difficult to find a depth that works well for all three bands, and excessive noise in some bands can result. Please see the documentation of the offset parameter, below, which explicitly sets the depth.)
"ior" uniform float both Specifies the index of refraction of the material. The default value is 1.5 (marble).
"unitlength" uniform float both Specifies the length in scene units corresponding to 1mm. For example, if the scene unit is centimeters, since 1mm = 0.1 * 1cm, set unitlength to 0.1. The default of 1 assumes the scene units are in mm.
"followtopology" uniform float both Specifies whether the subsurface scattering should be diminished across locally concave regions such as wrinkles, skin pores, creases, etc. Values are 0.0 (off) or 1.0 (on) or values in between; the default is 0.0.
"smooth" uniform float both Specifies whether the results should be smooth. Values are 0 (off) or 1 (on); default is 0. For point-based subsurface scattering, smoothing is necessary to avoid aliasing artifacts if the diffuse mean free path length is short relative to the point cloud density. For ray-traced subsurface scattering, smoothing can be used to reduce noise.
"samples" varying float ray-traced Specifies how many rays should be shot to sample the sphere. The default value is 16.
"adaptive" float ray-traced Indicates whether the subsurface scattering can be adaptively sampled. The default value is 1 (on) for "samples" at least 64.
"usemotionbias" string ray-traced controls application of ray origin compensation for motion when Attribute "trace" "int samplemotion" is set. This compensation offsets the ray origins by t * dPdtime for each ray. Valid settings are "auto", "on", and "off". The default is "auto" which preserves the behavior of version 16.0. This compensates only when the origin == P. Setting "on" always applies compensation, "off" never applies it.
"autobias" string ray-traced controls whether ray tracing bias is automatically computed. Valid settings are "on" (the default) and "off".
"maxdist" float ray-traced limits the distance from P in which ray hits can occur, defaults to RI_INFINITY.
"minsamples" float ray-traced Specifies the minimum number of samples for adaptive sampling. The default value is samples/4 if samples is at least 64; otherwise it is samples (corresponding to non-adaptive sampling).
"offset" varying float ray-traced Specifies how far inside the object the rays should be shot from (measured in millimeters). If no value is provided, the offset is calculated based on the scattering parameters and the resulting (real) dipole depth. If the scattering parameters (and hence the dipole depths) are similar in the three color bands, the offset is chosen as the min of the three dipole depths. If the dipole depths differ by more than a factor of two, then one third of the rays will be shot from each dipole depth. In all cases the offset is clamped by half of the distance to the backside of the object to avoid shooting subsurface rays from outside a thin object.
"label" string ray-traced Specifies the label associated with all rays spawned by this call. The default is "subsurfaceray" in PRMan 16 and "subsurface" in PRMan 17.
"weight" color ray-traced The weight is multiplied on the (automatically computed) importance of subsurface rays. The default value is (1,1,1).
"continuationrays" float ray-traced Trace subsurface continuation rays even from opaque hit points. Values are 0 or 1. The default value is 0 (no continuation rays). This parameter can be turned on in order to make the ray-traced subsurface() results look more like point-based subsurface() results (which don't take occlusion into account).
"switchtobrdf" float ray-traced Switch to faster diffuse brdf (single ray) instead of sampling the full bssrdf when the diffuse mean free path is smaller than this distance. Measured in pixels. Default is 0.
"subset" string ray-traced A trace set to consider for ray intersections. Only objects that are members of the named groups will be visible to the traced rays. Sets are defined with Attribute "grouping" "membership".
"excludesubset" string ray-traced Objects that are members of the named groups will not be visible to the traced rays.
"filename" string point-based The name of the point cloud file to use as input for the subsurface scattering computation. The point data must include float _area and color _radiance_t. If the point cloud is unorganized, the entire point cloud will be read in. If it is organized, the points and octree nodes will be read on demand and cached.
"filenames" array of strings point-based An array of point cloud file names to use for the subsurface scattering computation. (For more details, see "filename", above.)
"areachannel" string point-based Specifies the name of the point-cloud channel that contains area data. The default is "_area".
"radiancechannel" string point-based Specifies the name of the point-cloud channel that contains (transmitted) direct illumination. The default is "_radiance_t".
"maxsolidangle" varying float point-based Determines the accuracy of the computation. Smaller values mean better quality but longer rendering time. The default value is 0.1. (The default value was 1.0 in PRMan releases before 16.0.)
"coordsystem" uniform string|matrix point-based Specifies the name of the coordinate system the point-cloud has been baked in, or a transformation matrix to transform P by. By default the world coordinate system is used. Passing the string "_disable" or a unit matrix turns transformation off.

Implementations that don't support subsurface should return black.

```color trace( point P; vector R )
float trace( point P; vector R )
```
trace returns the incident light reaching a point P from a given direction R. If a particular implementation does not support the ray tracing capability, and cannot compute the incident light arriving from an arbitrary direction, trace will return 0 (black). When the float variant of trace is called, the distance to the nearest ray hit is returned. This variant can be faster because surface shaders may not be required to determine intersection locations.  When no geometry is encountered along the ray direction, a very large distance value is returned.
Optional trace() Parameters
Name Type Description
"usemotionbias" string controls application of ray origin compensation for motion when Attribute "trace" "int samplemotion" is set. This compensation offsets the ray origins by t * dPdtime for each ray. Valid settings are "auto", "on", and "off". The default is "auto" which preserves the behavior of version 16.0. This compensates only when the origin == P. Setting "on" always applies compensation, "off" never applies it.

```color transmission( point Psrc, Pdst;  [parameterlist]  )
```

transmission returns a color representing the ability of light to flow between Psrc and Pdst. If a particular implementation does not support the ray tracing capability, and cannot compute the incident light arriving from an arbitrary direction, transmission will always return 1 (white). Transmission rays are different than trace rays because their purpose isn't to find the nearest hit but rather to find how much light can move from point to point. transmission is usually called in light shaders to determine whether a surface point is in shadow.  Unlike trace rays, transmission rays can terminate as soon as they encounter a completely opaque object, even if it wouldn't turn out to be the nearest object after a complete search of the database. Intersection tests are governed by the Attribute "visibility" "transmission"  value associated with each primitive.

transmission() supports the common ray tracing function parameters (except as noted), as well as the following:

Optional transmission() Parameters
Name Type Description
"bias" float a bias value for ray origins, to prevent self-intersection. If not provided, the "trace" "bias" Attribute is used.
"usemotionbias" string controls application of ray origin compensation for motion when Attribute "trace" "int samplemotion" is set. This compensation offsets the ray origins by t * dPdtime for each ray. Valid settings are "auto", "on", and "off". The default is "auto" which preserves the behavior of version 16.0. This compensates only when the origin == P. Setting "on" always applies compensation, "off" never applies it.
"autobias" string controls whether ray tracing bias is automatically computed. Valid settings are "on" (the default) and "off".
"samples" varying float Specifies the number of rays.
"minsamples" varying float Specifies the (float) minimum number of rays for adaptive sampling.
"samplecone" varying float Specifies the angle of the cone over which rays are fired.
"samplebase" float scales the ray origin jitter area, which is the size of the origin micropolygon by default (i.e. 1.0).
"hitmode" string specifies how the opacity should be computed at shadow ray hit points. If the value is "default", the opacity is determined as specified by the hit object's "shade" "transmissionhitmode" attribute. If the value is "primitive", the opacity is copied from the object's Os vertex variable or Opacity attribute. If the value is "cache", the opacity is found by looking up in a point cloud or brick map, as specified with Attribute "shade" "transmissionhitcache" "file:..." and Attribute "shade" "diffusehitopacitychannel" "...". If the value is "shader", the shader is evaluated to get the opacity. In all but the "default" mode, if the opacity is less than othreshold, a continuation ray will be fired. In "default" mode, if no attribute "shade" "transmissionhitmode" is defined, the opacity will be considered 1.
"hitsides" string Specifies which side(s) of one-sided surfaces can be hit by the rays. The possible values are "front", "back", and "both". The default is "both".
"subset" string A trace set to consider for ray intersections. Only objects that are members of the named groups will be visible to the traced rays. Sets are defined with Attribute "grouping" "membership".
"excludesubset" string Objects that are members of the named groups will not be visible to the traced rays.
"type" string Explicitly specifies the ray type for all rays spawned by this call. Valid values are "specular", "diffuse", and "transmission"; the default type is "specular". (Note that the default type for occlusion() was "diffuse" in releases prior to 17.0.)
"label" string labels can be queried in shaders executed as the result of a ray hit.
• Note:

It is not always appropriate to specify samples and samplecone directly in the transmission() call. In some LightSource shaders, the caller may need to apply some sort of specific fall-off or other variation to each sub-sample result that must be done per-trace, not on the averaged result of the sub-sample traces.

Adaptive sampling will be be used if both samples and minsamples are specified (and minsamples is greater than 0 and smaller than samples): first minsamples transmission rays are shot, and if there is variation in the transmission values the remaining samples-minsamples rays will be shot.

The built-in sampling can be used to produce simple blurred soft shadows, similar to what would be produced by a spherical area light, where the shadow blur increases as a function of the relative distances between the light source, the occluding object, and the shadowed surface. In this case it is important to use the correct order of Psrc and Pdst so that the cone angle has its apex at the surface position, Ps. Here's a simple example LightSource shader:

```light
transmissionpoint (
point from = point "shader" (0,0,0);
float samples = 1;
float blur = 0;)
{
illuminate( from )
{
Cl = transmission(Ps, from, "samples", samples, "samplecone", blur);
}
}
```

### "Plausible" Shading Functions & Methods

```color directlighting( shader material, shader lights[],
["integrationdomain", "hemisphere|sphere"],
["diffuseresult", output color diffuseresult],
["specularresult", output color specularresult],
[uniform float "arealightsamples"]
)
```
directlighting combines the diffuse and specular integrators in a single function. directlighting, like diffuse and specular, is concerned only with light that can directly impinge upon the surface, but provides advantages because certain computations can be shared.
Optional directlighting() Parameters
Name Type Description
"integrationdomain" string Specifies the domain over which the directlighting integration is performed. Use sphere when your material is translucent and hemisphere when it is opaque.
"mis" uniform float Specifies the sampling strategy employed by the integrator. Use 0 to consider light samples only. Use 1 to perform multiple importance sampling, considering both light and material samples. Use 2 to consider material samples only. Usually the value 1 is suggested. A value of 2 is suggested for very narrow specular distributions (i.e. chrome) and 0 is suggested for very small light sources.
"diffuseresult" output color The results of the diffuse portion of integration are written to the optional output parameter. When directlighting is called within the specularlighting method, the diffuseresult parameter will always be 0.
"specularresult" output color The results of the specular portion of integration are written to the optional output parameter. When directlighting is called within the diffuselighting method, the specularresult parameter will always be 0.
"unshadoweddiffuseresult" output color Returns the unshadowed, diffuse-only portion of the direct lighting.
"unshadowedspecularresult" output color Returns the unshadowed, specular-only portion of the direct lighting.
"materialsamples" __radiancesample [] If the optional samples array is provided and has non-zero length, we use these in place of the material's generateSamples result in multiple-importance sampling modes. If the array is provided and has zero length, we fill it with the samples produced by the material's generateSamples. When used with indirectspecular it is suggested that the indirectspecular term be called prior to directlighting and that the samples generated by the indirectspecular integrator be passed to directlighting.
"arealightsamples" uniform float The "arealightsamples" parameter controls the number of samples to use for area lights. If not set, then Option "shading" "int directlightingsamples" is used. If "arealightsamples" is not provided, or if the value is -1, then automatic determination of the sample count is performed, using importance as a culling metric on the option value.
"heuristic" string Alters the variance reduction heuristic that is used to balance between samples the light generated and samples the material generated when MIS is in effect. The default string "veachpower2" uses the power heuristic with beta=2, as described by Eric Veach in his thesis "Robust Monte Carlo Methods For Light Transport Simulation". This heursitic takes into account the number of samples for each sampling strategy and may reduce variance in cases where the estimated variance is otherwise assumed to be even, but one sampling strategy has more samples. The string "pdfpower2" is the power heuristic using only the probabilities and does not include sample counts in its estimation. It may be more appropriate in cases where one technique has much higher variance than the other, but that technique still has a larger number of samples allocated to it.
"position" varying point Allows a user to specify a point other than P to be used for gathering direct illumination.
Optional directlighting() Grouped Output Parameters
Name Type Description
"lightgroups" string [] Specifies which light groups are to be returned for the following optional outputs.
"groupedresults" output varying color[]
Returns the grouped results of direct lighting per group specified
in the "lightgroups" parameter.
"groupeddiffuseresults" output varying color[] Returns the grouped diffuse portion of the direct lighting per group specified in the "lightgroups" parameter.
"groupedspecularresults" output varying color[] Returns the grouped specular portion of the direct lighting per group specified in the "lightgroups" parameter.
"groupedunshadowedresults" output varying color[] Returns the grouped results of unshadowed direct lighting per group specified in the "lightgroups" parameter.
"groupedunshadoweddiffuseresults" output varying color[] Returns the grouped diffuse portion of the unshadowed direct lighting per group specified in the "lightgroups" parameter.
"groupedunshadowedspecularresults" output varying color[] Returns the grouped specular portion of the unshadowed direct lighting per group specified in the "lightgroups" parameter.

```color indirectspecular( [ shader material, "materialsamples", output
| "materialsamples:direction", direction[],
"materialsamples:materialResponse", materialResponse[],
"materialsamples:materialPdf", materialPdf[],
"materialsamples:distance", distance[],
)
```

The indirectspecular function provides a means by which the specular response associated with indirect light transport paths can match the response to direct lighting. The sampling directions are either provided indirectly through a call to the generateSamples method of material, or directly in either the materialsamples __radiancesample array or individual component arrays.

It supports the same syntax as gather() for sending data to shaders at suface hits, via [send:|samplesend:]surface:varname. For samplesend:, the variable must be a varying array with the the same number of entries as the number of samples, and the data will be sent per sample.

indirectspecular() supports all of the common ray tracing function parameters, as well as the following:

Optional indirectspecular() Parameters
Name Type Description
"materialsamples" __radiancesample [] If the optional array is provided and has non-zero length, we use these in place of the material's generateSamples result. If array is provided with zero length, we fill it with the samples produced by the material's generateSamples. When used with directlighting for simple specular distributions we suggest that the indirectspecular term be called prior to directlighting and that the samples generated by the indirectspecular integrator be passed to directlighting.
"materialsamples:[direction materialResponse materialPdf distance radiance] float[] In lieu of "materialsamples", users may instead pass a collection of arrays to indirectspecular(). In this case, the materialsamples:direction array is required, while all other arrays are optional. If either of materialsamples:materialResponse or materialsamples:materialPdf is present, then both of them must be. Internally, the material response is weighted by the pdf values to support importance sampling. The shader may provide a pre-weighted version insteas using materialsamples:weightedMaterialResponse.
"position" point This optional parameter allows you to set the orgin used for the rays that are traced to retrieve the indirect lighting. If not provided, the current value of P will be used.
"materiallobecounts" float This optional parameter allows you to use samples that have not been set up with normalizeMaterialResponse() but still ensure geometric derivatives do not blur between lobes.
"integrationdomain" string Specifies the domain over which the indirectspecular integration is performed. Valid values are hemisphere (the default) and sphere. If a hemisphere domain is used, samples below the horizon will be culled.
"numvalidsamples" float Indicates how many of the provided samples have a non-zero material response and require indirect specular response. If not provided, indirectspecular() will derive this from the number of non-zero values of materialResponse.
"numgeneratedsamples" float Indicates how many of the provided samples have a non-zero pdf value and are part of the importance sampling. If not provided, indirectspecular() will derive this from the number of non-zero values of materialPdf.
"samplebase" float scales the ray origin jitter area, which is the size of the origin micropolygon by default (i.e. 1.0).
"samplesend:" float[] Permits per sample data to be sent. The argument must be a varying array whose length is the same as the length of either radiancesamples or the materialsamples arrays.
"send:" float[] Permits data to be sent. The argument must be a varying value.
"bias" float a bias value for ray origins, to prevent self-intersection. If not provided, the "trace" "bias" Attribute is used.
"usemotionbias" string controls application of ray origin compensation for motion when Attribute "trace" "int samplemotion" is set. This compensation offsets the ray origins by t * dPdtime for each ray. Valid settings are "auto", "on", and "off". The default is "auto" which preserves the behavior of version 16.0. This compensates only when the origin == P. Setting "on" always applies compensation, "off" never applies it.
"autobias" string controls whether ray tracing bias is automatically computed. Valid settings are "on" (the default) and "off".
"maxdist" float limits the distance from P in which ray hits can occur, defaults to RI_INFINITY.
"maxspeculardepth" float Constrains rays launched by indirectspecular() to no more than the specified number of pathlengths (bounce counts).
"subset" string A trace set to consider for ray intersections. Only objects that are members of the named groups will be visible to the traced rays. Sets are defined with Attribute "grouping" "membership".
"excludesubset" string Objects that are members of the named groups will not be visible to the traced rays.
"othreshold" color An opacity threshold that determines termination criteria for automatic continuation of rays through semi-transparent surfaces. Using color(0) effectively disables automatic continuation for the given call. The implementation sets the default opacity threshold, typically color(1 - epsilon ).
"ohitthreshold" color an opacity threshold that determines when a ray is considered to have "hit" anything or not. When it is desirable to use shading (or texture maps) to cause parts of objects to be "invisible" to rays, the shaders on those objects should set Ci and Oi to zero, for those parts. Rays that probe those objects will ignore them when the returned Ci and Oi are less than the "ohitthreshold" value. Using color(0) for this parameter causes shading at intersection points to be ignored for hit-testing purposes. The implementation sets the default threshold, typically color ( epsilon ).
"type" string Explicitly specifies the ray type for all rays spawned by this call. Valid values are "specular", "diffuse", and "transmission"; the default type is "specular". (Note that the default type for occlusion() was "diffuse" in releases prior to 17.0.)
"label" string labels can be queried in shaders executed as the result of a ray hit.
"hitmode" string

Specifies how the color should be computed at ray hit points. Possible values are:

"default" - use the value of Attribute "specularhitmode"
"primitive" - fetch primitive Cs and Os
"cache" - the color is retrieved from the radiosity cache. If an entry does not exist in the radiosity cache, diffuselighting will be run to fill the entry.
"filecache" - fetch results from the texture3d cache (note that this is the same behavior as using "cache" with the other ray tracing functions)
"hitsides" string Specifies which side(s) of one-sided surfaces can be hit by the rays. The possible values are "front", "back", and "both". The default is "both".
"importancethreshold" float Overrides the "trace" "importancethreshold" Attribute.
"importancecull" string Controls what happens to rays at or below importancethreshold. Current options are cutoff and roulette. With cutoff, any low-importance rays are not fired. With roulette, the Russian roulette introduced in 16.2 is used to determine whether or not a low-importance ray will fire. The default value is roulette.

```public void diffuselighting(output color Ci, Oi);
public void specularlighting(output color Ci, Oi);
```
The material pipeline methods express the separation of view-independent and view-dependent lighting. View-independent lighting and opacity are cached in the radiosity cache in order to deliver speedups. The diffuselighting method also takes an optional Irradiance parameter, which is required for ray-traced subsurface scattering.

```void randomstrat( uniform float sampleoffset, uniform float nsamples,
output float[] samples );
void randomstrat( uniform float sampleoffset, uniform float nsamples,
output triple[] samples );
void randomstrat( uniform float sampleoffset, uniform float nsamples,
```

When invoked, randomstrat() will fill in a slice, from sampleoffset up to, but not including, sampleoffset + nsamples, of the samples array with stratified random numbers. If the array is variable length, it will automatically be resized to an appropriate capacity. With an array of floats, it generates 1D samples in [0, 1). For an array of triples, it generates 2D samples in [0, 1) x [0, 1) and zeros the third component. For an array of radiancesamples, the 2D samples will be placed in the direction field. If generating more than one sample, we stratify over the set of samples produced for each grid point. If generating only one sample, we stratify across REYES grids.

The choice and order of the parameters are intended to mirror the stdrsl_AreaSampler methods and generateSamplesAS/Env.

The RenderMan Shading Language provides four specialized sample-generating functions designed to interoperate with the directlighting() and indirectspecular() integrator functions.

```uniform float generateSamplesAS ( varying color weight;
uniform float nSamples;
varying  float exp1, exp2;
varying vector Nn;
varying vector Tn;
varying vector Vn;  // Vn.Nn > 0

uniform float evaluateSamplesAS ( varying color weight;
varying  float exp1, exp2;
varying vector Nn;
varying vector Tn;
varying vector Vn;  // Vn.Nn > 0
```
These functions generate and evaluate (respectively) the specular lobe of the Ashikhmin/Shirley BRDF. generateSamplesAS may return fewer samples than asked for in order to provide better stratification of those samples.
```uniform float generateSamplesEnv ( uniform string envMapName,
varying point P,
varying normal N,
uniform float nSamples,
```
This function generates the contributions of environment light sources. generateSamplesEnv may return fewer samples than asked for in order to provide better stratification of those samples. Note that, currently, support is provided for latlong environment maps only.
Optional Args
Name Default
"uniform string integrationdomain" "hemisphere | sphere" ("hemisphere")
"uniform string distribution" "importance | cosine | uniform" ("importance")
"uniform string environmentspace"
or
"uniform matrix environmentspace"
("")
"varying color scale" (1,1,1)

Starting with revision 17, the distribution "warp" is called "importance".

```uniform float evaluateSamplesEnv ( uniform string envMapName,
varying point P,
varying normal N,
```
This function evaluates the contributions of environment light sources. Note that, currently, support is provided for latlong environment maps only.
Optional Args
Name Default
"uniform string integrationdomain" "hemisphere | sphere" ("hemisphere")
"uniform string distribution" "filteredimportance | importance | cosine | uniform" ("filteredimportance")
"uniform string environmentspace"
or
"uniform matrix environmentspace"
("")
"varying color scale" (1,1,1)

Starting with revision 17, the distribution "warp" is called "importance".

The following utility functions are useful when modeling a BSDF as a composition of individual components, i.e., with multiple specular lobes. They are generally used with the sampling functions above.

```void accumulateMaterialResponse ( output __radiancesample samples[],
[varying color layerOpacity]);
```
When evaluating samples, sequential calls to, e.g., evaluateSamplesAS should be followed by accumulateMaterialResponse. The optional layerOpacity parameter allows you to specify a layer compositing weight, which is used to influence the MIS computations. When no layering is required, the layerOpacity value needn't be provided; this is equivalent to setting the value to color(1).
```void normalizeMaterialResponse ( output __radiancesample samples[],
uniform float nsamplesPerComponent[],
[varying color layerOpacities[])
```
Similarly, when generating samples each component should contribute samples to the result. Now, while there may be multiple calls to, e.g., generateSamplesAS, there must be a single call to normalizeMaterialResponse. We assume that each component may contribute a unique number of samples; this is represented in the nsamplesPerComponent array. The length of this array is equal to the number of components that contribute to the samples. Finally, as above, layerOpacities is an optional parameter which, if not provided, is equivalent to array of 1 and with a length equal to the length of nsamplesPerComponent.

### Texture Mapping Functions

Texture maps contain data that can be mapped onto the surface of a geometric primitive. The RenderMan Interface supports several types of texture access: basic texture maps (via texture), environment maps (via environment), shadow or z-buffer maps (via shadow), per-face texture maps (via ptexture), and 3D textures (point clouds and brick maps via texture3d). Texture maps are accessed using two-dimensional coordinates and return floats or colors. Environment maps are accessed using a direction and return floats or colors. Shadow maps are accessed using points and return floats. Per-face textures are accessed using two-dimensional coordinates on the face of a surface and return floats or colors. 3D textures are accessed using points and directions and return arbitrary baked data.

For two-dimensional access (texture), the texture coordinates default to the texture coordinates attached to the surface, (s,t). These default texture coordinates are equal to the surface parameters, the current texture coordinates, or the texture coordinates passed with the geometric primitive. Texture coordinates can also be computed in RSL. This generality allows for many different types of coordinate mappings. Images stored in various map projections can be accessed by computing the map projection given a point on a sphere. This allows basic texture maps to be used as environment maps. Images can also be mapped onto surfaces using a two-step process. First the surface of the geometric primitive is mapped to the surface of a parametric primitive, such as a plane or cylinder, and then the parameters of this primitive are used as the texture coordinates. This is sometimes called a decal projection.

For three-dimensional access (environment, shadow, texture3d), the texture coordinates must always be explicitly specified.

There is no restriction on how texture map values are used in RSL. For example, displacement mapping can be performed by moving a point on the surface in the direction of the normal by the amount returned by a basic texture map. Transparency mapping differs from color mapping only in which variable, either Os or Cs, the texture is assigned to. There is also, in principle, no limit on the number of texture accesses per shader or the number of texture maps per shader or per frame.

Texture maps are created in advance from image data via three types of MakeTexture procedures that are defined as part of the RenderMan Interface. These are described in Part I in the section on Texture Map Utilities. RiMakeTexture creates a texture map for access via texture. RiMakeCubeFaceEnvironment and RiMakeLatLongEnvironment create an environment map for access via environment. RiMakeShadow creates a shadow map for access via shadow. A texture file may contain several channels of information and have any horizontal or vertical resolution. This information is normally inherited from the image from which the texture is made. The s coordinate is assigned to the horizontal direction with increasing values moving right. The t coordinate is assigned to the vertical direction with increasing values moving down. These coordinates are normalized to lie in the range 0 to 1 so that changing the resolution of the texture map has no effect on the shaders that access the texture map. When a texture map is created, the wrap mode is also specified. The wrap mode controls what values are returned if the texture coordinates fall outside the unit square. Allowed wrap modes are: periodic, black, and clamp. periodic causes the texture data to tile the plane, black causes accesses outside the unit square to return the value 0, and clamp causes the texture coordinates to be clamped to the closest point on the unit square and the texture value associated with that point to be returned.

The texture access functions normally pass the texture map through a low-pass filter to prevent aliasing. If one set of texture coordinates is given to the access function, the texture will be filtered over the area of the surface element being shaded (see the Shading Rate section of the RenderMan Interface Graphics State documentation). Four sets of texture coordinates can also be given to the access procedure, in which case the texture is filtered over the quadrilateral determined by those four points. The quality of texture antialiasing is controlled in the same way as spatial antialiasing. Parameters control how true the answer is, the effective number of samples used before filtering, and the type and width of the filter used. For this to be done properly (since texture maps are normally pre-filtered), these filtering parameters are best given to the appropriate RiMake... procedure. For flexibility, however, they can also be changed at access time. The table below gives the standard parameters to all the texture access functions; particular implementations may have additional parameters. If a parameter is encountered by an implementation that does not support its functionality, it should be ignored.

Texture Access Parameters
Name Type Description
"blur" varying float Specifies an additional area to be added to the texture area filtered in both the s and t directions, expressed in units of texture coordinates.  A value of 1.0 would request that the entire texture file be blurred into the result.  A value of 0.001 would request that one extra texture pixel be added in the case of a one-thousand by one-thousand texture file.
"sblur" varying float Specifies "blur" individually in the s direction.
"tblur" varying float Specifies "blur" individually in the t direction.
"width" uniform float This value multiplies the width of the area being filtered over both the s and t directions.  A value of 0 effectively turns off texture antialiasing.  The default value is 1.0.
"swidth" uniform float Specifies "width" individually in the s direction.
"twidth" uniform float Specifies "width" individually in the t direction.
"filter" uniform string Specifies the name of the filter to use for filtering over an area of the texture.  The default is "box".  Individual implementations may allow additional filters.
"fill" uniform float Specifies the value to be provided for channels requested that are not present in the texture file.  This is most often useful for a shader that knows how to use a texture containing an alpha channel.  If no alpha channel is present in the texture file, the texture system quietly provides a default value of 0.0 to requests for the alpha value resulting in a completely transparent texture.  Such a shader could provide its own "fill" value of 1.0 so that textures without an alpha channel would be opaque by default.
channelName uniform string OpenEXR images that contain arbitrary channels with names other than "R", "G", "B", "A", or "Z" must be accessed by channel name with the texture(), shadow() or enviroment() calls. To access arbitrary channel names, the additional parameter "channelName", "nameOfChannel" can be used. Only the first three channel name parameters will be used for a lookup into a color value and only the first channel name will be used for a lookup into a float value.

#### Basic Texture Maps

Basic texture maps return either floats or colors.

```float texture( string name[channel]; [texture coordinates;] [parameterlist] )
color texture( string name[channel]; [texture coordinates;] [parameterlist] )
```

where texture coordinates is one of the following:

```float s, t;
float s1,t1, s2,t2, s3,t3, s4,t4;
filterregion FR;
```

Return the filtered texture value. The cast before the function determines the type returned, either a float or a color. The name is the name of the texture map created using RiMakeTexture. The channel selector is optional; if it is not present, the brackets are also omitted and channel 0 is assumed. channel selects the starting channel in the texture. The number of channels returned depends on whether the texture is interpreted as a float or a color. Specifying texture coordinates is also optional. If present they consist either of a single 2D coordinate, or four 2D coordinates, or a filter region. If no texture coordinates are given, the current values of (s,t) are used. parameterlist is a list of name-value pairs that allow greater control over texture access.

Texture maps will always be available in implementations that support the RenderMan Shading Language, and may also be available in the implementation-dependent predefined shaders provided by a rendering system that does not support the Shading Language.

Some examples of the use of this function are:

```c = texture ( "logo" [0] );
c = color texture ( "logo" );
c = color texture ( "logo", 2*s, 4*t );
```

In the first two cases, the texture coordinates are the current values of the predefined variables (s,t).

The table below lists the optional filters that are supported by the texture() function.

Name Description
"box" This is the default filter if not specified.
"disk" Optimized for large blur sizes, and (unlike the other filters) is free of mipmap artifacts because it uses all mipmap levels in its computations; it is about twice as expensive as the other filters.
"gaussian" "gaussian" should produce higher quality results.
"lagrangian" The Lagrangian filter is designed from the ground up for speed and sharpness. Texture files with MIP map pyramids are required, and full pyramids are recommended. For each sample, the system selects the next highest resolution image plane and performs a 4x4 bicubic interpolation combined with a 4x4 decimation filter in one pass. The result is equivalent to a point sample of an exactly rescaled and subpixel-shifted image.
"radial-bspline" Specifically designed for optimally filtering displacement textures.
"ewa" The elliptical weighted average filter uses an elliptical region in S-T space to filter textures. The ellipse may be specified explicitly using the four-point invocation of the texture() call, where the four points define the convex hull of the ellipse. The order of the four S-T points does not matter.
Additionally, texture() supports an optional "lerp" argument, which selects whether to interpolate between adjacent resolutions of a multi-resolution texture in order to smooth the transition between resolutions. "lerp" takes a uniform float value; possible values are 0.0 to disable the interpolation and 1.0 to enable it. The default is 0.0 (i.e. don't interpolate).

#### Environment Maps

```float environment( string name[channel]; [texture coordinates;] [parameterlist] )
color environment( string name[channel]; [texture coordinates;] [parameterlist] )
```

where texture coordinates is one of the following:

```vector R;
vector R1, R2, R3, R4;
filterregion FR;
```

Return the filtered texture value from an environment map. The cast before the function determines the type returned, either a float or a color. The name is the name of the texture map created using RiMake...Environment. The channel selector is optional; if it is not present, the brackets are also omitted and channel 0 is assumed. channel selects the starting channel in the texture. The number of channels returned depends on whether the texture is interpreted as a float or a color. This function expects either a single texture coordinate or four texture coordinates or a filter region. These are points that are used to define a direction in space. The length of this vector is unimportant. parameterlist is a list of name-value pairs that allow greater control over texture access.

If a particular implementation does not support the environment mapping capability, environment will always return (0,0,0) (no illumination).

##### Ray-Traced Environments

The environment call usually looks up reflection colors in a previously rendered environment map. Starting with release 11.0, it can alternatively trace rays to reflections. This functionality overlaps signficantly with the trace and gather calls, but is provided so that existing shaders that make environment calls can continue to be used. Ray tracing will be used when the special keyword "raytrace" is provided as the environment map name.

For example, a surface source shader might contain a line like this:

```color e = environment("raytrace", dir);
```

Since the environment map name is usually passed in as a shader parameter from the RIB file, many existing surface source shaders can be used for ray tracing just by supplying "raytrace" as the map name from the RIB file, without even needing to recompile the shader.

Note that environment rays will only intersect objects that have their trace visibility enabled. This attribute controls whether environment, gather, and trace rays can see particular primitives, which is similar to including or excluding particular objects from the environment map generation pass when using the traditional map-based environment call.

When the function return value is assigned to a float, rather than a color, then environment returns occlusion, which is the fraction of rays that hit something; when samples=1 then the result will be either 0 or 1, when samples > 1 then the result will be fractional.

Optional environment() Parameters
Name Type Description
"bias" float a bias value for ray origins, to prevent self-intersection. If not provided, the "trace" "bias" Attribute is used.
"autobias" string controls whether ray tracing bias is automatically computed. Valid settings are "on" (the default) and "off".
"blur" float controls the samplecone of the underlying trace call.
"maxdist" float limits the distance from P in which ray hits can occur, defaults to RI_INFINITY.
"samples" uniform float controls the samples of the underlying trace call.
"subset" string A trace set to consider for ray intersections. Only objects that are members of the named groups will be visible to the traced rays. Sets are defined with Attribute "grouping" "membership".
"excludesubset" string Objects that are members of the named groups will not be visible to the traced rays.
"label" string labels can be queried in shaders executed as the result of a ray hit.
environment() Output Parameters
Name Type Description
"occlusion" output varying float returns the alpha value of the environment map or the coverage of the underlying trace call.
"opacity" output varying color returns the opacity of the environment or the underlying trace call.

#### Per-face Texture Maps

Per-face texture maps (or ptexture) return either floats or colors.

```float ptexture( string name; float channel, faceindex; [filter region;] [parameterlist] )
color ptexture( string name; float channel, faceindex; [filter region;] [parameterlist] )
```
Return the filtered ptexture value. The cast before the function determines the type returned, either a float or a color. The name is the name of the ptexture map. The channel selector is required. channel selects the starting channel in the texture. The number of channels returned depends on whether the texture is interpreted as a float or a color. The filter region is optional. If no filter region is given, a default filter region will be used. parameterlist is a list of name-value pairs that allow greater control over texture access.
Optional Parameters
Name Type Description
"blur" varying float Just like texture, specifies an additional area to be added to the texture area being filtered.
"width" uniform float Just like texture, specifies the multiplier of the width of the area being filtered over.
"lerp" uniform float Just like texture, selects whether to interpolate between adjacent resolutions in the multi-resolution texture, resulting in smoother transitions between levels. The default value of 0, disables interpolation, and 1 enables interpolation.
"filter" uniform string Just like texture, selects different reconstruction filters that can be used during texture lookup. The filters available for ptexture are: point, bilinear, box, gaussian, bspline, catmull-rom, and mitchell.

#### Texture Atlases

Texture Atlases return colors or floats. At this time, PRMan supports either Mari- or Mudbox-formatted texture atlases.

```float textureatlas( string atlas; string style; [texture coordinates;] [parameterlist] )
color textureatlas( string atlas; string style; [texture coordinates;] [parameterlist] )
```

The textureatlas() function can be used to look up textures implied by an atlas. atlas is a string filename reference with a special character pattern, "_MAPID_", which is replaced by filterregion-origin-dependendent information to produce the unique filename associated with that region of u-v space. style can be either "mari" or "mudbox", and texture coordinates are varying floats s and t.

The Optional Parameters below are equivalent to the standard texture access parameters, unless otherwise noted.

Optional Parameters
Name Type Description
"width" uniform float Specifies a multiplier for the width of the texture area filtered in both the s and t directions. Uniform values less than one should help to alleviate seams that may be exacerbated by soft filtering.
"fill" uniform color or float Specifies the value to be provided for channels requested that are not present in the texture file.
"filter" uniform string Specifies the name of the filter to use for filtering over an area of the texture.  The default is "gaussian". "disk" and "lagrangian" are not supported.
"usefilterregions" uniform float Specifies whether filtering is performed with the higher quality/more expensive filterregion method. When set to 0, the traditional, simple mechanism is used. When not set (or set to -1), filterregions are disabled for ray depths greater than 1.
"linearize" uniform float Set to 1 to convert 8 & 16 bit textures from srgb to linear rgb. Alpha is not affected by this setting. The default, 0, if off.
"alpha" varying float Filled with the alpha channel of the map, if present; set to 1 if the map has no alpha.
"sparse" uniform float A value of 1 signals that the atlas is "sparse", and will prevent non-existing files from producing errors or warnings.

#### 3D Texture Maps: Point Cloud Files and Brick Maps

Point cloud files are volumetric files containing 3D point samples of arbitrary data. Point cloud files are generated with the bake3d() function.

```float bake3d( string filename; string displaychannels; point P; normal N; [parameterlist] )
```
writes a point with associated data to the (unorganized) point cloud file given by filename. The return value indicates the success or failure of the write.
Required Parameters
Name Type Description
"filename" string the file name to which the 3D points are written. (If the optional parameter cachelifetime is "frame" or "shadinggrid", this parameter is a cache name instead of a file name.)
"displaychannels" string a string consisting of a comma-separated list of channel names. Each channel type must be specified in the RIB file with the DisplayChannel statement. Only those channel names listed in displaychannels will be written to file, so one can select a subset of potential data to be written by manipulating the displaychannels string. Note that displaychannels is ignored if the optional parameter cachelifetime is "frame" or "shadinggrid".
"P" point Describes the location for which the data were computed.
"N" normal Describes the surface orientation for which the data were computed.
Optional Parameters
Name Type Description
"radius" float The radius specifies the size of the area that the data point represents. If no radius is specified, one will be automatically computed from the distance to the nearest shading points.
"coordsystem" uniform string|matrix Specifies the name of the coordinate system to store the data points in, or a transformation matrix to transform P and N by. By default the world coordinate system is used. Passing the string "_disable" or a unit matrix turns transformation off.
"cachelifetime" string Specifies the lifetime of the cache. "file" or "" (the default) means that the data are streamed to a file via the display system. "frame" or "shadinggrid" means that the data are written to a cache of that lifetime.
"interpolate" float Point positions, normals, radii, and data are interpolated from four shading points when this parameter is set. This means that micropolygon midpoints are baked out instead of the exact shading points. This is great for many applications because it eliminates the double shading points along edges of shading grids. This behavior is probably only useful if the P points passed to bake3d() are the original shading point positions. This parameter is off by default (but recommended for tasks such as baking direct illumination for subsurface scattering).
"driver" string The name of the driver used to write the point information to disk. Depending on the implementation, there may be a choice of drivers supplied that support different on-disk representations of the baked data. Note that there is no guarantee that texture3d will support the data written by an arbitrary driver.
Data
Name Description
name, value Pairs of the name and values of the data to be stored. The data can be of type float, point, vector, normal, color, matrix, or arrays of those types. Only names listed in displaychannels will be written out.

3D textures are read with the texture3d function. The 3D texture can be a point cloud, an organized point cloud, or a brick map. Each file format has its advantages regarding memory use, filtering quality, and accuracy near tiny geometric details.

Unorganized point clouds are generated with bake3d() calls. Organized point clouds are generated from unorganized point clouds using the ptfilter program. Brick maps can be created from point clouds using the brickmake program or via the RiMakeBrickMap and MakeBrickMap procedures that are defined as part of the RenderMan Interface. They are described in the Texture Map Utilities documentation.

Unorganized point clouds are read in in their entirety at the first texture3D() call, even if only a few points are needed for that call, so large unorganized point clouds use a lot of memory. For organized point clouds the points and octree nodes are read on demand and cached, so they use a fixed amount of memory. Brick maps are also cached and use a fixed amount of memory, and have the further advantage that, since they are a MIP map representation, they have good filtering properties.

```float texture3d( string filename; point P; normal N; [parameterlist] )
float texture3d( string filenames[]; point P; normal N; [parameterlist] )
```
Reads texture values from the point cloud, organized point cloud, or brick map file given by filename[s]. The function return value is 1 if the read was successful, and 0 if it failed.
Required Parameters
Name Type Description
"filename" string The file name to read the 3D texture values from. (If the optional parameter cachelifetime is "frame" or "shadinggrid", this parameter is a cache name instead of a file name.)
"filenames" string A list of file names to read the 3D texture values from. If a list of point cloud files is provided, the lookup result will be the same as if all the points were in a single file. The data names and types in all point cloud files in a list must be in the same order. If a list of brick maps is provided, the lookups will be done in the the listed order and the result is the first successful brick map lookup.
"P" point the location for the 3D texture lookup.
"N" normal the surface orientation for the 3D texture lookup.
Optional Parameters
Name Type Description
"filterradius" float The radius of the disk/sphere that the lookup covers. Only for brick maps. If no radius is specified, one will be automatically computed from the distance to the nearest shading points. If set to 0, the voxel data are not interpolated; instead, we just use the data values of the finest voxel that point P is in.
"filterscale" float A multiplier on filterradius. Default is 1.
"maxdepth" float Maximum depth for lookup. Only for brick maps. (Great for debugging, especially when used with filterradius 0.)
"maxdist" float Maximum distance for lookup in point cloud or brick map. When performing a lookup in a point cloud, data points that are further away than maxdist are ignored. Similarly for brick map lookups: if there are no voxels at the appropriate level (corresponding to maxdist) that overlap the lookup point/filterbox, no data are returned.
"lerp" float Only for brick maps. If lerp is set to 1: do two lookups in the brick map (at two different depths) and linearly interpolate the results. This makes the result a quadrilinear interpolation: trilinear interpolation in 3D space and a linear interpolation in the resolution. The default value is 0 (no lerp).
"coordsystem" uniform string|matrix The name of the coordinate system to lookup the texture values in, or a transformation matrix to transform P and N by. By default the world coordinate system is used. Passing the string "_disable" or a unit matrix turns transformation off.
"usepresence" float For volume brick maps with a "_presence" channel, we use the presence values to mix input data values with the data values found in the brick map. The "usepresence" parameter can be used to turn this mixing off. The valid values for "usepresence" are 0.0 and 1.0; the default value is 1.0, ie. mix if there is a "_presence" channel in the volume brick map.
"errorcode" float

A return value indicating what caused the texture3d() lookup to fail.

Meaning for brick maps:

• 0 = no error (success)
• 1 = file does not exist
• 2 = file is not a brick map file
• 5 = the requested data do not exist in the brick map
• 6 = lookup point P is outside the bounding box of the brick map
• 7 = lookup point P is farther than maxdist away from data with an acceptable normal
• 8 = there are no data at all in the brick map for the given normal
• 9 = there was a mismatch between the type of the channel being read and the data value type
• 10 = some other error

Meaning for point clouds:

• 0 = no error (success)
• 1 = file does not exist
• 6 = lookup point P is outside the bounding box of the point cloud
• 7 = lookup point P is farther than maxdist away from data with an acceptable normal (or the point cloud has no points in it)
• 9 = there was a mismatch between the type of the channel being read and the data value type
• 10 = some other error.

If the file is a point cloud file, the filterradius, filterscale, maxdepth, and lerp parameters are ignored, and no errorcode value is returned. (The coordsystem parameter is still used, though, and the function return value still indicates success or failure.)

Data
Name Description
name, value pairs of the name and values of the data to be looked up. The data can be float, point, vector, normal, color, matrix, or arrays of those types.

As of PRMan 15.0, the data values are no longer set to 0 if the texture3d() lookup failed; instead, the data values are left unchanged. If the brick map contains a "_presence" channel (with values between 0 and 1) the data values in regions with partial presence will be a mix between the voxel data values and the data values passed in the call to texture3d(). This means that if data values corresponding to empty space are passed to texture3d() the returned values will reflect how much of the filter region contains valid data.

Point data can be read with the getpoints() function. The points can be read from a point cloud or from a local cache on the shading grid, or from a cache for the entire frame - as determined by the "cachelifetime" parameter.

This function can be used to get e.g. the positions of all shading points in the shading grid that a point is on, or data from the nearest points in a point cloud (baked with bake3d()) for custom filtering, et cetera.

```float getpoints( string filename; filterregion frP; filterregion frN;
float maxpoints; [parameterlist] )
float getpoints( string filenames[]; filterregion frP; filterregion frN;
float maxpoints; [parameterlist] )
```
Reads point data from point cloud, frame cache, or grid cache. The function return value is the number of points found (0 if none were found).
Required Parameters
Name Type Description
"filename" string The file name to read the 3D texture values from. (If the optional parameter cachelifetime is "frame" or "shadinggrid", this parameter is a cache name instead of a file name.)
"filenames" string A list of file names to read the 3D texture values from. If a list of point cloud files is provided, the lookup result will be the same as if all the points were in a single file. The data names and types in all point cloud files in a list must be in the same order.
"frP" filterregion the location filterregion for the point lookup.
"frN" filterregion the surface orientation filterregion for the point lookup.
"maxpoints" float the maximum number of points to look for.
Optional Parameters
Name Type Description
"coordsystem(s)" string The name of the coordinate system the points are in, or a matrix, or an array (one for each point cloud file). If "", the 'world' coordinate system is used.
"sort" float should the points and output data be sorted by distance from the center of frP?
Data
Name Description
name, value pairs of the name and values of the data to be looked up. The data can be float, point, vector, normal, color, matrix, or arrays of those types. Special, predefined variable names: "_position", "_normal", and "_radius" which returns those data even if they haven't been explicitly written in the data points.

#### Photon maps

Photon maps are sparse volumetric files containing photons. Photon maps can be computed in many ways but usually contain photons that have been previously scattered (in a separate pass) through the same 3D world in which the accesses are made. Photons represent light that has been "forward traced" into the 3D world and hit a surface.

```color photonmap( string filename; point P; normal N; [parameterlist] )
```
Returns the result of a photonmap lookup at surface point P with surface normal N.
Parameters
Name Type Description
"lookuptype" uniform string

Either:

or:

"radiance" - looks up the radiance (after interacting with the surface BRDF). Not supported in PRMan release 12 and higher.

"estimator" uniform float Specifies the number of photons to consider when estimating the photon effect.

#### Getting Information about Texture Maps

```float textureinfo( string texturename, query; output type variable )
```
Returns data about a particular texture map, specified by the file name texturename.  The query specifies the piece of information that will be returned in variable.  If the query is known to the renderer and its type and storage class match that of variable, the named data will be written into variable and textureinfo() will return a value of 1.0.  If the data is unknown or the types do not match, variable will be unchanged and textureinfo() will return 0.0. Note that textureinfo data is always uniform, except in the case of fetching per-face information from a PTexture.  If variable is varying, the appropriate varying-to-uniform conversion will take place. The queries supported by textureinfo() are listed below.
Supported textureinfo() Queries
Name Type Description
"resolution" uniform float[2] The highest resolution of the texture map. For PTexture, requires "__faceindex" optional parameter and the data returned is varying. A resolution of 0x0 is returned if a "__faceindex" value is invalid.
"type" uniform string Returns the type of the texture map file: "texture", "ptexture", "shadow", "environment", "brickmap", or "pointcloud".
"width" uniform float Returns the width of the texture file.
"height" uniform float Returns the height of the texture file.
"pixelaspectratio" uniform float Returns the original aspect ratio of the source image used to generate the texture map. Not valid for environment or ptexture maps.
"channels" uniform float Returns the number of channels in the map.
"faces" uniform float Returns the number of faces in the ptexture file. Invalid for normal texture files.
"exists" uniform float If the texture does not exists the textureinfo() routine will return 0, otherwise 1.
"viewingmatrix" uniform matrix Returns a matrix that transforms points from "current" space to the "camera" space from which the texture was created. *
"projectionmatrix" uniform matrix Returns a matrix that transforms points from "current" space to a 2D coordinate system where x and y range from -1 to 1. *
"viewingmatrixinverse" uniform matrix Returns the inverse of the matrix that transforms points from "current" space to the "camera" space from which the texture was created. *
"projectionmatrixinverse" uniform matrix Returns the inverse of the matrix that transforms points from "current" space to a 2D coordinate system where x and y range from -1 to 1. *
"fileformat" string Returns the format of the file. Valid values are "deepshadow", "openexr", "pixar", or "tiff".
"islatlong" int Returns an int with 1 if the texture is a latlong texture.
• Note:

Parameters marked with an asterisk are only available for shadow maps or other textures that were created by rendering an image, and assume a common world-space of all cameras.

The exists option can be used to query whether a texture map is actually present, with the shadeop itself returning 1 if the texture exists or 0 otherwise. The variable passed in as the third argument will be ignored.

```float dummy = 0;
if (textureinfo(texturename, "exists", dummy)) {
Ci = texture(texturename);
} else {
Ci = color(1, 0, 0); /* Mark color as red if texture map is missing */
}
```

The pixelaspectratio returns a float, which is the original aspect ratio of the source image used to generate the texture map (useful because a resize operation is often involved when creating the texture map). This lookup does not work on environment maps.

Optional textureinfo() Parameters
Name Type Description
"__faceindex" varying float For a PTexture, this provides the face-index to use for looking up per-face information.

#### Ray Differentials and Texture Filter Sizes

```void raydifferentials( output vector a, b, c )
```

raydifferentials computes three ray differentials. For ray hits on surfaces, a and b are the ray differentials at the hit point (projected so they are perpendicular to the ray direction I), and c is (0,0,0). For ray hits in volumes, a and b are as above, and c is the vector between the grid point and the next grid point along I.

For REYES surface grid points, a is constructed perpendicular to the x axis, and b perpendicular to the y axis (in camera space), and then projected to be perpendicular to I. The lengths of a and b are determined by the pixel size at the point's depth, adjusted by the shading rate and taking the pixel aspect ratio into account. c is (0,0,0) for REYES surface grids.

For REYES volumetric grids, a and b are constructed as above, while c is parallel to I, with length corresponding to the depth shading rate.

The raydifferentials function does not return a value. The ray differentials are independent of the surface parameterization, and are useful for, e.g., EWA texture filtering.

Shadow depth maps are z-buffer images as seen from a particular view point. Normally a shadow map is associated with a light source and represents a depth buffer rendered from the point of view of the light source. The texture coordinate of a shadow map is a point. The value returned is the fraction of points on the shaded surface that are farther from the light than the surface recorded in the depth map. A value of 1 indicates that the surface is completely in shadow and a value of 0 indicates that the surface is completely illuminated by the light source.

```float shadow( string name[channel]; [texture coordinates;] [parameterlist] )
color shadow( string name[channel]; [texture coordinates;] [parameterlist] )
```

where texture coordinates is one of the following:

```point P;
point P1, P2, P3, P4;
filterregion FR;
```

Return the shadow value from a shadow depth map. The name is the name of the texture map created using RiMakeShadow. The channel selector is optional; if it is not present, the brackets are also omitted and channel 0 is assumed. channel selects the starting channel in the texture. texture coordinates are points in the coordinate system in which the depth map was created, or a filter region. parameterlist is a list of name-value pairs that allow greater control over texture access.

Name Type Description
"bias" float a bias value for ray origins, to prevent self-intersection. If not provided, the "trace" "bias" Attribute is used.
"usemotionbias" string controls application of ray origin compensation for motion when Attribute "trace" "int samplemotion" is set. This compensation offsets the ray origins by t * dPdtime for each ray. Valid settings are "auto", "on", and "off". The default is "auto" which preserves the behavior of version 16.0. This compensates only when the origin == P. Setting "on" always applies compensation, "off" never applies it.
"autobias" string controls whether ray tracing bias is automatically computed. Valid settings are "on" (the default) and "off".
"blur" varying float Specifies an additional area to be added to the texture area filtered in both the s and t directions, expressed in units of texture coordinates. A value of 1.0 would request that the entire texture file be blurred into the result.  A value of 0.001 would request that one extra texture pixel be added in the case of a one-thousand by one-thousand texture file.
"sblur" varying float Specifies "blur" individually in the s direction.
"tblur" varying float Specifies "blur" individually in the t direction.
"width" uniform float This value multiplies the width of the area being filtered over both the s and t directions.  A value of 0 effectively turns off texture antialiasing.  The default value is 1.0.
"swidth" uniform float Specifies "width" individually in the s direction.
"twidth" uniform float Specifies "width" individually in the t direction.
"samples" uniform float The effective sampling rate when filtering.
"filter" uniform string Specifies the name of the filter to use for filtering over an area of the texture.  The default is "box".  Individual implementations may allow additional filters.
"subset" string A trace set to consider for ray intersections. Only objects that are members of the named groups will be visible to the traced rays. Sets are defined with Attribute "grouping" "membership".
"excludesubset" string Objects that are members of the named groups will not be visible to the traced rays.

The enhanced shadow call is fully backwards-compatible with the Specification, but supports a new form to allow specification of multiple shadow maps in a single call:

```float shadow(string maplist; texture coordinates; [parameterlist])
```

where maplist is a comma-separated list of shadowmap filenames.

In the past, the location of the point light source (as far as shadows were concerned) was implicit in the shadow map matrices. When using multiple maps to simulate an area light source, the user must also specify the size and shape of the intended light source in the shadow shadeop. The following new parameters to shadow support this new soft shadow method:

• "source", which takes one, two, three, or four uniform point values. These points determine the location and shape of the simulated area light source used in the soft shadow calculations, and specify a point, line segment, triangle, or quadrilateral, respectively.
• "gapbias", which takes a uniform float. Gap bias indicates how close (in z) two adjacent map pixels must be to be considered connected. This permits the renderer to identify when two objects in the map are touching and when they are separated by a tiny gap. Similar to normal shadow bias, the gap bias must be tuned based on the map resolution and scene complexity. (Gap bias values will usually be very close to the shadow bias values.)

The old parameters "bias" and "samples" still apply when using the new soft-shadow form:

• "bias", which takes a uniform float, specifies how far (in world space) to shift surface sample locations toward the light to prevent self-shadowing on the surface.
• "samples", which also takes a uniform float, when used with the multi-map form of shadow, specifies how many visibility samples are to be cast between each surface element and the light source. A larger number of samples reduces shadow noise and improves picture quality, but is proportionally more expensive to execute.

This new method of generating soft shadows requires multiple shadow maps to infer geometry between the surface being shaded and the light source. For best results, the views should be placed on or near the light source, pointing in the direction of the objects that will cast shadows. All views should fully contain the shadowing objects, although they will contribute slightly different information (due to their differing viewpoints). Specifying more views gives the renderer more information to work with, and thus can improve the quality of the shadows rendered. However, too many views can be unnecessarily expensive, so caution is advised. For most scenes, three to five shadow maps will be sufficient to capture the geometry sufficiently.

An example of the soft-shadow form of shadow, using four shadow maps and a triangular light source would be:

```attenuation = shadow("view1.shad,view2.shad,view3.shad,view4.shad", Ps, "source",
Pl1, Pl2, Pl3, "gapbias", 0.0015, "bias", 0.001);
```

• Better antialiasing of shadows, since multiple PixelSamples are taken into account when computing the answer for a single pixel;
• Shadows work for semi-transparent objects, including objects which should cast colored shadows;
• Limited cases of motion-blurred shadows are possible.

Creation of these new shadow files is achieved with a new display driver, deepshad.

Support for multiple subimages was added in 16.0, allowing a render to store additional outputs in a single deep texture file. To access data from these subimages, add one or more pairs of parameters in the form "get:subimagename", outvar to the parameter list. These lookups will be performed in addition to the lookup from the primary subimage and will use the same coordinates and filtering parameters.

Currently, the only way to access deep texture maps is through the shadow() shadeop.

The shadow call can also trace rays to compute whether a surface point is in shadow or not, as an alternative to using shadow maps. This functionality was added in release 11.0. Ray tracing is used when the special keyword "raytrace" is supplied as the "shadow map" name. For example, a light source shader might contain a line like this:

```attenuation = shadow("raytrace", Ps, "samples", samples);
```

Since the shadow map name is usually passed in as a shader parameter from the RIB file, many light source shaders can be used for ray tracing just by supplying "raytrace" as the map name, without even needing to recompile the shader. However, because ray traced shadow blur and other parameters can add new effects, most people will probably want to write new shaders.

• Note:

The transmission() function provides a direct interface to ray-traced shadow determination, with additional capabilities and options.

Note that shadow rays will only intersect objects that have their transmission visibility enabled. This attribute controls whether shadow and transmission rays can see particular primitives, which is similar to including or excluding particular objects from the shadow map generation pass when using the traditional map-based shadow call.

Ray-traced shadows can be used to obtain colored shadows from semi-transparent objects. These colored results are obtained by assigning the results of the shadow call to a color rather than the typical float; this is similar to the deep shadow behavior described above.

The ray tracing version of shadow() accepts most of the common ray tracing function parameters, plus the following:

Name Type Description
"blur" float
controls the ray traced shadow blurriness.
Units are radians, describing the half-angle of the sample cone. The effect is similar to sampling a spherical light source of finite size. You should almost always increase the number of samples as the blur cone increases to reduce noise.
"samples" uniform float causes supersampling of the underlying transmission function.

```varying color areashadow ( mapnames; point P | filterregion from;
lightsamples[]; [parameterlist]  )
( mapnames; point P | filterregion from;
lightsamples[];
output varying color perRayTransmission[]; [parameterlist]  )
( mapnames; point P | filterregion from;
lightsamples[];
output varying color perRayTransmission[];
output varying vector perRayL[];
output varying float perRayLLength[]; [parameterlist]  )
```

areashadow returns a color representing the ability of light to flow between from and the selection of samples embodied in the array lightsamples.

The map specified by the mapnames parameter is a traceable deep shadow map generated using the areashadow deep method (see below). Typically, mapnames will either be a single string (potentially empty) or an array of strings. from can be a point or a filter region: if called from a surface shader, P or filterregion(P); if called from a light shader, Ps or filterregion(Ps).

lightsamples represents sampled positions on an area light source and will be either an array of __radiancesamples or an array of points. If lightsamples is provided as __radiancesample, it is both an input and an ouput, you must fill in the radiance, lightPdf, materialResponse, and accumulatedMaterialResponse fields. If areashadow is invoked at the behest of the directlighting integrator, all of these fields will already have been set. On return, the lightVisibility field represents the per-ray transmission values.

If lightsamples is provided as an array of points, the return values are provided in the array perRayTransmission[] and can also optionally return values in the perRayL[] and perRayLLength[] arrays.

If areashadow()'s raytrace parameter is set to 1, rather than tracing a map (or maps) the map name (or map array) may be blank and ray-traced shadowing will be performed instead.

areashadow() supports the common ray tracing function parameters (except as noted), as well as the following:

Name Type Description

When enabled, adaptively samples the shadow function, using fewer samples in regions of low variance. The possible values/settings are:

0 = off
1 = conservative
2 = aggressive
"bias" float a bias value for ray origins, to prevent self-intersection. If not provided, the "trace" "bias" Attribute is used.
"autobias" string controls whether ray tracing bias is automatically computed. Valid settings are "on" (the default) and "off".
"mapbias" uniform float Scales an automatically computed bias value when tracing maps. For each ray, areashadow() will choose a map from mapnames to use. Then it will estimate an appropriate bias based on the map parameters and distance of the from point from the shadow map camera. In most cases the default value of 1 for mapbias should be appropriate.
"mapbias2" uniform float Helps to control light leaks. With values above 0, each texel traversed in the shadow map will contribute to the total shadowing using a slightly broader depth interval. This can mitigate cases of rays aliasing against geometry seen obliquely from the shadow map camera. Typical values are 1 to 5.
"usemotionbias" string controls application of ray origin compensation for motion when Attribute "trace" "int samplemotion" is set. This compensation offsets the ray origins by t * dPdtime for each ray. Valid settings are "auto", "on", and "off". The default is "auto" which preserves the behavior of version 16.0. This compensates only when the origin == P. Setting "on" always applies compensation, "off" never applies it.
"subset" string A trace set to consider for ray intersections. Only objects that are members of the named groups will be visible to the traced rays. Sets are defined with Attribute "grouping" "membership".
"excludesubset" string Objects that are members of the named groups will not be visible to the traced rays.
"hitmode" uniform string Specifies how the opacity should be computed at shadow ray hit points. If the value is "default", the opacity is determined as specified by the hit object's "shade" "transmissionhitmode" attribute. If the value is "primitive", the opacity is copied from the object's Os vertex variable or Opacity attributes. If the value is "cache", the opacity is found by looking up in a point cloud or brick map, as specified with Attribute "shade" "transmissionhitcache" "file:..." and Attribute "shade" "diffusehitopacitychannel" "...". If the value is "shader", the shader is evaluated to get the color and opacity. In "primitive" or "shader" mode, if the opacity is less than othreshold, a continuation ray will be fired. In "default" mode, if no attribute "shade" "transmissionhitmode" is defined, the opacity will be considered 1. This is only relevant if raytrace is set to 1; map-based lookups always compute opacity using data stored in the deep shadow.
"hitsides" string Specifies which side(s) of one-sided surfaces can be hit by the rays. The possible values are "front", "back", and "both". The default is "both".
"raytrace" uniform float Enables ray tracing. If mapnames is not empty, tracing will be performed in addition to the map query. If mapnames is empty, only ray tracing will be performed.
"weight" varying float Controls the culling of rays and is often available as a side-effect of importance sampling. When a weight value is near zero it will prevent the associated ray (at a given shading point and sample-index) from firing.
"weightthreshold" uniform float If "weight" (above) is at or less than "weightthreshold," no ray will be fired.
"maxdist" float limits the distance from P in which ray hits can occur, defaults to RI_INFINITY.
"falloff" float Determines the shadowing falloff with distance. The default falloff value of 0 disables shadowing falloff. The rate of falloff is set by the falloffmode parameter.
"falloffmode" uniform float Chooses between two types of distance falloff. Set to 0 (the default), the shadow has exponential falloff, exp(-falloff * dist); set to 1, the shadow has a power falloff, (1 - dist / maxdist)^falloff.
"falloffstart" float Sets the distance beyond which falloff has and effect, if enabled. Normal shadowing is applied from the source up to falloffstart. In the region between "falloffstart" and the light position (or maxdist), mode 0 falloff is computed as exp(-falloff * (dist - start)) and mode 1 falloff is computed as (1 - (dist - start) / (maxdist - start))^falloff. The default falloffstart value of 0 applies falloff to the entire region between the shadowed point and light samples. Note: higher values of falloffstart will result in better performance by limiting the range where the falloff curve is applied to shadowing.
"pdf" varying float[] Controls the angular spread of the ray, which is used to select tesselation levels for ray tracing. If pdf is passed it will be multiplied, internally, by the number of non-zero pdf values per grid point.
"premultpdf" varying float[] Controls the angular spread of the ray, which is used to select tesselation levels for ray tracing. If premultpdf is passed it is assumed that the value does not need to be multiplied by the number of non-zero pdf values per grid point, as above.
• Tip:

Generating a traceable deep shadow is typically done with the following RIB fragment:

```Option "limits" "color othreshold" [9 9 9]
# set how many opaque layers to record in the map
# specify deep shadow compression metric
Display "null" "null" "z"
# specify the output file using the areashadow method
Attribute "cull" "int backfacing" [0] "int hidden" [0]
# ensure all geometry is recorded in the map
```

### Shader and Message Passing Functions

```shader getlight( string handlename )
```

Returns the light or co-shader with the specified handle, or null if not found. For example, a co-shader can be declared in RIB by specifying the shader name, a handle name, and any desired parameter values:

```Shader "basic" "baselayer" "float Ks" [.5]
Shader "rust" "rustlayer" "float Ks" [0]
```

The surface method of the baselayer shader could then be called as follows:

```shader baselayer = getshader("baselayer");
if (baselayer != null)
baselayer->surface(Ci, Oi);
```

```shader[] getlights( ... )
```

Returns a variable-length array of the light shaders or the co-shaders that are active in the current attribute scope. If the parameter list is empty, all the active lights or co-shaders are returned. Otherwise the parameters must be name/value pairs that specify a subset of the results. Currently the only supported parameter is "category". For example, diffuse illumination can be implemented as follows:

```shader lights[] = getlights("category", "diffuse");
uniform float i, n = arraylength(lights);
for (i = 0; i < n; i += 1) {
vector L;
color Cl;
lights[i]->light(L, Cl);
C += Cl * max(0,Nn . normalize(-L));
}
```

```float getvar( shader shader; string name; [ output type variable ] )
```

Copies the value of the specified variable from the given shader into the output parameter, returning 1.0 if successful. Otherwise the output parameter is unchanged and getvar returns 0.0, which indicates that

• the given shader was null (e.g. an earlier call to getshader() failed); or
• the specified variable was not a parameter or public member variable of the given shader; or
• the type or detail of the specified variable did not match that of the output parameter.

For example:

```shader baselayer = getshader("baselayer");
float baseKd = 0;
getvar(baselayer, "Kd", baseKd);
```

The output parameter can be omitted, in which case getvar simply checks whether the specified variable exists. For convenience, the "arrow operator" can also be used instead of getvar:

```float baseKd = baselayer->Kd;
```

When this syntax is used, a warning is reported if the specified variable does not exist or does not have the expected type, in which case the arrow operator returns zero(s) (or the empty string, etc.)

```float hasmethod( shader shader; string methodname )
```

Returns 1.0 if the given shader defines a method with the specified name; otherwise it returns 0.0. Method calls employ the usual arrow operator syntax; for example:

```if ( hasmethod(surface, "GetBRDF") )
surface->GetBRDF( ... );
```

```shader surface;
```
These global variables provide access to the current surface shader and the current light. The current light can be used only within an illuminance loop.

```float atmosphere( string paramname; output type variable )
float displacement( string paramname; output type variable )
float lightsource( string paramname; output type variable )
float surface( string paramname; output type variable )
float incident( string paramname; output type variable )
float opposite( string paramname; output type variable )
```

These functions access the value of the parameter named paramname of one of the shaders attached to the geometric primitive that is currently being shaded. incident accesses values from the volume shader that describes the volume that contains the incident ray, Iopposite accesses values from the volume shader that describes the volume on the other side of the surface.  If the appropriate shader exists, and a parameter name paramname exists in that shader, and the parameter is the same type as variable, then the value of that parameter is stored in variable and the function returns 1.0; otherwise, variable is unchanged and the function returns 0.0.

Note that if the data corresponding to paramname is uniform, but the variable variable is varying, the appropriate uniform-to-varying conversion will take place. However, the reverse case is considered failure.

The lightsource function is only available inside illuminance blocks and refers to the light being examined by the current iteration.

It should be noted that, as of PRMan 14, these functions have been deprecated in favor of techniques available in RSL 2.0.

### Information Functions

```float attribute( string name, output type variable )
```

Returns data that is part of the primitive's attribute state, either from individual RenderMan Interface calls that set attributes or from the RiAttribute call.  The name specifies the piece of RenderMan Interface attribute state that will be returned in variable.  If the data name is known to the renderer and its type and storage class match that of variable, the named data will be written into variable and attribute() will return a value of 1.0.  If the data is unknown or the types do not match, variable will be unchanged and attribute() will return 0.0.

Note that if the data corresponding to paramname is uniform, but the variable variable is varying, the appropriate uniform-to-varying conversion will take place. However, the reverse case is considered failure.

The standard data names supported by attribute are listed below.  A particular implementation may support additional attribute queries.

attribute() Data Names
Name Type
"Sides" uniform float
"matte" uniform float
"GeometricApproximation:motionfactor" uniform float
"displacementbound:sphere" uniform float
"displacementbound:coordinatesystem" uniform string
"identifier:name" uniform string
• Note:

Note that "displacementbound:sphere" does not return the value exactly as specified in the RIB file, but rather returns its length in the coordinate system returned by "displacementbound:coordinatesystem".

The pieces of attribute state that can be retrieved via the attribute() function are:
Name Type Comment
"Matte" float
"Ri:Matte" float Same as Matte. This form is preferred.
"Sides"` float
"Ri:Sides" float Same as Sides. This form is preferred.
"Ri:Color" color
"Ri:Opacity" color
"Ri:DetailRange" float[4]
"Ri:TextureCoordinates" float[8]
"Ri:Orientation" string Either inside or outside
"Ri:ShadingInterpolation" string Either smooth or constant
"Ri:Transformation" matrix The object to world transformation
"cull:backfacing" float
"cull:hidden" float
"derivatives:centered" float
"derivatives:extrapolate" float
"dice:binary" float
"dice:hair" float
"dice:rasterorient" float
"dice:referencecamera" string
"displacementbound:sphere" float
"displacementbound:coordinatesystem" string
"grouping:membership" string The name of the trace group or an empty string if there is no group (NOTE: due to an optimization, this is not implemented for surfaces with a ray depth of zero).
"geometry:frontfacing" float Returns 1.0 if the geometry's normals are front-facing, 0.0 if the geometry has had its orientation reversed (normals flipped). Note that this supercedes "geometry:backfacing", which is still supported but not recommended.
"geometry:backfacing" float 1.0 if the geometry has had its orientation reversed (normals flipped), which may be due to various factors (negative determinant, orientation, or double shading). 0.0 otherwise. Note that the reverse - "geometry:frontfacing" - is preferred, due largely to the aforementioned factors.
"geometry:outside" float Returns 1.0 if a point is "outside", 0.0 otherwise. This attribute is explicitly varying, and allows one to consistently determine whether the point being shaded is intended to be used for the outside or inside of a surface. It works consistently whether or not ray tracing is being used, whether double-shading is used, or whether or not the current shading context is being used in a caching context. Moreover, it can be used without double-shading when the geometry is two-sided.
"GeometricApproximation:motionfactor" float
"identifier:name" string
"photon:estimator" float
"photon:globalmap" string
"photon:causticmap" string
"sides:backfacetolerance" float
"stitch:enable" float
"stitch:group" float
"stochastic:sigma" float
"trace:bias" float
"trace:decimationrate" float
"trace:displacements" float
"trace:maxspeculardepth" float
"trace:maxdiffusedepth" float
"trace:samplemotion" float
"user:myname" variable allows a shader to access a user defined attribute named myname, and requires a variable with type matching the RiDeclare declaration.
"visibility:camera" float
"visibility:diffuse" float
"visibility:specular" float
"visibility:transmission" float
"visibility:photon" float
```float option( string name; output type variable )
```

Returns data that is part of the renderer's global option state, either from individual RenderMan Interface calls that set options or from the RiOption call. The name parameter specifies the piece of RenderMan Interface option state that will be returned in variable.  If name is known to the renderer and its type and storage class match that of variable, the named data will be written into variable and option() will return a value of 1.0.  If the data is unknown or the types do not match, variable will be unchanged and option() will return 0.0. Note that option data is always uniform.  If variable is varying, the appropriate uniform-to-varying conversion will take place.

The standard data names supported by option are listed below.  A particular implementation may support additional option queries.

option() Data Names
Name Type Description
"Format" uniform float[3] The resolution (x, y) and pixel aspect ratio.
"DeviceResolution" uniform float[3] The resolution (x, y) and pixel aspect ratio.  These are usually the three numbers passed to RiFormat, but may be different when RiFrameAspectRatio or RiScreenWindow are non-square.
"FrameAspectRatio" uniform float Frame aspect ratio.
"CropWindow" uniform float[4] Boundaries of the crop window.
"DepthOfField" uniform float[3] fstop, focallength, focaldistance.
"Shutter" uniform float[2] Shutter open and close time.
"Hider" uniform string The name of the active hider.
"Clipping" uniform float[2] Near and far clip depths.
The pieces of option state that can be retrieved via the option() function are:
Name Type Comment
"BucketSize" float[2] returns the bucket size
"limits:bucketsize" float[2] Same as BucketSize. Preferred.
"limits:gridsize" float
"limits:texturememory" float
"limits:brickmemory" float
"limits:geocachememory" float
"limits:zthreshold" color
"limits:othreshold" color
"limits:extremedisplacement" float
"Clipping" float[2] See RiClipping
"Ri:Clipping" float[2] Same as Clipping. Preferred.
"CropWindow" float[4] See RiCropWindow
"Ri:CropWindow" float[4] Same as CropWindow. Preferred.
"curve:orienttotransform" float
"decimationrate" float
"DepthOfField" float[3] See RiDepthOfField
"Ri:DepthOfField" float[3] Same as DepthOfField. Preferred.
"DeviceResolution" float[3] Returns the resolution in x and y and the pixel aspect ratio. These are usually the three numbers passed to RiFormat, but may be different when FrameAspectRatio or ScreenWindow are non-square.
"Format" float[3] Returns the current resolution as specified in RiFormat.
"Ri:Format" float[3] Same as Format. Preferred.
"Frame" float Returns the current frame number as specified in RiFrameBegin
"Ri:FrameBegin" float Same as Frame. Preferred.
"FrameAspectRatio" float Returns the current frame aspect ratio.
"Ri:FrameAspectRatio" float Same as FrameAspectRatio. Preferred.
"hair:spatialgrouping" float
"Hider" string Returns the name of the current hider.
"RiHider:name" string Same as Hider. Preferred.
"RiHider:jitter" float
"RiHider:mpcache" float
"RiHider:mpmemory" float
"RiHider:mpcachedir" string
"RiHider:samplemotion" float
"RiHider:subpixel" float
"RiHider:maxvpdepth" float
"RiHider:zfile" string
"RiHider:reversesign" float
"RiHider:depthbias" float
"RiHider:emit" float
"RiHider:secondarycaustics" float
"RiHider:extrememotiondof" float
"RiHider:sigma" float
"RiHider:sigmablur" float
"RiHider:integrationmode" string
"RiHider:maxsamples" float
"render:rerendering" float
0 - not re-rendering
1 - REYES re-rendering
2 - ray-traced re-rendering
"Shutter" float[2] See RiShutter
"Ri:Shutter" float[2] Same as Shutter. Preferred.
"RiProjection:name" string
"RiProjection:fov" float
To recover:
float fov = degrees( 2 * atan(x));
"Ri:ScreenWindow" float[4] Returns the left, right, top, and bottom of the ScreenWindow, in that order
"searchpath:resource"
"searchpath:texture"
"searchpath:archive"
"searchpath:procedural"
string Returns the indicated searchpath.
"shutter:offset" float
"shutter:clampmotion" float
"statistics:endofframe" float Enable end-of-frame statistics.
"statistics:filename.xml" string The name of the statistics XML file.
"texture:enable gaussian" float
"texture:enable lerp" float
"trace:maxdepth" float
"user:myname"   Allows a shader to access a user defined option named myname, and requires a variable with type matching the RiDeclare declaration.

```uniform float rayinfo( uniform string keyword, result, ... )
```

Provides access to state associated with the ray that caused the current shader to execute. rayinfo fills in result with the current value associated with the query keyword(s). Returns 1 or 0 to indicate whether the query succeeded or not. For example:

```uniform float d=0;
success = rayinfo("depth", d);
if (d < 3) {
} else {
/* we're shading for the third or deeper reflection bounce
* so do something cheaper than usual
*/
}
```
Keywords
Name Type Description
"type" uniform string

returns the type of the ray that caused this shader to be invoked. These are built-in types, distinguished by fundamentally different handling of the ray within the renderer. Note that ray labels (next item) are used to associate user-defined names to rays. The current ray types returned are:

• camera
• light
• specular
• diffuse
• transmission
"label" uniform string returns the value of the user-defined label assigned to the incoming ray that caused this shader to be invoked. Labels are assigned via the "label" parameter to the gather(), transmission(), shadow(), environment(), etc. functions.
"depth" uniform float returns the current depth of the ray that caused this shader to be invoked. depth is the sum of speculardepth, diffusedepth, and shadowdepth. Depth is 0 for camera rays (i.e. standard REYES invocation).
"diffusedepth" uniform float returns the diffuse depth of the ray that caused this shader to be invoked.
"shadowdepth" uniform float returns the "shadow depth" of the ray that caused this shader to be invoked. Shadow depth is 1 if this is a shadow ray and 0 otherwise.
"speculardepth" uniform float returns the specular depth of the ray that caused this shader to be invoked.
"subsurfacedepth" uniform float returns the subsurface depth of the ray that caused the shader to be invoked.
"importance" color or float returns the importance of the incoming ray as an rgb value. The float version returns the maximum value of the r, g, and b importance. For more information, see the Importance of Importance application note.
"integrationcounter" uniform float returns the current iteration associated with the current integrator. Integrators the employ single-iteration implementations return 0. Converging integrators like path-tracing return a number greater than or equal to 0.
"integrationlod" uniform float returns the current level of decimation associated with the current integrator. Will be non-zero only during progressive-refinement rendering modes (re-rendering).
"origin" varying point returns the origin of the incoming ray, which is the same as (P - I).  Note: this query has been deprecated, shaders should use (P - I) directly.
"direction" varying vector returns the normalized incoming ray direction.  For camera rays, this is equivalent to I/|I|. Note: this query has been deprecated, shaders should use normalize(I) directly.
"length" varying float returns the length of the incoming ray, which is equivalent to |I|. Note: this query has been deprecated, shaders should use length(I) directly.

```float rendererinfo( string name; output type variable )
```
Returns data about the renderer itself.  The name parameter specifies the piece of information that will be returned in variable.  If name is known to the renderer and its type and storage class match that of variable, the named data will be written into variable and rendererinfo() will return a value of 1.0.  If the data is unknown or the types do not match, variable will be unchanged and rendererinfo() will return 0.0.  Note that renderer data is always uniform. If variable is varying, the appropriate uniform-to-varying conversion will take place.
rendererinfo() Data Names
Name Type Description
"renderer" uniform string The brand name of the renderer.
"version" uniform float[4] Major, minor, release and patch numbers.
"versionstring" uniform string The release numbers expressed as a string.

```uniform float shaderinfo( uniform string keyword, result )
```

Provides access to state associated with the currently executing shader. shaderinfo fills in result with the current value associated with the query keyword. Returns 1 or 0 to indicate whether the query succeeded or not. For example:

```uniform string s;
if (s == "lighting") {
/* specialize for lighting */
} else {
/* don't */
}
```
Keywords
Name Type Description
"pipelinestage" uniform string returns the pipeline stage as one of "diffuselighting", "displacement", "imager", "light", "lighting", "opacity", "postlighting", "prelighting", "refinement", "specularlighting", "surface", or "volume".
"lightingintent" uniform string returns information on which of the lighting methods the shading system wishes to invoke. The result may be "none", "diffuselighting", "specularlighting", or "lighting". Note that the method or methods actually called may differ depending on which ones actually exist on the shader. For example, if no lighting() method exists, PRMan can fall back to running diffuselighting() and specularlighting() in succession. The intent, however, would still be "lighting".

```string shadername()
```
If no parameter is passed, returns the name of the shader that is currently running.  If the shadertype is supplied, this function returns the name of the shader of the specified type that is bound to the geometric primitive that is being shaded.  Acceptable values of shadertype are "surface", "displacement", "atmosphere", "lightsource", "interior", "exterior".  If the surface being shaded does not have a shader bound to it that matches the type, this function will return the empty string ("").

### Debugging Functions

```void rbug( point | vector | normal dbgP )
void rbug( point | vector | normal dbgP, color dbgC )
void rbug( point | vector | normal dbgP, color dbgC, normal dbgN )

void rbug( point dbgP0, point dbgP1 )
void rbug( point dbgP0, point dbgP1, color dbgC )
void rbug( point dbgP0, point dbgP1, color dbgC, normal dbgN )
```
Spawns a debug window that will graphically plot the point dbgP or the line segment from dbgP0 to dbgP1. If a color dbgC is provided, that color will be used instead of white. If a dbgN is provided that will be plotted at the point dbgP as well.

### Appendix

#### Ray Tracing Function Parameters

The following optional parameters are common to all ray tracing functions (except trace and as noted for certain other functions):

Name Type Description
"bias" float

a bias value for ray origins, to prevent self-intersection. If not provided, the "trace" "bias" Attribute is used.

Not supported by emit.

"usemotionbias" string

controls application of ray origin compensation for motion when Attribute "trace" "int samplemotion" is set. This compensation offsets the ray origins by t * dPdtime for each ray. Valid settings are "auto", "on", and "off". The default is "auto" which preserves the behavior of version 16.0. This compensates only when the origin == P. Setting "on" always applies compensation, "off" never applies it.

Not supported by environment.

"autobias" string controls whether ray tracing bias is automatically computed. Valid settings are "on" (the default) and "off".
"maxdist" float

limits the distance from P in which ray hits can occur, defaults to RI_INFINITY.

Not supported by emit, shadow, or transmission.

"samplebase" float

scales the ray origin jitter area, which is the size of the origin micropolygon by default (i.e. 1.0).

Not supported by environment, shadow, or subsurface.

"hitsides" string

Specifies which side(s) of one-sided surfaces can be hit by the rays. The possible values are "front", "back", and "both". The default is "both".

Not supported by emit, environment, shadow, or subsurface.

"subset" string A trace set to consider for ray intersections. Only objects that are members of the named groups will be visible to the traced rays. Sets are defined with Attribute "grouping" "membership".
"excludesubset" string Objects that are members of the named groups will not be visible to the traced rays.
"type" string

Explicitly specifies the ray type for all rays spawned by this call. Valid values are "specular", "diffuse", and "transmission"; the default type is "specular". (Note that the default type for occlusion() was "diffuse" in releases prior to 17.0.)