$envmap

From Valve Developer Community
< Ru
Jump to navigation Jump to search
English (en)Русский (ru)中文 (zh)Translate (Translate)
Информацию о наборе параметров материала, используемых в качестве маски зеркального отражения с помощью текстур, смотрите здесь $envmapmask(en).

$envmap - это параметр материала шейдера(en), доступно для всех игр на движке Source Source.

Info content.png
This page has not been fully translated.
You can help by finishing the translation.
If this page cannot be translated for some reason, or is left untranslated for an extended period of time after this notice is posted, the page should be requested to be deleted.
Also, please make sure the article complies with the alternate languages guide.(en)
Зеркальные отражения в полную яркость.

Чаще всего используется для имитации зеркальных отражений, наблюдаемых на гладких поверхностях, таких как металлы, стекло и пластмассы. Это достигается путём сопоставления нормалей вершин(en) модели с точками изображения карты-куба, заданной параметром $envmap, и добавления результирующего цвета от карты-куба к поверхности модели(en). Как правило, карта-куб является просто статичной "картой окружения", которая была предварительно отрисована (хотя пользовательская карта-куб может быть анимирована).

Когда в объекте env_cubemap указан параметр $envmap и на карте выполнена команда buildcubemaps, движок автоматически выберет карту окружения, содержащуюся в BSP-файле(en) карты, которая находится ближе всего к модели при её перемещении в мире, обеспечивая очень упрощённую имитацию динамических отражений.

Другим типом имитации зеркального отражения, поддерживаемым Source, является затенение Фонга(en), которое обеспечивает простые отражения как на статичных, так и на динамичных моделях.

Доступность

$envmap был представлен в Source Source в Half-Life 2 и Counter-Strike: Source. Также доступен во всех поздних играх.

Note.pngПримечание: Большинство текстур в Half-Life: Source Half-Life: Source по-умолчанию используют статичные изображения отражений вместо env_cubemap. Поэтому если вы уже создали карты-кубы, то большинство из этих текстур продолжат использовать статичные изображения отражений, до тех пор пока их .vmt файлы не будут отредактированы.

Синтаксис

$envmap env_cubemap

Обычно используется значение "env_cubemap", которое указывает VBSP(en) подменить имя ближайшего env_cubemap при компиляции карты. Однако можно использовать статичное изображение карты-куба, созданное самостоятельно.

Note.pngПримечание: Если параметр $envmap использован без указания $basetexture, то даже в этом случае зеркальные отражения будут отображены.
Note.pngПримечание: Прозрачность карты-куба зависит от альфа-канала в $basetexture, даже при использовании $envmapmask. Это вызывает ошибки конфликтования.
Icon-Important.pngВажно: Наклейки, использующие env_cubemap, будут использовать ближайшую к игроку карту-куб, а не ближайшую к самой наклейке!
Подтвердить:Накладки могут быть исправлены с помощью VBSP, как это происходит для элементов карты и деформированных поверхностей.

Создание собственной текстуры карты-куба

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

Icon-Bug.pngБаг:Cubemaps flagged as sRGB will only properly load as sRGB when HDR(en) is disabled. Either include an HDR .hdr.vtf equivalent for an sRGB-encoded SDR .vtf cubemap, or encode the SDR cubemap in regular RGB.
Подтвердить:What games can actually load SDR cubemaps in HDR mode? Counter-Strike: Source handles such fine (printing warnings about missing a proper HDR cubemap in the console), but Day of Defeat: Source seems not be able to load SDR cubemaps in HDR mode (regardless of sRGB-ness), resulting in the surface glowing white.
  [нужно проверить в ?]

В VTFEdit(en)

For this to work you will need to have the 6 sides of the cubemap saved as individual textures in the correct orientation for it to appear correctly in the Source Engine. So some faces might need to be rotated either clockwise or counter clockwise. Each face will need to be mirrored horizontally before orientation.

Note.pngПримечание: Pre-Alien Swarm Alien Swarm games require 7 faces for the cubemap to work. The seventh in this case is a round texture, used as a sphere map for the (broken) $envmapsphere parameter. VTFEdit can generate this face automatically, via the "Advanced" tab when importing.

To the right hand side of this page you will find two guide images to aid in properly rotating each side of your environment render.
Save one or both of those guides on your computer and then import your environment render onto it or recreate it in a smaller scale, then rotate your sides as instructed by the images.
Save every side as a separate image file, their names should be the number found on that specific square. This will ensure that the environment texture will be built correctly, as the numbers also represent the import order in VTFEdit(en).

Подсказка по расположению для T-образной компоновки окружения. Нажмите для увеличения.
Подсказка по расположению для результата отрисовки в Blender. Нажмите для увеличения.

Once you have all the image sides ready you can just import them all into VTFEdit and select "Environment Map". Texture format(en) is up to you, generally DXT1 will do.

Cubemap tut1 cra0.png

Enable the "Clamp S" and "Clamp T" texture flags.

Then just save it all as a .vtf file and use it in your VMT like so:

"$Envmap" "environment maps/my_cubemap"

"environment maps" is the usual folder for environments/cubemaps You may put yours anywhere you like.

В VTEX(en)

VTEX автоматически отобразит и ориентирует стороны, нужно только правильно назвать текстуры. Назовите каждый файл например, envmap001a*.tga, где * - это BK, FT, LF, RT, UP или DN. Если сделали снимок экрана для карты-куба в игре, этот шаг уже будет выполнен, но для правильной работы с Vtex.exe необходимо использовать HDRShop (но перед этим нужно изменить формат текстур на BMP, так как HDRShop работает только с этим форматом), а затем преобразовать их в формат PFM-файлов. VTEX will automatically mirror and orient your faces, you need only to provide correctly named or built textures.
You may either supply six separate faces, or one "T-Assembly" image with the faces arranged in a specific layout. Some games, like Left 4 Dead 2 Left 4 Dead 2 require this T-Assembly shape when building HDR Cubemaps.
If you want to have HDR envmaps, you must export the texture(s) as a BMP format and run those through HDRShop to create PFM files.

If you would like a video guide with the prefabs to create LDR & HDR cubemaps (as well as skyboxes) via a mostly automated Python script, visit this link. Following this guide will circumvent everything shown below.

Separate faces

Each one of your faces must have the correct suffix BK, FT, LF, RT, UP, DN for VTEX to use them.
You have two ways of making such textures from within the game. Either using the Envmap ConCommand, or the Garry's mod addon Cubemap Camera. Both have their Pro's and Con's.
You may also source these images from anywhere you'd like. They don't need to be made from within a game.

Note.pngПримечание: The naming convention of the faces makes little sense, as the names do not actually align with the cardinal directions of hammer.
BK is north, RT is east, FT is south, LF is west, relative to Hammer's 2D "Top" view.
Using Envmap ConCommand

Using the Envmap ConCommand is possible in every game, but the image quality is not the best, as the gamma is slighty different, and the images appear to be less saturated.

Note.pngПримечание: The command runs on the same system as the buildcubemaps command, except it renders everything. Including dynamic props, npc's, players, etc.

First you may want to set the ConVars mat_envmaptgasize and mat_envmapsize to set the scale of the faces you will get.
In some games, such as Left 4 Dead 2 Left 4 Dead 2 these commands are hidden and cannot be changed, unless you wrap the commands in the following string:

script Convars.SetValue( "mat_envmaptgasize" ,256)
script Convars.SetValue( "mat_envmapsize" ,256)

Resolutions larger than 256x256 are possible, but require a specific screen resolutiuon. More info here.
After setting the scale you may run the Envmap ConCommand. The game will generate cubemap faces from your current location and deposit the PFM files in the folder cubemap_screenshots.

Now that you have these PFM files, you can either run these through VTEX immediately, or turn them into a T-Assembly.

Using Garry's Mod Addon

The aforementioned Cubemap Camera addon generates PNG files as an output, but the orientation is incorrect for our uses, so they need to be changed later.

First, keep in mind that this addon's output is oriented along your current view. So the Front is wherever you look, even if it's down at the ground.
You may want to use the command Setang 0 270 0 to make the player look towards the "front" (which is actually south), so it aligns in the same way as the Envmap ConCommand would.

On this image below you have the result of this addon as png on the top, and the outputs of the Envmap ConCommand on the bottom (after turning them to a TGA).
Note how the Down.png needs to be rotated 90° clockwise, Up.png needs to be rotated 90° counter clockwise, Left.png and Right.png need to be swapped.
Furthermore, the filenames must be renamed to use the BK, FT, LF, RT, UP, DN suffixes that VTEX requires.
Envmap-concommand-vs-gmod-addon.jpg

For the lazy individual, you may use the FFMPEG script in the expandbox below as a .bat file to do the rotation and renaming for you.

ffmpeg	-i down.png	-vf "transpose=1" -y tmp_dn.png
ffmpeg	-i up.png	-vf "transpose=2" -y tmp_up.png
del 	down.png
del 	up.png
move	/Y	tmp_dn.png		envdn.png
move	/Y	tmp_up.png		envup.png
move		left.png		tmp_lf.png
move	/Y	right.png		env_lf.png
move	tmp_lf.png			envrt.png
move	front.png			envft.png
move	back.png			envbk.png

Now that you have these PNG files, you can turn them into a T-Assembly layout to run through HDRShop or VTEX. Neither of those tools accept PNG, but the next FFMPEG scripts on this page will sort that out for you.

Preparing T-Assembly

To create the T-Assembly image you can use any image editing software of your choice to align the faces as seen in the image below.

If you prefer to automate this, you can use the FFMPEG script in the expand box below as a .bat file to do this for you.
The resulting image is what you see below. Ignore that the UP face was copied over multiple times, as it has no effect and it was easier to do in the script.

@echo off

:: If you want to run this through HDRShop, set the z_output at the end to BMP. As HDRShop cannot interpret FFMPEG's TGA files
:: If you do not want HDR PFM's, use TGA for the Z_output instead.

:: Uncomment these lines below if you want to turn your PFM to PNG, and then turn it into a T-Assembly immediately.
::	for %%S in (up dn bk ft lf rt) do (
::		for %%F in (*%%S.pfm) do (
::			ffmpeg -i "%%F" -y -vf "scale=in_range=full:out_range=full,eq=gamma=2.2" -pix_fmt bgr24 "env%%S.png"
::		)
::	)

ffmpeg ^
-i envup.png -i envup.png -i envup.png -i envup.png ^
-i envft.png -i envlf.png -i envbk.png -i envrt.png ^
-i envup.png -i envup.png -i envup.png -i envdn.png ^
-filter_complex "xstack=inputs=12:layout=0_0|w0_0|w0+w4_0|w0+w4+w8_0|0_h0|w0_h0|w0+w4_h0|w0+w4+w8_h0|0_h0+h1|w0_h0+h1|w0+w4_h0+h1|w0+w4+w8_h0+h1" -y Z_output.tga

Cubemap axis reference 1.jpg

With this image done, you can either run the resulting TGA through VTEX as-is, or turn it into a BMP to import into HDRShop, to alter the gamma and create a PFM file.

Создание карт окружения

Once you have one T-Assembly TGA/PFM texture — or six TGA/PFM faces named as such: EnvBK.tga, EnvFT.tga, EnvLF.tga, EnvRT.tga, EnvUP.tga, EnvDN.tga. — You're ready for VTEX.

VTEX however needs a text file to receive inputs such as flags or settings. You may create this file manually, or use yet another script.

Автоматически

Use the script in the expand box below to create this text file, generate a finished cubemap, and then delete the text file. Which removes some manual labor.
Simply create a bat file with the following contents, edit the paths in the yellow lines, and then drag-drop your tga file onto the script.

@echo off
setlocal enabledelayedexpansion

:: Path to your game
SET Exe_Path=D:\Programme\Steam\steamapps\common\Left 4 Dead 2

:: Create the txt next to the bat
set txtfile=%~n1.txt

:: Write content into the txt
(
echo // pfm 1				// For HDR only. read .pfm file instead of .tga
echo // pfmscale 1			// For HDR only. higher values will result in a brighter sky
echo // nocompress 1		// Outputs a BGR888 instead of DXT1/
echo stripalphachannel 1	// Skyboxes and cubemaps do not need an alpha channel. removing them saves disk space.
echo nonice 1				// prevent seams appearing at low texture detail.
echo clamps 1				// Clamping sides to prevent wrapping.
echo clampt 1				// Clamping top/bottom to prevent wrapping.
echo nolod 1				// flags vtf with "No Level of Detail"
echo cubemap 1				// Vtex may need this, else it prints errors.
) > "%txtfile%"

::	Create cubemap. change subfolder  below HERE from "left4dead2" to wherever your gameinfo.txt is.
"%Exe_Path%\bin\vtex.exe" -game "%Exe_Path%\left4dead2" -outdir "%~dp0\" -nopause %~n1.txt

del "%~dp0\%~n1.txt"
endlocal

HDR envmaps will be named like Env.hdr.vtf, and only need to exist to work. You might need to add the .hdr.vtf suffix yourself. You may also get pwl.vtf files which in most cases have no use and can be deleted.

Вручную

Create a text file the same name as your textures, but without the suffix. For this example it would be Env.txt.
If building for HDR write in the following, otherwise leave it blank:

pfm 1        // read .pfm file instead of .tga
pfmscale 1   // higher values will result in a brighter sky
nocompress 1 // disable compression (HDR compression is only supported by skyboxes)
// cubemap 1 // Vtex may need this, else it prints errors.

Put all your textures and the text file into materialsrc and then just drag-n-drop the .txt file into vtex.exe and you should end up with a working cubemap!
HDR envmaps will be named like Env.hdr.vtf, and only need to exist to work. You might need to add the .hdr.vtf suffix yourself. You may also get pwl.vtf files which in most cases have no use and can be deleted.

Параметры и эффекты

$envmapmask(en) <texture(en)>
Смотреть $envmapmask. Текстура, которая по-тексельно(en) определяет яркость зеркального отражения.

$envmaptint(en) <КЗС(en) матрица(en)>
Контролирует яркость отражения красного, зелёного и синего(en) канала. Использоваться может любое положительное число. По умолчанию: "[1 1 1]", что означает 100% яркость.
Icon-Important.pngВажно: На VertexLitGeneric этот параметр конвертируется из гамма в линейное пространство. Вводимые значения преобразуются в X^2.2f. Например, 0.25 равно не 25% отражения, а ~5%!
Note.pngПримечание: Вы обязаны использовать кавычки, так как внутри значения есть пробелы.
Note.pngПримечание: Можно указать значение одиночным числом с плавающей запятой. В таком случае это значение будет применено ко всем трём каналам одинаково (Например $envmaptint 0.5 будет равен $envmaptint "[0.5 0.5 0.5]"). Однако, судя по всему, этот метод не является полностью надёжным.[подтвердить]
Tip.pngСовет: Этот параметр часто используется для того, чтобы приглушить яркость зеркального отражения без использования выше описанной $envmapmask.

$envmapcontrast(en) <норма(en)>
Контролирует контраст отражения. 0 - натуральный контраст, а 1 возводит цвет в квадратную степень (т.е. цвет*цвет).
Note.pngПримечание: Не работает при включённом $phong(en).
Tip.pngСовет: Use higher contrasts to diminish relatively darker areas and increase "hot spots".

$envmapsaturation(en) <КЗС(en) матрица(en)>
Контролирует цветовую насыщенность отражения. 0 - серые тона, а 1 - натуральный цвет. Красный, Зелёный и Синий цвета можно изменять используя "[к з с]" соответственно.
Note.pngПримечание: In the Shadercode for Source 2013 Source 2013 and Alien Swarm Alien Swarm the parameter is defined as a float parameter. However it will be used as a vec3 and the Shader expects and uses it as such.
Note.pngПримечание: Не работает при включённом $phong(en) на моделях.
Icon-Bug.pngБаг:Counter-Strike: Source Работает только на моделях.
Подтвердить:Эта ошибка существует в других Source 2013 Multiplayer играх использующие обычные затенения? (кроме: Half-Life 2: Deathmatch Half-Life Deathmatch: Source Day of Defeat: Source Team Fortress 2)
  [нужно проверить в ?]

$envmapframe(en) <целое число(en)>
Указывает стартовый кадр анимированной карты-куба.

$envmapmode(en) <целое число(en)> Obsolete
Depreciated MATERIAL_VAR_ENVMAPMODE = (1 << 25), // OBSOLETE

$basetexturenoenvmap(en) and $basetexture2noenvmap(en) <булева переменная(en)> (DX9 SM2) (удалено начиная с Counter-Strike: Global Offensive)
Shader(s): WorldVertexTransition
Used for materials with two albedo(en)s, to make one or the other matte. See also $basetexture and $basetexture2.
Note.pngПримечание: Superseded in Counter-Strike: Global Offensive by $envmapmask2(en).

$envmapoptional(en) <варианты выбора> (удалено начиная с Left 4 Dead)
Указывает нижнюю версию DirectX(en), при которой будут отображать отражения. Выбирается из вариантов:
  • 80 (DirectX 8)
  • 81 (DirectX 8.1)
  • 90 (DirectX 9)
  • 95 (DirectX 9 с Shader Model 3)

$envmapsphere(en) <булева переменная(en)> Obsolete (также в Garry's Mod) (удалено начиная с Alien Swarm)
Determines whether the material's envmap should be a spheremap (using matcap shading like GoldSrc "chrome"(en) textures) instead of a cubemap. Set this to 1 to use a spheremap.
Icon-Bug.pngБаг:In DirectX 9(en) mode, this will instead act like a regular cubemap with all 6 faces being identical.  [нужно проверить в ?]

$noenvmapmip(en) <булева переменная(en)> (только в Counter-Strike: Global Offensive)
Shader(s): LightmappedGeneric
Only use the top-level mipmap of the cubemap.
Вентиляционные короба без применения и с наложением маски бликов. Внизу изображения указаны параметры, использованные для создания этого эффекта.

$fresnelreflection(en) <число с плавающей запятой(en)> (Во всех играх начиная с Source 2006)
Shader(s): LightmappedGeneric, Lightmapped_4WayBlend, WorldVertexTransition
Добавляет эффект Френеля отражению. 0 - нет эффекта, а 1 - накладывает полный эффект, схож с Water(en). Эффект умножается при значениях выше 1.
Icon-Bug.pngБаг:Значения инвертированы в Black Mesa, 0 - накладывает полный эффект, а 1 - нет эффекта.  [нужно проверить в ?]

$envmapfresnel(en) <число с плавающей запятой(en)> (DX9 SM2) (Во всех играх начиная с Source 2007)
Shader(s): VertexLitGeneric
Тоже самое что и $fresnelreflection, но для VertexLitGeneric. По умолчанию будет использовать диапазон установленный $phongfresnelranges.
Note.pngПримечание: Работает только если сначала был включён $phong(en) Left 4 Dead.
Пример анизотропных отражений в игре, при параметре $envmapanisotropyscale = 1.

$envmapfresnelminmaxexp(en) <вектор данных(en)> (Во всех играх начиная с Left 4 Dead)
Shader(s): VertexLitGeneric
Устанавливает диапазон френеля для материалов, использующих $envmapfresnel без фонга. По умолчанию: "[0 1 2]".
Note.pngПримечание: Значения френеля для этого параметра отличаются от $phongfresnelranges(en). Первое значение - минимальное количество френеля, второе значение - максимальное количество френеля, а третье значение - экспонента.
Icon-Bug.pngБаг:Не может быть использован вместе с $bumpmap. Вместо этого используйте $phongfresnelranges.  [нужно проверить в ?]

$envmaplightscale(en) <число с плавающей запятой(en)> (Во всех играх начиная с Alien Swarm) (также в Garry's Mod)
Shader(s): LightmappedGeneric, Lightmapped_4WayBlend Counter-Strike: Global Offensive, VertexLitGeneric Counter-Strike: Global Offensive, WorldVertexTransition Counter-Strike: Global Offensive
Tint the surface's specular reflection with its lightmap. This matches a surface's reflection with its diffuse lighting and acts as rudimentary reflection occlusion. With a value of 1, a surface will have no reflection if it isn't lit at all. For models in Counter-Strike: Global Offensive, vertex lighting is used for the tinting instead of a lightmap.
Note.pngПримечание: Values above 1 for this parameter are technically permitted, but start inverting the effect.

$envmaplightscaleminmax(en) <вектор данных2(en)> (только в Counter-Strike: Global Offensive) (также в Garry's Mod)
Shader(s): LightmappedGeneric, Lightmapped_4WayBlend, VertexLitGeneric, WorldVertexTransition
Thresholds for the lightmap reflection tinting effect. Setting the minimum value higher increases the minimum light amount at which the reflection gets nerfed to nothing.

$envmapanisotropy(en) <булева переменная(en)> (только в Counter-Strike: Global Offensive)
Shader(s): LightmappedGeneric, Lightmapped_4WayBlend, WorldVertexTransition
Enables anisotropic reflection emulation by warping the reflection downwards.
For this it uses the alpha channel of the $bumpmap.
It linearly interpolates between a normal reflection vector and an anisotropic one.
This means that values of 0 in the alpha will result in normal reflections, and a value of 1 will result in anisotropic reflections.
Icon-Bug.pngБаг:Does not work with $normalmapalphaenvmapmask  [нужно проверить в ?]
Icon-Bug.pngБаг:Does not work with $basealphaenvmapmask except Lightmapped_4WayBlend  [нужно проверить в ?]
Note.pngПримечание: Requires a $bumpmap to be present.

$envmapanisotropyscale(en) <норма(en)> (только в Counter-Strike: Global Offensive)
Shader(s): LightmappedGeneric, Lightmapped_4WayBlend, WorldVertexTransition
Multiplier for how much the reflection should be warped.

Команды управления

Cvar /
команда
Параметры или
значение по умолчанию
Величины Получаемый результат
buildcubemaps Создаёт карты-кубы (cubemaps) для использования в материалах. Если эта функция не запущена, объекты будут отражать небосвод, или использовать карты-кубы по умолчанию или неправильные отражения, такие как отсутствующие текстуры(en), выглядящие либо очень ярко (при включённом HDR) или полностью чёрным.
envmap Создаёт карту окружения в местоположении игрока и сохраняет её в директории cubemap_screenshots/, в виде шести отдельных PFM-файлов (или, если выполняется без HDR, в TGA-файлах).
Tip.pngСовет: Созданные этой командой карты-кубы будут содержать подвижные объекты и модели, которые обычно игнорируются при использовании buildcubemaps.
mat_envmaptgasize 32 <целое число(en)> Устанавливает разрешение для файлов созданных с помощью envmap.
mat_fastspecular 0 отключено, 1 включено Быстрое отключение или включение отображения зеркальных отражений без перезагрузки материалов. Это не влияет на производительность, только на внешний вид. Для правильного тестирования производительности необходимо использовать параметр mat_specular.
Icon-Bug.pngБаг:Не работает в некоторых играх.  [нужно проверить в ?]
Note.pngПримечание: Вопреки распространенному заблуждению, установка значения 0 НЕ включает режим "причудливых зеркальных отражений", а просто полностью отключает зеркальные отражения.
mat_specular 1 0 отключено, 1 включено Отключает или включает зеркальные отражения, выгружает или загружает зеркальные материалы из памяти.
Note.pngПримечание: Данная команда управления в Left 4 Dead и Left 4 Dead 2 применима только через "launcher", поэтому используйте вместо неё следующие варианты:
Left 4 Dead sm_cvar building_cubemaps <0 или 1> команду (с установленным SourceMod)
или
Left 4 Dead 2 script Convars.SetValue("mat_specular", "<0 или 1>") (используя VScript).
r_showenvcubemap <булева переменная(en)> Команда для отображения всех карт-кубов на всех динамических объектах в полную яркость. Использована для создания изображения в начале статьи.

Смотреть также