Open Shading Language

Open Shading Language (OSL) is a programmable shading system developed for advanced rendering engines. It allows technical artists and developers to write custom shader code using a C-like scripting language.

In Blender, OSL can be used within Cycles to define custom surface, volume, and displacement shaders. This gives users full control over shading behavior, enabling procedural effects, advanced lighting models, and custom geometry-based material logic that may not be possible with built-in shader nodes alone.

Unlike node-based materials, OSL shaders are authored as text scripts using Blender’s internal Text Editor or loaded from external .osl or .oso files. These scripts are then compiled and used in the Shader Editor through the Script Node.

Truco

OSL is especially useful for generating procedural textures, custom BRDFs, or implementing research prototypes. It also allows sharing shaders across compatible rendering applications that support the OSL standard.

Uso

To use Open Shading Language (OSL) in Blender, follow these steps:

  1. Habilitar procesamiento con OSL

    In the Render Properties enable Open Shading Language.

  2. Agregar un nodo Script

    In the Shader Editor add Script Node then in the node’s properties:

    • Set the Mode to Internal to use a Blender text data-block, or

    • Set it to External to load a shader file from disk (either .osl or compiled .oso).

    For the internal mode, create a new text data-block in the Text Editor, then write or paste your OSL code there.

    Blender will compile the OSL source file automatically. If the source is .osl, it will be compiled into .oso bytecode. Compilation errors will be shown in the system console.

  3. Usar salidas de sombreadores

    Once compiled, the node’s outputs will reflect the output parameters defined in the OSL code. These outputs can be connected to any part of the material node tree.

Escritura de sombreadores

For more details on how to write shaders, see the OSL Documentation.

Here is a simple example:

shader simple_material(
    color Diffuse_Color = color(0.6, 0.8, 0.6),
    float Noise_Factor = 0.5,
    output closure color BSDF = diffuse(N))
{
    color material_color = Diffuse_Color * mix(1.0, noise(P * 10.0), Noise_Factor);
    BSDF = material_color * diffuse(N);
}

Clausuras

OSL es distinto de, por ejemplo, RSL o GLSL, en cuanto a que no tiene un bucle de luz. No hay acceso a las luces de la escena y el material debe ser construido a partir de clausuras (funciones cerradas) que son implementadas en el propio motor de procesamiento. Este método es más limitado, pero también hace posible que el motor de procesamiento efectúe optimizaciones y se asegure de que todos los sombreadores puedan usar muestreo de importancia.

Las clausuras disponibles en Cycles corresponderán a los nodos de sombreado y sus conectores; para más detalles sobre lo que hacen y el significado de los parámetros, ver el manual de los nodos de sombreado.

Ver también

Documentación sobre las clausuras incorporadas de OSL <https://open-shading-language.readthedocs.io/en/latest/stdlib.html#material-closures>`__.

BSDF

  • diffuse(N)

  • oren_nayar(N, rugosidad)

  • diffuse_ramp(N, colores[8])

  • phong_ramp(N, exponente, colores[8])

  • diffuse_toon(N, tamaño, suavizado)

  • glossy_toon(N, tamaño, suavizado)

  • translucent(N)

  • reflection(N)

  • refraction(N, ir)

  • transparent()

  • microfacet_ggx(N, rugosidad)

  • microfacet_ggx_aniso(N, T, ax, ay)

  • microfacet_ggx_refraction(N, rugosidad, ir)

  • microfacet_beckmann(N, rugosidad)

  • microfacet_beckmann_aniso(N, T, ax, ay)

  • microfacet_beckmann_refraction(N, rugosidad, ir)

  • ashikhmin_shirley(N, T, ax, ay)

  • ashikhmin_velvet(N, rugosidad)

Pelo

  • hair_reflection(N, rugosidad_u, rugosidad_v, T, desplazamiento)

  • hair_transmission(N, rugosidad_u, rugosidad_v, T, desplazamiento)

  • principled_hair(N, absorción, rugosidad, rugosidad_radial, barniz, desplazamiento, ir)

BSSRDF

Usado para simular transluminiscencia.

bssrdf(method, N, radius, albedo)
Parámetros:
  • method (string) –

    Métodos de procesamiento para simular la transluminiscencia.

    • burley: Una aproximación a una dispersión volumétrica basada en principios físicos. Este método es menos preciso que random_walk, sin embargo en algunas situaciones producirá menos ruido en menos tiempo.

    • random_walk_skin: Produce resultados precisos en objetos delgados y curvos. El método de camino aleatorio calculará una dispersión volumétrica real por debajo de la superficie de la malla, lo que significa que funcionará mejor en mallas cerradas. Caras superpuestas y huecos en la malla producirán problemas en el cálculo.

    • random_walk: Behaves similarly to random_walk_skin but modulates the Radius based on the Color, Anisotropy, and IOR. This method thereby attempts to retain greater surface detail and color than random_walk_skin.

  • N (vector) – Vector normal del punto de la superficie que está siendo sombreado.

  • radius (vector) – Factor de distancia que, multiplicado por la Escala, determinará el radio que la luz podrá atravesar por debajo de la superficie, para cada canal de color. Una radio mayor producirá una apariencia más suave, debido a que la luz se filtrará hacia las áreas en sombra y a través del objeto. La distancia de dispersión se especificará de forma separada para cada canal RVA, para posibilitar recrear materiales tales como piel, en los cuales la luz roja se dispersa más que los otros dos componentes. Los valores X, Y, Z serán mapeados respectivamente a valores de R, V, A.

  • albedo (color) – Color de la superficie o, dicho en términos físicos, la probabilidad de que la luz de las distintas longitudes de onda sea reflejada.

Volumen

  • henyey_greenstein(g)

  • absorption()

Otro

  • emission()

  • ambient_occlusion()

  • holdout()

  • background()

Atributos

Geometry attributes can be read through the getattribute() function. This includes UV maps, color attributes and any attributes output from geometry nodes.

The following built-in attributes are available through getattribute() as well.

geom:generated

Coordenadas de texturizado generadas automáticamente, a partir de la malla sin deformar.

geom:uv

Mapa UV predefinido para el procesamiento.

geom:tangent

Default tangent vector along surface, in object space.

geom:undisplaced

Position before displacement, in object space.

geom:dupli_generated

For instances, generated coordinate from instancer object.

geom:dupli_uv

For instances, UV coordinate from instancer object.

geom:trianglevertices

Las coordenadas de los tres vértices del triángulo.

geom:numpolyvertices

Number of vertices in the polygon (always returns three currently).

geom:polyvertices

Vertex coordinates array of the polygon (always three vertices currently).

geom:name

Nombre del objeto.

geom:is_smooth

Is mesh face smooth or flat shaded.

geom:is_curve

Is object a curve or not.

geom:curve_intercept

0..1 coordinate for point along the curve, from root to tip.

geom:curve_thickness

Grosor de la curva en espacio del objeto.

geom:curve_length

Length of the curve in object space.

geom:curve_tangent_normal

Tangent Normal of the strand.

geom:is_point

Es un punto de una nube de puntos o no.

geom:point_radius

Radius of point in point cloud.

geom:point_position

Center position of point in point cloud.

geom:point_random

Random number, different for every point in point cloud.

path:ray_length

Ray distance since last hit.

object:random

Random number, different for every object instance.

object:index

Object unique instance index.

object:location

Object location.

material:index

Material unique index number.

particle:index

Particle unique instance number.

particle:age

Particle age in frames.

particle:lifetime

Total lifespan of particle in frames.

particle:location

Posición de la partícula.

particle:size

Tamaño de la partícula.

particle:velocity

Velocidad de la partícula.

particle:angular_velocity

Velocidad angular de la partícula.

Trazado

sólo CPU

We support the trace(point pos, vector dir, ...) function, to trace rays from the OSL shader. The «shade» parameter is not supported currently, but attributes can be retrieved from the object that was hit using the getmessage("trace", ..) function. See the OSL specification for details on how to use this.

Esta función no podrá ser usada en vez de la iluminación; su propósito principal es permitir que los sombreadores «sondeen» a la geometría cercana, por ejemplo para aplicar una textura proyectada que pueda ser bloqueada por ésta, aplicar más «desgaste» a las partes expuestas de una geometría o realizar otros efectos similares a la oclusión ambiental.

Metadatos

Metadata on parameters controls how they are displayed in the user interface. The following metadata entries are supported:

[[ string label = "My Label" ]]

Nombre personalizado del parámetro en la interfaz de usuario.

[[ string widget = "null" ]]

Hides the parameter from the user interface.

[[ string widget = "boolean" ]] or [[ string widget = "checkbox" ]]

Displays an integer parameter as a boolean checkbox.

[[ string widget = "filename" ]]

Displays the parameter as a file path selector.

[[ string widget = "mapper", string options = "left:0|right:1" ]]

Displays an integer parameter as an enumerated menu. The options string defines a list of label-value pairs separated by |.

[[ string vecsemantics = "POINT" ]]

Marks a vector parameter as a translation input (position vector).

[[ string vecsemantics = "NORMAL" ]]

Marks a vector parameter as a normal input (direction vector).

[[ string unit = "radians" ]]

Marks a float parameter as an angle input, displayed in radians.

[[ string unit = "m" ]]

Marks a float parameter as a distance input, displayed in meters.

[[ string unit = "s" ]] or [[ string unit = "sec" ]]

Marks a float parameter as a time input, displayed in seconds.

Limitaciones

Importante

OSL is not supported with GPU rendering unless using the OptiX backend.

Some OSL features are not available when using the OptiX backend. Examples include:

  • Memory usage reductions offered by features like on-demand texture loading and

    mip-mapping are not available.

  • Texture lookups require OSL to be able to determine a constant image file path for each

    llamada a textura.

  • Some noise functions are not available. Examples include Cell, Simplex, and Gabor.

  • The trace function is not functional. As a result of this, the Ambient Occlusion and Bevel nodes do not work.