Spatial Material

Введение

SpatialMaterial это 3D материал по умолчанию, который дает большинство возможностей необходимых художникам в материале, без необходимости писать шейдерный код. Тем не менее, он может быть сконвертирован в шейдерный код если возникнет необходимость в дополнительной функциональности.

Этот урок объясняет большинство параметров представленных в SpatialMaterial.

Вы можете добавить SpatialMaterial на объект выбрав «Новый SpatialMaterial» в свойстве Material в Инспекторе.

Flags

Пространственные(spatial) материалы имеют много флажков для управлением их поведением.

../../_images/spatial_material1.png

Transparent

В Godot, материалы не прозрачны если не были настроены быть ими. Главная причина этого в том что прозрачные материалы отрисовываются через отдельный метод (сортируются от дальних и ближних и отрисовываются по порядку).

Этот метод менее производительный (проходит много изменений состояний) и делает такие материалы не доступными для многих эффектов средне- и пост-обработки (таких как SSAO, SSR, итд.) которые требуют идеально непрозрачной геометрии.

По этой причине, материалы в Godot по умолчанию непрозрачны если не настроено обратное. Главные настройки включающие прозрачность это:

  • Флаг Transparent (этот самый)
  • Режим смешивания(blend mode) иной чем «Mix»
  • Включение резкости или размытия дистанции

Unshaded

В большинстве случаев он необходим материалам которые не зависят от освещения (shaded).

Тем не менее, в некоторых случаях вам может потребоваться отобразить только альбедо (цвет) и игнорировать остальное. Включение этого флага убирает весь шейдинг и показывает чистый, неосвещенный цвет.

../../_images/spatial_material26.png

Vertex Lighting

Godot более и менее одинаков в отображении каждого пикселя благодаря пре-обработке глубины. Все вычисления света делаются запуском шейдера света на каждом пикселе.

Так как эти вычисления дорогостоящие, производительность может значительно понизиться в некоторых особых случаях таких как отрисовка множества слоёв прозрачности (что обычно происходит в системах частиц). Переключение на режим света для-каждой-вершины может помочь в этих случаях.

Дополнительно, на низко-производительных или мобильных устройствах, переключение на режим вершинного освещения может существенно повысить производительность отрисовки.

../../_images/spatial_material2.png

Имейте ввиду что когда вершинное освещение включено, только направленный свет может создавать тени (по причинам производительности).

No Depth Test

Для того чтобы показывать близкие объекты над дальними объектами, проводится тест глубины. Его выключение ведёт к тому что объекты будут показывать над (или под) всеми остальными.

Его отключение имеет смысл для отрисовки индикаторов в мировом пространстве, и отлично работает в связке со свойством Render Priority на Материале (смотрите внизу данной страницы).

../../_images/spatial_material3.png

Use Point Size

Этот флаг работает только с геометрией представленной через точки (обычно всё сделано из треугольников когда импортируется из редакторов 3D графики). Если же это так, то размер этих точек может быть изменён (смотрите ниже).

World Triplanar

Когда используется трипланарное наложение (смотрите нижу, в настройках UV1 и UV2), триплан вычисляется из локального пространства объекта. Этот флаг заставляет его вычисляться из мирового пространства.

Fixed Size

Этот флаг заставляет объект рисоваться в одинаковом размере вне зависимости от расстояния. Это полезно для индикаторов (без теста глубины и высокого приоритета отрисовки) и некоторых типов билбордов.

Do Not Receive Shadows

Заставляет объект не принимать тени которые иначе были бы отброшены на него.

Disable Ambient Light

Заставляет объект не принимать окружающий свет который бы иначе осветил его.

Ensure Correct Normals

Fixes normals when non-uniform scaling is used.

Vertex Color

Эта настройка позволяет выбрать цвет для вершин которые будут взяты из вашей 3D модели. По умолчанию эти цвета отбрасываются.

../../_images/spatial_material4.png

Use as Albedo

Использование этого параметра заставляет цвет вершин использовать цвет альбедо.

Is sRGB

Most 3D DCCs will likely export vertex colors as sRGB, so toggling this option on will help them look correct.

Parameters

SpatialMaterial also has several configurable parameters to tweak many aspects of the rendering:

../../_images/spatial_material5.png

Diffuse Mode

Specifies the algorithm used by diffuse scattering of light when hitting the object. The default is Burley. Other modes are also available:

  • Burley: Default mode, the original Disney Principled PBS diffuse algorithm.
  • Lambert: Is not affected by roughness.
  • Lambert Wrap: Extends Lambert to cover more than 90 degrees when roughness increases. Works great for hair and simulating cheap subsurface scattering. This implementation is energy conserving.
  • Oren Nayar: This implementation aims to take microsurfacing into account (via roughness). Works well for clay-like materials and some types of cloth.
  • Toon: Provides a hard cut for lighting, with smoothing affected by roughness. It is recommended you disable sky contribution from your environment’s ambient light settings or disable ambient light in the spatial material to achieve a better effect.
../../_images/spatial_material6.png

Specular Mode

Specifies how the specular blob will be rendered. The specular blob represents the shape of a light source reflected in the object.

  • ShlickGGX: The most common blob used by PBR 3D engines nowadays.
  • Blinn: Common in previous-generation engines. Not worth using nowadays, but left here for the sake of compatibility.
  • Phong: Same as above.
  • Toon: Creates a toon blob, which changes size depending on roughness.
  • Disabled: Sometimes the blob gets in the way. Begone!
../../_images/spatial_material7.png

Blend Mode

Controls the blend mode for the material. Keep in mind that any mode other than Mix forces the object to go through the transparent pipeline.

  • Mix: Default blend mode, alpha controls how much the object is visible.
  • Add: Object is blended additively, nice for flares or some fire-like effects.
  • Sub: Object is subtracted.
  • Mul: Object is multiplied.
../../_images/spatial_material8.png

Cull Mode

Determines which side of the object is not drawn when backfaces are rendered:

  • Back: The back of the object is culled when not visible (default).
  • Front: The front of the object is culled when not visible.
  • Disabled: Used for objects that are double-sided (no culling is performed).

Depth Draw Mode

Specifies when depth rendering must take place.

  • Opaque Only (default): Depth is only drawn for opaque objects.
  • Always: Depth draw is drawn for both opaque and transparent objects.
  • Never: No depth draw takes place (do not confuse this with the No Depth Test option above).
  • Depth Pre-Pass: For transparent objects, an opaque pass is made first with the opaque parts, then transparency is drawn above. Use this option with transparent grass or tree foliage.
../../_images/material_depth_draw.png

Line Width

When drawing lines, specify the width of the lines being drawn. This option is not available on most modern hardware.

Point Size

When drawing points, specify the point size in pixels.

Billboard Mode

Enables billboard mode for drawing materials. This controls how the object faces the camera:

  • Disabled: Billboard mode is disabled.
  • Enabled: Billboard mode is enabled, the object’s -Z axis will always face the camera.
  • Y-Billboard: The object’s X axis will always be aligned with the camera.
  • Particles: Most suited for particle systems, because it allows specifying animation options.
../../_images/spatial_material9.png

The above options are only enabled for Particle Billboard.

Billboard Keep Scale

Enables scaling a mesh in billboard mode.

Grow

Grows the object vertices in the direction pointed by their normals:

../../_images/spatial_material10.png

This is commonly used to create cheap outlines. Add a second material pass, make it black and unshaded, reverse culling (Cull Front), and add some grow:

../../_images/spatial_material11.png

Use Alpha Scissor

When transparency other than 0 or 1 is not needed, it’s possible to set a threshold to prevent the object from rendering semi-transparent pixels.

../../_images/spatial_material12.png

This renders the object via the opaque pipeline, which is faster and allows it to use mid- and post-process effects such as SSAO, SSR, etc.

Material colors, maps and channels

Besides the parameters, what defines materials themselves are the colors, textures, and channels. Godot supports an extensive list of them. They are described in detail below:

Albedo

Albedo is the base color for the material, on which all the other settings operate. When set to Unshaded, this is the only color that is visible. In previous versions of Godot, this channel was named Diffuse. The change of name mainly happened because, in PBR (Physically Based Rendering), this color affects many more calculations than just the diffuse lighting path.

Albedo color and texture can be used together as they are multiplied.

Alpha channel in albedo color and texture is also used for the object transparency. If you use a color or texture with alpha channel, make sure to either enable transparency or alpha scissoring for it to work.

Metallic

Godot uses a metallic model over competing models due to its simplicity. This parameter defines how reflective the material is. The more reflective, the less diffuse/ambient light affects the material and the more light is reflected. This model is called «energy-conserving».

The Specular parameter is a general amount for the reflectivity (unlike Metallic, this is not energy-conserving, so leave it at 0.5 and don’t touch it unless you need to).

The minimum internal reflectivity is 0.04, so it’s impossible to make a material completely unreflective, just like in real life.

../../_images/spatial_material13.png

Roughness

Roughness affects the way reflection happens. A value of 0 makes it a perfect mirror while a value of 1 completely blurs the reflection (simulating natural microsurfacing). Most common types of materials can be achieved with the right combination of Metallic and Roughness.

../../_images/spatial_material14.png

Emission

Emission specifies how much light is emitted by the material (keep in mind this does not include light surrounding geometry unless GI Probes are used). This value is added to the resulting final image and is not affected by other lighting in the scene.

../../_images/spatial_material15.png

Normalmap

Normal mapping allows you to set a texture that represents finer shape detail. This does not modify geometry, only the incident angle for light. In Godot, only the red and green channels of normal maps are used for wider compatibility.

../../_images/spatial_material16.png

Rim

Some fabrics have small micro-fur that causes light to scatter around it. Godot emulates this with the Rim parameter. Unlike other rim lighting implementations, which just use the emission channel, this one actually takes light into account (no light means no rim). This makes the effect considerably more believable.

../../_images/spatial_material17.png

Rim size depends on roughness, and there is a special parameter to specify how it must be colored. If Tint is 0, the color of the light is used for the rim. If Tint is 1, then the albedo of the material is used. Using intermediate values generally works best.

Clearcoat

This feature is only available when using the GLES3 backend.

The Clearcoat parameter is used to add a secondary pass of transparent coat to the material. This is common in car paint and toys. In practice, it’s a smaller specular blob added on top of the existing material.

Anisotropy

This feature is only available when using the GLES3 backend.

This changes the shape of the specular blob and aligns it to tangent space. Anisotropy is commonly used with hair, or to make materials such as brushed aluminum more realistic. It works especially well when combined with flowmaps.

../../_images/spatial_material18.png

Ambient Occlusion

It is possible to specify a baked ambient occlusion map. This map affects how much ambient light reaches each surface of the object (it does not affect direct light by default). While it is possible to use Screen-Space Ambient Occlusion (SSAO) to generate ambient occlusion, nothing beats the quality of a well-baked AO map. It is recommended to bake ambient occlusion whenever possible.

../../_images/spatial_material19.png

Глубина

This feature is only available when using the GLES3 backend.

Setting a depth map on a material produces a ray-marched search to emulate the proper displacement of cavities along the view direction. This is not real added geometry, but an illusion of depth. It may not work for complex objects, but it produces a realistic depth effect for textures. For best results, Depth should be used together with normal mapping.

../../_images/spatial_material20.png

Subsurface Scattering

This feature is only available when using the GLES3 backend.

This effect emulates light that penetrates an object’s surface, is scattered, and then comes out. It is useful to create realistic skin, marble, colored liquids, etc.

../../_images/spatial_material21.png

Transmission

This controls how much light from the lit side (visible to light) is transferred to the dark side (opposite from the light). This works well for thin objects such as plant leaves, grass, human ears, etc.

../../_images/spatial_material22.png

Refraction

This feature is only available when using the GLES3 backend.

When refraction is enabled, it supersedes alpha blending, and Godot attempts to fetch information from behind the object being rendered instead. This allows distorting the transparency in a way similar to refraction in real life.

../../_images/spatial_material23.png

Detail

Godot allows using secondary albedo and normal maps to generate a detail texture, which can be blended in many ways. By combining this with secondary UV or triplanar modes, many interesting textures can be achieved.

../../_images/spatial_material24.png

UV1 and UV2

Godot supports two UV channels per material. Secondary UV is often useful for ambient occlusion or emission (baked light). UVs can be scaled and offset, which is useful when using repeating textures.

Triplanar Mapping

Triplanar mapping is supported for both UV1 and UV2. This is an alternative way to obtain texture coordinates, sometimes called «Autotexture». Textures are sampled in X, Y and Z and blended by the normal. Triplanar mapping can be performed in either world space or object space.

In the image below, you can see how all primitives share the same material with world triplanar, so the brick texture continues smoothly between them.

../../_images/spatial_material25.png

Proximity and distance fade

Godot allows materials to fade by proximity to each other as well as depending on the distance from the viewer. Proximity fade is useful for effects such as soft particles or a mass of water with a smooth blending to the shores. Distance fade is useful for light shafts or indicators that are only present after a given distance.

Keep in mind enabling these enables alpha blending, so abusing them for an entire scene is usually not a good idea.

../../_images/spatial_material_proxfade.gif

Render priority

The rendering order of objects can be changed, although this is mostly useful for transparent objects (or opaque objects that perform depth draw but no color draw, such as cracks on the floor).