Areaportal
Areaportal — брашевая сущность, func_areaportal, func_areaportalwindow, которую можно использовать для 'запечатывания' листьев и управления видимостью.
Areaportal'ы служат двум разным целям: отбраковке геометрии и удалению целых областей из отрисовки.
Areaportal'ы похожи на дверные проёмы, которые либо открыты, либо закрыты. Когда Areaportal закрыт, он блокирует видимость геометрии и объектов в области за ним. Когда он открыт, геометрия вновь видна. Areaportal'ы можно динамически открывать и закрывать во время игры. Обычно, они настраиваются на открытие и закрытие набором брашей trigger_multiple с помощью системы вводов/выводов или связью с сущностью двери.
Свойства
Areaportal'ы:
- связаны с сущностью func_areaportal;
- должны состоять только из одного браша. Areaportal'ы из более чем одного браша будут выдавать ошибку компиляции vbsp;
- должны использовать материал
tools\toolsareaportal
, покрывающий все стороны браша; - не должны содержать деформированных поверхностей, иначе будет выдана ошибка vbsp;
- должны использоваться для запечатывания всех зон, с которыми соприкасаются, чтобы избежать утечек;
- это объём, а не отдельные поверхности. Areaportal'ы могут быть любого размера, но обычно они состоят из тонких брашей по размеру зон (дверных проёмов), которые они соединяют;
- создают новый visleaf по своему объёму;
- можно настроить на открытие или закрытие в зависимости от логики сущности или путём присоединения их к сущности двери.
areaportal_window
Сущность func_areaportalwindow ведёт себя как обычный Areaportal, с добавлением затухания и закрытия в зависимости от удалённости игрока. Это позволяет избежать «резкого» открытия Areaportalа.
Конструкция
- Создайте объём из одного твёрдого браша, полностью запечатав пространство между двумя зонами, которыми вы желаете управлять. Это может быть несколько Areaportal, соприкасающихся гранями. Не создавайте Areaportal с более, чем шестью сторонами.
- Если Areaportal соединяет две области, например, дверной проём, сделайте браш размером с проём и такой же толщиной, как и стены, с которыми он соприкасается. Если область представляет собой открытое пространство, то толщина может быть любой (типичные размеры сетки: 8, 16, 32 и т. д.).
- Наложите материал Tool textures#Optimisation tools\toolsareaportal на все грани браша.
- Свяжите браш с сущностью func_areaportal или func_areaportalwindow.
- Установите значение ключа Initial State (изначальное состояние) так, чтобы оно не блокировало видимость, когда этого не должно быть. Если вы хотите связать портал с наименованной дверью, установите его Initial State в то же состояние, что и для двери, и внесите имя двери в строку портала Name of Linked Door (имя связываемой двери). Если дверь закрыта, изначальное состояние портала также должно быть закрытым, и наоборот.

Влияние на производительность
Открытые порталы (не важно, открыты они всегда, или временами) ведут себя, как шторки для видимой сквозь них геометрии. Подобно окну дома, движок отрисовывает только те листья, которые непосредственно видны через портал. То есть, область за ним обрезается по размеру окна, уменьшая величину отображаемой геометрии и улучшая производительность. Вдобавок ко всему, часть модели (prop) вообще не отрисовывается, когда она видна под усечённым конусом (или видимым углом). Это делает открытые порталы весьма полезными для управления видимостью геометрии моделей.
Благодаря таким преимуществам в производительности, Areaportal часто используются в состоянии всегда открыт. Всегда открытый портал создаётся путём установки ключа "Initial State" (изначальное состояние) сущности func_areaportal в значение «Open» (открыт). Открытые порталы используются на входе в другие области, содержащие большое число листов и геометрии. Например, такой портал, размещённый в конце коридора, выходящего на более широкое пространство, может дать существенный прирост производительности. Пока игрок смотрит сквозь дверь изнутри, будут отрисовываться только те листья с геометрией, которые видны непосредственно через проём.
Перебор
Будьте осторожны, и не создавайте слишком много видимых порталов. Каждый из них съедает ресурсы, и если портал отсекает недостаточно деталей, отрисовка сцены без него ускорится!
На скомпилированной карте Areaportal не образуют брашей, поэтому нет ограничений на их размер. Это может быть полезно, когда у вас переполненный BSP и вы используете множество Hint-брашей.
Компилирование
Жизненно важно, чтобы любые зоны, которые должен изолировать Areaportal, не перетекали друг в друга. Как и при обычных утечках, область карты считается изолированной от другой только тогда, когда она полностью окружена простыми брашами (не являющимися сущностями, кроме брашей Areaportal), без промежутков. Если области соединены по-разному, каждая из них должна быть заполнена Areaportal.
Понять это поможет воображаемый аквариум с водой и несколькими отверстиями по краям. Ареа-портал должен заполнить каждое из этих отверстий, иначе область будет утекать, выдавая ошибку утечки в vbsp.
Ареа-порталы должны запечатывать каждый вход в область. func_detail brushes, translucent textures, and displacements cannot seal an area, and will generate leaks that prevent the map from running. If the compiler can still find a way between the two main surfaces of any one portal, it will report a portal leak.
Spotting compile errors
Areaportal compile errors are output by VBSP. If a leak occurs, you will see this:
Brush <brush number>: areaportal brush doesn't touch two areas done
These error messages are sometimes not as easy to spot as normal leak error messages, but when it comes to locating the leak in the map, vbsp will generate a pointfile to help you, just as for regular geometry leaks.


Areaportals and water
One other tricky aspect of using areaportals is that they are not allowed to cross water boundaries, like the water surface. To accomplish this, you will need to divide the portal into two - one areaportal above the water surface, and another areaportal below it - so that they both meet at the water plane.
Merging
For optimization reasons, areaportals that share the same plane (are aligned) are automatically merged by the engine. If this behavior is unwanted, simply ensure the areaportal brushes are not along the same plane. This is usually as simple as shrinking or moving one of the areaportals slightly in the editor so they are no longer aligned. Even one grid unit is sufficient to avoid an automatic merge.

r_DrawPortals 1
console command.Looking through areas
Areaportals only cull between the areas that they seal off. Consider the image to the right: while the contents of the building are culled away as you would expect, visibility between visleaf one and two is unaffected because they are connected to each other via the sides of the building.
This can be fixed by creating two further areaportals on either side of the building.
Console commands
You can debug and test portals in-game, using some portal-specific console variables:
- r_DrawPortals 0/1
- Outlines any portal border surface (between two areas) in green when set to "1". Sometimes more than one portal is condensed into one. If the portal belonging to it is open, a second green box is also drawn, showing what the visibility on the other side is clipped to.
- mat_wireframe 0/1/2/3
- Draws geometry in wireframe mode, making it easy to see the effects of areaportals in the level. When debugging areaportals, you should typically use mat_wireframe set to "1" or "2", as the "3" setting can hide geometry that is actually rendering.
- r_portalscloseall 0/1
- Setting this to "1" forces all areaportals closed (so that they cannot be opened). Overrides
r_portalsopenall 1
. (Try this if portals don't seem to be doing anything. It can tell you whether the problem is just that the portals aren't closing properly.)
- r_portalsopenall 0/1
- Setting this to "1" forces all areaportals open (so that they cannot be closed).

BindToggle
console command to allow a single key to be used to toggle a console variable.In multiplayer
Areaportals are very useful in multiplayer games. Their creation is identical to those in single-player games, but their function and usage is slightly different. With multiple players in a game server, there is less control of when an areaportal is going to be open, and level performance needs to be optimized for worst case scenarios (i.e. when all visible portals are open). Because of this, in most cases, 'always open' areaportals are placed most often, followed by areaportals linked to doors, and then areaportals controlled by triggers. In worst case scenarios, well-crafted 'always open' areaportals will increase performance more than portals that are designed to be triggered.
An areaportal window can also be used seal structures in multiplayer, but are less useful because they can create gameplay imbalances in competitive multiplayer games. A player inside the structure that is near the areaportal window would be able to see any players outside, but players farther away outside would not be able to see the player inside.
Relationship to occluders
Areaportals are similar to occluders in that they help control visibilty. The main differences between them are:
- Occluders only hide model (prop) geometry that is behind them. Areaportals hide all types of objects.
- Areaportals must fully seal areas (allow no leaks), while occluders can be free-standing inside areas.
- Occluders are more expensive per object than open areaportals.
- Occluders have controls for the size of objects they will hide, based upon screen area.

See also
- func_areaportal / CAreaPortal
- func_areaportalwindow
- CAreaPortalOneWay (C++ code for new entity)
- Controlling Geometry Visibility and Compile Times
- Leak
- Visleaf