<html>
<head>
<title>Shaders</title>
</head>
<body bgcolor="#ffffff">
<tab id=0 indent=0>
<tab id=1 indent=4>
<tab id=2 indent=8>
<tab id=3 indent=12>
<tab id=4 indent=16>
<tab id=5 indent=20>
<tab id=6 indent=24>
<tab id=7 indent=28>
<tab id=8 indent=32>
<tab id=9 indent=36>
<tab id=10 indent=40>
<tab id=11 indent=44>
<tab id=12 indent=48>
<tab id=13 indent=52>
<tab id=14 indent=56>
<tab id=15 indent=60>
<tab id=16 indent=64>
<tab id=17 indent=68>
<tab id=18 indent=72>
<tab id=19 indent=76>
<p><a name=cB><h1>Using and Writing Shaders</h1></a> 

<p><a name=iHCA></a>All color computation in mental ray is based on shaders. There are various types of shaders for different situations, such as material shaders to evaluate the material properties of a surface, light shaders to evaluate the light-emitting properties of a light source, lens shaders to specify camera properties other than the default pinhole camera, and so on. 

<p>There are built-in shaders that support SOFTIMAGE, Wavefront, and Alias compatibility. Much of the power of mental ray relies on the possibility to write custom shaders and link them dynamically to mental ray at runtime to replace some or all of the built-in shaders. Custom shaders are written in C, using the full language and library support available in C. 

<p>

<p> <p><a name=cC><h2>Dynamic Linking of Shaders</h2></a> 

<p>Shaders are written as C subroutines, stored in files with the extension ``<tt><b>.c</b></tt>''. To use these shaders in a scene, they must be dynamically linked into mental ray at runtime<a name=iHCB></a>. mental ray accepts shaders in three forms: 

<p>
<ul>

<li>  Directly as <a name=iHCC></a><u>source code</u>. The .mi file offers the <a name=iHCD></a><u><tt><b>code</b></tt></u> statement and the standalone renderer has a <tt><b>-code</b></tt> option. Both accept a source file with a <tt><b>.c</b></tt> extension. 

<p>
</ul>

<ul>

<li>  In object format. Source files can be compiled<a name=iHCE></a> to <a name=iHCF></a><u>object code</u> using Unix commands such as ``<tt><b>cc -O -c source.c</b></tt>'' (assuming that the shader source is in a file named <tt><b>source.c</b></tt>). The command may vary on some platforms, consult the manual (see ``<tt><b> </b></tt> man cc)''. This is the most common form on systems that do not support DSOs; it is faster than source because mental ray does not have to compile the shader. The compilation leaves a <tt><b>source.o</b></tt> file with the extension <tt><b>.o</b></tt> in the current directory. This file can be passed to mental ray using the <a name=iHCG></a><u><tt><b>link</b></tt></u> statement in the .mi file, or with the <tt><b>-link</b></tt> option of the standalone renderer. 

<p>
</ul>

<ul>

<li>  In DSO format. DSO stands for<a name=iHCH></a> Dynamic Shared Object. DSOs are supported on most platforms, such as SGI systems running IRIX 5.2 or higher. The <a name=iHCI></a><u>operating system version</u> can be found by running the Unix command ``<tt><b>uname -r</b></tt>''. DSOs have the extension <tt><b>.so</b></tt> on SGI systems and other extensions on other systems, but it is highly recommended to use <tt><b>.so</b></tt> on all systems. This makes it possible to use the same name on all systems regardless of type. mental ray automatically substitutes <tt><b>.dll</b></tt> for <tt><b>.so</b></tt> on Windows NT platforms. 

<p>
</ul>
To create a DSO, first compile the shader source to object format using <tt><b>cc</b></tt> as described above, then run the Unix command ``<tt><b>ld </b></tt> -shared source.o'', again assuming that the object file is called <tt><b> </b></tt> source.o.  This <tt><b>ld</b></tt> command applies to SGI IRIX 5.2, refer to ``<tt><b>man ld</b></tt>'' on other platforms. Using DSOs is the fastest way to load shaders, there is very little overhead.  DSOs, like object files, are loaded using <tt><b>link</b></tt> statements or <tt><b>-link</b></tt> options. 

<p>The commands to create a DSO depend on the operating system type. To create a DSO named <i>shader.so</i> from a source file <i>shader.c</i>, use the following commands. Insert the <tt><b>-g</b></tt> command line option after <tt><b>-c</b></tt> to insert debugging information, or insert <tt><b>-O</b></tt> to compile an optimized version. On most systems <tt><b>-g</b></tt> and <tt><b>-O</b></tt> cannot be combined. Refer to the compiler documentation for details. 

<p> 
<dl>

<dt>SGI IRIX 5.x/6.x
<dd>  <tt><b>cc -shared -o shader.so shader.c</b></tt> 

<p>
</dl>

<dl>

<dt>IBM AIX
<dd>  <tt><b>cc -o shader.o shader.c </b></tt> ld -o shader.so shader.o  <tt><b>shader.exp is a user supplied export file for the shader </b></tt> and must contain the names of the exported symbols, one at a line. <tt><b>keep.exp</b></tt> is the list of symbols exported by mental ray, either for use by shaders or for internal linking purposes. It is supplied with mental ray and can be referenced using an absolute path name.

<p>
</dl>

<dl>

<dt>HP/UX 9.x
<dd>  <tt><b>cc -c shader.c </b></tt> mv shader.o shader.so

<p>
</dl>

<dl>

<dt>HP/UX 10.x
<dd>  <tt><b>cc -c -Aa +z shader.c </b></tt> ld -b -o shader.so shader.o

<p>
</dl>

<dl>

<dt>Convex SPP-UX 5.x
<dd>  <tt><b>cc -c -DPARALLEL shader.c </b></tt> ld -b -o shader.so shader.o

<p>
</dl>

<dl>

<dt>Sun Solaris 2
<dd>  <tt><b>cc -c shader.c </b></tt> ld -G -o shader.so shader.o -ldl (Using Sun CC; gcc can also be used.) 

<p>
</dl>

<dl>

<dt>Digital Unix
<dd>  <tt><b>cc -c shader.c </b></tt> ld -expect_unresolved '*' -shared -o shader.so shader.o -ldl

<p>
</dl>

<dl>

<dt>Linux x86
<dd>  <tt><b>gcc -c -O2 shader.c </b></tt> ld -export-dynamic   

<p>
</dl>

<dl>

<dt>Linux Alpha
<dd>  <tt><b>gcc -mieee -c -O2 shader.c </b></tt> ld -export-dynamic   

<p>
</dl>

<dl>

<dt>Windows NT
<dd>  <tt><b>cl -c shader.c </b></tt> link /DLL /OUT:shader.dll shader.obj ray.lib (Using Visual C++ 4.x or 5.x.) <tt><b>ray.lib</b></tt> is a stub library that is provided with mental ray. It is necessary because Windows NT cannot automatically share symbols between modules sharing a process. Note that the Visual C++ optimizer may introduce bugs into your code, causing (possibly intermittent) malfunctions that are very hard to find. Always test without optimization (without <tt><b>/O2</b></tt>)! Or use Intel's Proton compiler.

<p>
</dl>
Compiling and creating DSOs requires that a <a name=iHCJ></a><u>C development environment</u> is installed on the system. If the <tt><b>cc</b></tt> and <tt><b>ld</b></tt> commands are not found, check if a development environment exists. On most platforms, it is a separate product that must be purchased separately. On SGI systems, the product name is <a name=iHDA></a><u>IDO</u>, which stands for <a name=iHDB></a><u>IRIS Development Option</u>. Dynamically loading a DSO does not require compilers or development options. 

<p>SGI machines search for DSO files whose name does not contain a ``/'' in all directories specified by the <a name=iHDC></a><u><tt><b>LD_LIBRARY_PATH</b></tt></u> <a name=iHDD></a><a href=functionality.html#iCE>environment variable</a>. It contains a sequence of paths, separated by colons. If <tt><b> </b></tt> LD_LIBRARY_PATH is undefined, the directories /usr/lib, /lib, /lib/cmplrs/cc, and /usr/lib/cmplrs/cc are searched. If <tt><b> </b></tt> LD_LIBRARY_PATH is set by the user, it is very important to always include these default directories because otherwise the standard Unix libraries will no longer be found, and the shell will be unable to start virtually all utilities and applications. This can be fixed by setting <tt><b>LD_LIBRARY_PATH</b></tt> correctly, or by exiting the shell and starting another one. For example, if all .so files to be linked are in /tmp, the following command at a shell prompt before starting mental ray or the application containing mental ray will make mental ray search /tmp: 

<p><br> <pre>
     setenv LD_LIBRARY_PATH /usr/lib:/lib:/lib/cmplrs/cc:/usr/lib/cmplrs/cc:/tmp
     LD_LIBRARY_PATH=/usr/lib:/lib:/lib/cmplrs/cc:/usr/lib/cmplrs/cc:/tmp
     export LD_LIBRARY_PATH
</pre>


<p><br> The first line applies to the <i>csh</i> and <i>tcsh</i> shells; the other two lines apply to the <i>sh</i> and <i>bash</i> shells. Slaves started from the /usr/etc/inetd.conf file should be started with a matching <tt><b>LD_LIBRARY_PATH</b></tt> by using the following line as the last column of the respective /usr/etc/inetd.conf entry: 

<p><pre>
     env LD_LIBRARY_PATH=/usr/lib:...:/tmp /path/rayslave
</pre>


<p>It is recommended that .so files are given with a ``/'' in the name to avoid having to change <tt><b>LD_LIBRARY_PATH</b></tt>. For example, to link a shared object ``myshader.so'' in the current directory, give the name as ``./myshader.so''. 

<p>Note that source code (<tt><b>.c extension</b></tt>) is normally portable, unless nonportable system features (such as <i>fsqrt</i> on SGIs) are used. <a name=iHDE></a>This means that the shader will run on all other vendors' systems unchanged. Both object files (<tt><b>.o extension</b></tt>) and DSOs (<tt><b>.so extension</b></tt>) do not have this advantage, they must be compiled separately for each platform and, usually, for each major operating system release. For example, a Hewlett-Packard object file will not run on an SGI system, and an SGI IRIX 4.x object file cannot be used on an IRIX 5.x system, and vice versa. 

<p><a name=iHDF></a>On SGI systems, a shader can be debugged after it has been called for the first time, which attaches it to the program and makes its symbols available for the debugger. It must have been compiled with the <tt><b>-g</b></tt> compiler option. On non-SGI systems, debugging shaders is, unfortunately, difficult. The reason is that most debuggers cannot deal with parts of a program that have been dynamically linked. In general, the debugger will refuse to set breakpoints in dynamically linked shaders, and will step over calls to these shaders as if they were a single operating system call. Some vendors are working on fixing these problems, but at this time the only option on non-SGI systems is using <i>printf</i> or <a name=iHDG></a><a href=shaders.html#iBBIH><i>mi_debug</i></a> statements in the shader sources. Note that when using <i>printf</i>, you <b>must</b> include <tt><b><i>&lt;</i>stdio.h<i>&gt;</i></b></tt>, or mental ray will crash. 

<p><p><a name=cD><h2>Coordinate Systems</h2></a> 

<p><a name=iHDH></a><a name=iHDI></a><i>Internal space</i> is the coordinate system mental ray uses to present intersection points and other points and vectors to shaders. All points and vectors in the state except bump basis vectors (which are in object space) are presented in internal space, namely, <tt><b>org</b></tt>, <tt><b>dir</b></tt>, <tt><b>point</b></tt>, <tt><b>normal</b></tt>, and <tt><b>normal_geom</b></tt>. The actual meaning of internal space is left undefined, it varies between different versions of mental ray. <b>A shader may not assume that internal space is </b> identical to camera space, even though this was true in versions of mental ray prior to 1.9. 

<p><a name=iHDJ></a><i>World space</i> is the coordinate system in which modeling and animation takes place. 

<p><a name=iHEA></a><i>Object space</i> is a coordinate system relative to the object's origin. The modeler that created the scene defines the object's origin; for example, the SOFTIMAGE translator uses the center of the bounding box of the object as the object origin. 

<p><a name=iHEB></a><i>Camera space</i> is a coordinate system in which the camera is at the coordinate origin <i>(0, 0, 0)</i> with an <i>up</i> vector of <i>(0, 1, 0)</i> and points down the negative Z axis. 

<p><a name=iHEC></a>In addition to these 3D coordinate spaces, <i>raster space</i> is is a two-dimensional pixel location on the screen bounded by <i>(0, 0)</i> in the lower left corner of the image, and the rendered image resolution. The center of the pixel in the lower left corner of raster space has the coordinate <i>(0.5, 0.5)</i>. 

<p><a name=iHED></a><i>Screen space</i> is defined such that <i>(-1, -1/a)</i> is in the lower left corner of the screen and <i>(1, 1/a)</i> is in the the upper right, where <i>a</i> is the <a name=iHEE></a><u>aspect ratio</u> of the screen. 

<p>Most shaders never need to transform between spaces. Texture shaders frequently need to operate in object space; for example, in order to apply bump basis vectors to <i>state<i>-&gt;</i>normal</i>, the normal must be transformed to object space before the bump basis vectors are applied, and back to internal space before the result is passed to any mental ray function such as <i>mi_trace_reflect</i>. mental ray offers twelve functions to convert points and vectors between coordinate spaces: 

<p><a name=iHEF></a> (see <a href=shaders.html#iBBBA><i>mi_point_to_world</i></a>) <a name=iHEG></a> (see <a href=shaders.html#iBBBB><i>mi_point_to_camera</i></a>) <a name=iHEH></a> (see <a href=shaders.html#iBBBC><i>mi_point_to_object</i></a>) <a name=iHEI></a> (see <a href=shaders.html#iBBBD><i>mi_point_from_world</i></a>) <a name=iHEJ></a> (see <a href=shaders.html#iBBBE><i>mi_point_from_camera</i></a>) <a name=iHFA></a> (see <a href=shaders.html#iBBBF><i>mi_point_from_object</i></a>) <a name=iHFB></a> (see <a href=shaders.html#iBBBG><i>mi_vector_to_world</i></a>) <a name=iHFC></a> (see <a href=shaders.html#iBBBH><i>mi_vector_to_camera</i></a>) <a name=iHFD></a> (see <a href=shaders.html#iBBBI><i>mi_vector_to_object</i></a>) <a name=iHFE></a> (see <a href=shaders.html#iBBBJ><i>mi_vector_from_world</i></a>) <a name=iHFF></a> (see <a href=shaders.html#iBBCA><i>mi_vector_from_camera</i></a>) <a name=iHFG></a> (see <a href=shaders.html#iBBCB><i>mi_vector_from_object</i></a>) 
<p><pre> <i>function</i>                   <i>operation</i> 
 <hr>
 mi_point_to_world(<i>s</i>,<i>p<sub>r</sub></i>,<i>p</i>)		 internal point to world space 
 mi_point_to_camera(<i>s</i>,<i>p<sub>r</sub></i>,<i>p</i>)		 internal point to camera space 
 mi_point_to_object(<i>s</i>,<i>p<sub>r</sub></i>,<i>p</i>)		 internal point to object space 
 mi_point_from_world(<i>s</i>,<i>p<sub>r</sub></i>,<i>p</i>)	 world point to internal space 
 mi_point_from_camera(<i>s</i>,<i>p<sub>r</sub></i>,<i>p</i>)	 camera point to internal space 
 mi_point_from_object(<i>s</i>,<i>p<sub>r</sub></i>,<i>p</i>)	 object point to internal space 
 mi_vector_to_world(<i>s</i>,<i>v<sub>r</sub></i>,<i>v</i>)		 internal vector to world space 
 mi_vector_to_camera(<i>s</i>,<i>v<sub>r</sub></i>,<i>v</i>)	 internal vector to camera space 
 mi_vector_to_object(<i>s</i>,<i>v<sub>r</sub></i>,<i>v</i>)	 internal vector to object space 
 mi_vector_from_world(<i>s</i>,<i>v<sub>r</sub></i>,<i>v</i>)	 world vector to internal space 
 mi_vector_from_camera(<i>s</i>,<i>v<sub>r</sub></i>,<i>v</i>)	 camera vector to internal space 
 mi_vector_from_object(<i>s</i>,<i>v<sub>r</sub></i>,<i>v</i>)	 object vector to internal space 
 <hr>
 
</pre><p> 

<p>Point and vector transformations are similar, except that the vector versions ignore the translation part of the matrix. The length of vectors is preserved only if the transformation matrix does not scale. The <a name=iHFH></a><a href=shaders.html#iBBAH><i>mi_point_transform</i></a> and <a name=iHFI></a><a href=shaders.html#iBBAJ><i>mi_vector_transform</i></a> functions are also available to transform points and vectors between arbitrary coordinate systems given by a transformation matrix. 

<p>

<p><p><a name=cE><h2>Shader Type Overview</h2></a> 

<p>There are five types of shaders, all of which can be substituted by user-written shaders: 

<p> <a name=iHFJ></a>
<ul>

<li>  <b>material shaders</b> describe the visible material of an object. They are the only mandatory part of any material description. Material shaders are called whenever a visible ray (eye ray, reflected ray, refracted ray, or transparency ray) hits an object. Material shaders have a central function in mental ray. 

<p>
</ul>
<a name=iHGA></a>
<ul>

<li>  <b>volume shaders</b> are called to account for atmospheric effects encountered by a ray.  The state (see below) distinguishes two types of volume shaders: the standard <i>volume</i> shader that is called in most cases, and the <i>refraction volume</i> shader that is taken from the object material at the current intersection point, and becomes the standard <i>volume</i> shader<a name=iHGB></a> if a refraction or transparency ray is cast. Many material shaders substitute a new standard <i>volume</i> shader based on inside/outside calculations. Volume shaders, unlike other shaders, accept an input color (such as the one calculated by the material shader at the last intersection point) that they are expected to modify. 

<p>
</ul>
<a name=iHGC></a>
<ul>

<li>  <b>light shaders</b> implement the characteristics of a light source. For example, a spot light shader would use the illumination direction to attenuate the amount of light emitted. A light shader is called whenever a material shader uses a built-in function to evaluate a light. Light shaders normally cast shadow rays if shadows are enabled to detect obscuring objects between the light source and the illuminated point. 

<p>
</ul>
<a name=iHGD></a>
<ul>

<li>  <b>shadow shaders</b> are called instead of material shaders when a shadow ray intersects with an object. Shadow rays are cast by light sources to determine visibility of an illuminated object. Shadow shaders are basically light-weight material shaders that calculate the transmitted color of an object without casting secondary or shadow rays. 

<p>
</ul>
<a name=iHGE></a>
<ul>

<li>  <b>environment shaders</b> are called instead of a material shader when a visible ray leaves the scene entirely without intersecting an object. Typical environment shaders evaluate a texture mapped on a virtual infinite sphere enclosing the scene (virtual because it is not part of the scene geometry). 

<p>
</ul>
<a name=iHGF></a>
<ul>

<li>  <b>texture shaders</b> come in three flavors: color, scalar, and vector. Each calculates and returns the respective type. Typical texture shaders return a color from a texture image after some appropriate coordinate transformation, or compute a color at a location in 3D space using some sort of noise function. Their main purpose is to relieve other shaders, such as material or environment shaders, from performing color and other computations. For example, if a marble surface were needed, it should be written as a texture shader and not a material shader because a texture shader does not have to calculate illumination by light sources, reflections, and so on. It is much easier to write a texture shader than a material shader. mental ray never calls a texture shader directly, it is always called from one of the other types of shaders. 

<p>
</ul>
<a name=iHGG></a>
<ul>

<li>  <b>lens shaders</b> are called when a primary ray is cast by the camera. They may modify the eye ray's origin and direction to implement cameras other than the standard pinhole camera, and may modify the result of the primary ray to implement effects such as lens flares. 

<p>
</ul>
<a name=iHGH></a>
<ul>

<li>  <b>output shaders</b> are different from all other shaders and receive different parameters. They are called when the entire scene has been completely rendered and the output image resides in memory. Output shaders operate on the output image to implement special filtering or compositing operations. Output shaders are not associated with any particular ray because they are called after the last ray is completed. 

<p>
</ul>
<br>
 <a name=iHGI></a>The following diagram illustrates the path of a ray cast by the camera. It first intersects with a sphere at point A. The sphere's material shader first casts a reflection ray that hits a box, then a refraction ray that intersects the sphere at its other side T, and finally it casts a transparency ray that also intersects the sphere, at D. (This example is contrived, it is very unusual for a material shader to cast both a refraction and a transparency ray.) The same material shader is called at points A, T, and D. In this example, the reflection trace depth may have prevented further reflection rays to be cast at T and D. 

<p> <br> 
<p><center>
<img src="volume_rays.fig.ps.gif" alt="volume_rays.fig.ps.gif">
 </center><p>
 <br>  

<p>The annotations set in <i>italics</i> are numbered; the events described happen in the sequence given by the numbers. 

<p>Since material shaders may do inside/outside calculations based on the surface normal or the parent state chain (see below), the volume shaders are marked (1) and (2), depending on whether the volume shader left by A or by T/D in the <i>refraction volume</i> field of the state. The default refraction volume shader is the one found in the material definition, or the standard volume shader if the material defines no volume shader. For details on choosing volume shaders, see the section on writing material and volume shaders. Note that the volume shaders in this diagram are called immediately after the material shader returns. 

<p><br>
 The next diagram depicts the situation when the material shader at the intersection point M requests a <a name=iHGJ></a><u>light ray</u> from the light source at L, by calling a function such as <a name=iHHA></a><a href=shaders.html#iBACG><i>mi_sample_light</i></a>. This results in the light shader of L to be called. No intersection testing is done at this point. Intersection testing takes place when shadows are enabled and the light shader casts <i>shadow rays</i><a name=iHHB></a> (see <a href=shaders.html#iJFH>shadow ray</a>)  from the light source L to the illuminated point M.  For each obscuring object (A and B), a <a name=iHHC></a><a href=shaders.html#iJFH>shadow ray</a> is generated with the origin L and the intersection point A or B, and the <a name=iHHD></a><a href=scene.html#iECC>shadow shader</a>s of objects A and B are called to modify the light emitted by the light source based on the transparency attributes of the obscuring object. Note that no shadow ray is generated for the segment from B to M because no other obscuring object whose shadow shader could be called exists. Note also that although shadow rays always go from the light source towards the illuminated point, the order in which the shadow shaders are called is not defined unless the <tt><b>shadow_sort</b></tt> option is set in the view. Here, steps 4 and 5 may be reversed if it is not. Two shadow rays are cast, even though the light shader has called <i>trace_shadow</i> only once. 

<p> <br> 
<p><center>
<img src="shadow_rays.fig.ps.gif" alt="shadow_rays.fig.ps.gif">
 </center><p>
 <br>  

<p>The remainder of this chapter describes how to write all types of shaders. First, the concepts of ray tracing state parameter passing common to all shaders are presented, followed by a detailed discussion of each type of shader. <br>
 

<p><p><a name=cF><h2>State Variables</h2></a> 

<p><a name=iHHE></a>Every shader needs to access information about the current state of mental ray, and information about the intersection that led to the shader call. This information is stored in a single structure known as the <i>state</i>. Not all information in the state is of interest or defined for all shaders; for example, lens shaders are called before an intersection is done and hence have no information such as the intersection point or the normal there. It is recommended to call the state parameter that shaders receive as a formal parameter <i>state</i> because some macros provided in the <tt><b>mi_shader.h</b></tt> include file that require access to the state rely on this name. The state, and everything else needed to write shaders, is defined in <tt><b>mi_shader.h</b></tt>, which must be included by all shader source files. Note that the <i>state</i> parameter of a shader should have the name <tt><b>state</b></tt> because several convenience macros depend on this. 

<p>Before a shader is called, mental ray prepares a new state structure that provides global information to the shader. This state may be the same data structure that was used in the previous call (this is the case for shaders that modify another shader's result, like lens, shadow, and volume shaders); or it may be a new state structure that is a copy of the calling shader's state with some state variables changed (this is done if a secondary ray is cast with one of the tracing functions provided by mental ray). For example, if a material shader that is using state A casts a reflected ray, which hits another object and causes that object's material shader to be called with state B, state B will be a copy of state A except for the ray and intersection information, which will be different in states A and B. State A is said to be the <i>parent</i> of state B. The state contains a parent pointer that allows sub-shader to access the state of parent shaders. If a volume shader is called after the material shader, the volume shader modifies the color calculated by the material shader, and gets the same state as the material shader, instead of a fresh copy. 

<p><a name=iHHF></a>This means that it is possible to pass information from one shader to another in the call tree for a primary ray, by one of two methods: either the parent (the caller) changes its own state that will be inherited by the child, or the child follows the parent pointer. The state contains a <i>user pointer</i> that a parent can store the address of a local data structure in, for passing it to sub-shaders. Since every sub-shader inherits this pointer, it may access information <a name=iHHG></a>provided by its parent. A typical application of this are inside/outside calculations performed by material shaders to find out whether the ray is inside a closed object to base the interpretation of parameters such as the index of refraction on. 

<p>Note that the state can be used to pass information from one shader to sub-shaders that are lower in the call tree. Care must be taken not to destroy information in the state because some shaders (shadow, volume, and the first eye shader) re-use the state from the previous call. In particular, the state cannot be used to pass information from one primary (camera) ray to the next. Static variables can be used in the shader for this purpose, but care must be taken to avoid multiple access on multiprocessor shared-memory machines. On such a machine, all processors share the same set of static variables, and every change by one processor becomes immediately visible to all other processors, which may be executing the same shader at the same time. Locking facilities are available in mental ray to protect critical sections that may execute only once at any time. 

<p>    

<p>Here is a complete list of state variables usable by shaders. Variables not listed here are for internal use only and should not be accessed or modified by shaders. The first table lists all state variables that remain unchanged for the duration of the frame: 

<p><p><a name=cG><h3>Frame</h3></a> 

<p><a name=iHHH></a>
<p><pre> <i>type</i>               <i>name</i>                <i>content</i> 
 <hr>
 <tt><b>int</b></tt>                <tt><b>version</b></tt>             shader interface version 
 <tt><b>miTag</b></tt>              <tt><b>camera_inst</b></tt>         tag of camera instance 
 <tt><b>miCamera *</b></tt>         <tt><b>camera</b></tt>              camera information 
 <tt><b>miRc_options *</b></tt>     <tt><b>options</b></tt>             general rendering options 
 <hr>
 
</pre><p> 

<p><a name=iHHI></a><a name=iHHJ></a>The camera data structure pointed to by <i>camera</i> has the following fields. None of these may be written to by a shader. <br> 

<p><a name=iHIA></a>
<p><pre> <i>type</i>               <i>name</i>                <i>content</i> 
 <hr>
 <tt><b>miBoolean</b></tt>          <tt><b>orthographic</b></tt>        orthographic rendering 
 <tt><b>miScalar</b></tt>           <tt><b>focal</b></tt>               focal length of the camera 
 <tt><b>miScalar</b></tt>           <tt><b>aperture</b></tt>            aperture of the camera 
 <tt><b>miScalar</b></tt>           <tt><b>aspect</b></tt>              aspect ratio <i>y /x</i> 
 <tt><b>miRange</b></tt>            <tt><b>clip</b></tt>                Z clipping distances 
 <tt><b>int</b></tt>                <tt><b>x_resolution</b></tt>        image width in pixels 
 <tt><b>int</b></tt>                <tt><b>y_resolution</b></tt>        image height in pixels 
 <tt><b>int</b></tt>                <tt><b>window.xl</b></tt>           left image margin 
 <tt><b>int</b></tt>                <tt><b>window.yl</b></tt>           bottom image margin 
 <tt><b>int</b></tt>                <tt><b>window.xh</b></tt>           right image margin 
 <tt><b>int</b></tt>                <tt><b>window.yh</b></tt>           top image margin 
 <tt><b>miTag</b></tt>              <tt><b>volume</b></tt>              view volume (atmosphere) 
 <tt><b>miTag</b></tt>              <tt><b>environment</b></tt>         view environment shader 
 <tt><b>int</b></tt>                <tt><b>frame</b></tt>               frame number 
 <tt><b>float</b></tt>              <tt><b>frame_time</b></tt>          frame time in seconds 
 <hr>
 
</pre><p> 

<p><a name=iHIB></a><a name=iHIC></a>The option data structure pointed to by <i>option</i> has this format. The option structure may also not be written to by shaders. 

<p><a name=iHID></a>
<p><pre> <i>type</i>               <i>name</i>                <i>content</i> 
 <hr>
 <tt><b>miBoolean</b></tt>          <tt><b>shadow</b></tt>              shadow casting turned on? 
 <tt><b>miBoolean</b></tt>          <tt><b>trace</b></tt>               ray tracing turned on? 
 <tt><b>miBoolean</b></tt>          <tt><b>scanline</b></tt>            scanline mode turned on? 
 <tt><b>miBoolean</b></tt>          <tt><b>shadow_sort</b></tt>         sort shadow shader calls? 
 <tt><b>miBoolean</b></tt>          <tt><b>contour</b></tt>             contours turned on? 
 <tt><b>miBoolean</b></tt>          <tt><b>motion</b></tt>              motion blur turned on? 
 <tt><b>enum miRc_sampling</b></tt> <tt><b>sampling</b></tt>            image sampling mode 
 <tt><b>enum miRc_filter</b></tt>   <tt><b>filter</b></tt>              nonlocal sampling filter 
 <br> <tt><b>enum miRc_acceleration</b></tt> <tt><b>acceleration</b></tt>     <br> ray tracing algorithm 
 <tt><b>enum miRc_face</b></tt>     <tt><b>face</b></tt>                front, back, or both faces 
 <tt><b>enum miRc_field</b></tt>    <tt><b>field</b></tt>               odd, even, or both fields 
 <tt><b>int</b></tt>                <tt><b>reflection_depth</b></tt>    max reflection trace depth 
 <tt><b>int</b></tt>                <tt><b>refraction_depth</b></tt>    max refraction trace depth 
 <tt><b>int</b></tt>                <tt><b>trace_depth</b></tt>         max combined trace depth 
 <hr>
 
</pre><p> 

<p>
<dl>

<dt><i>version</i>
<dd>  The version number of the interface and the state structure. Useful to check if the version is compatible with the shader. Version 1 stands for mental ray 1.8, version 2 stands for 1.9. 

<p>
</dl>

<dl>

<dt><i>camera_inst</i>
<dd>  The camera instance is for internal use by mental ray only. 

<p>
</dl>
The following parameters are in the <i>state<i>-&gt;</i>camera</i> structure: 

<p>
<dl>

<dt><i>orthographic</i>
<dd>  <a name=iHIE></a>This flag is <tt><b>miTRUE</b></tt> if the renderer is in orthographic mode, and <tt><b>miFALSE</b></tt> if it is in perspective mode. 

<p>
</dl>

<dl>

<dt><i>focal</i>
<dd>  The focal length of the camera (the distance from the origin in camera space to the viewing plane that the image pixels are mapped on). 

<p>
</dl>

<dl>

<dt><i>aperture</i>
<dd>  The aperture of the camera (the width of the viewing plane in camera space). 

<p>
</dl>

<dl>

<dt><i>aspect</i>
<dd>  The aspect ratio (the ratio of the width and height of the viewing plane in camera space). 

<p>
</dl>

<dl>

<dt><i>clip</i>
<dd>  This data structure has two members, <i>min</i> and <i>max</i>, that specify the hither and yon clipping planes in camera space. Objects will be clipped if their Z coordinate in camera space is less than <i>-max</i> or greater than <i>-min</i>. 

<p>
</dl>

<dl>

<dt><i>x_resolution</i>
<dd>  The x resolution of the image in pixels. 

<p>
</dl>

<dl>

<dt><i>y_resolution</i>
<dd>  The y resolution of the image in pixels. 

<p>
</dl>

<dl>

<dt><i>window</i>
<dd>  The window specifies the lower left and the upper right pixel of the sub-region of the image to be rendered. If <i>xl</i> and <i> </i> yl are 0 and <i>xh</i> and <i>yh</i> match or exceed the resolution minus one, the entire image is rendered. The window is clipped to the resolution. Pixels outside the window are set to black. 

<p>
</dl>

<dl>

<dt><i>volume</i>
<dd>  <a name=iHIF></a> (see <a href=shaders.html#iHGA>volume shader</a>) The global volume (atmosphere) shader of the view that is used for attenuating rays outside of objects, such as the primary ray from the camera to the first object intersection. Material shaders inherit this volume shader because the <tt><b>volume</b></tt> state variable defaults to the view volume, but shaders may override the volume. See below. 

<p>
</dl>

<dl>

<dt><i>environment</i>
<dd>  <a name=iHIG></a> (see <a href=shaders.html#iHGE>environment shader</a>) The environment (reflection map) shader of the view. It is used to assign a color to primary eye rays that leave the scene without ever intersecting an object. Material shaders that do not define their own environment shaders for evaluation of local reflection maps inherit the view environment shader. Reflection maps give the illusion of true raytraced reflections by looking up a texture based on the reflection direction. 

<p>
</dl>

<dl>

<dt><i>frame</i>
<dd>  The current <a name=iHIH></a><u>frame number</u>. In field mode, this is the field number, two successive frames rendered by mental ray are combined into a single output frame by an output shader. In field mode, the odd frame is the first frame and the even frame is the second. 

<p>
</dl>

<dl>

<dt><i>frame_time</i>
<dd>  The current frame number, expressed as a time in seconds. The relation between <i>frame</i> and <i>frame_time</i> depends on the frame rate. Both numbers are taken verbatim from the input scene, mental ray does not change or verify either number. If the frame time is omitted in the .mi file, it is set to 0.0. 

<p>
</dl>
The following parameters are in the <i>state<i>-&gt;</i>options</i> structure: 

<p>
<dl>

<dt><i>shadow</i>
<dd>  <a name=iHII></a>If this flag is <tt><b>miTRUE</b></tt>, shadow casting is enabled. If it is <tt><b>miFALSE</b></tt>, no shadows are rendered regardless of the shadow flags of individual objects, and no shadow shaders will be called. 

<p>
</dl>

<dl>

<dt><i>trace</i>
<dd>  If this flag is <tt><b>miTRUE</b></tt>, secondary ray tracing (reflection and refraction) is enabled. If it is <tt><b>miFALSE</b></tt>, only eye and transparency rays are evaluated, and no shadows are computed regardless of the <tt><b>shadow</b></tt> flag. 

<p>
</dl>

<dl>

<dt><i>scanline</i>
<dd>  If this flag is <tt><b>miTRUE</b></tt>, the scanline algorithm is enabled for primary rays. In this case, lens shaders may not change the ray origin and direction, and motion blurring may not be used. If <tt><b>scanline</b></tt> is <tt><b>miFALSE</b></tt>, primary rays are cast using pure ray tracing, which may slow down the rendering process. 

<p>
</dl>

<dl>

<dt><i>shadow_sort</i>
<dd>  If this flag is <tt><b>miTRUE</b></tt>, shadow shaders are called in order, the one closest to the light source first. If it is off, shadow shaders are called in random order. This flag is here to allow shadow shaders that depend on the correct order to abort if the flag is <tt><b>miFALSE</b></tt>. 

<p>
</dl>

<dl>

<dt><i>contour</i>
<dd>  If this flag is <tt><b>miTRUE</b></tt>, contour rendering is enabled; if it is <tt><b>miFALSE</b></tt>, contour rendering is disabled. Contours and color images cannot be rendered at the same time. 

<p>
</dl>

<dl>

<dt><i>motion</i>
<dd>  If this flag is <tt><b>miTRUE</b></tt>, motion blurring is enabled; if it is <tt><b>miFALSE</b></tt>, motion blurring is disabled even if motion vectors are present. 

<p>
</dl>

<dl>

<dt><i>sampling</i>
<dd>  Sampling specifies the supersampling algorithm. Three constants are defined: <tt><b>miRC_SAMPLING_RECURSIVE</b></tt> is the default recursive supersampling algorithm that generally results in the highest quality; <tt><b>miRC_SAMPLING_CONSTANT</b></tt> takes a constant number of samples per pixels, and <tt><b>miRC_SAMPLING_ADAPTIVE</b></tt> is a nonrecursive adaptive algorithm. 

<p>
</dl>

<dl>

<dt><i>filter</i>
<dd>  Nonlocal filtering weighs samples according to their distance from the pixel center. Possible values are <tt><b>miRC_FILTER_BOX</b></tt>, <tt><b>miRC_FILTER_TRIANGLE</b></tt>, and <tt><b>miRC_FILTER_GAUSS</b></tt>. 

<p>
</dl>

<dl>

<dt><i>acceleration</i>
<dd>  The ray tracing algorithm. This is either <tt><b> </b></tt> miRC_ACCEL_RAY_CLASSIFICATION (an algorithm based on ray classification), or <tt><b>miRC_ACCEL_SPACE_SUBDIVISION</b></tt> (which is a BSP algorithm). The latter is often, but by no means always, faster. Note that by default, primary rays are computed using a scanline algorithm if possible. 

<p>
</dl>

<dl>

<dt><i>face</i>
<dd>  This variable specifies whether front-facing, back-facing, or both triangles are taken into account. All others are ignored, resulting in speed improvements. This is also called <i>back </i> face culling.<a name=iHIJ></a> The possible values are <tt><b> </b></tt> miRC_FACE_FRONT, <tt><b>miRC_FACE_BACK</b></tt>, and <tt><b> </b></tt> miRC_FACE_BOTH. 

<p>
</dl>

<dl>

<dt><i>field</i>
<dd>  <a name=iHJA></a> (see <a href=scene.html#iFEJ>field rendering</a>) Field rendering, if turned on, renders only the even or odd scanlines of an image. Two successive renders are then combined to a full frame, resulting in smoother animations. <tt><b>miRC_FIELD_OFF</b></tt> turns off field rendering, <tt><b>miRC_FIELD_EVEN</b></tt> renders only even scanlines (top is odd), and <tt><b>miRC_FIELD_ODD</b></tt> renders only odd scanlines. 

<p>
</dl>

<dl>

<dt><i>reflection_depth</i>
<dd>  <a name=iHJB></a>The maximal allowed number of recursive reflections. A reflection ray will only by cast when this limit is not exceeded. If set to 0, <a name=iHJC></a> (see <a href=shaders.html#iHJI>secondary ray</a>) no secondary reflection rays will be cast. See <tt><b>reflection_level</b></tt> below. 

<p>
</dl>

<dl>

<dt><i>refraction_depth</i>
<dd>  The maximal allowed number of recursive refractions. A refraction ray will only be cast if this number is not exceeded. If set to 0, <a name=iHJD></a> (see <a href=shaders.html#iHJI>secondary ray</a>) <a name=iHJE></a><a name=iHJF></a> no secondary refraction or transparency rays will be cast. See <tt><b> </b></tt> refraction_level below. 

<p>
</dl>

<dl>

<dt><i>trace_depth</i>
<dd>  The maximal summed trace depth. mental ray will allow this many segments of the ray tree when it is followed through the scene, with<a name=iHJG></a> any combination of reflections and refractions permitted by the previous two values until the total trace depth is reached. A ray will only be cast if this number is not exceeded. 

<p>
</dl>
 <p><a name=cH><h3>Image Samples</h3></a> 

<p><a name=iHJH></a>The state variables in the next table describe an eye (primary) ray. There is one eye ray for every sample that contributes to a pixel in the output image. If a material shader that evaluates a material hit <a name=iHJI></a>by a primary ray casts secondary reflection, refraction, transparency, light, or shadow rays, all shaders called as a consequence will inherit these variables unmodified: 

<p><a name=iHJJ></a>
<p><pre> <i>type</i>               <i>name</i>                <i>content</i> 
 <hr>
 <tt><b>miScalar</b></tt>           <tt><b>raster_x</b></tt>            X coordinate of image pixel 
 <tt><b>miScalar</b></tt>           <tt><b>raster_y</b></tt>            Y coordinate of image pixel 
 <tt><b>struct miFunction</b></tt>  <tt><b>shader</b></tt>              current shader 
 <tt><b>miLock</b></tt>             <tt><b>global_lock</b></tt>         lock shared by all shaders<a name=iIAA></a> (see <a href=shaders.html#iBBHA>locking</a>) 
 <hr>
 
</pre><p> 

<p>
<dl>

<dt><i>raster_x</i>
<dd>  The X coordinate of the point in raster space to be rendered. Raster space is the pixel grid of the rendered image file, with 0/0 at the lower left corner. 

<p>
</dl>

<dl>

<dt><i>raster_y</i>
<dd>  The Y coordinate of the point in raster space to be rendered. 

<p>
</dl>

<dl>

<dt><i>shader</i>
<dd>  This pointer points to a data structure describing the current shader. The fields usable by shaders are <tt><b>lock</b></tt>, which is a lock shared by all calls to this shader<a name=iIAB></a> (see <a href=shaders.html#iBBHA>locking</a>) , <tt><b>miTag </b></tt> next_function for chained shaders such as lens shaders, and <tt><b>char parameters[]</b></tt> which contains the shader parameters. The latter is redundant for the current shader because the parameter pointer is also passed as the third shader argument, but it can be used to find the parameters of parent shaders. This should be used with care because the C data structure of parent shader parameter lists is not generally known. 

<p>
</dl>

<dl>

<dt><i>global_lock</i>
<dd>  This lock is shared by all shaders, regardless of their name. It can be used to lock critical sections common to all shaders. For example, it could be used to protect a nonreentrant user-defined random-number generator, or initialization of a more specific set of locks.<a name=iIAC></a> (see <a href=shaders.html#iBBHA>locking</a>)  

<p>
</dl>
 <p><a name=cI><h3>Rays</h3></a> 

<p>Whenever a ray is cast the following state variables are set to describe the ray: 

<p><a name=iIAD></a>
<p><pre> <i>type</i>               <i>name</i>                <i>content</i> 
 <hr>
 <tt><b>miState *</b></tt>          <tt><b>parent</b></tt>              state of parent shader 
 <tt><b>int</b></tt>                <tt><b>type</b></tt>                type of ray: reflect, light... 
 <tt><b>miBoolean</b></tt>          <tt><b>contour</b></tt>             set in contour-line mode 
 <tt><b>miBoolean</b></tt>          <tt><b>scanline</b></tt>            from scanline algorithm
 <tt><b>void *</b></tt>             <tt><b>cache</b></tt>               RC intersection cache 
 <tt><b>miVector</b></tt>           <tt><b>org</b></tt>                 start point of the ray 
 <tt><b>miVector</b></tt>           <tt><b>dir</b></tt>                 direction of the ray 
 <tt><b>miScalar</b></tt>           <tt><b>time</b></tt>                shutter interval time 
 <tt><b>miTag</b></tt>              <tt><b>volume</b></tt>              volume shader of primitive 
 <tt><b>miTag</b></tt>              <tt><b>environment</b></tt>         environment shader 
 <tt><b>int</b></tt>                <tt><b>reflection_level</b></tt>    current reflection ray depth 
 <tt><b>int</b></tt>                <tt><b>refraction_level</b></tt>    current refraction ray depth 
 <hr>
 
</pre><p> 

<p>
<dl>

<dt><i>parent</i>
<dd>  <a name=iIAE></a> (see <a href=shaders.html#iHHF>shader call tree</a>) Points to the state of the parent ray. In the first lens shader, it is <tt><b>NULL</b></tt>. In subsequent lens shaders, it points to the previous lens shader. In the material shader that is called when the primary ray hits an object, it points to the last lens shader's state, or is <tt><b>NULL</b></tt> if no lens shader has been applied. For material shaders called when a secondary reflection or refraction ray hits an object, it points to the parent material shader that cast the ray. In light shaders and environment shaders, it points to the state of the shader which requested the light or environment lookup. For shadow shaders, it points to the state of the light shader that started the shadow trace. In volume shaders, its value is the same as for a material or light shader of the same ray. 

<p>
</dl>

<dl>

<dt><i>type</i>
<dd>  <a name=iIAF></a>Specifies the reason for this ray. This is an enumerator: <tt><b>miRAY_EYE</b></tt> rays are primary rays; <tt><b> </b></tt> miRAY_TRANSPARENT, <tt><b>miRAY_REFRACT</b></tt> and <tt><b> </b></tt> miRAY_REFLECT rays are cast by material shaders to determine <a name=iIAG></a><u>transparency</u>, refractions, and reflections, respectively, <tt><b>miRAY_SHADOW</b></tt> rays are light rays cast from a light source, <tt><b>miRAY_LIGHT</b></tt> rays are cast when a light source is evaluated (which may result in the light source casting shadow rays back), <tt><b>miRAY_ENVIRONMENT</b></tt> rays sample an environment (reflection) map, and <tt><b>miRAY_NONE</b></tt> is a catch-all for other types of rays. 

<p>
</dl>

<dl>

<dt><i>contour</i>
<dd>  <a name=iIAH></a>This flag is set if mental ray is in contour rendering mode. In this mode, shaders can often simplify calculations, such as computing only the diffuse color. 

<p>
</dl>

<dl>

<dt><i>scanline</i>
<dd>  <a name=iIAI></a>This flag is set if the current intersection was found by means of the scanline algorithm. 

<p>
</dl>

<dl>

<dt><i>cache</i>
<dd>  This variable is used by the renderer internally to improve speed. Its existence determines which shaders may call which tracing functions. By setting this pointer to 0, the shader can ease these restrictions and call tracing functions that are not normally legal for this type of shader. For details, see the section <i>Shaders </i> and Trace Functions below. 

<p>
</dl>

<dl>

<dt><i>org</i>
<dd>  The origin (start point) of the ray in <a name=iIAJ></a><a href=shaders.html#iHDI>internal space</a>. In the primary material shader, it is set by the last lens shader, or is (0, 0, 0) if there is no lens shader and the default non-orthogonal pinhole camera is used. In all other material shaders, it is the previous intersection point. In light and shadow shaders, it is the origin of the light source. If the light source does not have an origin, it is undefined. 

<p>
</dl>

<dl>

<dt><i>dir</i>
<dd>  The direction of the ray in <a name=iIBA></a><a href=shaders.html#iHDI>internal space</a>. This is basically the normalized difference between <tt><b>point</b></tt> and <tt><b>org</b></tt>, pointing towards the current intersection point (except in the case of directional light sources that have no origin; in this case the light direction is used). Light and shadow rays point from the light source to the intersection. 

<p>
</dl>

<dl>

<dt><i>time</i>
<dd>  The time of the ray in the shutter interval. If motion blurring is turned off, the time is always 0. Otherwise, it is systematically sampled in the range from 0 to the shutter time. 

<p>
</dl>

<dl>

<dt><i>volume</i>
<dd>  <a name=iIBB></a> (see <a href=shaders.html#iHGA>volume shader</a>) The volume shader to be applied to the ray. The volume shader is called immediately after the material shader returns, without any change to the state. The volume shader changes the result color of the material shader to take the distance the ray to the<a name=iIBC></a> (see <a href=shaders.html#iHJH>primary ray</a>) <a name=iIBD></a> (see <a href=shaders.html#iHJI>secondary ray</a>)  <a name=iIBE></a>material has traveled into account. For primary rays this is the <tt><b>volume</b></tt> of the view, for reflection and light rays the<a name=iIBF></a><a name=iIBG></a> <tt><b>volume</b></tt> of the parent, and for refraction and transparency rays the <tt><b> </b></tt> refraction_volume of the parent. Note that the<a name=iIBH></a> (see <a href=shaders.html#iBABG><i>         mi_trace_refraction</i></a>) <a name=iIBI></a> (see <a href=shaders.html#iBACB><i>mi_trace_transparent</i></a>)  <tt><b> </b></tt> mi_trace_refract and <tt><b>mi_trace_transparent</b></tt> functions copy <tt><b>refraction_volume</b></tt> to <tt><b>volume</b></tt> to ensure that sub-shaders<a name=iIBJ></a> (see <a href=shaders.html#iHHF>shader call tree</a>)  use the volume shader that applies to the interior of the object.  Volume shaders are also applied to light rays. 

<p>
</dl>

<dl>

<dt><i>environment</i>
<dd>  <a name=iICA></a> (see <a href=shaders.html#iHGE>environment shader</a>) The active environment shader. For primary rays this is the environment of the view.  For reflection and refraction rays the active shader is taken from the material, if it specifies an environment shader. If it does not, the environment shader defaults to the environment shader in the view, if present. The purpose of the environment shader is to provide a color if a ray leaves the scene entirely. 

<p>
</dl>

<dl>

<dt><i>reflection_level</i>
<dd>  <a name=iICB></a>The reflection level of the ray. It may range from 0 for primary rays to <tt><b>reflection_depth</b></tt> minus one. The <tt><b>trace_depth</b></tt> imposes another limit: The sum of <tt><b> </b></tt> reflection_level and <tt><b>refraction_level</b></tt> must be one less than <tt><b>trace_depth</b></tt>. A shader may decrement or reset the reflection level to circumvent the restrictions imposed by the trace depth state variables. 

<p>
</dl>

<dl>

<dt><i>refraction_level</i>
<dd>  The refraction level of the ray. This is equivalent to the reflection level but applies to refraction and transparency (which is a variation of refraction that does not take the index of refraction into account) rays. A shader may decrement or reset the reflection level to circumvent the restrictions imposed by the trace depth state variables. 

<p>
</dl>
 <br> <p><a name=cJ><h3>Intersection</h3></a> 

<p><a name=iICC></a>The variables in the next table are closely related to the previous. They describe the intersection of the ray with an object, and give information about that object and how it was hit. 

<p><a name=iICD></a>
<p><pre> <i>type</i>               <i>name</i>                <i>content</i> 
 <hr>
 <tt><b>miTag</b></tt>              <tt><b>refraction_volume</b></tt>   volume shader for refraction 
 <tt><b>unsigned int</b></tt>       <tt><b>label</b></tt>               object label for label file 
 <tt><b>miTag</b></tt>              <tt><b>instance</b></tt>            instance of object 
 <tt><b>miTag</b></tt>              <tt><b>light_instance</b></tt>      instance of light 
 <tt><b>miScalar [4]</b></tt>       <tt><b>bary</b></tt>                barycentric coordinates 
 <tt><b>miVector</b></tt>           <tt><b>point</b></tt>               intersection (ray end) point 
 <tt><b>miVector</b></tt>           <tt><b>normal</b></tt>              interpolated normal at <tt><b>point</b></tt> 
 <tt><b>miVector</b></tt>           <tt><b>normal_geom</b></tt>         geometry normal at <tt><b>point</b></tt> 
 <tt><b>miBoolean</b></tt>          <tt><b>inv_normal</b></tt>          true if normals were inverted 
 <tt><b>miScalar</b></tt>           <tt><b>dot_nd</b></tt>              dot prod of <tt><b>normal</b></tt> and <tt><b>dir</b></tt> 
 <tt><b>miScalar</b></tt>           <tt><b>dist</b></tt>                length of the ray 
 <tt><b>int</b></tt>                <tt><b>pri</b></tt>                 indentifies hit primitive 
 <tt><b>miScalar</b></tt>           <tt><b>shadow_tol</b></tt>          safe zone against self-shadows 
 <tt><b>miScalar</b></tt>           <tt><b>ior</b></tt>                 index of refraction of medium 
 <tt><b>miScalar</b></tt>           <tt><b>ior_in</b></tt>              index of refraction of previous medium 
 <hr>
 
</pre><p> 

<p>
<dl>

<dt><i>refraction_volume</i>
<dd>  <a name=iICE></a> (see <a href=shaders.html#iHGA>volume shader</a>) The volume at the other side of the object. This is set to the volume shader of the material. It will be applied to refraction rays. This is implemented by copying <tt><b> </b></tt> refraction_volume to <tt><b>volume</b></tt> (which is the shader that gets called when the material shader returns) in the <tt><b> </b></tt> mi_trace_refract and <tt><b>mi_trace_transparent</b></tt> functions. The material shader may decide that the ray is leaving and not entering the object, and look in the state's parents for an outside volume shader, or simply copy <tt><b>view_volume</b></tt> to <tt><b>refraction_volume</b></tt> to make the ray resume in the outside atmosphere. 

<p>
</dl>

<dl>

<dt><i>label</i>
<dd>  The label of the hit object. Every object may contain a label that is made available by this variable. When the primary material shader returns, the <tt><b>label</b></tt> is copied from the state to the ``tag'' frame buffer, if one was created by an appropriate <tt><b>output</b></tt> statement in the <tt><b>view</b></tt>. The primary material shader is free to change this variable to any value to put different values into the tag frame buffer. 

<p>
</dl>

<dl>

<dt><i>instance</i>
<dd>  The instance of the object containing the primitive hit by the ray. 

<p>
</dl>

<dl>

<dt><i>light_instance</i>
<dd>  If the ray is a <a name=iICF></a>light ray or the corresponding <a name=iICG></a> (see <a href=shaders.html#iJFH>shadow ray</a>) shadow ray: the light instance. 

<p>
</dl>

<dl>

<dt><i>bary</i>
<dd>  <a name=iICH></a>The three barycentric coordinates of the intersection in the hit primitive. The fourth value is reserved for implicit patches and is not currently used. Barycentric coordinates are weights that specify the contribution by each vertex or control point. The sum of all barycentric coordinates is 1. 

<p>
</dl>

<dl>

<dt><i>point</i>
<dd>  The intersection point (end point of the ray) in <a name=iICI></a><a href=shaders.html#iHDI>internal space</a>. 

<p>
</dl>

<dl>

<dt><i>normal</i>
<dd>  The (interpolated) surface normal at the intersection point if vertex normals are present, or the uninterpolated geometric normal of the primitive otherwise, in <a name=iICJ></a><a href=shaders.html#iHDI>internal space</a>. It points to the side of the primitive from which it is hit by the ray, and is normalized to within the precision of a <tt><b>float</b></tt>. Care should be taken when calculating the length of the normal; the result of this calculation might be very slightly greater than 1 because a <tt><b>float</b></tt> has only a little over six significant digits. This can cause math functions like <tt><b>acos</b></tt> to return <tt><b>NaN</b></tt> (Not a Number, an illegal result), which usually results in white pixels in the output if the <tt><b>NaN</b></tt> finds its way into a result color.<a name=iIDA></a><a name=iIDB></a> 

<p>
</dl>

<dl>

<dt><i>normal_geom</i>
<dd>  The uninterpolated normal of the hit primitive in <a name=iIDC></a><a href=shaders.html#iHDI>internal         space</a>. It points to that side of the primitive from which it is hit by the ray.  It is normalized. 

<p>
</dl>

<dl>

<dt><i>inv_normal</i>
<dd>  If a ray hits geometry from behind (that is, if the dot product of the ray direction and the normal is positive), mental ray inverts both <i>normal</i> and <i>normal_geom</i> and sets <i> </i> inv_normal to <tt><b>miTRUE</b></tt>. 

<p>
</dl>

<dl>

<dt><i>dot_nd</i>
<dd>  The negative dot product of the normal and the direction (after the normals have been inverted in the case of backfacing geometry). In the case of <a name=iIDD></a><u>light ray</u>s, it is the negative dot product of the light ray direction and the normal at the point which is to be illuminated. 

<p>
</dl>

<dl>

<dt><i>dist</i>
<dd>  The length of the ray, which is the distance from <tt><b>org</b></tt> to <tt><b>point</b></tt> if there is an origin, in <a name=iIDE></a><a href=shaders.html#iHDI>internal space</a>. A value lower or equal to 0.0 indicates that no intersection was found, and that the length is infinite. 

<p>
</dl>

<dl>

<dt><i>material</i>
<dd>  The <a name=iIDF></a><a href=scene.html#iDJG>material</a> of the primitive hit by the ray. The data can be accessed using <i>mi_db_access</i> followed by <i>mi_db_unpin</i>. This is generally not necessary because all relevant information is also available in the state. 

<p>
</dl>

<dl>

<dt><i>pri</i>
<dd>  This number uniquely identifies the primitive in the current box.  All primitives are grouped in boxes. When casting light rays, mental ray may check whether the primitive's normal is pointing away from the light and ignore the light in this case; for this reason some shaders, such as ray-marching<a name=iIDG></a> volume shaders, assign 0 to <i>pri</i> before sampling a light. Shaders other than volume shaders should restore <i>pri</i> before returning. 

<p>
</dl>

<dl>

<dt><i>shadow_tol</i>
<dd>  If a shadow ray is found to intersect the primitive in shadow, at a distance of less than this tolerance, the intersection is ignored. This prevents self-shadowing in the case of numerical inaccuracies. 

<p>
</dl>

<dl>

<dt><i>ior</i>
<dd>  This field is intended for use by material shaders that need to keep track of the index of refraction for inside/outside<a name=iIDH></a> determination. It is not used by mental ray. The <a name=iIDI></a><u>mi_mtl_refraction_index</u> shader interface function stores the index of refraction of the medium the ray travels through in this state variable. 

<p>
</dl>

<dl>

<dt><i>ior_in</i>
<dd>  Like <i>ior</i>, this field helps the shader with inside/outside calculations. It contains the ``previous'' index of refraction, in the medium the ray was travelling through before the intersection. Like <i>ior</i>, <i>ior_in</i> is neither set nor used by mental ray, it exists to allow the material shader to inherit the previous index of refraction to subsequent shaders. 

<p>
</dl>
 <p><a name=cBA><h3>Textures, Motion, Derivatives</h3></a> 

<p><a name=iIDJ></a> (see <a href=scene.html#iDJA>texture</a>) The following table is an extension to the previous. These variables give information about the intersection point for texture mapping. They are defined when the ray has hit a textured object: 

<p><a name=iIEA></a>
<p><pre> <i>type</i>               <i>name</i>                <i>content</i> 
 <hr>
 <tt><b>miVector *</b></tt>         <tt><b>tex_list</b></tt>            list of texture coordinates 
 <tt><b>miVector *</b></tt>         <tt><b>bump_x_list</b></tt>         list of X bump basis vectors 
 <tt><b>miVector *</b></tt>         <tt><b>bump_y_list</b></tt>         list of Y bump basis vectors 
 <tt><b>miVector</b></tt>           <tt><b>tex</b></tt>                 texture coord (tex shaders) 
 <tt><b>miVector</b></tt>           <tt><b>motion</b></tt>              interpolated motion vector 
 <tt><b>miVector</b></tt>           <tt><b>u_deriv</b></tt>             Surface U derivative 
 <tt><b>miVector</b></tt>           <tt><b>v_deriv</b></tt>             Surface V derivative 
 <hr>
 
</pre><p> 

<p>
<dl>

<dt><i>tex_list</i>
<dd>  <a name=iIEB></a>        A pointer to an array containing the texture coordinates of the intersection point in all <a name=iIEC></a><a href=scene.html#iGJI>texture space</a>s. When material shaders that support multiple textures on a surface call a texture lookup function, they must specify which texture coordinate to use, usually by choosing one of the texture vertices in <i>tex_list</i> and copying it to <i>tex</i>. 

<p>
</dl>

<dl>

<dt><i>bump_x_list</i>
<dd>  <a name=iIED></a>        A pointer to an array containing the x bump basis vectors in all texture spaces. The vectors are in <a name=iIEE></a><u>object space</u>. 

<p>
</dl>

<dl>

<dt><i>bump_y_list</i>
<dd>  A pointer to an array containing the y bump basis vectors in all texture spaces. The vectors are in <a name=iIEF></a><u>object space</u>. 

<p>
</dl>

<dl>

<dt><i>tex</i>
<dd>  The texture coordinates where the texture should be evaluated. This variable is available only in texture shaders; it is set by the caller (for example, a texture lookup from a material shader). 

<p>
</dl>

<dl>

<dt><i>motion</i>
<dd>  The <a name=iIEG></a><u>motion vector</u><a name=iIEH></a> of the intersection point. If the object has no motion vectors (<tt><b>m</b></tt> statements in the vertices in the scene description file), the motion vector is a null vector. 

<p>
</dl>

<dl>

<dt><i>u_deriv</i>
<dd>  If the object is a free-form surface object, the surface U derivative vector. For polygonal objects, the derivative vectors are null vectors.<a name=iIEI></a> 

<p>
</dl>

<dl>

<dt><i>v_deriv</i>
<dd>  If the object is a free-form surface object, the surface V derivative vector. The U and V derivative vectors and the normal always form right angles with one another.In  version 1.9 of mental ray, surface derivative vectors are not supported, <i>u_deriv</i> and <i>v_deriv</i> are always null vectors.

<p>
</dl>
 <p><a name=cBB><h3>User Fields</h3></a> 

<p>Finally, the user field allows a shader to store a pointer to an arbitrary data structure in the shader. Subsequent shaders called as a result of operations done by this shader (such as casting a reflection ray or evaluating a light or a texture) inherit the pointer and can read and write this shader's local data. Sub-shaders can also find other parent's user data by following state parent pointers, see above. With this method, extra parameters can be provided to and extra return values received from sub-shaders. The user variables are initialized to 0. 

<p><a name=iIEJ></a>
<p><pre> <i>type</i>               <i>name</i>                <i>content</i> 
 <hr>
 <tt><b>void *</b></tt>             <tt><b>user</b></tt>                user data pointer 
 <tt><b>int</b></tt>                <tt><b>user_size</b></tt>           user data size (optional) 
 <tt><b>miFunction *</b></tt>       <tt><b>shader</b></tt>              shader data structure 
 <hr>
 
</pre><p> 

<p>The shader pointer can be used to access the shader parameters, as <i> </i> state<i>-&gt;</i>parameters. This is redundant for the current shader because this pointer is also passed as the third shader argument, but it can be used to find a parent shader's parameters. For example, the SOFTIMAGE material shader uses this to perform inside/outside<a name=iIFA></a> calculations. 

<p> 

<p><p><a name=cBC><h2>User Parameter Declarations</h2></a> 

<p><a name=iIFB></a>In addition to the state variables that are provided by mental ray and are shared by all shaders, every shader has <i>user parameters</i>.  In the .mi scene file, shader references look much like a function call: the shader name is given along with a list of parameters. Every shader call may have a different list of parameters. mental ray does not restrict or predefine the number and types of user parameters, any kind of information may be passed to the shader. Typical examples for user parameters are ambient, diffuse, and specular colors<a name=iIFC></a><a name=iIFD></a><a name=iIFE></a> for material shaders, attenuation parameters for light shaders, and so on.  An empty parameter list in a shader call (as opposed to a shader declaration) has a special meaning; see the note at the end of this chapter. 

<p>In this manual, the term ``<a name=iIFF></a><u>parameters</u>'' refers to shader parameters in the .mi scene file; the term ``arguments'' is used for arguments to C functions. 

<p>Shaders need both state variables and user parameters. Generally, variables that are computed by mental ray, or whose interpretation is otherwise known to mental ray, and that are useful to different types or instances of shaders are found in state variables. Variables that are specific to a shader, and that may change for each instance of the shader, are found in user variables. mental ray does not access or compute user variables in any way, it merely passes them from the .mi file to the shader when it is invoked. 

<p><a name=iIFG></a><a name=iIFH></a>To interpret these parameters in the .mi file, mental ray needs a declaration of parameter names and types that is equivalent to the C struct that the shader later uses to access the parameters. The declaration in the .mi file must be exactly equivalent to the C struct, or the shader will mis-interpret the parameter data structure constructed by mental ray. This means that three parts are needed to write a shader: the C source of the shader, the C parameter struct, and the .mi declaration. The latter is normally stored in a separate file that is included into the .mi scene file using a <tt><b>$include</b></tt> statement. 

<p>Every .mi declaration has the following form: 

<p>
<p><pre>    <tt><b>declare</b></tt> <tt><b>"</b></tt><i>shadername</i><tt><b>" (</b></tt> 
        <i>type</i> <tt><b>"</b></tt><i>parametername</i><tt><b>",</b></tt> 
        <i>type</i> <tt><b>"</b></tt><i>parametername</i><tt><b>",</b></tt> 
        ... 
        <i>type</i> <tt><b>"</b></tt><i>parametername</i><tt><b>"</b></tt> 
    <tt><b>)</b></tt> 
 
</pre><p> 

<p>It is recommended that <i>shadername</i> and <i>parametername</i> are enclosed in double quotes to disambiguate them from reserved keywords and to allow special characters such as punctuation marks. 

<p>The declaration gives the name of the shader to declare, which is the name of the C function and the name used when the shader is called, followed by a list of parameters with types. Names are normally quoted to disambiguate them from keywords reserved by mental ray. Commas separate parameter declarations. The following types are supported: 

<p><a name=iIFI></a> 
<dl>

<dt><tt><b>boolean</b></tt>
<dd>  A boolean is either true or false. Possible values are <tt><b>on</b></tt>, <tt><b>off</b></tt>, <tt><b>true</b></tt>, and <tt><b>false</b></tt>. 

<p>
</dl>

<dl>

<dt><tt><b>integer</b></tt>
<dd>  Integers are in the range <i>-2<sup>31</sup> ...2<sup>31</sup>-1</i>. 

<p>
</dl>

<dl>

<dt><tt><b>scalar</b></tt>
<dd>  Scalars are floating-point numbers, defined as an optional minus sign, a sequence of digits containing a decimal point at any place, followed by an optional decimal exponent. A decimal exponent is the letter <tt><b> </b></tt> e followed by a positive or negative integer. Examples are <tt><b>1.0</b></tt>, <tt><b>.5</b></tt>, <tt><b>2.</b></tt>, <tt><b>1.e4</b></tt>, or <tt><b>-2.3e-6</b></tt> . 

<p>
</dl>

<dl>

<dt><tt><b>vector</b></tt>
<dd>  A vector is a sequence of three scalars as defined above, describing the <i>x</i>, <i>y</i>, and <i>z</i> components of the vector. 

<p>
</dl>

<dl>

<dt><tt><b>transform</b></tt>
<dd>  A transformation is a <i> 4 *4</i> matrix of scalars, with the translation in the last row. The data structure consists of an array of 16 <tt><b>miScalar</b></tt>s in row-major order. 

<p>
</dl>

<dl>

<dt><tt><b>color</b></tt>
<dd>  A color is a sequence of three or four scalars as defined above, describing the red, blue, green, and alpha components of the color, in this order. If alpha is omitted, it defaults to 0.0. 

<p>
</dl>

<dl>

<dt><tt><b>color texture</b></tt>
<dd>  Color textures name a texture as defined by a <tt><b>color texture</b></tt> statement in the .mi file. That <tt><b>color texture</b></tt> statement names either a texture file, or a texture shader followed by a user parameter list. Note that a color texture does not name the texture shader directly. When a color texture is evaluated, it returns an RGBA color. 

<p>
</dl>

<dl>

<dt><tt><b>scalar texture</b></tt>
<dd>  Scalar textures are equivalent to color textures, except that they name a <tt><b>scalar texture</b></tt> statement in the .mi file. When a scalar texture is evaluated, it returns a scalar (a single floating-point number). This is most often used to apply a texture map to a scalar material parameter such as transparency. 

<p>
</dl>

<dl>

<dt><tt><b>vector texture</b></tt>
<dd>  Vector textures are another variation; they name a <tt><b>vector texture</b></tt> statement in the .mi file, which returns a vector when evaluated. Bump maps on materials are typical applications for vector textures.Since mental ray regards all types of textures as generic shading  functions, the distinction between different texture types may disappear in future versions.  
<dt><tt><b>light</b></tt>
<dd>  Lights specify a light as defined by a <tt><b>light</b></tt> statement in the .mi file, which names a light. Like textures, light parameters do not name light shaders directly. 

<p>
</dl>
 
<dl>

<dt><tt><b>struct <i>{</i> ... <i>}</i></b></tt>
<dd>  Structures define a sub-list of parameters. This is normally used to build arrays of structures, for example to declare an array of textures, each of which comes with a blending factor. The ellipsis ... stands for another comma-separated sequence of type/parametername pairs. 

<p>
</dl>

<dl>

<dt><tt><b>array <i>type</i></b></tt></i>
<dd>  Arrays are different from all other types in that they are not named. The <tt><b>array</b></tt> keyword is a prefix to any of the above types that turns a single value into a one-dimensional array of values. For example, <tt><b>array scalar "terms"</b></tt> declares a parameter named <tt><b>terms</b></tt> that is an array of scalars. The array size is unlimited. Arrays of arrays are not supported; but arrays of structs containing arrays can be used. 

<p>
</dl>
<a name=iIFJ></a>For example, a simple material shader containing ambient, diffuse, and specular colors, transparency, an optional array of bump map <a name=iIGA></a><a name=iIGB></a><a name=iIGC></a><a name=iIGD></a><a name=iIGE></a><a name=iIGF></a>textures, and an array of lights could be declared in the .mi file as: 

<p>
<p><pre><tt><b> </b></tt>   declare "my_material" ( 
        color "ambient", 
        color "diffuse", 
        color "specular", 
        scalar "shiny", 
        scalar "reflect", 
        scalar "transparency", 
        scalar "ior", 
        vector texture "bump", 
        array light "lights" 
    ) 
 
</pre><p> 

<p>If there is only one array, there is a small efficiency advantage in listing it last. The material shader declared in this example can be used in a <tt><b>material</b></tt> statement like this: 

<p><br> 
<p><pre><tt><b> </b></tt>   material "mat1" 
        "my_material" ( 
            "specular" 1.0 1.0 1.0, 
            "ambient" 0.3 0.3 0.0, 
            "diffuse" 0.7 0.7 0.0, 
            "shiny" 50.0, 
            "bump" "tex1", 
            "lights" [ "light1", "light2", "light3" ], 
            "reflect" 0.5 
        ) 
    <tt><b>end material</b></tt> 
 
</pre><p> 

<p>Note that the parameters can be defined in any order, and that parameters can be omitted. This example assumes that the texture <tt><b> </b></tt> tex1 and the three lights have been defined prior to this material definition. Again, be sure to use the names of the textures and lights, not the names of the texture and light shaders. All names in the above two examples were written as strings enclosed in double quotes to disambiguate names from reserved keywords, and to allow special characters in the names that would otherwise be illegal. 

<p><a name=iIGG></a>When the shader <tt><b>my_material</b></tt> is called, its third argument will be a pointer to a data structure built by mental ray from the declaration and the actual parameters in the .mi file. In order for the C source of the shader to access the parameters, it needs an equivalent declaration in C syntax that must agree exactly with the .mi declaration. The type names can be translated according to the following table: 

<p>
<p><pre><tt><b> </b></tt> <i>.mi syntax</i>        <i>mental ray 1.8 syntax</i> <i>mental ray 1.9 syntax</i>
 <hr>
 boolean            int                 miBoolean 
 integer            int                 miInteger 
 scalar             float               miScalar 
 vector             Vector              miVector 
 transform          Trans               miMatrix 
 color              Color               miColor 
 color texture      Texture *           miTag 
 scalar texture     Texture *           miTag 
 vector texture     Texture *           miTag 
 light              Light *             miTag 
 string             char *              N/A 
 struct             struct              struct 
 
</pre><p> 

<p>It is strongly recommended to use the same parameter names in the C declaration as in the .mi declaration. 

<p>Arrays are more complicated than the types in this table because the size of the <a name=iIGH></a><u>array</u> is not known at declaration time. In mental ray 1.8 syntax, an <tt><b>array</b></tt> keyword in the .mi declaration must be declared as a pointer to the appropriate type followed by an integer with the same name with <tt><b>n_</b></tt> prepended. mental ray will store the number of elements in the array pointed to by the pointer in the integer. If the array is empty, both the pointer and the integer will be 0. 

<p>In mental ray 1.9, the C declaration consists of a start index prefixed with <tt><b>i_</b></tt>, the size of the array prefixed with <tt><b>n_</b></tt>, and the array itself, declared as a pointer.Future versions of mental ray  will change this pointer to an array of size [1]; see below. mental ray will allocate the structure as large as required by the actual array size at call time. To access array element <i>i</i> in the range <i> 0 ...n_array</i>, the C expression <i>array[i + i_array]</i> must be used. This expression allows mental ray 1.9 to store the user parameters in virtual shared memory regardless of the base address of the user parameter structure, which is different on every host on the network. 

<p>For the above example .mi declaration, the equivalent C structure declaration using mental ray types looks like this: 

<p>
<p><pre><tt><b> </b></tt>   struct my_material <i>{</i> 
        Color ambient; 
        Color diffuse; 
        Color specular; 
        miScalar shiny; 
        miScalar reflect; 
        miScalar transparency; 
        miScalar ior; 
        Texture *bump; 
        Light **lights; 
        int n_lights; 
    <i>}</i>; 
 
</pre><p> 

<p>while the equivalent declaration using mental ray 1.9 types is: 

<p>
<p><pre><tt><b> </b></tt>   struct my_material <i>{</i> 
        miColor ambient; 
        miColor diffuse; 
        miColor specular; 
        miScalar shiny; 
        miScalar reflect; 
        miScalar transparency; 
        miScalar ior; 
        miTag bump; 
        int i_lights; 
        int n_lights; 
        miTag *lights; 
    <i>}</i>; 
 
</pre><p> 

<p>Note that here the order of structure members must match the order in the .mi declaration exactly. For example, suppose a shader has a .mi declaration containing an <a name=iIGI></a><u>array</u> of integers: 

<p><pre>
     declare "myshader" ( array integer "list" )
</pre>


<p>The C declaration for the shader's parameters is: 

<p><pre>
     struct myshader {
          int       i_list;
          int       n_list;
          miInteger *list;
     };
</pre>


<p>A shader that needs to operate on this array, for example printing all the array elements to stdout, would use a loop like this: 

<p><pre>
     int i;
     for (i=0; i &lt; paras-&gt;n_list; i++)
          printf("%d\n", paras-&gt;list[paras-&gt;i_list + i]);
</pre>


<p>assuming that <tt><b>paras</b></tt> is the third shader argument and has type <tt><b>struct myshader *</b></tt>. (Note that printf requires that stdio.h is included.) The use of the <tt><b>i_list</b></tt> parameter may seem strange to C programmers, who may wish to hide it in a macro like 

<p><pre>
     #define EL(array,nel) array[i_##array + nel]
</pre>


<p>This macro requires an ANSI C preprocessor; K&R preprocessors do not support the <tt><b>##</b></tt> notation and should use <tt><b>/**/</b></tt> instead. This macro is not predefined in shader.h. The reason for this peculiar way of accessing arrays is improved performance. Future versions of mental ray will not use a pointer to the array, as in <tt><b>*list</b></tt> above, but an array of size 1, like <tt><b>list[1]</b></tt>. The <a name=iIGJ></a><u>array</u> <tt><b>list[1]</b></tt> has space for only one element, because the actual number of array elements depends on the shader instance in the .mi file, which may list an arbitrary number of elements. Since future versions of mental ray (2.0 and later) are based on a <a name=iIHA></a><u>virtual shared database</u> that moves pieces of data such as shader parameters transparently from one host to another, no such piece of data may contain a pointer. Pointers would not be valid in another host's virtual address space. Adjusting the pointer on the other host is impractical because it would significantly reduce performance for some scenes, and would require knowledge of the structure layout for finding the pointers that may not be available in versions of mental ray not based on a .mi front-end parser. Therefore, the array is appended to the parameter structure, so the entire block can be moved to another host in a single network transfer. It is safe to access the first element of the array, because space for it is always allocated by declarations such as <tt><b>list[1]</b></tt>, but the second is a problem because in a C declaration like 

<p><pre>
     struct myshader {
          int       i_list;
          int       n_list;
          miInteger list[1];
          miScalar  factor;
          miBoolean bool;
     };
</pre>


<p>the second element, <tt><b>list[1]</b></tt>, occupies the same address as <tt><b> </b></tt> factor, and the third overlays <tt><b>bool</b></tt>. The situation becomes more complex for arrays of structures. The solution is to put the value of the first element after the last ``regular'' shader parameter, <tt><b> </b></tt> bool in this example, followed by the other element values. This means that the first few C array elements that overlay other parameters must be skipped. The <tt><b>i_</b></tt> variable tells the shader writer exactly how many. In the example, <tt><b>i_list</b></tt> would be 3. Assuming the following shader instance, used as part of a material, texture, or some other definition requiring a shader call: 

<p><pre>
     "myshader" (
          "factor"  1.4142136,
          "list"  [ 42, 123, 486921, 777 ],
          "bool"    on
     )
</pre>


<p>mental ray would arrange the values in memory like this: 

<p> 
<p><center>
<img src="array.fig.ps.gif" alt="array.fig.ps.gif">
 </center><p>
  

<p>This diagram assumes that a <tt><b>miScalar</b></tt> uses four bytes; this may not be true in all versions. If it used eight bytes, four bytes of padding would be inserted before it by mental ray and the C compiler, and <tt><b>i_list</b></tt> would have the value 5. 

<p>There is one exception to shader parameter passing that can be a hard-to-find source of errors. If a shader is called with no parameters in the .mi file, using an opening parenthesis directly followed by a closing parenthesis, the shader will receive a zero-sized parameter block instead of a zero-filled parameter block. This is done to support an optimization for shadow shaders:  a shadow shader called with no parameters is called with the parameters of the material shader. This reduces memory consumption because the shadow shader and the material shader almost always have the same parameters, which can be quite large. The problem occurs if a shader <i>other</i> than a shadow shader is called with no parameters because there is no material shader whose parameters could be substituted. 

<p>The following sections discuss the various types of shaders, and how to write custom shaders of those types. Basic concepts are introduced step by step, including supporting functions and state variables supplied by mental ray. All support functions are summarized at the end of this chapter. All descriptions apply to mental ray 1.9. 

<p><br>
 

<p><p><a name=cBD><h2>Material Shaders</h2></a> 

<p>Material shaders are the primary type of shaders. All materials defined in the scene must at least define a <a name=iIHB></a><u>material shader</u>. Materials may also define other types of shaders, such as shadow, volume, and environment shaders, which are optional and of secondary importance. 

<p><a name=iIHC></a><a name=iIHD></a>When mental ray casts a visible ray, such as those cast by the camera (called <i>primary rays</i>) or those that are cast for reflections and refractions (collectively called <i> </i> secondary rays), mental ray determines the next object in the scene that is hit by that ray. This process is called<a name=iIHE></a> <i>intersection testing</i>. For example, when a primary ray cast from the camera through the viewing plane's pixel <i>(100,100)</i> intersects with a yellow sphere, pixel <i>(100, 100)</i> in the output image will be painted yellow. (The actual process is slightly complicated by supersampling, which can cause more than one primary ray to contribute to a pixel.) 

<p>The core of mental ray has no concept of ``yellow''. This color is computed by the material shader attached to the sphere that was hit by the ray. mental ray records general information about the sphere object, such as point of intersection, normal vector, transformation matrix etc. in a data structure called the <i>state</i>, and calls the material shader attached to the object. More precisely, the material shader, along with its parameters (called <i>user parameters</i>), is part of the material, which is attached to the polygon or surface that forms the part of the object that was hit by the ray. Objects are usually built from multiple polygons and/or surfaces, each of which may have a different material. 

<p>The material shader uses the values provided by mental ray in the state and the variables provided by the .mi file in the user parameters to calculate the color of the object, and returns that color. In the above example, the material shader would return the color yellow. mental ray stores this color in the frame buffer and casts the next primary ray. Note that if the material shader has a bug that causes it to return <a name=iIHF></a><u>infinity</u> or <a name=iIHG></a><u>NaN (Not a Number)</u> in the <tt><b>result</b></tt> color, the infinity or NaN is stored as 1.0 in integer color frame buffers. This usually results in <a name=iIHH></a><u>white pixels</u> in the rendered image. This is true for subshaders such as texture shaders also.<a name=iIHI></a> 

<p>If an appropriate <tt><b>output</b></tt> statement (see the scene decsription chapter), mental ray computes depth, label, and normal-vector frame buffers in addition to the standard color frame buffer. The color returned by the first-generation material shader is stored in the color <a name=iIHJ></a><a href=shaders.html#iBAGD>frame buffer</a> (unless a <a name=iIIA></a><a href=shaders.html#iHGG>lens shader</a> exists; lens shaders also have the option of modifying colors). The material shader can control what gets stored in the depth, label, and normal-vector frame buffers by storing appropriate values into <i>state-&gt; point.z</i>, <i>state-&gt;label</i>, and <i>state-&gt;normal</i>, respectively. Depth is the negative Z coordinate. 

<p>Material shaders normally do quite complicated computations to arrive at the final color of a point on the object: 

<p> <a name=iIIB></a><a name=iIIC></a><a name=iIID></a><a name=iIIE></a> (see <a href=scene.html#iDJA>texture</a>) 
<ul>

<li>  The user parameters usually contain constant ambient, diffuse, and specular colors and other parameters such as transparency, and optional textures that need to be evaluated to compute the actual values at the intersection point. If textures are present, texture shaders are called by using one of the lookup functions provided by mental ray. Texture shaders are discussed in the next section. 

<p>
</ul>
<a name=iIIF></a>
<ul>

<li>  The illumination computation sums up the contribution from various light sources listed in the user parameters. To obtain the amount of light arriving from a light source, a light shader is called by calling a light trace or sample function provided by mental ray. Light shaders are discussed in a separate section below. After the illumination computation is finished, the ambient, diffuse, and specular colors have been combined into a single material color (assuming a more conventional material shader). 

<p>
</ul>
<a name=iIIG></a> (see <a href=shaders.html#iHJI>secondary ray</a>) <a name=iIIH></a><a name=iIII></a><a name=iIIJ></a><a name=iIJA></a>
<ul>

<li>  If the material is reflective, transparent, or using refraction, as indicated by appropriate user parameters, the shader must cast secondary rays and apply the result to the material color calculated in the previous step. (Transparency is a variation of refractive transparency where the ray continues in the same direction, while refraction rays may alter the direction based on an index of refraction.) Secondary rays, like primary rays, cause mental ray to do intersection testing and call another material shader if the intersection test hit an object. For this reason, material shaders must be re-entrant. In particular, a secondary refraction or transparency ray will hit the back side of the same object if <tt><b>face both</b></tt> is set in the view and the object is a closed volume. 

<p>
</ul>
Note that the user parameters of a material shader are under no obligation to define and use classical parameters like ambient, diffuse, and specular color and reflection and refraction parameters. Here is a full-featured example for the C source of the shader declared in the previous section: 

<p><a name=iIJB></a><a name=iIJC></a> (see <a href=shaders.html#iBAEF><i>mi_call_shader</i></a>) <a name=iIJD></a> (see <a href=shaders.html#iBACG><i>mi_sample_light</i></a>) <a name=iIJE></a> (see <a href=shaders.html#iBBCC><i>mi_reflection_dir</i></a>) <a name=iIJF></a> (see <a href=shaders.html#iBBCD><i>mi_refraction_dir</i></a>) <a name=iIJG></a> (see <a href=shaders.html#iBABE><i>mi_trace_reflection</i></a>) <a name=iIJH></a> (see <a href=shaders.html#iBABG><i>mi_trace_refraction</i></a>) <a name=iIJI></a> (see <a href=shaders.html#iBACF><i>mi_trace_environment</i></a>) <pre>
     miBoolean my_material(
        miColor            *result,
        miState            *state,
        struct my_material *paras)
     {
        miVector           bump, dir;
        miColor            color;
        int                num;
        miTag              *light;
        miScalar           ns;

        /*
         * bump map
         */
        state-&gt;tex = state-&gt;tex_list[0];
        (void)mi_call_shader((miColor *)&amp;bump,
                             miSHADER_TEXTURE,
                             state, paras-&gt;bump);

        if (bump.x != 0 || bump.y != 0) {
            mi_vector_to_object(&amp;state-&gt;normal,
                                &amp;state-&gt;normal);
            state-&gt;normal.x+=bump.x * state-&gt;bump_x_list-&gt;x
                            +bump.y * state-&gt;bump_y_list-&gt;x;
            state-&gt;normal.y+=bump.x * state-&gt;bump_x_list-&gt;y
                            +bump.y * state-&gt;bump_y_list-&gt;y;
            state-&gt;normal.z+=bump.x * state-&gt;bump_x_list-&gt;z
                            +bump.y * state-&gt;bump_y_list-&gt;z;
            mi_vector_from_object(&amp;state-&gt;normal,
                                  &amp;state-&gt;normal);
            mi_vector_normalize(&amp;state-&gt;normal);
            state-&gt;dot_nd = mi_vector_dot(&amp;state-&gt;normal,
                                          &amp;state-&gt;dir);
        }

        /*
         * illumination
         */
        *result = paras-&gt;ambient;
        for (num=0; num &lt; paras-&gt;n_lights; num++) {
            miColor    color, sum;
            miInteger  samples = 0;
            miScalar   dot_nl;

            sum.r = sum.g = sum.b = 0;
            light = paras-&gt;lights[paras-&gt;i_lights + num];
            while (mi_sample_light(&amp;color, &amp;dir, &amp;dot_nl,
                                  state, light, &amp;samples)) {

                 sum.r += dot_nl*paras-&gt;diffuse.r * color.r;
                 sum.g += dot_nl*paras-&gt;diffuse.g * color.g;
                 sum.b += dot_nl*paras-&gt;diffuse.b * color.b;

                 ns = mi_phong_specular(paras-&gt;shiny,
                                        state, &amp;dir);
                 sum.r += ns * paras-&gt;specular.r * color.r;
                 sum.g += ns * paras-&gt;specular.g * color.g;
                 sum.b += ns * paras-&gt;specular.b * color.b;
            }
            if (samples) {
                 result-&gt;r += sum.r / samples;
                 result-&gt;g += sum.g / samples;
                 result-&gt;b += sum.b / samples;
            }
        }
        result-&gt;a = 1;

        /*
         * reflections
         */
        if (paras-&gt;reflect &gt; 0) {
            miScalar f = 1 - paras-&gt;reflect;
            result-&gt;r *= f;
            result-&gt;g *= f;
            result-&gt;b *= f;

            mi_reflection_dir(&amp;dir, state);
            if (mi_trace_reflection (&amp;color,state,&amp;dir) ||
                mi_trace_environment(&amp;color,state,&amp;dir)) {

                 result-&gt;r += paras-&gt;reflect * color.r;
                 result-&gt;g += paras-&gt;reflect * color.g;
                 result-&gt;b += paras-&gt;reflect * color.b;
            }
        }

        /*
         * refractions
         */
        if (paras-&gt;transparency &gt; 0) {
            miScalar f = 1 - paras-&gt;transparency;
            result-&gt;r *= f;
            result-&gt;g *= f;
            result-&gt;b *= f;
            result-&gt;a  = f;

            if (mi_refraction_dir(&amp;dir,state,1.0,state-&gt;ior)
             &amp;&amp; mi_trace_refraction (&amp;color,state,&amp;dir) ||
                mi_trace_environment(&amp;color,state,&amp;dir))) {

                 result-&gt;r += paras-&gt;transparency * color.r;
                 result-&gt;g += paras-&gt;transparency * color.g;
                 result-&gt;b += paras-&gt;transparency * color.b;
                 result-&gt;a += paras-&gt;transparency * color.a;
            }
        }
        return(miTRUE);
     }
</pre>


<p>Four steps are required for computing the material color in this shader. First, the normal is perturbed by looking up a vector in the vector <a name=iIJJ></a><a name=iJAA></a>texture, and using the bump basis vectors to determine the orientation of the perturbation (the lookup always returns an XY vector). The second step loops over all light sources in the light array parameter, adding the contribution of each light according to the Phong equation. <a name=iJAB></a>In the case of area lights, the light is sampled more than once, until the light sampling function is satisfied. 

<p>Finally, reflection and refraction rays are cast if the appropriate parameters are nonzero. In both cases, first the direction vector <tt><b> </b></tt> dir is computed using a built-in function, and a ray is cast in that direction. If either trace function returns <tt><b>miFALSE</b></tt>, indicating that no object was hit, the material's environment map that forms a sphere around the entire scene is evaluated. (Note that if the material has no environment map, the environment map in the state defaults to the environment shader from the view, if present.) When all computations are finished, the calculated color, including the alpha component, is returned in the <tt><b>result</b></tt> parameter. The shader returns <tt><b>miTRUE</b></tt> indicating that the computation succeded. 

<p><br>
 

<p><p><a name=cBE><h2>Texture Shaders</h2></a> 

<p><a name=iJAC></a><a name=iJAD></a><a name=iJAE></a>Texture shaders evaluate a texture and return a color. Textures can either be procedural, for example evaluating a 3D texture based on noise functions or calling other shaders, or they can do an image lookup. The .mi format provides different <tt><b>texture</b></tt> statements for these two types, one with a function call and one with a texture file name. Refer to the scene description for details. 

<p><a name=iJAF></a>Texture shaders are not first-class shaders, mental ray never calls one by itself and provides no special support for them. Texture shaders are called exclusively by other shaders. There are three ways of calling a texture shader from a material shader or other shaders: either by simply calling the shader by name like any other C function, or by using a built-in convenience function like <a name=iJAG></a><a href=shaders.html#iBBEH><i>mi_lookup_color_texture</i></a>, or by a statement like 

<p><a name=iJAH></a> (see <a href=shaders.html#iBAEF><i>mi_call_shader</i></a>) <pre>
     mi_call_shader(result, miSHADER_TEXTURE, state, tag);
</pre>


<p>The <i>tag</i> argument references the texture function. The texture function is a data structure in the scene database that contains a reference to the C function itself, plus a user parameter block that is passed to the texture shader when it is called. All textures listed in the .mi scene description file are installed as texture shaders callable only with the <tt><b>mi_call_shader</b></tt> method, because only then can user parameters be passed. Although the texture shader could also be called directly with a statement such as 

<p><pre>
     soft_color(result, state, &amp;soft_color_paras);
</pre>


<p>the caller would have to write the required arguments into the user argument structure <i>soft_color_paras</i> itself; it would not have access to user parameters specified in the .mi file. Also, this call <a name=iJAI></a> (see <a href=shaders.html#iHHF>shader call tree</a>) does not copy the state, as <tt><b>mi_call_shader</b></tt> does. 

<p><a name=iJAJ></a>Unlike material shaders, texture shaders return a simple color or scalar or other return value. There are no lighting calculations or secondary rays. This greatly simplifies the task of changing a textured surface. For example, a simple texture shader that does a simple, non-antialiased lookup in a texture image could be written as: 

<p><a name=iJBA></a><a name=iJBB></a> (see <a href=shaders.html#iBAFF><i>mi_db_access</i></a>) <a name=iJBC></a> (see <a href=shaders.html#iBAHB><i>mi_img_get_color</i></a>) <a name=iJBD></a> (see <a href=shaders.html#iBAFH><i>mi_db_unpin</i></a>) <pre>
     miBoolean mytexture(
        register miColor    *result,
        register miState    *state,
        struct image_lookup *paras)
     {
        miImg_image         *image;
        int                 xs, ys;

        image = mi_db_access(paras-&gt;texture);
        mi_texture_info(paras-&gt;texture, &amp;xs, &amp;ys, 0);
        mi_img_get_color(image, result,
                         state-&gt;tex.x * (xs - 1),
                         state-&gt;tex.y * (ys - 1));
        mi_db_unpin(paras-&gt;texture);
        return(miTRUE);
     }
</pre>


<p><a name=iJBE></a>This shader assumes that the texture coordinate can be taken from <i> </i> state<i>-&gt;</i>tex, where the caller (usually a material shader) has stored it, probably by selecting a texture coordinate from <i> </i> state<i>-&gt;</i>tex_list. A more complicated shader that can properly anti-alias <a name=iJBF></a><a href=scene.html#iDJC>image texture</a>s with a simple box filter, could look like this: 

<p><a name=iJBG></a><a name=iJBH></a> (see <a href=shaders.html#iBAFC>tag type</a>) <a name=iJBI></a> (see <a href=shaders.html#iBAFB><i>mi_db_type</i></a>) <a name=iJBJ></a> (see <a href=shaders.html#iBAEF><i>mi_call_shader</i></a>) <a name=iJCA></a> (see <a href=shaders.html#iBAFF><i>mi_db_access</i></a>) <a name=iJCB></a> (see <a href=shaders.html#iBAHB><i>mi_img_get_color</i></a>) <a name=iJCC></a> (see <a href=shaders.html#iBAFH><i>mi_db_unpin</i></a>) <pre>
     miBoolean mytexture2(
        register miColor    *result,
        register miState    *state,
        struct image_lookup *paras)
     {
        miImg_image         *image;
        int                 xs, ys;
        miColor             col00, col01, col10, col11;
        register int        x, y;
        register miScalar   u, v, nu, nv;

        image = mi_db_access(paras-&gt;texture);
        mi_texture_info(paras-&gt;texture, &amp;xs, &amp;ys, 0);
        x = u = state-&gt;tex.x * (xs - 2);
        y = v = state-&gt;tex.y * (ys - 2);
        u -= x;
        v -= y;
        nu = 1 - u;
        nv = 1 - v;

        mi_img_get_color(image, &amp;col00, x,   y);
        mi_img_get_color(image, &amp;col01, x+1, y);
        mi_img_get_color(image, &amp;col10, x,   y+1);
        mi_img_get_color(image, &amp;col11, x+1, y+1);

        result-&gt;r = nv * (nu * col00.r + u * col01.r) +
                     v * (nu * col10.r + u * col11.r);
        result-&gt;g = nv * (nu * col00.g + u * col01.g) +
                     v * (nu * col10.g + u * col11.g);
        result-&gt;b = nv * (nu * col00.b + u * col01.b) +
                     v * (nu * col10.b + u * col11.b);
        result-&gt;a = nv * (nu * col00.a + u * col01.a) +
                     v * (nu * col10.a + u * col11.a);

        mi_db_unpin(paras-&gt;texture);
        return(miTRUE);
     }
</pre>


<p>The implementation of the body of this shader is equivalent to the built-in <a name=iJCD></a><a href=shaders.html#iBBEH><i>mi_lookup_color_texture</i></a> function if called with <i>paras<i>-&gt;</i>texture</i>, except that this function also recognizes if the texture is a shader, and calls <a name=iJCE></a><a href=shaders.html#iBAEF><i>mi_call_shader</i></a> in this case. 

<p>This shader can further be extended by applying texture transformations to <i>state<i>-&gt;</i>tex</i> before it is used for the lookup, for example for rotated, scaled, repeating, or cropped textures. The shader <a name=iJCF></a>may also decide that a scaled-down texture was missed, and return <tt><b> </b></tt> miFALSE. The material shader must then skip this texture if <a name=iJCG></a><a href=shaders.html#iBAEF><i> mi_call_shader</i></a> returns <tt><b>miFALSE</b></tt>; the built-in SOFTIMAGE material shader does this. 

<p>Both of the above shaders have user parameters that consist of a single texture. Textures always have type <tt><b>miTag</b></tt>. Image file textures are read in by the translator and provided as a tag. 

<p><br>
 

<p><p><a name=cBF><h2>Volume Shaders</h2></a> 

<p><a name=iJCH></a>Volume shaders may be attached to the view or to a material. They modify the color returned from an intersection point to account for the distance the ray traveled through a volume. The most common application for volume<a name=iJCI></a><a name=iJCJ></a> shaders is atmospheric fog effects; for example, a simple volume shader may simulate fog by fading the input color to white depending on the ray distance. By definition, the distance <i>dist</i> given in the state is 0.0 and the intersection <i>point</i> is undefined if the ray has infinite length. 

<p><a name=iJDA></a> (see <a href=shaders.html#iHHF>shader call tree</a>) Volume shaders are normally called in three situations. When a material shader returns, the volume shader that the material shader left in the <i>state<i>-&gt;</i>volume</i> variable is called, without copying the state, as if it had been called as the last operation of the material shader. Copying the state is not necessary because the volume shader does not return to the material shader, so it is not necessary to preserve any variables in the state. 

<p><a name=iJDB></a><a name=iJDC></a>Volume shaders are also called when a light shader has returned; in this case the volume shader <i>state<i>-&gt;</i>volume</i> is called once for the entire distance from the light source to the illuminated point (i.e., to the point that caused the material shader that sampled the light to be called). Some volume shaders may decide that they should not apply to such light rays; this can be done by returning immediately if the <i>state<i>-&gt;</i>type</i> variable is <tt><b> </b></tt> miRAY_LIGHT.  Finally, volume shaders are called after an <a name=iJDD></a><a href=shaders.html#iHGE>environment shader</a> was called. Note that if a volume shader is called after the material, light, or other shader, the return value of that other shader is discarded and the return value of the volume shader is used. The reason is that a volume shader can substitute a non-black color even the original shader has given up. Volume shaders return <tt><b>miFALSE</b></tt> if no light can pass through the given volume, and <tt><b>miTRUE</b></tt> if there is a non-black result color. 

<p><a name=iJDE></a> (see <a href=scene.html#iDJH>material shader</a>) <a name=iJDF></a>Material shaders have two separate state variables dealing with volumes, <i>volume</i> and <i>refraction_volume</i>. If the material shader casts a refraction or transparency ray, the tracing function will copy the refraction volume shader, if there is one, to the volume shader after copying the state.  This means that the next intersection point finds the refraction volume in <i>state<i>-&gt;</i>volume</i>, which effectively means that once the ray has entered an object, that object's interior volume shader is used. However, the material shader is responsible to detect when a refraction ray exits an object, and overwrite <i>state<i>-&gt;</i>refraction_volume</i>  with an appropriate outside volume shader, such as <i> </i> state<i>-&gt;</i>camera<i>-&gt;</i>volume, or a volume shader found by following the <i>state<i>-&gt;</i>parent</i> links. 

<p>Since volume shaders modify a color calculated by a previous material shader, environment shader, or light shader, they differ from these shaders in that they receive an input color in the <i>result</i> argument that they are expected to modify. A very simple fog volume shader could be written as: 

<p><a name=iJDG></a><pre>
     miBoolean myfog(
        register miColor      *result,
        register miState      *state,
        register struct myfog *paras)
     {
        register miScalar     fade;

        if (state-&gt;type == miRAY_LIGHT)
             return(miTRUE);

        fade = state-&gt;dist &gt; paras-&gt;maxdist
                   ? 1.0
                   : state-&gt;dist / paras-&gt;maxdist;

        result-&gt;r = fade     * paras-&gt;fogcolor.r
                  + (1-fade) * result-&gt;r;
        result-&gt;g = fade     * paras-&gt;fogcolor.g
                  + (1-fade) * result-&gt;g;
        result-&gt;b = fade     * paras-&gt;fogcolor.b
                  + (1-fade) * result-&gt;b;
        result-&gt;a = fade     * paras-&gt;fogcolor.a
                  + (1-fade) * result-&gt;a;

        return(miTRUE);
     }
</pre>


<p>This shader linearly fades the input color to <i> </i> state<i>-&gt;</i>fogcolor (probably white) within <i> </i> state<i>-&gt;</i>maxdist internal space units.  <a name=iJDH></a> (see <a href=shaders.html#iJCJ>atmosphere</a>) Objects more distant are completely lost in <a name=iJDI></a><a href=shaders.html#iJCI>fog</a>. The length of the ray to be modified can be found in <i>state<i>-&gt;</i>dist</i>, its start point in <i>state<i>-&gt;</i>org</i>, and its end point in <i> </i> state<i>-&gt;</i>point. This example shader does not apply to <a name=iJDJ></a><u>light ray</u>s, light sources can penetrate fog of any depth because of the <tt><b>miRAY_LIGHT</b></tt> check. In this case, the shader returns <tt><b> </b></tt> miTRUE anyway because the shader did not fail; it merely decided not to apply fog. 

<p>If this shader is attached to the view, the atmosphere surrounding the scene will contain fog. Every <i>state<i>-&gt;</i>volume</i> will inherit this view volume shader, until a refraction or transparency ray is cast. <a name=iJEA></a> (see <a href=shaders.html#iHHF>shader call tree</a>) The ray will copy the material's volume shader, <i>state<i>-&gt;</i>refraction_volume</i>, if there is one, to <i> </i> state<i>-&gt;</i>volume, and the ray is now assumed to be in the object. If the material has no volume shader to be copied, the old volume shader will remain in place and will be inherited by subsequent rays. 

<p>Some volume shaders employ <a name=iJEB></a><u>ray marching</u> techniques to sample lights from empty space, to achieve effects such as visible light beams. Before such a shader calls <i>mi_sample_light</i>, it should store 0 in <i>state<i>-&gt;</i>pri</i> to inform mental ray that there is no primitive to illuminate, and to not attempt certain optimizations such as backface elimination. Shaders other than volume shaders may do this too, but must restore <i>pri</i> before returning. 

<p><br>
 

<p><p><a name=cBG><h2>Environment Shaders</h2></a> 

<p><a name=iJEC></a>Environment shaders provide a color for rays that leave the scene entirely, and for rays that would exceed the trace depth limit. Environment shaders are called automatically by mental ray if a ray leaves<a name=iJED></a> the scene, but not when a ray exceeds the trace depth. This can be done by the shader that tried to cast the ray if the ray-tracing function returned <tt><b>miFALSE</b></tt>, by calling <i> </i> mi_trace_environment: 

<p><a name=iJEE></a> (see <a href=shaders.html#iBBCC><i>mi_reflection_dir</i></a>) <a name=iJEF></a> (see <a href=shaders.html#iBABE><i>mi_trace_reflection</i></a>) <a name=iJEG></a> (see <a href=shaders.html#iBACF><i>mi_trace_environment</i></a>) <pre>
     mi_reflection_dir(&amp;dir, state);
     if (mi_trace_reflection (&amp;color, state, &amp;dir) ||
         mi_trace_environment(&amp;color, state, &amp;dir))
             /* use the returned color */
</pre>


<p>This code fragment was taken from the example material shader in the section on materials above. If the <i>mi_trace_reflection</i> call fails, call <i>mi_trace_environment</i>; if that also fails, do not use the returned color. Environment shaders, like any other shader, may return <tt><b>miFALSE</b></tt> to inform the caller that the environment lookup failed. 

<p>In both the explicit case and the automatic case (when a ray cast by a function call such as <i>mi_trace_reflection</i> leaves the scene without intersecting with any object) mental ray calls the environment shader found in <i>state<i>-&gt;</i>environment</i>. In <a name=iJEH></a><a href=shaders.html#iHJH>primary ray</a>s, this variable is initialized with the global environment shader in the view (also found in <i>state<i>-&gt;</i>camera<i>-&gt;</i>environment</i>). <a name=iJEI></a> (see <a href=shaders.html#iHHF>shader call tree</a>) Subsequent material shaders get the environment defined in the material if present, or the view environment otherwise. Material shaders never inherit the environment from the parent shader, they always use the environment in the material or the view. All other types of shaders inherit the environment from the parent shader. 

<p>Here is an example environment shader that uses a texture that covers an infinite sphere around the scene: 

<p><a name=iJEJ></a><a name=iJFA></a><pre>
    miBoolean myenv(
        register miColor      *result,
        register miState      *state,
        register struct myenv *paras)
    {
        register miScalar     theta;
        miVector              coord;

        theta = fabs(state-&gt;dir.z)*HUGE &lt; fabs(state-&gt;dir.x)
                ? state-&gt;dir.x &gt; 0
                        ? 1.5*M_PI
                        : 0.5*M_PI
                : state-&gt;dir.z &gt; 0
                        ? 1.0*M_PI + atan(state-&gt;dir.x /
                                          state-&gt;dir.z)
                        : 2.0*M_PI + atan(state-&gt;dir.x /
                                          state-&gt;dir.z);
        if (theta &gt; 2 * M_PI)
             theta -= 2 * M_PI;

        coord.x = 1 - theta / (2 * M_PI);
        coord.y = 0.5 * (state-&gt;dir.y + 1.0);
        coord.z = 0;

        state-&gt;tex = coord;
        return(mi_call_shader(result, miSHADER_TEXTURE,
                               state, paras-&gt;texture));
     }
</pre>


<p>This shader gets a single parameter in its user parameter structure, a <tt><b>miTag</b></tt> for a texture shader. The texture is evaluated by storing the texture coordinate in <i>state<i>-&gt;</i>tex</i> and calling the texture shader with <i>mi_call_shader</i>. For a description of texture shaders and how to call them, see the Texture section above. 

<p><br>
 <p><a name=cBH><h2>Light Shaders</h2></a> 

<p><a name=iJFB></a>Light shaders are called from other shaders by sampling a light using the <a name=iJFC></a><a href=shaders.html#iBACG><i>mi_sample_light</i></a> or <a name=iJFD></a><a href=shaders.html#iBADH><i> mi_trace_light</i></a> functions, which perform some calculations and then call the given light shader. <i>mi_sample_light</i> may also request that it is called more than once if an <a name=iJFE></a><u>area light</u> source is to be sampled, at locations chosen by the sampling algorithm chosen by the <tt><b>-mc</b></tt> or <tt><b>-qmc</b></tt> command-line options. For an example for using <i>mi_sample_light</i>, see the section on material shaders above. <i>mi_trace_light</i> performs less exact shading for area lights, and is provided for backwards compatibility only. 

<p>The light shader computes the amount of light contributed by the light source to a previous intersection point, stored in <i> </i> state<i>-&gt;</i>point. The calculation may be based on the direction <i>state<i>-&gt;</i>dir</i> to that point, and the distance <i> </i> state<i>-&gt;</i>dist from the light source to that ray. There may also be user parameters that specify directional and distance attenuation. Directional lights have no location; <i>state<i>-&gt;</i>dist</i> is undefined in this case. 

<p><a name=iJFF></a>Light shaders are also responsible for shadow casting. Shadows are computed by finding all objects that are in the path of the light <a name=iJFG></a>from the light source to the illuminated intersection point. This is <a name=iJFH></a>done in the light shader by casting ``shadow rays'' after the standard light color computation including attenuation is finished. Shadow rays are cast from the light source back towards the illuminated point, in the same direction of the <a name=iJFI></a><u>light ray</u>. Every time an occluding object is found, that object's shadow shader is called, if it has one, which reduces the amount of light based on the object's <a name=iJFJ></a><u>transparency</u> and color. If an occluding object is found that has no shadow shader, it is assumed to be opaque, so no light from the light source can reach the illuminated point. For details on shadow shaders, see the next section. 

<p><a name=iJGA></a>Here is an example for a simple point light that supports no attenuation, but casts shadows: 

<p><a name=iJGB></a><a name=iJGC></a> (see <a href=shaders.html#iBAEB><i>mi_trace_shadow</i></a>) <pre>
     miBoolean mypoint(
        register miColor        *result,
        register miState        *state,
        register struct mypoint *paras)
     {
        *result = paras-&gt;color;
        return(mi_trace_shadow(result, state));
     }
</pre>


<p>The user parameters are assumed to contain the light color. The shadows are calculated simply by giving the shadow shaders of all occluding objects the chance to reduce the light from the light source, by calling <i>mi_trace_shadow</i>. The shader returns <tt><b>miTRUE</b></tt> if some light reaches the illuminated point. 

<p><a name=iJGD></a>The point light can be turned into a spot light by adding directional attenuation parameters for the inner and outer cones and a spot direction parameter to the user parameters, and change the shader to reduce the light intensity if the illuminated point falls between the inner and outer cones, and turns the light off if it doesn't fall into the outer cone at all: 

<p><a name=iJGE></a><a name=iJGF></a> (see <a href=shaders.html#iBAEB><i>mi_trace_shadow</i></a>) <pre>
     miBoolean myspot(
        register miColor           *result,
        register miState           *state,
        register struct soft_light *paras)
     {
        register miScalar          d, t;

        *result = paras-&gt;color;

        d = mi_vector_dot(&amp;state-&gt;dir, &amp;paras-&gt;direction);
        if (d &lt;= 0)
             return(miFALSE);
        if (d &lt; paras-&gt;outer)
             return(miFALSE);
        if (d &lt; paras-&gt;inner) {
             t = (paras-&gt;outer - d) /
                 (paras-&gt;outer - paras-&gt;inner);
             result-&gt;r *= t;
             result-&gt;g *= t;
             result-&gt;b *= t;
        }
        return(mi_trace_shadow(result, state));
     }
</pre>


<p>Again, <tt><b>miFALSE</b></tt> is returned if no illumination takes place, and <tt><b>miTRUE</b></tt> otherwise. Note that none of these light shaders takes the normal at the illuminated point into account; the light shader is merely responsible for calculating the amount of light that reaches <a name=iJGG></a> (see <a href=scene.html#iDJH>material shader</a>) that point. The material shader (or other shader) that sampled the light must use the <i>dot_nd</i> value returned by <i>mi_sample_light</i>, and its own user parameters such as the diffuse color, to calculate the actual fraction of light reflected by the material. 

<p><br>
 <p><a name=cBI><h2>Shadow Shaders</h2></a> 

<p><a name=iJGH></a>As described in the previous section, light shaders may trace a shadow ray from the light source to the point to be illuminated. When this ray hits an occluding object, that object's shadow shader is called, if present. (If the object has no shadow shader, the object is assumed to block all light.) Shadow shaders accept an input color that is dimmed according to the <a name=iJGI></a><u>transparency</u> and color of the occluding object. 

<p>If there is more than one occluding object between the light source and the illuminated point, the order in which the shadow shaders of the occluding objects is called is undefined, unless the <tt><b>shadow_sort</b></tt> option in the view is turned on. Shadow shaders that rely on being called in the correct order, the one closest to the light source first, should check that <i>state<i>-&gt;</i>shadow_sort</i> is <tt><b>miTRUE</b></tt>, and abort with a fatal error message otherwise, telling the user to turn on shadow sorting. 

<p>If a new material shader is written, it is often necessary to also write a matching shadow shader. The shadow shader performs a subset of the calculations done in the material shader: it may evaluate textures and transparencies, but it will not sample lights and it will not cast rays. The shader writer can either write a separate shadow shader, or let the <a name=iJGJ></a><a href=scene.html#iDJH>material shader</a> double as shadow shader by building the scene such that the material shader appears twice in the material definition. SOFTIMAGE shaders take the latter approach. It relies on the material shader to omit all calculations that are necessary only in the material shader when called as a shadow shader. The shader can find out whether it is called as a material shader or as a shadow shader by checking if <i>state<i>-&gt;</i>type</i> is <tt><b> </b></tt> miRAY_SHADOW: if yes, this is a shadow shader. This sharing of shaders pays off only when the texture computations are very complicated, as is the case in SOFTIMAGE materials. 

<p>The following shadow shader is a separate shader that attenuates the light that passes through the object based on two user parameters, <a name=iJHA></a><a name=iJHB></a><a name=iJHC></a><a name=iJHD></a>the diffuse color and the transparency. Material shaders usually also have ambient and specular colors, but the best approach is to pass the diffuse color to shadow shaders because it describes the ``true color'' of the object best. Note that the scene can be arranged such that although the shadow shader is separate from the material shader, <a name=iJHE></a> (see <a href=shaders.html#iIFB>shader parameters</a>) it still gets a copy of the material shader's user parameters so the shadow shader can access the ``true'' material parameters. In a .mi file, this is done by declaring the shadow shader with no parameters and naming none in the <tt><b>shadow</b></tt> statement in the material definition (just give <tt><b>()</b></tt>). This sharing of parameters even if the shader itself is not shared can save duplicating a large set of parameters. 

<p><pre>
     miBoolean myshadow(
        register miColor         *result,
        register miState         *state,
        register struct myshadow *paras)
     {
        register miScalar        opacity;
        register miScalar        f, omf;

        opacity = 1 - paras-&gt;transp;
        if (opacity &lt; 0.5) {
             f = 2 * opacity;
             result-&gt;r *= f * diffuse.r;
             result-&gt;g *= f * diffuse.g;
             result-&gt;b *= f * diffuse.b;
        } else {
             f = 2 * (opacity - 0.5);
             omf = 1 - f;
             result-&gt;r *= f + omf * diffuse.r;
             result-&gt;g *= f + omf * diffuse.g;
             result-&gt;b *= f + omf * diffuse.b;
        }
        return(result-&gt;r != 0 ||
               result-&gt;g != 0 ||
               result-&gt;b != 0);
     }
</pre>


<p>The <i>org</i> variable in the state always contains the position of the light source responsible for casting the shadow rays; the <tt><b> </b></tt> point state variable contains the point on the shadow-casting object. The <i>dist</i> state variable is the distance to the light source (except for directional lights, which have no origin). 

<p><br>
 <p><a name=cBJ><h2>Lens Shaders</h2></a> 

<p><a name=iJHF></a><a name=iJHG></a><a name=iJHH></a>Lens shaders are called for primary rays from the camera. The camera is normally a simple pinhole camera. A lens shader modifies the origin and direction of a primary ray from the camera. More than one lens shader may be attached to the camera; each modifies the origin and direction calculated by the previous one. By convention, all rays up to and including the one leaving the last lens are called ``primary rays''. <a name=iJHI></a>The origin and direction input parameters can be found in the state, in the <i>origin</i> and <i>dir</i> variables. The outgoing ray is cast with <a name=iJHJ></a> (see <a href=shaders.html#iBABD><i>mi_trace_eye</i></a>) <i>mi_trace_eye</i>, whose return color may be modified before the shader itself returns. Lens shaders are called recursively; a call to <i> </i> mi_trace_eye will call the next lens shader if there is another one. 

<p>Here is a sample lens shader that implements a fish-eye lens: 

<p><a name=iJIA></a><a name=iJIB></a> (see <a href=shaders.html#iBABD><i>mi_trace_eye</i></a>) <pre>
     miBoolean fisheye(
        register miColor  *result,
        register miState  *state,
        register void     *paras)
     {
        register miVector camdir, dir;
        register miScalar x, y, r, t;

        mi_vector_to_camera(state, &amp;camdir, &amp;state-&gt;dir);
        t = state-&gt;camera-&gt;focal / -camdir.z /
                                   (state-&gt;camera-&gt;aperture/2);
        x = t * camdir.x;
        y = t * camdir.y * state-&gt;camera-&gt;aspect;
        r = x * x + y * y;
        if (r &lt; 1) {
             dir.x = camdir.x * r;
             dir.y = camdir.y * r;
             dir.z = -sqrt(1 - dir.x*dir.x - dir.y*dir.y);
             return(mi_trace_eye(result, state,
                                 &amp;state-&gt;point, &amp;dir));
        } else {
             result-&gt;r = result-&gt;g =
             result-&gt;b = result-&gt;a = 0;
             return(miFALSE);
        }
     }
</pre>


<p>This shader does not take the image aspect ratio into account, and is not physically correct. It merely bends rays away from the camera axis depending on their angle to the camera axis. Rays that fall outside the circle that touches the image edges are set to black (note that alpha is also set to 0). The rays are bent according to the square of the angle, which approaches the physically correct deflection for small values of <i></i>. This example shader has no user parameters, which is why the type of the <i>paras</i> parameter is <tt><b>void *</b></tt>. 

<p><br>
 <p><a name=cCA><h2>Output Shaders</h2></a> 

<p><a name=iJIC></a> Output shaders are functions that are run after rendering has finished. They modify the resulting image or images. Typical uses are output filters and compositing operations. Since rendering has completed, the state variables are not available in an <a name=iJID></a><u>output shader</u>; an output shader uses a simple structure called <i>miOutstate</i>: 

<p><a name=iJIE></a>
<p><pre> <i>type</i>               <i>name</i>                <i>content</i> 
 <hr>
 <tt><b>int</b></tt>                <tt><b>xres</b></tt>                image X resultion in pixels 
 <tt><b>int</b></tt>                <tt><b>yres</b></tt>                image Y resultion in pixels 
 <tt><b>miImg_image *</b></tt>      <tt><b>frame_rgba</b></tt>          RGBA color frame buffer
 <tt><b>miImg_image *</b></tt>      <tt><b>frame_z</b></tt>             depth frame buffer
 <tt><b>miImg_image *</b></tt>      <tt><b>frame_n</b></tt>             normal-vector frame buffer
 <tt><b>miImg_image *</b></tt>      <tt><b>frame_label</b></tt>         label frame buffer 
 <tt><b>miCamera *</b></tt>         <tt><b>camera</b></tt>              camera 
 <tt><b>miRc_options *</b></tt>     <tt><b>options</b></tt>             options 
 <tt><b>miMatrix</b></tt>           <tt><b>camera_to_world</b></tt>     world transformation 
 <tt><b>miMatrix</b></tt>           <tt><b>world_to_camera</b></tt>     inverse world transformation 
 <hr>
 
</pre><p> 

<p>All frame buffers have the same resolution of <i>xres *yres</i> pixels. The four <a name=iJIF></a><a href=shaders.html#iBAGD>frame buffer</a>s are passed for use by the frame buffer access functions, <a name=iJIG></a><a href=shaders.html#iBAHB><i>mi_img_get_color</i></a>, <a name=iJIH></a><a href=shaders.html#iBAGF><i>mi_img_put_color</i></a>, etc. For each type of frame buffer, there are functions to retrieve and store a pixel value that accept the frame buffer pointer as their first argument. All output shaders must be declared like any other type of shader, and the same types of arguments can be declared. This includes textures and lights. Nonprocedural textures can be looked up using functions like <a name=iJII></a><a href=shaders.html#iBBEH><i>mi_lookup_color_texture</i></a> and <a name=iJIJ></a><a href=shaders.html#iBBFB><i>mi_texture_info</i></a>, and lights can be looked up with <a name=iJJA></a><a href=shaders.html#iBBFA><i>mi_light_info</i></a>. Since rendering has completed, it is not possible to look up procedural textures or to use tracing functions such as <i>mi_sample_light</i>. 

<p>Output shaders are called with two arguments, the <a name=iJJB></a><u>output shader state</u> and the shader parameters. There is no result argument like for the other types of shaders; output shaders do not return a value. By convention, they should still be declared as <tt><b>miBoolean</b></tt>, although the return value is discarded by mental ray. Here is a typical output shader C declaration:<a name=iJJC></a><a name=iJJD></a> 

<p><pre>
     miBoolean my_output(
        miOutstate       *state,
        struct my_output *paras)
</pre>


<p>The <i>my_output</i> parameter data structure is defined normally, matching the declaration of the <i>my_output</i> shader in the .mi file. Here is a simple output shader that depth-fades the rendered image towards total transparency: first, the C code is written: 

<p><pre>
     #include &lt;shader.h&gt;

     struct out_depthfade {
        miScalar   near;   /* no fade closer than this */
        miScalar   far;    /* farther objects disappear */
     };

     miBoolean out_depthfade(
        register miOutstate   *state,
        struct out_depthfade  *paras)
     {
        register int          x, y;
        miColor               color;
        miScalar              depth, fade;

        for (y=0; y &lt; state-&gt;yres; y++)
             for (x=0; x &lt; state-&gt;xres; x++) {
                  mi_img_get_color(state-&gt;frame_rgba,
                                   &amp;color, x, y);
                  mi_img_get_depth(state-&gt;frame_z,
                                   &amp;depth, x, y);

                  if (depth &gt;= paras-&gt;far || depth == 0.0)
                       color.r=color.g=color.b=color.a = 0;
                  else if (depth &gt; paras-&gt;near) {
                       fade = (paras-&gt;far - depth) /
                              (paras-&gt;far - paras-&gt;near);
                       color.r *= fade;
                       color.g *= fade;
                       color.b *= fade;
                       color.a *= fade;
                  }
                  mi_img_put_color(state-&gt;frame_rgba,
                                   &amp;color, x, y);
             }
        return(miTRUE);
     }
</pre>


<p>This shader is stored in a file <tt><b>out_depthfade.c</b></tt> and installed in the .mi file with a <a name=iJJE></a><u><tt><b>code</b></tt></u> statement and a <a name=iJJF></a><a href=shaders.html#iIFH>declaration</a>: 

<p><pre>
     code "out_depthfade.c"
     declare "out_depthfade" (scalar "near", scalar "far")
</pre>


<p>This declaration should appear before the <tt><b>frame</b></tt> statement of the first frame using this shader. The shader is referenced in a <tt><b>output</b></tt> statement in the view: 

<p><pre>
     view
         output "rgba,z" "out_depthfade"
                              ("near" 10.0, "far" 100.0)
         output "pic" "filename.pic"
         min samples 0
         max samples 0
         ...
</pre>


<p>Note that the output shader statement appears before the output file statement. The output shader must get a chance to change the output image before it is written to the file <tt><b>filename.pic</b></tt>. It is possible to insert another file output statement before the output shader statement; in this case two files would be written, one with and one without depth fading. 

<p>Note also that the output shader has a type string <tt><b>"rgba,z"</b></tt>. This string tells mental ray to render both an RGBA and a Z (depth) frame buffer. The RGBA buffer would have been rendered anyway because the file output statement requires it, but the depth buffer would not have been rendered without the <tt><b>z</b></tt> in the type string. In this case, all depth values returned by <a name=iJJG></a><a href=shaders.html#iBAHJ><i>mi_img_get_depth</i></a> would be 0.0. 

<p>The <tt><b>min samples</b></tt><a name=iJJH></a> parameter should be set to 0 or greater, because otherwise there might be fewer than one sample per pixel, leaving gaps in the depth frame buffer. mental ray interpolates only the color frame buffer to ``bridge'' unsampled pixels; depths, normals, and labels cannot be interpolated by their nature. Either way, this shader does not anti-alias very well because there is only one depth value per pixel. 

<p>The shader makes pixels for which a depth of 0.0 is returned totally transparent to fade edges of objects correctly that have no other object behind them. By definition, <a name=iJJI></a><a href=shaders.html#iBAHJ><i>mi_img_get_depth</i></a> returns 0.0 for a position <i>x, y</i> if no object was hit at that pixel. This may be true for anti-aliased edges because the last subsample shot for that pixel may happen to miss the object, and only the last sample for a pixel is stored in the <a name=iJJJ></a><u>depth frame buffer</u>. 

<p><br>
 <p><a name=cCB><h2>Functions for Shaders</h2></a> 

<p>mental ray 1.9 makes a range of functions available to shaders that can be used to access data, cast rays, looking up images, performing standard mathematical computations. The functions are grouped by the module that supplies them. The shader writer may also use C library functions, but <a name=iBAAA></a>it is <b>very important</b> to include <tt><b> </b></tt> <i>&lt;</i>stdio.h<i>&gt;</i> and <tt><b><i>&lt;</i>math.h<i>&gt;</i></b></tt><a name=iBAAB></a> if printing functions such as <i>printf</i> or math functions such as <i>sin</i> are used. Not including these headers may abort rendering at runtime, even though the compiler did not complain. All shaders must include the standard mental ray header file, <tt><b>mi_shader.h</b></tt>. 

<p>Here is a summary of functions provided by mental ray: <a name=iBAAC></a> <br> <b>RC Functions</b> 

<p>
<p><pre><tt><b> </b></tt> <i>type</i>      <i>name</i>                <i>arguments</i> 
 <hr>
 miBoolean  mi_trace_eye        *result, *state, *org, *dir 
 miBoolean  mi_trace_reflection *result, *state, *dir 
 miBoolean  mi_trace_refraction *result, *state, *dir 
 miBoolean  mi_trace_transparent *result, *state 
 miBoolean  mi_trace_environment *result, *state, *dir 
 miBoolean  mi_trace_light      *result, *dir, *nl, *st, i 
 miBoolean  mi_sample_light     *result, *dir, *nl, *st,i,*s
 miBoolean  mi_trace_shadow     *result, *state 
 miBoolean  mi_call_shader      *result, type, *state, tag 
 <hr>
 
</pre><p> 

<p><br> <b>DB</b> 

<p>
<p><pre><tt><b> </b></tt> <i>type</i>      <i>name</i>                <i>arguments</i> 
 <hr>
 int        mi_db_type          tag 
 void *     mi_db_access        tag 
 void       mi_db_unpin         tag 
 void       mi_db_flush         tag 
 <hr>
 
</pre><p> 

<p><br> <b>IMG Functions</b> 

<p>
<p><pre><tt><b> </b></tt> <i>type</i>      <i>name</i>                <i>arguments</i> 
 <hr>
 void       mi_img_put_color    *image, *color, x, y 
 void       mi_img_get_color    *image, *color, x, y 
 void       mi_img_put_scalar   *image, scalar, x, y 
 void       mi_img_get_scalar   *image, *scalar, x, y 
 void       mi_img_put_vector   *image, *vector, x, y 
 void       mi_img_get_vector   *image, *vector, x, y 
 void       mi_img_put_depth    *image, depth, x, y 
 void       mi_img_get_depth    *image, *depth, x, y 
 void       mi_img_put_normal   *image, *normal, x, y 
 void       mi_img_get_normal   *image, *normal, x, y 
 void       mi_img_put_label    *image, label, x, y 
 void       mi_img_get_label    *image, *label, x, y 
 <hr>
 
</pre><p> 

<p><br> <b>Math Functions</b> 

<p>
<p><pre><tt><b> </b></tt> <i>type</i>      <i>name</i>                <i>arguments</i> 
 <hr>
 void       mi_vector_neg       *r 
 void       mi_vector_add       *r, *a, *b 
 void       mi_vector_sub       *r, *a, *b 
 void       mi_vector_mul       *r, f 
 void       mi_vector_div       *r, f 
 void       mi_vector_prod      *r, *a, *b 
 miScalar   mi_vector_dot       *a, *b 
 miScalar   mi_vector_norm      *a 
 void       mi_vector_normalize *r 
 void       mi_vector_min       *r, *a, *b 
 void       mi_vector_max       *r, *a, *b 
 miScalar   mi_vector_det       *a, *b, *c 
 miScalar   mi_vector_dist      *a, *b 
 void       mi_matrix_ident     r 
 miBoolean  mi_matrix_invert    r, a 
 void       mi_matrix_prod      r, a, b 
 void       mi_matrix_rotate    a, x, y, z 
 double     mi_random           
 <hr>
 void       mi_point_transform  *r, *a, m 
 void       mi_vector_transform *r, *a, m 
 void       mi_point_to_world   *state, *r, *v 
 void       mi_point_to_camera  *state, *r, *v 
 void       mi_point_to_object  *state, *r, *v 
 void       mi_point_from_world *state, *r, *v 
 void       mi_point_from_camera *state, *r, *v 
 void       mi_point_from_object *state, *r, *v 
 void       mi_vector_to_world  *state, *r, *v 
 void       mi_vector_to_camera *state, *r, *v 
 void       mi_vector_to_object *state, *r, *v 
 void       mi_vector_from_world *state, *r, *v 
 void       mi_vector_from_camera *state, *r, *v 
 void       mi_vector_from_object *state, *r, *v 
 <hr>
 
</pre><p> 

<p><br> <b>Auxiliary Functions</b> 

<p>
<p><pre><tt><b> </b></tt> <i>type</i>      <i>name</i>                <i>arguments</i> 
 <hr>
 void       mi_reflection_dir   *dir, *state 
 miBoolean  mi_refraction_dir   *dir, *state, *in, *out 
 double     mi_fresnel          n1, n2, t1, t2 
 <br> double      mi_fresnel_reflection *state, *i, *o 
 double      mi_phong_specular   spec, *state, *dir 
 double      mi_blinn_specular   spec, *state, *dir 
 void        mi_fresnel_specular *ns, *ks, s, *st, *dir, *in, *out 
 <br> double    mi_spline           t, n, *ctl 
 double     mi_noise_1d         p 
 double     mi_noise_2d         u, v 
 double     mi_noise_3d         *p 
 double     mi_noise_1d_grad    p, *g 
 double     mi_noise_2d_grad    u, v, *gu, *gv 
 double     mi_noise_3d_grad    *p, *g 
 <br> miBoolean   mi_lookup_color_texture *col, *state, tag, *v
 miBoolean   mi_lookup_scalar_texture *scal, *state, tag, *v
 miBoolean   mi_lookup_vector_texture *vec, *state, tag, *v
 <br> void      mi_light_info       tag, *org, *dir, **paras
 void       mi_texture_info     tag, *xres, *yres, **paras
 miBoolean  mi_tri_vectors      *state, wh, nt, **a, **b, **c
 <hr>
 
</pre><p> 

<p><br> <b>Memory Allocation</b> 

<p>
<p><pre><tt><b> </b></tt> <i>type</i>      <i>name</i>                <i>arguments</i> 
 <hr>
 void *     mi_mem_allocate     size 
 void *     mi_mem_reallocate   mem, size 
 void       mi_mem_release      mem 
 void       mi_mem_check        
 void       mi_mem_dump         mod 
 <hr>
 
</pre><p> 

<p><br> <b>Thread Parallelism and Semaphores</b> 

<p>
<p><pre><tt><b> </b></tt> <i>type</i>      <i>name</i>                <i>arguments</i> 
 <hr>
 void       mi_init_lock        *lock 
 void       mi_delete_lock      *lock 
 void       mi_lock             lock 
 void       mi_unlock           lock 
 int        mi_par_localvpu     
 int        mi_par_nthreads     
 <hr>
 
</pre><p> 

<p><br> <b>Messages and Errors</b> 

<p>
<p><pre><tt><b> </b></tt> <i>type</i>      <i>name</i>                <i>arguments</i> 
 <hr>
 void       mi_fatal            *message, ... 
 void       mi_error            *message, ... 
 void       mi_warning          *message, ... 
 void       mi_info             *message, ... 
 void       mi_progress         *message, ... 
 void       mi_debug            *message, ... 
 void       mi_vdebug           *message, ... 
 <hr>
 
</pre><p> 

<p>Note that many of these functions return <tt><b>double</b></tt> instead of <tt><b>miScalar</b></tt>, or have <tt><b>double</b></tt> parameters. This allows these functions to be used from shaders written in classic (K&R) C, which always promotes floating-point arguments to <tt><b>double</b></tt>. 

<p><br> <p><a name=cCC><h3>RC Functions</h3></a> 

<p>These are the functions supplied by the Rendering Core of mental ray, RC. All following trace functions return <tt><b>miTRUE</b></tt> if any subsequent call of a shader returned <tt><b>miTRUE</b></tt> to indicate presence of <a name=iBAAD></a><u>illumination</u>.  Otherwise no illumination is present and <tt><b> </b></tt> miFALSE is returned.<a name=iBAAE></a><a name=iBAAF></a> (see <a href=shaders.html#iHHF>shader call tree</a>) <a name=iBAAG></a> All trace functions derive from the given state of the parent ray the state of the ray to be cast. The state is always copied, and the given state is not modified. This state is passed to subsequent calls of shaders, which are eventually a lens<a name=iBAAH></a> (see <a href=shaders.html#iHGG>lens shader</a>) , material<a name=iBAAI></a> (see <a href=scene.html#iDJH>material shader</a>) , light<a name=iBAAJ></a> (see <a href=scene.html#iDHI>light shader</a>) , <a name=iBABA></a><a href=shaders.html#iHGE>environment shader</a>, and in the case of material, light, and environment shaders optionally a <a name=iBABB></a><a href=shaders.html#iHGA>volume shader</a>. The volume shader gets the same state as the previous (material) shader. Note that all point and direction vectors passed as arguments to tracing functions must be in <a name=iBABC></a><a href=shaders.html#iHDI>internal space</a>. 

<p><a name=iBABD></a><pre>
     miBoolean mi_trace_eye(
                miColor         *result,
                miState         *state,
                miVector        *origin,
                miVector        *direction)
</pre>


<p>casts an eye ray from <tt><b>origin</b></tt> in <tt><b>direction</b></tt>, or calls the next lens shader. The allowed <tt><b>origin</b></tt> and <tt><b>direction</b></tt> values are restricted when using ray classification. If scanline is turned on and <i>state<i>-&gt;</i>scanline</i> is not zero, <tt><b>origin</b></tt> and <tt><b> </b></tt> direction must be the same as in the initial call of <tt><b>mi_trace_eye</b></tt>. Lens shaders may not modify them. Origin and directiuon must be given in internal space. 

<p><a name=iBABE></a><a name=iBABF></a><pre>
     miBoolean mi_trace_reflection(
                miColor         *result,
                miState         *state,
                miVector        *direction)
</pre>


<p>casts a reflection ray from <tt><b>state-&gt;point</b></tt> to <tt><b>direction</b></tt>. It returns <tt><b>miFALSE</b></tt> if the trace depth has been exhausted. If no intersection is found, the optional environment shader is called. The direction must be given in internal space. 

<p><a name=iBABG></a><a name=iBABH></a><pre>
     miBoolean mi_trace_refraction(
                miColor         *result,
                miState         *state,
                miVector        *direction)
</pre>


<p>casts a refraction ray from <tt><b>state-&gt;point</b></tt> to <tt><b>direction</b></tt>.  It returns <tt><b>miFALSE</b></tt> if the <a name=iBABI></a><u>trace depth</u> has been exhausted.  If no intersection is found, the optional environment shader is called. Before this functions casts the refraction ray, after copying the state, it copies <i>state<i>-&gt;</i>refraction_volume</i> to <i> </i> state<i>-&gt;</i>volume because the ray is now assumed to be ``inside''<a name=iBABJ></a> the object, so the <a name=iBACA></a><a href=shaders.html#iHGA>volume shader</a> that describes the inside should be used to modify the ray while travelling inside the object. It is the caller's responsibility to set <i>state<i>-&gt;</i>refraction_volume</i> to the camera's volume shader <i>state<i>-&gt;</i>camera<i>-&gt;</i>volume</i> or some other volume shader if it determines that the ray has now left the object. The direction must be given in internal space. 

<p><a name=iBACB></a><a name=iBACC></a><pre>
     miBoolean mi_trace_transparent(
                miColor         *result,
                miState         *state)
</pre>


<p>does the same as <tt><b>mi_trace_refraction</b></tt> with <i>dir</i> == <i> </i> state<i>-&gt;</i>dir (that is, no change in the ray direction) but may be executed faster if the parent ray is an eye ray. It also works when ray tracing is turned off. If the ray direction does not change (because no <a name=iBACD></a><u>index of refraction</u> or similar modification is applied), it is more efficient to cast a transparency ray than a refraction ray. Like <i>mi_trace_refraction</i>, this function copies the refraction volume <a name=iBACE></a>volume shader because the ray is now assumed to be inside the object. 

<p><a name=iBACF></a><pre>
     miBoolean mi_trace_environment(
                miColor         *result,
                miState         *state,
                miVector        *direction)
</pre>


<p>casts a ray into the environment. The trace depth is not incremented or checked. The environment shader in the state is called to evaluate the returned color. The direction must be given in internal space. 

<p><a name=iBACG></a><pre>
     miBoolean mi_sample_light(
                miColor         *result,
                miVector        *dir,
                miScalar        *dot_nl,
                miState         *state,
                miTag           light_inst,
                miInteger       *samples)
</pre>


<p><a name=iBACH></a><a name=iBACI></a><a name=iBACJ></a> (see <a href=scene.html#iDHI>light shader</a>) casts a light ray from the light source to the intersection point, causing the light source's light shader to be called. The <a name=iBADA></a><a href=scene.html#iDHI>light shader</a> may then calculate <a name=iBADB></a><u>shadow</u>s by casting a <a name=iBADC></a><a href=shaders.html#iJFH>shadow ray</a> to the intersection point. This may cause <a name=iBADD></a><a href=scene.html#iECC>shadow shader</a>s of occluding objects to be called, and will also cause the <a name=iBADE></a><a href=shaders.html#iHGA>volume shader</a> of the state to be called, if there is one.  Before the light is sampled, the direction from the current intersection point in the state to the light and the dot product of this direction and the normal in the state are calculated and returned in <i>dir</i> and <i>dot_nl</i> if these pointers are nonzero. The direction is returned in internal space. The light instance to sample must be given in <i>light_inst</i>. <i>samples</i> must point to an integer that is initialized to 0. <i> </i> mi_sample_light must be called in a loop until it returns <tt><b> </b></tt> miFALSE. <i>*samples</i> will then contain the total number of light samples taken; it may be larger than 1 for <a name=iBADF></a><u>area light</u> sources. 

<p>For every call in the loop, a different <i>dir</i> and <i>dot_nl</i> is returned because the rays go to different points on the area light source. The caller is expected to use these variables, the returned color, and other variables such as diffuse and specular colors from  the shader parameters to compute a color. These colors are accumulated until <i>mi_sample_light</i> returns <tt><b>miFALSE</b></tt> and the loop terminates. The caller then divides the accumulated color by the number of samples (<tt><b>*</b></tt><i>samples</i>) if it is greater than 0, effectively averaging all the intermediate results. 

<p>Multiple samples are controlled by the <tt><b>-mc</b></tt> or <tt><b>-qmc</b></tt> command-line options. See the section on material shaders for an example. When casting light rays with <i>mi_sample_light</i>, mental ray may check whether the primitive's normal is pointing away from the light and ignore the light in this case. For this reason some shaders, such as ray-marching<a name=iBADG></a> volume shaders, should assign 0 to <i> </i> state<i>-&gt;</i>pri first, and restore it before returning. 

<p><a name=iBADH></a><pre>
     miBoolean mi_trace_light(
                miColor         *result,
                miVector        *dir,
                miScalar        *dot_nl,
                miState         *state,
                miTag           light_inst)
</pre>


<p><a name=iBADI></a><a name=iBADJ></a><a name=iBAEA></a> (see <a href=scene.html#iDHI>light shader</a>) is a simpler variation of <i>mi_sample_light</i> that does not keep a sample counter, and is not called in a loop. It is equivalent to <i>mi_sample_light</i> except for area light sources. Area light sources must be sampled multiple times with different directions. 

<p><a name=iBAEB></a><pre>
     miBoolean mi_trace_shadow(
                miColor * const result,
                miState * const state)
</pre>


<p><a name=iBAEC></a> (see <a href=shaders.html#iJFH>shadow ray</a>) computes shadows for the given light ray. This function is normally <a name=iBAED></a> (see <a href=scene.html#iDHI>light shader</a>) called from a light shader to take occluding objects that prevent some or all of the light emitted by the light source to reach the illuminated <a name=iBAEE></a> (see <a href=scene.html#iDJH>material shader</a>) point (whose material shader has probably called the light shader). The <tt><b>result</b></tt> color is modified by the shadow shaders that are called if occluding objects are found. 

<p><a name=iBAEF></a><pre>
     miBoolean mi_call_shader(
                miColor * const result,
                miShader_type   type,
                miState * const state,
                miTag           shader)
</pre>


<p>This function calls the shader specified by the tag <i>shader</i>. The tag is normally a <a name=iBAEG></a><a href=scene.html#iDJD>texture shader</a> or <a name=iBAEH></a><a href=scene.html#iDHI>light shader</a> or some other type of shader found in the calling shader's parameter list. The caller must pass its own state and the shader type, which must be one of miSHADER_LENS, miSHADER_MATERIAL, miSHADER_LIGHT, miSHADER_SHADOW, miSHADER_ENVIRONMENT, miSHADER_VOLUME, and miSHADER_TEXTURE. The sequence of operations is: 

<p>
<dl>

<dt>1.
<dd> <i>shader</i> is written into <i>state-&gt;shader</i>.  <i>shader</i> is written into <i>state-&gt;shader</i>. 

<p>
</dl>

<dl>

<dt>2.
<dd> If the called shader is dynamically loaded and has an  If the called shader is dynamically loaded and has an initialization function that has not been called yet, it is called now, with <i>state</i> as its only argument. 

<p>
</dl>

<dl>

<dt>3.
<dd> The shader referenced by <i>shader</i> is called with three  The shader referenced by <i>shader</i> is called with three arguments: the <i>result</i> pointer, the given <i>state</i>, and the shader parameters retrieved from <i>shader</i>. 

<p>
</dl>

<dl>

<dt>4.
<dd> After the shader returns, <i>state-&gt;shader</i> is  After the shader returns, <i>state-&gt;shader</i> is restored to its old value. 

<p>
</dl>
The return value of the shader is returned. If the shader expects a result argument of a type other than <tt><b>miColor</b></tt>, the pointer must be cast to <tt><b>miColor</b></tt> when passed to <i>mi_call_shader</i>. Note that the <i>shader</i> tag references an entire function call, as defined in the .mi file with a <tt><b>texture</b></tt>, <tt><b>light</b></tt>, or some other statement combining shading function and shader parameters; <tt><b>shader</b></tt> is not just a simple pointer or reference to a C function. 

<p><p><a name=cCD><h3>DB Functions</h3></a> 

<p><a name=iBAEI></a><a name=iBAEJ></a>Database access functions can be used to convert pointers into tags, and to get the type of a tag. The scene database contains only tags and no pointers at all, because pointers are not valid on other hosts. All DB functions are available in all shaders, including output shaders. <a name=iBAFA></a> <a name=iBAFB></a><pre>
     int mi_db_type(
                const miTag tag)
</pre>


<p><a name=iBAFC></a>Return the type of a database item, or 0 if the given <i>tag</i> does not exist. Valid types that are of interest in shaders are: 

<p>
<p><pre> <tt><b>miSCENE_FUNCTION</b></tt>   Function to call, such as a shading function
 <tt><b>miSCENE_MATERIAL</b></tt>   Material containing shaders and flags 
 <tt><b>miSCENE_LIGHT</b></tt>      Light source 
 <tt><b>miSCENE_IMAGE</b></tt>      Image in memory 
 
</pre><p> 

<p>The most important are functions and images, because general-purpose texture shaders need to distinguish procedural and image textures. <a name=iBAFD></a> (see <a href=scene.html#iDJB>procedural texture</a>) <a name=iBAFE></a> (see <a href=scene.html#iDJC>image texture</a>) See the texture shader example above. 

<p><a name=iBAFF></a><pre>
     void *mi_db_access(
                const miTag tag)
</pre>


<p>Look up the tag in the database, pin it, and return a pointer to the<a name=iBAFG></a> referenced item. Pinning means that the database item is guaranteed to stay in memory at the same location until the item is explicitly unpinned. Rendering aborts if the given <i>tag</i> does not exist.  <tt><b>mi_db_access</b></tt> always returns a valid pointer. If an item is accessed twice, it must be unpinned twice; <i>pinned</i> is a counter, not a flag. The maximum number of pins is 255. 

<p><a name=iBAFH></a><pre>
     void mi_db_unpin(
                const miTag tag)
</pre>


<p>Every tag that was accessed with <tt><b>mi_db_access</b></tt> must be unpinned<a name=iBAFI></a> with this function when the pointer is no longer needed. Failure to unpin can cause a pin overflow, which aborts rendering. After unpinning, the pointer may not used any more. 

<p><a name=iBAFJ></a><pre>
     void mi_db_flush(
                const miTag tag)
</pre>


<p><a name=iBAGA></a>Normally, a shader does not use a pointer obtained with <i>mi_db_access</i> to write to a database item. If it does, other hosts on the network may still hold stale copies, which must explicitly be deleted by calling this function. This function must be used with great care; it is an error to flush an item that another shader has pinned. For this reason, it is not generally possible to pass information back and forth between shaders or hosts by writing into database items and then flushing them. 

<p>

<p><p><a name=cCE><h3>IMG Functions</h3></a> 

<p>The IMG module of mental ray provides functions that deal with images. There are functions to read and write <a name=iBAGB></a><u>image</u> files in various formats, and to<a name=iBAGC></a> (see <a href=scene.html#iDJA>texture</a>)  access in-core <a name=iBAGD></a><u>frame buffer</u>s such as image textures. First, the functions that access frame buffers are listed. These functions are<a name=iBAGE></a> (see <a href=scene.html#iDJD>texture shader</a>)  typically used by texture shaders, which can obtain an image pointer by calling <i> </i> mi_db_access with the image tag as an argument.  All these functions do nothing or return defaults if the <i>image</i> pointer is 0.  They do not check whether the frame buffer has the correct data type.  All these functions are available in all shaders, including output shaders. 

<p><a name=iBAGF></a><pre>
     void mi_img_put_color(
                miImg_image *image,
                miColor     *color,
                int         x,
                int         y)
</pre>


<p>Store the color <i>color</i> in the color frame buffer <i>image</i> at coordinate <i>x y</i>, after performing <a name=iBAGG></a><u>desaturation</u> or <a name=iBAGH></a><u>color clipping</u>, <a name=iBAGI></a><u>gamma correction</u>, <a name=iBAGJ></a><u>dithering</u>, and compensating for <a name=iBAHA></a><u>premultiplication</u>.  This function works with 1, 2, or 4 components per pixel, and with 8 or 16 bits per component. The normal range for the R, G, B, and A color components is <i>[0, 1]</i> inclusive. 

<p><a name=iBAHB></a><pre>
     void mi_img_get_color(
                miImg_image *image,
                miColor     *color,
                int         x,
                int         y)
</pre>


<p>This is the reverse function to <i>mi_img_put_color</i>, it returns the color stored in a frame buffer at the specified coordinates. Gamma compensation and premultiplication, if enabled by <i>mi_img_mode</i>, are applied in reverse. The returned color may differ from the original color given to <i>mi_img_put_color</i> because of color clipping and <a name=iBAHC></a><u>color quantization</u>. 

<p><a name=iBAHD></a><pre>
     void mi_img_put_scalar (
                miImg_image *image,
                float       scalar,
                int         x,
                int         y)
</pre>


<p>Store the scalar <i>scalar</i> in the scalar frame buffer <i>image</i> at coordinate <i>x y</i>, after clipping to the range <i>[0, 1]</i>. Scalars are stored as 8-bit or 16-bit unsigned values. This function is intended for scalar texture files of type miIMG_S or miIMG_S_16. 

<p><a name=iBAHE></a><pre>
     void mi_img_get_scalar (
                miImg_image *image,
                float       *scalar,
                int         x,
                int         y)
</pre>


<p>This is the reverse function to <i>mi_img_put_scalar</i>, it returns the scalar stored in a frame buffer at the specified coordinates, converted to a scalar in the range <i>[0, 1]</i>. If the frame buffer pointer is 0, the scalar is set to 0. 

<p><a name=iBAHF></a><pre>
     void mi_img_put_vector (
                miImg_image *image,
                miVector    *vector,
                int         x,
                int         y)
</pre>


<p>Store the X and Y components of the vector <i>vector</i> in the vector frame buffer <i>image</i> at coordinate <i>x y</i>, after clipping to the range <i>[-1, 1]</i>. Vectors are stored as 16-bit signed values. This function is intended for vector texture files of type miIMG_VTA or miIMG_VTS. 

<p><a name=iBAHG></a><pre>
     void mi_img_get_vector (
                miImg_image *image,
                miVector    *vector,
                int         x,
                int         y)
</pre>


<p>This is the reverse function to <i>mi_img_put_vector</i>, it returns the UV vector stored in a frame buffer at the specified coordinates, with coordinates converted to the range <i>[-1, 1]</i>. The Z component of the vector is always set to 0. If the frame buffer pointer is 0, all components are set to 0. 

<p><a name=iBAHH></a><pre>
     void mi_img_put_depth(
                miImg_image *image,
                float       depth,
                int         x,
                int         y)
</pre>


<p><a name=iBAHI></a>Store the depth value <i>depth</i> in the frame buffer <i>image</i> at the coordinates <i>x y</i>. The depth value is not changed in any way.  The standard interpretation of the depth is the (positive) Z distance of objects relative to the camera. mental ray uses this function internally to store <i>-state-&gt;point.z</i> (in camera space) if the depth frame buffer is enabled with an appropriate <tt><b>output</b></tt> statement. 

<p><a name=iBAHJ></a><pre>
     void mi_img_get_depth(
                miImg_image *image,
                float       *depth,
                int         x,
                int         y)
</pre>


<p>Read the depth value to the float pointed to by <i>depth</i> from frame buffer <i>image</i> at the coordinates <i>x y</i>. If the image pointer is 0, return the <tt><b>MAX_FLT</b></tt> constant from limits.h. 

<p><a name=iBAIA></a><pre>
     void mi_img_put_normal(
                miImg_image *image,
                miVector    *normal,
                int         x,
                int         y)
</pre>


<p>Store the <a name=iBAIB></a><u>normal vector</u> <i>normal</i> in the frame buffer <i> </i> image at the coordinates <i>x y</i>. The normal vector is not changed in any way. 

<p><a name=iBAIC></a><pre>
     void mi_img_get_normal(
                miImg_image *image,
                miVector    *normal,
                int         x,
                int         y)
</pre>


<p>Read the normal vector <i>normal</i> from frame buffer <i>image</i> at the coordinates <i>x y</i>. If the image pointer is 0, return a null vector. 

<p><a name=iBAID></a><pre>
     void mi_img_put_label(
                miImg_image *image,
                miUint      label,
                int         x,
                int         y)
</pre>


<p>Store the <a name=iBAIE></a><u>label</u> value <i>label</i> in the frame buffer <i>image</i> at the coordinates <i>x y</i>. The label value is not changed in any way. 

<p><a name=iBAIF></a><pre>
     void mi_img_get_label(
                miImg_image *image,
                miUint      *label,
                int         x,
                int         y)
</pre>


<p>Read the label value to the unsigned integer pointed to by <i>label</i> from frame buffer <i>image</i> at the coordinates <i>x y</i>. If the image pointer is 0, return 0. 

<p>

<p><p><a name=cCF><h3>Math Functions</h3></a> 

<p><a name=iBAIG></a>Math functions include common vector and matrix operations. More specific rendering functions can be found in the next section, Auxiliary Functions. 

<p><a name=iBAIH></a><a name=iBAII></a><pre>
     void mi_vector_neg(
                miVector    *r)
</pre>


<p><i>r := -r</i> 

<p><a name=iBAIJ></a><pre>
     void mi_vector_add(
                miVector    *r,
                miVector    *a,
                miVector    *b)
</pre>


<p><i>r := a + b</i> 

<p><a name=iBAJA></a><pre>
     void mi_vector_sub(
                miVector    *r,
                miVector    *a,
                miVector    *b)
</pre>


<p><i>r := a - b</i> 

<p><a name=iBAJB></a><pre>
     void mi_vector_mul(
                miVector    *r,
                double      f)
</pre>


<p><i>r := r *f</i> 

<p><a name=iBAJC></a><pre>
     void mi_vector_div(
                miVector    *r,
                double      f)
</pre>


<p><i>r := r *1 /f</i>  (If <i>f</i> is zero, leave <i>r</i> unchanged.) 

<p><a name=iBAJD></a><pre>
     void mi_vector_prod(
                miVector    *r,
                miVector    *a,
                miVector    *b)
</pre>


<p><i>r := a *b</i> 

<p><a name=iBAJE></a><pre>
     double mi_vector_dot(
                miVector    *a,
                miVector    *b)
</pre>


<p><i>a *b</i> 

<p><a name=iBAJF></a><pre>
     double mi_vector_norm(
                miVector    *a)
</pre>


<p><i>|a |</i> 

<p><a name=iBAJG></a><pre>
     void mi_vector_normalize(
                miVector    *r)
</pre>


<p><i>r := r /|r |</i>  (If <i>r</i> is a null vector, leave <i>r</i> unchanged.) 

<p><a name=iBAJH></a><pre>
     void mi_vector_min(
                miVector    *r,
                miVector    *a,
                miVector    *b)
</pre>


<p><i>r := a<sub>x</sub> &lt; b<sub>x</sub> ? a<sub>x</sub> : b<sub>x</sub>  a<sub>y</sub> &lt; b<sub>y</sub> ? a<sub>y</sub> : b<sub>y</sub> a<sub>z</sub> &lt; b<sub>z</sub> ? a<sub>z</sub> : b<sub>z</sub></i> 

<p> <a name=iBAJI></a><pre>
     void mi_vector_max(
                miVector    *r,
                miVector    *a,
                miVector    *b)
</pre>


<p><i>r := a<sub>x</sub> &gt; b<sub>x</sub> ? a<sub>x</sub> : b<sub>x</sub>  a<sub>y</sub> &gt; b<sub>y</sub> ? a<sub>y</sub> : b<sub>y</sub> a<sub>z</sub> &gt; b<sub>z</sub> ? a<sub>z</sub> : b<sub>z</sub></i> 

<p> <a name=iBAJJ></a><pre>
     double mi_vector_det(
                miVector    *a,
                miVector    *b,
                miVector    *c)
</pre>


<p><i>a<sub>x</sub>  b<sub>x</sub>  c<sub>x</sub>  a<sub>y</sub>  b<sub>y</sub>  c<sub>y</sub> a<sub>z</sub>  b<sub>z</sub>  c<sub>z</sub></i> 

<p> <a name=iBBAA></a><pre>
     double mi_vector_dist(
                miVector    *a,
                miVector    *b)
</pre>


<p><i>|a - b|</i> 

<p> <a name=iBBAB></a><a name=iBBAC></a><pre>
     void mi_matrix_ident(
                miMatrix     r)
</pre>


<p><i><tt><b>R</b></tt> := <tt><b>1</b></tt>  <tt><b>0</b></tt>  <tt><b>0</b></tt>  <tt><b>0</b></tt>  <tt><b>0</b></tt>  <tt><b>1</b></tt>  <tt><b>0</b></tt>  <tt><b>0</b></tt> <tt><b>0</b></tt>  <tt><b>0</b></tt>  <tt><b>1</b></tt>  <tt><b>0</b></tt> <tt><b>0</b></tt>  <tt><b>0</b></tt>  <tt><b>0</b></tt>  <tt><b>1</b></tt></i> 

<p> <a name=iBBAD></a><pre>
     miBoolean mi_matrix_invert(
                miMatrix     r,
                miMatrix     a)
</pre>


<p><i><tt><b>R</b></tt> := <tt><b>A</b></tt><sup>-1</sup></i>  (Returns miFALSE if the matrix cannot be inverted.) 

<p><a name=iBBAE></a><pre>
     void mi_matrix_prod(
                miMatrix     r,
                miMatrix     a,
                miMatrix     b)
</pre>


<p><i><tt><b>R</b></tt> := <tt><b>A</b></tt> *<tt><b>B</b></tt></i> 

<p><a name=iBBAF></a><pre>
     void mi_matrix_rotate(
                miMatrix        a,
                const double    xrot,
                const double    yrot,
                const double    zrot)
</pre>


<p>Create a rotation matrix <i>a</i> rotating by <i>xrot</i>, then <i>yrot</i>, then <i>zrot</i>, in radians. 

<p><a name=iBBAG></a><pre>
     double mi_random(void)
</pre>


<p>Return a random number in the range <i>[0, 1)</i>. 

<p><a name=iBBAH></a><pre>
     void mi_point_transform(
                miVector    *r,
                miVector    *v,
                miMatrix     m)
</pre>


<p><i>r := v *<tt><b>A</b></tt> </i> 

<p>All fourteen transformation functions may be called with identical pointers <i>r</i> and <i>v</i>. The vector is transformed in-place in this case. If the result of one of the 14 transformations is a homogeneous vector<a name=iBBAI></a> with a <i>w</i> component that is not equal to 1.0, the result vector's <i>x</i>, <i>y</i>, and <i>z</i> components are divided by <i>w</i>. For the multiplication, a <i>w</i> component of 1.0 is implicitly appended to the <i>a</i> vector. If the matrix <i>m</i> is a null pointer, no transformation is done and <i>v</i> is copied to <i>r</i>. 

<p><a name=iBBAJ></a><pre>
     void mi_vector_transform(
                miVector    *r,
                miVector    *v,
                miMatrix     m)
</pre>


<p>Same as <tt><b>void mi_point_transform</b></tt>, but ignores the translation row in the matrix. 

<p><a name=iBBBA></a><pre>
     void mi_point_to_world(
                miState  * const  state,
                miVector * const  r,
                miVector * const  v)
</pre>


<p>Convert internal point <i>v</i> in the state to world space, <i>r</i>. 

<p><a name=iBBBB></a><pre>
     void mi_point_to_camera(
                miState  * const  state,
                miVector * const  r,
                miVector * const  v)
</pre>


<p>Convert internal point <i>v</i> in the state to camera space, <i>r</i>. 

<p><a name=iBBBC></a><pre>
     void mi_point_to_object(
                miState  * const  state,
                miVector * const  r,
                miVector * const  v)
</pre>


<p>Convert internal point <i>v</i> in the state to object space, <i>r</i>. For a light, object space is the space of the light, not the illuminated object. 

<p><a name=iBBBD></a><pre>
     void mi_point_from_world(
                miState  * const  state,
                miVector * const  r,
                miVector * const  v)
</pre>


<p>Convert point <i>v</i> in world space to internal space, <i>r</i>. 

<p><a name=iBBBE></a><pre>
     void mi_point_from_camera(
                miState  * const  state,
                miVector * const  r,
                miVector * const  v)
</pre>


<p>Convert point in camera space <i>v</i> to internal space, <i>r</i>. 

<p><a name=iBBBF></a><pre>
     void mi_point_from_object(
                miState  * const  state,
                miVector * const  r,
                miVector * const  v)
</pre>


<p>Convert point <i>v</i> in object space to internal space, <i>r</i>. For a light, object space is the space of the light, not the illuminated  object. 

<p><a name=iBBBG></a><pre>
     void mi_vector_to_world(
                miState  * const  state,
                miVector * const  r,
                miVector * const  v)
</pre>


<p>Convert internal vector <i>v</i> in the state to world space, <i>r</i>. Vector transformations work like point transformation, except that the translation row of the transformation matrix is ignored. The resulting vector is not (re-)normalized. Vector transformations transform normals correctly only if there is no scaling. 

<p><a name=iBBBH></a><pre>
     void mi_vector_to_camera(
                miState  * const  state,
                miVector * const  r,
                miVector * const  v)
</pre>


<p>Convert internal vector <i>v</i> in the state to camera space, <i>r</i>. 

<p><a name=iBBBI></a><pre>
     void mi_vector_to_object(
                miState  * const  state,
                miVector * const  r,
                miVector * const  v)
</pre>


<p>Convert internal vector <i>v</i> in the state to object space, <i>r</i>. For a light, object space is the space of the light, not the illuminated  object. 

<p><a name=iBBBJ></a><pre>
     void mi_vector_from_world(
                miState  * const  state,
                miVector * const  r,
                miVector * const  v)
</pre>


<p>Convert vector <i>v</i> in world space to internal space, <i>r</i>. 

<p><a name=iBBCA></a><pre>
     void mi_vector_from_camera(
                miState  * const  state,
                miVector * const  r,
                miVector * const  v)
</pre>


<p>Convert vector in camera space <i>v</i> to internal space, <i>r</i>. 

<p><a name=iBBCB></a><pre>
     void mi_vector_from_object(
                miState  * const  state,
                miVector * const  r,
                miVector * const  v)
</pre>


<p>Convert vector <i>v</i> in object space to internal space, <i>r</i>. For a light, object space is the space of the light, not the illuminated  object. 

<p>

<p><p><a name=cCG><h3>Auxiliary Functions</h3></a> 

<p>The following functions are provided for support of shaders, to simplify common mathematical operations required in shaders: 

<p><a name=iBBCC></a><pre>
     void mi_reflection_dir(
                miVector        *dir,
                miState         *state);
</pre>


<p>Calculate the reflection direction based on the <i>dir</i>, <i>normal</i>, and <i>normal_geom</i> state variables. The returned direction <i>dir</i> can be passed to <i>mi_trace_reflect</i>. It is returned in internal space. 

<p><a name=iBBCD></a><pre>
     miBoolean mi_refraction_dir(
                miVector        *dir,
                miState         *state,
                double          ior_in,
                double          ior_out);
</pre>


<p><a name=iBBCE></a>Calculate the refraction direction in internal space based on the interior and exterior indices of refraction<a name=iBBCF></a> <i> </i> ior_in and <i>ior_out</i>, and on <i>dir</i>, <i>normal</i>, and <i> </i> normal_geom state variables. The returned direction <i>dir</i> can be passed to <i>mi_trace_refract</i>.  Returns <tt><b>miFALSE</b></tt> and leaves <tt><b>*</b></tt><i>dir</i> undefined in case of total internal reflection. 

<p><a name=iBBCG></a><pre>
     double mi_fresnel(
                double          n1,
                double          n2,
                double          t1,
                double          t2);
</pre>


<p>Calculate the <a name=iBBCH></a><u>Fresnel</u> factor. 

<p><a name=iBBCI></a><pre>
     double mi_fresnel_reflection(
                miState         *state,
                double          ior_in,
                double          ior_out);
</pre>


<p>Call <i>mi_fresnel</i> with parameters appropriate for the given indices of refraction <i>ior_in</i> and <i>ior_out</i>, and for the <i>dot_nd</i> <a name=iBBCJ></a><a name=iBBDA></a>state variable. 

<p><a name=iBBDB></a><pre>
     double mi_phong_specular(
                double          spec_exp,
                miState         *state,
                miVector        *dir);
</pre>


<p><a name=iBBDC></a>Calculate the Phong factor based on the direction of illumination <i> </i> dir, the specular exponent <i>spec_exp</i>, and the state variables <i>normal</i> and <i>dir</i>. The direction must be given in internal space. 

<p><a name=iBBDD></a><pre>
     double mi_blinn_specular(
                double          spec_exp,
                miState         *state,
                miVector        *dir);
</pre>


<p><a name=iBBDE></a>As <i>mi_phong_specular</i>, but attenuated by a geometric attenuation factor (see [Foley 90]). 

<p><a name=iBBDF></a><pre>
     void mi_fresnel_specular(
                miScalar        *ns,
                miScalar        *ks,
                double          spec_exp,
                miState         *state,
                miVector        *dir,
                double          ior_in,
                double          iot_out);
</pre>


<p><a name=iBBDG></a><a name=iBBDH></a><a name=iBBDI></a>Calculate the specular factor <i>ns</i> based on the illumination direction <i>dir</i>, the specular exponent <i>spec_exp</i>, the inside and outside indices of refraction <i>ior_in</i> and <i>ior_out</i>, and the state variables <i>normal</i> and <i>dir</i>. <i>ks</i> is the value returned by <i>mi_fresnel</i>, which is called by <i>mi_fresnel_specular</i>. The direction must be given in internal space. 

<p><a name=iBBDJ></a><pre>
     double mi_spline(
                double            t,
                const int         n,
                miScalar * const  ctl)
</pre>


<p>This function calculates a one-dimensional cardinal spline at location <i>t</i>. The <i>t</i> parameter must be in the range <i> 0 ...1</i>. The spline is defined by <i>n</i> control points specified in the array <i>ctl</i>. There must be at least two control points. To calculate multi-dimensional splines, this function must be called once for each dimension. For example, <i>spline</i> can be used three times to interpolate colors smoothly. 

<p><a name=iBBEA></a><a name=iBBEB></a><pre>
     double mi_noise_1d(
                const double     p)
</pre>


<p>Return a one-dimensional coherent noise function of <i>p</i>. All six noise functions compute a Perlin noise function from the given one, two, or three dimension parameters such that the noise changes gradually with changing parameters. The returned values are in the range <i> 0 ...1</i>, with a bell-shaped distribution centered at 0.5 and falling off to both sides. This means that 0.5 is returned most often, and values of less than 0.0 and more than 1.0 are never returned. See [Perlin 85]. 

<p><a name=iBBEC></a><pre>
     double mi_noise_2d(
                const double     u,
                const double     v)
</pre>


<p>Return a two-dimensional noise function of <i>u, v</i>. 

<p><a name=iBBED></a><pre>
     double mi_noise_3d(
                miVector * const p)
</pre>


<p>Return a three-dimensional noise function of the vector <i>p</i>. This is probably the most useful noise function; a simple procedural texture shader can be written that converts a copy of the <i> </i> state<i>-&gt;</i>point vector to object space, passes it to <i> </i> mi_noise_3d, and assigns the returned value to the red, green, and blue components of the result color. The average feature size of the texture will be approximately one unit in space. 

<p><a name=iBBEE></a><pre>
     double mi_noise_1d_grad(
                const double     p,
                miScalar * const g)
</pre>


<p>Return a one-dimensional noise function of <i>p</i>. The gradient of the computed texture at the location <i>p</i> is assigned to <tt><b>*</b></tt><i>g</i>. Gradients are not normalized. 

<p><a name=iBBEF></a><pre>
     double mi_noise_2d_grad(
                const double     u,
                const double     v,
                miScalar * const gu,
                miScalar * const gv)
</pre>


<p>Return a two-dimensional noise function of <i>u, v</i>. The gradient is assigned to <tt><b>*</b></tt><i>gu</i> and <tt><b>*</b></tt><i>gv</i>. 

<p><a name=iBBEG></a><pre>
     double mi_noise_3d_grad(
                miVector * const p,
                miVector * const g)
</pre>


<p>Return a three-dimensional noise function of the vector <i>p</i>. The gradient is assigned to the vector <i>g</i>. 

<p><a name=iBBEH></a><pre>
     miBoolean mi_lookup_color_texture(
                miColor         *color,
                miState         *state,
                miTag           tag,
                miVector        *coord)
</pre>


<p><i>tag</i> is assumed to be a texture as taken from a color texture parameter of a shader. This function checks whether the tag refers to a shader (procedural texture) or an image, depending on which type of <tt><b>color texture</b></tt> statement was used in the .mi file. If <i>tag</i> is a shader, <i>coord</i> is stored in <i>state<i>-&gt;</i>tex</i>, the referenced texture shader is called, and its return value is returned. If <i>tag</i> is an image, <i>coord</i> is brought into the range <i>(0..1, 0..1)</i> by removing the integer part, the image is looked up at the resulting 2D coordinate, and <tt><b>miTRUE</b></tt> is returned. In both cases, the color resulting from the lookup is stored in <tt><b>*</b></tt><i>color</i>. 

<p><a name=iBBEI></a><pre>
     miBoolean mi_lookup_scalar_texture(
                miScalar        *scalar,
                miState         *state,
                miTag           tag,
                miVector        *coord)
</pre>


<p>This function is equivalent to <i>mi_lookup_color_texture</i>, except that <i>tag</i> is assumed to refer to a scalar texture shader or scalar image, as defined in the .mi file with a <tt><b>scalar texture</b></tt> statement, and a scalar is looked up returned in <tt><b>*</b></tt><i>scalar</i>. 

<p><a name=iBBEJ></a><pre>
     miBoolean mi_lookup_vector_texture(
                miVector        *vector,
                miState         *state,
                miTag           tag,
                miVector        *coord)
</pre>


<p>This function is also equivalent to <i>mi_lookup_color_texture</i>, except that <i>tag</i> is assumed to refer to a vector texture shader or vector image, as defined in the .mi file with a <tt><b>vector texture</b></tt> statement, and a vector is looked up returned in <tt><b>*</b></tt><i>vector</i>. 

<p><a name=iBBFA></a><pre>
     void mi_light_info(
                miTag           tag,
                miVector        *org,
                miVector        *dir,
                void            **paras)
</pre>


<p><i>tag</i> is assumed to be a light source as found in a light parameter of a shader. It is looked up, and its origin (location in internal space) is stored in <tt><b>*</b></tt><i>org</i>, and its direction (also in internal space) is stored in <tt><b>*</b></tt><i>dir</i>. Since light sources can only have one or the other but not both, the unused vector is set to a null vector. This can be used to distinguish directional (infinite) light sources; their <i>org</i> vector is set to <i>(0, 0, 0)</i>. The <i>paras</i> pointer is set to the shader parameters of the referenced light shader; if properly cast by the caller, it can extract information such as whether a non-directional light source is a point or a spot light, and its color and attenuation parameters. (mental ray considers a spot light to be a point light with directional attenuation.) Any of the three pointers <i>org</i>, <i>dir</i>, and <i>paras</i> can be a null pointer. 

<p><a name=iBBFB></a><pre>
     void mi_texture_info(
                miTag           tag,
                int             *xres,
                int             *yres,
                void            **paras)
</pre>


<p><i>tag</i> is assumed to be a texture as found in a texture parameter of a shader. If <i>tag</i> refers to a procedural texture shader, <tt><b>*</b></tt><i> </i> xres and <tt><b>*</b></tt><i>yres</i> are set to 0 and <tt><b>*</b></tt><i>paras</i> is set to the shader parameters of the texture shader. If <i>tag</i> is an image texture, <tt><b>*</b></tt><i>xres</i> and <tt><b>*</b></tt><i>yres</i> are set to the image resolution in pixels, and <tt><b>*</b></tt><i>paras</i> is set to 0. Any of the three pointers can be a null pointer. 

<p><a name=iBBFC></a><pre>
     void mi_tri_vectors(
                miState         *state,
                int             which,
                int             ntex,
                miVector        **a,
                miVector        **b,
                miVector        **c)
</pre>


<p>All the information in the state pertains to the interpolated intersection point in a triangle. This function can be used to obtain information about the uninterpolated <a name=iBBFD></a><u>triangle vertices</u>. Together with the <a name=iBBFE></a><u>barycentric coordinates</u> in the state, parameters retrieved with <i>mi_tri_vectors</i> may be interpolated differently by the shader. The <i>which</i> argument is a character that controls which triple of vectors is to be retrieved: 

<p> 
<dl>

<dt><tt><b>'p'</b></tt>
<dd>	the points in space 	the points in space 

<p>
</dl>

<dl>

<dt><tt><b>'n'</b></tt>
<dd>	the normal vectors 	the normal vectors 

<p>
</dl>

<dl>

<dt><tt><b>'m'</b></tt>
<dd>	the motion vectors 	the motion vectors 

<p>
</dl>

<dl>

<dt><tt><b>'t'</b></tt>
<dd>	the texture coordinates of texture space <i>ntex</i> 	the texture coordinates of texture space <i>ntex</i> 

<p>
</dl>

<dl>

<dt><tt><b>'u'</b></tt>
<dd>	the U bump basis vectors 	the U bump basis vectors 

<p>
</dl>

<dl>

<dt><tt><b>'v'</b></tt>
<dd>	the V bump basis vectors 	the V bump basis vectors 

<p>
</dl>
A pointer to the vectors is stored in <tt><b>*</b></tt><i>a</i>, <tt><b>*</b></tt><i>b</i>, and <tt><b>*</b></tt><i>c</i>. The shader may not modify these vectors. They are stored in <a name=iBBFF></a><a href=shaders.html#iHDI>internal space</a>. If the requested triple is not available, <tt><b> </b></tt> miFALSE is returned. 

<p> <p><a name=cCH><h3>Memory Allocation</h3></a> 

<p>mental ray's memory allocation functions replace the standard <i> </i> malloc packages found on most systems. They have built-in functions for memory leak tracing and consistency checks, and handle error automatically. 

<p><a name=iBBFG></a><pre>
     void *mi_mem_allocate(
                const int     size)
</pre>


<p>Accepts one argument specifying the size of the memory to allocate. A pointer to the allocated memory is returned. If the allocation fails, an error is reported automatically, and mental ray is aborted. This call is guaranteed to return a valid pointer, or not to return at all. The allocated memory is zeroed. 

<p><a name=iBBFH></a><pre>
     void *mi_mem_reallocate(
                void * const  mem,
                const int     size)
</pre>


<p>Change the size of an allocated block of memory. There are two arguments: a pointer to the old block of memory, and the requested new size of that block. A pointer to the new block is returned, which may be different from the pointer to the old block. If the old pointer was a null pointer, <tt><b>mi_mem_reallocate</b></tt> behaves like <tt><b> </b></tt> mi_mem_allocate. If the new size is zero, <tt><b>mi_mem_reallocate</b></tt> behaves like <tt><b>mi_mem_release</b></tt>, and returns a null pointer. If there is an allocation error, an error is reported and raylib is aborted. Like <tt><b>mi_mem_alloc</b></tt>, <tt><b>mi_mem_reallocate</b></tt> never returns if the re-allocation fails. If the block grows, the extra bytes are undefined. 

<p><a name=iBBFI></a><pre>
     void *mi_mem_release(
                void * const  mem)
</pre>


<p>Frees a block of memory. There is one argument: the address of the block. If a null pointer is passed, nothing is done. There is no return value. 

<p><a name=iBBFJ></a><pre>
     void *mi_mem_check(void)
</pre>


<p>This call is currently not available. It will be available in version 2.0. 

<p><a name=iBBGA></a><pre>
     void *mi_mem_dump(
                const miModule module)
</pre>


<p>This call is currently not available. It will be available in version 2.0. 

<p>

<p> <p><a name=cCI><h3>Thread Parallelism and Semaphores</h3></a> 

<p><a name=iBBGB></a><a name=iBBGC></a><a name=iBBGD></a>In addition to network parallelism, <i>mental ray</i> also supports shared memory parallelism through <a name=iBBGE></a><u>threads</u>. Network parallelism is a form of distributed memory parallelism where processes cooperate by exchanging messages.  Messages are used to exchange data as well as to synchronize.  With <a name=iBBGF></a><u>shared memory</u> data can easily be exchanged, a process must only access the common memory to do so. A different mechanism has to be used for synchronization. This is usually done by <i>locking</i>. Basically what has to be done is one process has to tell the other that it is waiting to access data, and another process can signal that it has finished working with it, so that any other process may now access it. 

<p>By default threads are used on shared memory multiprocessor machines. Threads are sometimes also called lightweight processes.  Threads behave like processes running on a common shared memory. 

<p>Since memory is shared between two threads both can write to memory at the same time. It can also happen that one thread writes while another reads the same memory. Both these cases can lead to surprising unwanted results. Therefore -- to guard against these surprises -- when using threads certain precautions have to be observed.  Care has to be taken when using heap memory such as global or static data, as any thread may potentially modify it.  To prevent corrupting any data (or reading corrupted data), locking must be used when it is not otherwise guaranteed that concurrent accesses<a name=iBBGG></a> will not occur. 

<p>In addition to making sure that write accesses to data are performed when no other thread accesses the data, it is important to use only so-called concurrency safe libraries and calls. If a call to a non<a name=iBBGH></a><u>reentrant</u> function is done, locking should be used. A function is called <i>reentrant</i> if it can be executed by multiple threads at the same time without adverse effects.  (Reentrancy and concurrency safety are related, but the terms stem from different historical contexts.) Details and examples are explained below. 

<p>For example, static data on a shared memory multiprocessor can be modified by more than one processor at a time. Consider this test: 

<p><pre>
     if (!is_init) {
         is_init = miTRUE;
         initialize();
     }
</pre>


<p>This does not guarantee that <tt><b>initialize</b></tt> is called only once. The reason is that all threads share the <i>is_init</i> flag, so two threads may simultaneously examine the flag. Both will find that it has not been set, and enter the <i>if</i> body. Next, both will set the flag to <tt><b>miTRUE</b></tt>, and then both will call the <tt><b>initialize</b></tt> function. This situation is called a <i>race condition</i>. The example is contrived because initialization and termination should be done with <tt><b>init</b></tt> and <tt><b>exit</b></tt> functions as described in the next section, but this problem can occur with any heap variable. In general, all threads on a host share all data except local <tt><b>auto</b></tt> variables on the stack. 

<p>The behavior described above could also occur if more than one thread is used on a single processor, but by default <i>mental ray</i> does not create more threads then processors are available. 

<p><a name=iBBGI></a><a name=iBBGJ></a><a name=iBBHA></a>There are two methods for guarding against race conditions. One is to guarantee that only one thread executes certain code at a time. Such code surrounded by lock and unlock operations is called a <i>critical </i> section. Code inside of critical sections may access global or static data or call any function that does so (as long as all is protected by the same lock). The lock used in this example is assumed to have been created and initialized with a call to <tt><b>mi_init_lock</b></tt> before it used here.  (See below how locks are initialized.) Here is an example of how a critical section may be used: 

<p><pre>
     miLock lock;

     mi_lock(lock);
     if (!is_init) {               /* critical section */
         is_init = miTRUE;
         initialize();
     }
     mi_unlock(lock);
</pre>


<p>The other method is to use separate variables for each thread. This is done by allocating an array with one entry for each thread, and indexing this array with the current thread number. Allocation is done in the shader's initialization routine (which has the same name as the shader with <tt><b>_init</b></tt> appended). No locking is required because it is called only once. The termination routine (which also has the same name but with <tt><b>_exit</b></tt> appended) must release the array. 

<p>mental ray provides two locks for general use: <i> </i> state<i>-&gt;</i>global_lock is a lock shared by all threads and all shaders. No two critical sections protected by this lock can execute simultaneously on this host. The second is <i> </i> state<i>-&gt;</i>shader<i>-&gt;</i>lock, which is local to all instances of the current shader. The lock is tied to the shader, not the particular call with particular shader parameters. Every shader in mental ray, built-in or dynamically linked, has exactly one such lock. 

<p>The relevant functions provided by the parallelism modules are: 

<p><a name=iBBHB></a><pre>
     void mi_init_lock(
                miLock * const  lock)
</pre>


<p>Before a lock can be used by one of the other locking functions, it must be initialized with this function. Note that the lock variable must be static or global. Shaders will normally use this function in their <i>_init</i> function. 

<p><a name=iBBHC></a><pre>
     void mi_delete_lock(
                miLock * const  lock)
</pre>


<p>Destroy a lock. This should be done when it is no longer needed. The code should use lock and immediately unlock the lock first to make sure that no other thread is in or waiting for a critical section protected by this lock. Shaders will normally use this function in their <i>_exit</i> function. 

<p><a name=iBBHD></a><pre>
     void mi_lock(
                const miLock    lock)
</pre>


<p>Check if any other code holds the lock. If so, block; otherwise set the lock and proceed. This is done in a parallel-safe way so only one <a name=iBBHE></a><a href=shaders.html#iBBGJ>critical section</a> locked can execute at a time. Note that locking the same lock twice in a row without anyone unlocking it will block the thread forever, effectively freezing mental ray, because the second lock can never succeed. 

<p><a name=iBBHF></a><pre>
     void mi_unlock(
                const miLock    lock)
</pre>


<p>Release a lock. If another thread was blocked attempting to set the lock, it can proceed now. Locks and unlocks must always be paired, and the code between locking and unlocking must be as short and as fast as possible to avoid defeating parallelism. 

<p><a name=iBBHG></a><pre>
     miVpu mi_par_localvpu(void)
     int miTHREAD(miVpu vpu)
</pre>


<p><a name=iBBHH></a><a name=iBBHI></a>The term <i>VPU</i> stands for Virtual Processing Unit. All threads on the network have a unique VPU number. <i>mi_par_localvpu</i> returns the VPU number of the VPU this thread is running on. VPUs are a concatenation of the host number and the thread number, both numbered from <i> 0</i> to the number of hosts or threads, respectively, minus <i> 1</i>. The <i>miTHREAD</i> macro extracts a thread number from a VPU. Thread 0 on host 0 is normally running the translator that controls the entire operation. The <i>mi_par_localvpu</i> function returns the VPU of the current thread on the local host. 

<p>

<p><a name=iBBHJ></a><pre>
     int mi_par_nthreads(void)
</pre>


<p>Returns the number of threads on the local host. This is normally <i> 1</i> on a single-processor system. This number can be used to allocate an array of per-thread variables in the shader initialization code. The array can then be indexed by the shader with <i>miTHREAD(mi_par_localvpu())</i>. 

<p><p><a name=cCJ><h3>Messages and Errors</h3></a> 

<p><a name=iBBIA></a><a name=iBBIB></a>Shaders may print messages and errors. They are printed in the same format as rendering (RC) messages. Options given to the translator determine which messages are printed and which are suppressed. All message routines have the same parameters as <i>printf(3)</i>. All append a newline to the message. Messages are printed in the form 

<p> <tt><b>RC</b></tt> <i>host.thread level: message</i> 

<p>with the module name <tt><b>RC</b></tt>, the host number <i>host</i> if available, the thread number <i>thread</i> with a leading dot if available, the message type <i>level</i> (fatal, error, warning etc), and the message given in the function call. 

<p><a name=iBBIC></a><pre>
     void mi_fatal(
                const char * const message,
                ...)
</pre>


<p>An unrecoverable error has occurred. Unlike all others, this call will not return; it will attempt to recover mental ray and return to the top-level translator. Recovering may involve aborting all operations in progress and clearing the entire database. Fatal messages can be suppressed, but mental ray is always re-initialized. 

<p><a name=iBBID></a><pre>
     void mi_error(
                const char * const message,
                ...)
</pre>


<p>An unrecoverable error has occurred. This call returns; the caller must abort the current operation gracefully and return. 

<p><a name=iBBIE></a><pre>
     void mi_warning(
                const char * const message,
                ...)
</pre>


<p>A recoverable error occurred. The current operation proceeds. 

<p><a name=iBBIF></a><pre>
     void mi_info(
                const char * const message,
                ...)
</pre>


<p>Prints information about the current operation, such as the number of triangles and timing information. Infos should be used sparingly; do not print information for every intersection point or shader call. 

<p><a name=iBBIG></a><pre>
     void mi_progress(
                const char * const message,
                ...)
</pre>


<p>Prints progress reports, such as rendering percentages. 

<p><a name=iBBIH></a><pre>
     void mi_debug(
                const char * const message,
                ...)
</pre>


<p>Prints debugging information useful only for shader development. 

<p><a name=iBBII></a><pre>
     void mi_vdebug(
                const char * const message,
                ...)
</pre>


<p>Prints more debugging information useful only for shader development. Messages that are likely to be useful only in rare circumstances, or that generate a very large number of lines should be printed with this function. 

<p>

<p><p><a name=cDA><h2>Initialization and Cleanup</h2></a> 

<p><a name=iBBIJ></a><a name=iBBJA></a>mental ray 1.9 provides a way to define initialization and cleanup functions for each user defined function. Many shaders need to perform operations such as initializing color tables or allocating arrays before rendering starts. They may also need to do cleanup operations after rendering has finished, for operations like releasing storage to prevent memory leaks. <a name=iBBJB></a> Before a shader is called for the first time, ray checks if a function of the same name with <tt><b>_init</b></tt> appended exists. If so, it assumes that this is an initialization routine and calls it once before the first call of the function. The state passed to the initialization function is the same as passed to the first call of the actual shader to be initialized. Note that the order of shader calls is unpredictable because the order of pixel samples is unpredictable, so the initialization function should not rely on sample-specific state variables such as <i> </i> state<i>-&gt;</i>point. 

<p>The initialization function has the option of requesting <i>shader </i> instance intializations by setting the boolean variable its third argument points to to <tt><b>miTRUE</b></tt>. A shader instance is a unique pair of shader and shader parameters. For example, if the shader <i> </i> soft_material is used in two different materials it is said to have two different instances (even if the parameter values are similar). 

<p>When rendering has finished, ray checks for each user provided shader which was called if a function of the same name with <tt><b>_exit</b></tt> appended exists. If yes, it assumes that this is a cleanup routine and calls it once. For example, if a shader <i>myshader</i> exists, the functions <i>myshader_init</i> and <i>myshader_exit</i> are called for initialization and cleanup if they exist. 

<p>Both routines are assumed to have the following type: 

<p><pre>
     void myshader_init(miState   *state,
                        void      *paras,
                        miBoolean *inst_init_req);

     void myshader_exit(void      *paras);
</pre>


<p>Here is an example for init and exit shaders for a shader named <i> </i> myshader. When <i>myshader</i> is about to be used for the first time in a frame, the calling order is: 

<p> 
<dl>

<dt>1.
<dd>  <i>myshader_init</i> with a null parameter argument 

<p>
</dl>

<dl>

<dt>2.
<dd>  <i>myshader_init</i> with non-null parameter argument 

<p>
</dl>

<dl>

<dt>3.
<dd>  <i>myshader</i> itself with the same non-null parameter argument 

<p>
</dl>

<dl>

<dt>4.
<dd>  more calls to <i>myshader</i> with the same parameter argument, and calls to other instances of <i>myshader_init</i> and <i>myshader</i> with different parameter arguments 

<p>
</dl>

<dl>

<dt>5.
<dd>  one <i>mi_shader_exit</i> with a non-null parameter argument for each corresponding <i>myshader_init</i> 

<p>
</dl>

<dl>

<dt>6.
<dd>  finally one <i>myshader_exit</i> with a null parameter argument. 

<p>
</dl>
Steps 2 and 5 would have been omitted if <i>myshader_init</i> in step 1 had not set its third argument <i>inst_req</i> to <tt><b>miTRUE</b></tt>. Two different instances of the same shader always have different parameter argument pointers. However, a shadow shader and a material shader in the same material may share parameters as described above; in this case both shaders are called with the same parameter argument. Most scenes are built this way. 

<p><pre>
void myshader_init(             /* must end with "_init" */
    miState         *state,         
    struct myshader *paras,     /* valid for inst inits */
    miBoolean       *inst_req)  /* for inst init request */
{
    if (!paras) {               /* main shader init */
        *inst_req = miTRUE;     /* want inst inits too */
        ...
    } else {                    /* shader instance init */
        paras-&gt;something = 1;   /* just an example */
        ...
    }
}

void myshader_exit(             /* must end with "_exit" */
    struct myshader *paras)     /* valid for inst inits */
{
    if (!paras) {               /* main shader exit */
        ...                     /* no further inst exits
                                 * will occur */
    } else {                    /* shader instance exit */
        paras-&gt;something = 0;   /* just an example */
        ...
    }
}
</pre>


<p>Note that there will generally be many instance init/exits (if enabled), but only one shader init/exit. If an init/exit shader isn't available, it isn't called; this is not an error. Initialization and cleanup are done on every host where the function was used, but only once on shared memory parallel machines. They are done for each frame separately. 

<p><br>
 <p><a name=cDB><h2>Shaders and Trace Functions</h2></a> 

<p>Trace functions are functions provided by mental ray that allow a shader to cast a ray into the scene, most of them using standard ray tracing. Not all types of tracing functions can be used in all types of shaders. Conversely, many trace functions cause shaders to be called. This chapter lists these interdependencies. 

<p>The following list shows which shaders are called from which trace functions: 

<p> <a name=iBBJC></a> (see <a href=shaders.html#iBABD><i>mi_trace_eye</i></a>) <a name=iBBJD></a> (see <a href=shaders.html#iBABE><i>mi_trace_reflection</i></a>) <a name=iBBJE></a> (see <a href=shaders.html#iBABG><i>mi_trace_refraction</i></a>) <a name=iBBJF></a> (see <a href=shaders.html#iBACB><i>mi_trace_transparent</i></a>) <a name=iBBJG></a> (see <a href=shaders.html#iBACF><i>mi_trace_environment</i></a>) <a name=iBBJH></a> (see <a href=shaders.html#iBACG><i>mi_sample_light</i></a>) <a name=iBBJI></a> (see <a href=shaders.html#iBAEB><i>mi_trace_shadow</i></a>)  <br> 
<p><pre>                         lens    material environ light  shadow  volume 
 <hr>
 <i>mi_trace_eye</i>            yes      yes    yes     no      no      yes 
 <i>mi_trace_reflection</i>     no      yes     yes     no      no      yes 
 <i>mi_trace_refraction</i>     no      yes     yes     no      no      yes 
 <i>mi_trace_transparent</i>    no      yes     yes     no      no      yes 
 <i>mi_trace_environment</i>    no      no      yes     no      no      yes 
 <i>mi_sample_light</i>         no      no      no      yes     no      yes 
 <i>mi_trace_shadow</i>         no      no      no      no      yes     no 
 <hr>
 
</pre><p> <br>  

<p><a name=iBBJJ></a> (see <a href=shaders.html#iHHF>shader call tree</a>) mental ray's RC module holds internal data corresponding to the ray tree. Therefore shaders may not call arbitrary trace functions, since in RC's data structures entries are only provided for the following children at a node: 

<p> 
<dl>

<dt>eye rays:
<dd>  <a name=iBCAA></a> (see <a href=shaders.html#iHJH>primary ray</a>) reflection, refraction rays up to <a name=iBCAB></a><u>trace depth</u>, light rays to each light instance. 

<p>
</dl>

<dl>

<dt>reflection, refraction, transparency rays:
<dd>    <a name=iBCAC></a><u>reflection</u>, <a name=iBCAD></a><u>refraction</u><a name=iBCAE></a> rays up to trace depth, light rays to each light instance. 

<p>
</dl>

<dl>

<dt>light rays:
<dd>  <a name=iBCAF></a>shadow rays. 

<p>
</dl>

<dl>

<dt>shadow rays:
<dd>  <a name=iBCAG></a> (see <a href=shaders.html#iJFH>shadow ray</a>) none. 

<p>
</dl>
Environment rays do not have entries in this tree. The data in the tree is used for acceleration and can be overridden if a shader wants to cast rays not normally allowed, by setting the state variable <i> </i> state<i>-&gt;</i>cache to zero. This should only be done if necessary because it reduces efficiency. The following table shows which trace functions may be called from which shaders: 

<p> <br> 
<p><pre>                                                                 ray     light 
                         lens    material environ light  shadow  volume  volume
 <hr>
 <i>mi_trace_eye</i>            yes     no      no      no      no      no      no 
 <i>mi_trace_reflection</i>     **      yes     *       **      **      yes     ** 
 <i>mi_trace_refraction</i>     **      yes     *       **      **      yes     ** 
 <i>mi_trace_transparent</i>    **      yes     *       **      **      yes     ** 
 <i>mi_trace_environment</i>    *       yes     yes     *       yes     yes     yes
 <i>mi_sample_light</i>         *       yes     *       **      **      yes     ** 
 <i>mi_trace_shadow</i>         **      **      **      yes     **      no      yes
 <hr>
 
</pre><p> <br>  

<p> 

<p>
<dl>

<dt>*
<dd>  yes, if the shader generates an artificial intersection point   yes, if the shader generates an artificial intersection point by setting <i>point</i>, <i>normal</i>, and <i>normal_geom</i> in the state. 

<p>
</dl>

<dl>

<dt>**
<dd> yes, if the shader removes RC's internal ray tree data  yes, if the shader removes RC's internal ray tree data by setting <i>cache</i> in the state to <tt><b>NULL</b></tt> and generates an artifical intersection point if not present. 

<p>
</dl>
<br>
 <p><a name=cDC><h2>Converting 1.8 to 1.9</h2></a> 

<p>The shader interface of the previous generation of mental ray, 1.8, differed from version 1.9 in various ways. When converting shaders from 1.8 to 1.9, the following changes should be made: 

<p> 
<ul>

<li>  Matrices are now in column-major order, so that the translation is in the last row. Consequently, the point and vector transform functions multiply vectors from the left; the argument order of these functions has changed. The matrix layout is the only change that affects the .mi file. 

<p>
</ul>

<ul>

<li>  All shaders should return a <tt><b>miBoolean</b></tt> that indicates whether the shader succeeded. Shaders that used to be <tt><b>void</b></tt> should now return <tt><b>miTRUE</b></tt>. Texture shaders no longer need to return an alpha of <i>-1</i>. If shaders neglect to return either <tt><b>miTRUE</b></tt> or <tt><b>miFALE</b></tt>, some functions such as <i>mi_lookup_color_texture</i> that pass shader return values back to their callers may return undefined values. 

<p>
</ul>

<ul>

<li>  Since mental ray 2.0 will available as a library that must co-exist with the symbol namespace of a client application, and since version 1.9 is compatible with version 2.0, all data types, constants, and internal functions have been prefixed with <tt><b>mi_</b></tt> to allow simple upgrades. In some cases, capitalization changed also. 

<p>
</ul>

<ul>

<li>  Most floating-point numbers now have the type <tt><b>miScalar</b></tt>, which is currently a <tt><b>double</b></tt>. Special versions of mental ray may be made available that use <tt><b>float</b></tt> instead, for high-speed applications with low demands on precision. Shaders should not rely on the actual precision of <tt><b>miScalar</b></tt>. 

<p>
</ul>

<ul>

<li>  The scene database is linked using <tt><b>miTag</b></tt> references, replacing pointers to allow virtual shared databases. Shaders that directly access scene database elements must now use access and unpinning functions. In general, this allows complete traversal of the entire scene database, but care should be taken because certain data structures such as instances may be changed in future versions of mental ray. 

<p>
</ul>

<ul>

<li>  The state has changed. Constants have been moved out to option and camera structures. Some variables have been added or removed. Thread numbers are now available by function call. A boolean type is used for flags, and enumerators have been introduced. 

<p>
</ul>

<ul>

<li>  Arrays must now be accessed by adding a constant, prefixed by <tt><b>i_ </b></tt>, to the array index. User parameter structures no longer contain pointers, to allow network transparency. 

<p>
</ul>

<ul>

<li>  Material shaders should now sample lights using the <i>mi_sample_light</i> functions instead of <i>mi_trace_light</i>. An extra loop is also required, controlled by the <tt><b>-mc</b></tt> or <tt><b>-qmc</b></tt> command-line options. This allows greater precision when sampling area light sources. <a name=iBCAH></a> 
<li>  Error messages have been consolidated into a number of standard functions that can be turned on and off externally, much like mental ray's own messages. 

<p>
</ul>
<a name=iBCAI></a> (see <a href=shaders.html#iBBIJ>shader initialization</a>) <a name=iBCAJ></a> (see <a href=shaders.html#iBBJA>shader cleanup</a>) <a name=iBCBA></a> (see <a href=shaders.html#iBBJB>memory leaks</a>) 
<ul>

<li>  Initialization and termination of shaders using separate <tt><b>_init</b></tt> and <tt><b>_exit</b></tt> functions for each shader are now supported. It is not recommended to use a static variable to self-initialize a shader when it is called for the first time. Shaders can no longer assume that all allocated memory is released when mental ray has finished the animation; since mental ray may now be part of a client application instead of being forked as a separate process, data may have a very long lifetime. Memory leaks should be avoided. 

<p>
</ul>
<br>
 <p><hr>
<a href=index.html#contents>Table of Contents</a>
</body>
</html>
