Open Shading Language#

Cycles Only

It is also possible to create your own nodes using Open Shading Language (OSL). These nodes will only work with the CPU and OptiX rendering backend.

Para ativá-la, selecione Linguagem de Sombreamento Aberto como o sistema de sombreamento nas configurações de renderização.

Nota

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 texture call.

  • 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.

Nó Script#

Nó Scripts.

LSA foi desenhada para sombreamento baseado em nós, e cada sombreador LSA corresponde a um nó em uma configuração de nó. Para adicionar um sombreador LSA, adicione um nó script e conecte ele a um bloco de dados ou a um arquivo externo. Soquetes de entrada e saída serão criados a partir dos parâmetros do sombreador ao clicar no botão atualizar no Nó ou Editor de Texto.

Sombreadores LSA podem ser conectados ao nó de algumas diferentes maneiras. Com o modo Interno, um bloco de dados de texto é usado para armazenar o sombreador LSA, e o OSO bytecode é armazenado no próprio nó. Isso é útil para distribuir um arquivo blend com tudo armazenado nele.

O modo Externo pode ser usado para especificar um arquivo .osl de uma unidade, e isso será então automaticamente compilado em um arquivo .oso no mesmo diretório. Também é possível especificar um caminho para um arquivo .oso, que será então usado diretamente, com a compilação feita manualmente pelo usuário. A terceira opção é especificar apenas o nome do módulo, que será procurado no caminho de busca do sombreador.

O caminho de busca do sombreador está localizado no mesmo lugar que os scripts ou caminho de configuração, dentro de:

Linux
$HOME/.config/blender/4.1/shaders/
Windows
C:\Users\$user\AppData\Roaming\Blender Foundation\Blender\4.1\shaders\
macOS
/Users/$USER/Library/Application Support/Blender/4.1/shaders/

Dica

Para uso em produção, nós sugerimos usar um grupo de nó para agrupar os nós de script de sombreadores, e conectá-los a outros arquivos blend. Isso torna mais fácil fazer modificações aos nós depois a medida que soquetes são adicionados ou removidos, sem precisar atualizar os nós de script em todos os arquivos.

Escrevendo 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);
}

Encerramentos#

LSA é diferente de, por exemplo, RSL ou GLSL, no fato de que não possui um laço de luz. Não há acesso a luzes na cena, e o material deve ser construído a partir de encerramentos que são implementados no próprio renderizador. Isso é mais limitado, mas também torna possível o renderizador fazer otimizações e assegura que todos os sombreadores possam ter importância amostrada.

The available closures in Cycles correspond to the shader nodes and their sockets; for more details on what they do and the meaning of the parameters, see the shader nodes manual.

Veja também

Documentation on OSL’s built-in closures.

BSDF#

  • diffuse(N)

  • oren_nayar(N, roughness)

  • diffuse_ramp(N, colors[8])

  • phong_ramp(N, exponent, colors[8])

  • diffuse_toon(N, size, smooth)

  • glossy_toon(N, size, smooth)

  • translucent(N)

  • reflection(N)

  • refraction(N, ior)

  • transparent()

  • microfacet_ggx(N, roughness)

  • microfacet_ggx_aniso(N, T, ax, ay)

  • microfacet_ggx_refraction(N, roughness, ior)

  • microfacet_beckmann(N, roughness)

  • microfacet_beckmann_aniso(N, T, ax, ay)

  • microfacet_beckmann_refraction(N, roughness, ior)

  • ashikhmin_shirley(N, T, ax, ay)

  • ashikhmin_velvet(N, roughness)

Hair#

  • hair_reflection(N, roughnessu, roughnessv, T, offset)

  • hair_transmission(N, roughnessu, roughnessv, T, offset)

  • principled_hair(N, absorption, roughness, radial_roughness, coat, offset, IOR)

BSSRDF#

Used to simulate subsurface scattering.

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

    Rendering method to simulate subsurface scattering.

    • burley: An approximation to physically-based volume scattering. This method is less accurate than random_walk however, in some situations this method will resolve noise faster.

    • random_walk_skin: Provides accurate results for thin and curved objects. Random Walk uses true volumetric scattering inside the mesh, which means that it works best for closed meshes. Overlapping faces and holes in the mesh can cause problems.

    • 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) – Normal vector of the surface point being shaded.

  • radius (vector) – Average distance that light scatters below the surface. Higher radius gives a softer appearance, as light bleeds into shadows and through the object. The scattering distance is specified separately for the RGB channels, to render materials such as skin where red light scatters deeper. The X, Y and Z values are mapped to the R, G and B values, respectively.

  • albedo (color) – Color of the surface, or physically speaking, the probability that light is reflected for each wavelength.

Volume#

  • henyey_greenstein(g)

  • absorption()

Other#

  • 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

Automatically generated texture coordinates, from undeformed mesh.

geom:uv

Mapa UV padrão para a renderização.

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

Three vertex coordinates of the triangle.

geom:numpolyvertices

Número de vértices no polígono (sempre retorna três atualmente).

geom:polyvertices

Matriz de coordenadas de vértices do polígono (sempre três vértices atualmente).

geom:name

Nome do 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

Thickness of the curve in object space.

geom:curve_length

Length of the curve in object space.

geom:curve_tangent_normal

Normal Tangente da vertente.

geom:is_point

Is point in a point cloud or not.

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

Distância do raio desde o último encontro.

object:random

Random number, different for every object instance.

object:index

Object unique instance index.

object:location

Localização do objeto.

material:index

Material unique index number.

particle:index

Particle unique instance number.

particle:age

Idade da partícula em quadros.

particle:lifetime

Vida útil total da partícula em quadros.

particle:location

Localização das partículas.

particle:size

Tamanho das partículas.

particle:velocity

Velocidade das partículas.

particle:angular_velocity

Velocidade angular das partículas.

Traço#

CPU Only

Nós suportamos a função traço(pos ponto, dir vetor, ...), para traçar raios a partir do sombreador LSA. O parâmetro «sombreador» não é suportado atualmente, mas atributos podem ser recuperados do objeto que foi atingido usando a função getmessage("traço", ..). Veja a especificação LSA para mais detalhes em como usar isso.

Essa função não pode ser usada em vez de iluminação; o principal objetivo é permitir sombreadores «examinar» a geometria próxima, por exemplo para aplicar uma textura projetada que pode ser bloqueada por geometria, aplicar mais «roupa» à geometria exposta, ou fazer outros efeitos tipo oclusão ambiente.

Metadata#

Metadata on parameters controls their display in the user interface. The following metadata is supported:

[[ string label = "My Label" ]]

Name of parameter in in the user interface

[[ string widget = "null" ]]

Hide parameter in the user interface.

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

Display integer parameter as a boolean checkbox.