srctools.fgd

Parse FGD files, used to describe Hammer entities.

class srctools.fgd.ValueTypes(
value,
names=None,
*,
module=None,
qualname=None,
type=None,
start=1,
boundary=None,
)

Bases: Enum

Types which can be applied to a KeyValue.

VOID = 'void'
CHOICES = 'choices'
SPAWNFLAGS = 'flags'
STRING = 'string'
BOOL = 'boolean'
INT = 'integer'
FLOAT = 'float'
VEC = 'vector'
ANGLES = 'angle'
TARG_DEST = 'target_destination'

Aliases: ENT_HANDLE, EHANDLE

TARG_DEST_CLASS = 'target_name_or_class'
TARG_SOURCE = 'target_source'
TARG_NPC_CLASS = 'npcclass'
TARG_POINT_CLASS = 'pointentityclass'
TARG_FILTER_NAME = 'filterclass'
TARG_NODE_DEST = 'node_dest'
TARG_NODE_SOURCE = 'node_id'
STR_SCENE = 'scene'
STR_SOUND = 'sound'
STR_PARTICLE = 'particlesystem'
STR_SPRITE = 'sprite'
STR_DECAL = 'decal'
STR_MATERIAL = 'material'
STR_MODEL = 'studio'
STR_VSCRIPT = 'scriptlist'
STR_VSCRIPT_SINGLE = 'script'
ANGLE_NEG_PITCH = 'angle_negative_pitch'
VEC_LINE = 'vecline'
VEC_ORIGIN = 'origin'
VEC_AXIS = 'axis'
COLOR_1 = 'color1'
COLOR_255 = 'color255'
SIDE_LIST = 'sidelist'
INST_FILE = 'instance_file'
INST_VAR_DEF = 'instance_parm'
INST_VAR_REP = 'instance_variable'
EXT_STR_TEXTURE = 'texture'
EXT_VEC_DIRECTION = 'vec_dir'
EXT_VEC_LOCAL = 'vec_local'
EXT_ANGLE_PITCH = 'angle_pitch'
EXT_ANGLES_LOCAL = 'angle_local'
has_list

Is this a flag or choices value, and needs a [] list?

valid_for_io

Is this type valid for I/O definitions?

extension

Is this an extension to the format?

is_ent_name

Several types are simply a targetname.

class srctools.fgd.EntityTypes(
value,
names=None,
*,
module=None,
qualname=None,
type=None,
start=1,
boundary=None,
)

Bases: Enum

The kind of entity each definition is.

BASE = 'baseclass'

Not an entity, others inherit from this.

POINT = 'pointclass'

Point entity

BRUSH = 'solidclass'

Brush entity. Can’t have a model keyvalue.

ROPES = 'keyframeclass'

Used for move_rope etc

TRACK = 'moveclass'

Used for path_track etc

FILTER = 'filterclass'

Used for filters.

NPC = 'npcclass'

An NPC.

is_point

Return whether this is a point entity.

class srctools.fgd.HelperTypes(
value,
names=None,
*,
module=None,
qualname=None,
type=None,
start=1,
boundary=None,
)

Bases: Enum

Types of functions in the entity header.

INHERIT = 'base'
HALF_GRID_SNAP = 'halfgridsnap'
CUBE = 'size'

Sets size of purple cube

BBOX = 'bbox'

Sets bounding box of entity

TINT = 'color'
SPHERE = 'sphere'
LINE = 'line'
FRUSTUM = 'frustum'
CYLINDER = 'cylinder'
ORIGIN = 'origin'

Adds circle at an absolute position.

VECLINE = 'vecline'

Draws line to an absolute position.

BRUSH_SIDES = 'sidelist'

Highlights brush faces.

BOUNDING_BOX_HELPER = 'wirebox'

Displays bounding box from two keyvalues

SWEPT_HULL = 'sweptplayerhull'

Draws the movement of a player-sized bounding box from A to B.

ORIENTED_BBOX = 'obb'

Bounding box oriented to angles.

SPRITE = 'iconsprite'
MODEL = 'studio'
MODEL_PROP = 'studioprop'
MODEL_NEG_PITCH = 'lightprop'

Uses separate pitch keyvalue

ENT_SPRITE = 'sprite'
ENT_INSTANCE = 'instance'
ENT_DECAL = 'decal'
ENT_OVERLAY = 'overlay'
ENT_OVERLAY_WATER = 'overlay_transition'
ENT_LIGHT = 'light'
ENT_LIGHT_CONE = 'lightcone'
ENT_ROPE = 'keyframe'
ENT_TRACK = 'animator'
ENT_BREAKABLE_SURF = 'quadbounds'

Sets the 4 corners on save

ENT_WORLDTEXT = 'worldtext'

Renders 3D text in-world.

ENT_CATAPULT = 'catapult'

Renders trigger_catpault trajectors prediction

ENT_LIGHT_CONE_BLACK_MESA = 'lightconenew'

New helper added in Black Mesa.

EXT_APPLIES_TO = 'appliesto'

Indicates this entity is only available in the given games.

EXT_ORDERBY = 'orderby'

Reorder keyvalues. Args = names in order.

EXT_AUTO_VISGROUP = 'autovis'

Convenience only used in parsing, adds @AutoVisgroup parents for the current entity. ‘Auto’ is implied at the start.

extension

Is this an extension to the format?

class srctools.fgd.AutoVisgroup(
name: str,
parent: str,
ents: Set[str] = NOTHING,
)

Represents one of the autovisgroup options that can be set.

Due to how these are coded into Hammer, our representation is rather strange. We put all the groups into a single dictionary, and on each specify the name of the parent. Note they’re case-sensitive, and can include punctuation.

class srctools.fgd.FGD

A FGD set for a game. May be composed of several files.

classmethod parse(
file: File[Any] | str,
filesystem: FileSystem[Any] | None = None,
) FGD

Parse an FGD file.

Parameters:
  • file – A :py:class:filesystem.File` representing the file to read, or a file path.

  • filesystem – The system to lookup files in. This is needed to resolve file inclusions. If not passed, file must be a :py:class:filesystem.File` to retrieve this automatically.

apply_bases() None

Fix base values in entities after parsing.

While parsing the classnames may be set as strings, so order in the file doesn’t matter. This fixes them to the real entity objects.

sorted_ents() Iterator[EntityDef]

Yield all entities in sorted order.

This ensures only all bases for an entity are yielded before the entity. Otherwise, entities are ordered in alphabetical order.

collapse_bases(ignore_aliases: bool = True) None

Collapse all bases into the entities that use them.

This operates in-place, and clears all the base attributes as a result.

export(
file: TextIO | None = None,
) str | None

Write the FGD contents into a text file.

If none are provided, the text will be returned.

parse_file(
filesys: FileSysT,
file: File[FileSysT],
*,
eval_bases: bool = True,
encoding: str = 'cp1252',
) None

Parse one file (recursively if needed).

If eval_bases is False, bases will not be computed. This makes it impossible in some cases to evaluate these later, but it can help if it is not required.

classmethod engine_dbase() FGD

Load and return a database of entity keyvalues and I/O.

This can be used to identify the kind of keys present on an entity. If you only need specific entities, use EntityDef.engine_def() instead to avoid needing to fetch all the entities.

class srctools.fgd.EntityDef(
type: EntityTypes,
classname: str = '',
*,
keyvalues: Dict[str, Dict[TagsSet, KVDef]] = NOTHING,
inputs: Dict[str, Dict[TagsSet, IODef]] = NOTHING,
outputs: Dict[str, Dict[TagsSet, IODef]] = NOTHING,
kv_order: List[str] = NOTHING,
bases: List[EntityDef | str] = NOTHING,
helpers: List[Helper] = NOTHING,
desc: str = '',
resources: Sequence[Resource] = (),
is_alias: bool = False,
)

A definition for an entity.

type: EntityTypes

The kind of entity.

classname: str

The classname of this entity, as originally typed.

kv_order: List[str]

Keyvalues have an order. If not present in here, they appear at the end.

bases: List[EntityDef | str]

The parent entity classes defined using base() helpers.

helpers: List[Helper]

All other helpers defined on the entity.

resources: Sequence[Resource]

A list of resources this entity may precache. Use get_resources() to recursively fetch sub-entity resources.

is_alias: bool

If set, the aliasof() helper was used. This entity should have 1 base, which this is simply an alternate classname for.

classmethod parse(
fgd: FGD,
tok: BaseTokenizer,
ent_type: EntityTypes,
eval_bases: bool = True,
) None

Parse an entity definition from an FGD file.

The @PointClass etc keyword should already have been read, and is passed as ent_type.

classmethod engine_def(
classname: str,
) EntityDef

Return the specified entity from an internal copy of the Hammer Addons database.

This can be used to identify the kind of keys/inputs/outputs present on an entity, as well as resources the entity requires/Precache()es.

Raises:

KeyError – If the classname is not found in the database.

classmethod engine_classes() AbstractSet[str]

Return a set of known entity classnames, from the Hammer Addons database.

get_helpers(
typ: Type[HelperT] | str,
) Iterator[Helper]

Find all helpers with this specific type.

get_resources(ctx: ~srctools.fgd.ResourceCtx, *, ent: ~srctools.vmf.Entity | None, on_error: ~typing.Callable[[str], object] = <function EntityDef.<lambda>>) Iterator[Tuple[FileType, str]]

Recursively fetch all the resources this entity may use, simulating Precache().

Parameters:
  • ent – A specific entity to evaluate against. If not provided, functions will silently be skipped.

  • ctx – Common information about the current map and game configuration. This is passed along to defined entclass functions, and is seperate, so it can be reused for many calls to this function.

  • on_error – If provided, when functions or entities are missing this will be called with the specific error, and raised if it returns an exception type. If not set, lookups are ignored. Most exceptions can be passed directly here to cause that to be raised.

strip_tags(
tags: FrozenSet[str],
) None

Strip all tags from this entity, blanking them.

Only values matching the given tags will be kept.

export(file: TextIO) None

Write the entity out to a FGD file.

iter_bases(
_done: Set[EntityDef] | None = None,
) Iterator[EntityDef]

Yield all base entities for this one.

If an entity is repeated, it will only be yielded once.

class srctools.fgd.KVDef(
name: str,
type: ValueTypes,
disp_name: str,
default: str = '',
desc: str = '',
val_list: List[Tuple[int, str, bool, FrozenSet[str]]] | List[Tuple[str, str, FrozenSet[str]]] | None = None,
readonly: bool = False,
reportable: bool = False,
)

Represents a keyvalue that may be set on entities

If the type is choices or spawnflags, val_list is required: * For choices it’s a list of (value, name, tags) tuples. * For spawnflags it’s a list of (bitflag, name, default, tags) tuples.

property choices_list: List[Tuple[str, str, FrozenSet[str]]]

Check that the keyvalues are CHOICES type, and then return val_list.

This isolates the type ambiguity of the attr.

property flags_list: List[Tuple[int, str, bool, FrozenSet[str]]]

Check that the keyvalues are SPAWNFLAGS type, and then return val_list.

This isolates the type ambiguity of the attr.

copy() KVDef

Create a duplicate of this keyvalue.

known_options() Iterator[str]

Use the default value and value list to determine values this can be set to.

export(
file: TextIO,
tags: Collection[str] = (),
) None

Write this back out to a FGD file.

class srctools.fgd.IODef(
name: str,
type: ValueTypes = ValueTypes.VOID,
desc: str = '',
)

Represents an input or output for an entity.

copy() IODef

Create a duplicate of this IODef.

export(
file: TextIO,
io_type: str,
tags: Collection[str] = (),
) None

Write this back out to a FGD file.

io_type should be “input” or “output”.

class srctools.fgd.EntAttribute

Common base class for IODef and KVDef.

class srctools.fgd.Helper

Base class for representing helper() commands in the header of an entity.

These mainly add visual widgets in Hammer’s views for manipulating and previewing keyvalues.

This should not be instantiated, only subclasses in _fgd_helpers.

classmethod parse(
args: List[str],
) HelperT

Parse this helper from the given arguments.

The default implementation expects no arguments.

export() List[str]

Produce the argument text to recreate this helper type.

get_resources(
entity: EntityDef,
) Iterable[str]

Return the resources used by this helper.

overrides() Collection[HelperTypes]

Specify which types can be overriden by this.

If any of these helper types are present before this type, they’re redundant and can be removed. For example size() is ignored if a studio() is present after it.

class srctools.fgd.UnknownHelper(name: str, args: List[str])

Represents an unknown helper.

export() List[str]

Produce the argument text to recreate this helper type.

srctools.fgd.match_tags(
search: Container[str],
tags: Collection[str],
) bool

Check if the search constraints satisfy tags.

The search tags should be uppercased.

All !tags or -tags cannot be present, all +tags must be present, and at lest one normal tag must be present (if they are) to pass.

srctools.fgd.validate_tags(tags: ~typing.Collection[str], error: ~typing.Callable[[str], BaseException] = <class 'ValueError'>) FrozenSet[str]

Check these tags have valid values.

The error exception is raised if invalid.

class srctools.fgd.Resource(
filename: str,
type: FileType = FileType.GENERIC,
tags: FrozenSet[str] = frozenset({}),
)

Resources used by an entity, with filetype.

If the tags mapping is present, that indicates branch features that should/should not be present. Examples: ‘episodic’ (vs HL2), ‘mapbase’.

classmethod mdl(
filename: str,
tags: FrozenSet[str] = frozenset({}),
) Resource

Create a resource definition for a model.

classmethod mat(
filename: str,
tags: FrozenSet[str] = frozenset({}),
) Resource

Create a resource definition for a material.

classmethod snd(
filename: str,
tags: FrozenSet[str] = frozenset({}),
) Resource

Create a resource definition for a soundscript.

classmethod part(
filename: str,
tags: FrozenSet[str] = frozenset({}),
) Resource

Create a resource definition for a particle system.

classmethod weapon_script(
filename: str,
tags: FrozenSet[str] = frozenset({}),
) Resource

Create a resource definition for a weapon script.

class srctools.fgd.ResourceCtx(tags: ~typing.Iterable[str] = (), fsys: ~srctools.filesys.FileSystem = VirtualFileSystem('<virtual>'), fgd: ~srctools.fgd.FGD | ~typing.Mapping[str, ~srctools.fgd.EntityDef] | ~typing.Callable[[str], ~srctools.fgd.EntityDef] = <bound method EntityDef.engine_def of <class 'srctools.fgd.EntityDef'>>, mapname: str = '', funcs: ~typing.Mapping[str, ~typing.Callable[[~srctools.fgd.ResourceCtx, ~srctools.vmf.Entity], ~typing.Iterator[~srctools.fgd.Resource | ~srctools.vmf.Entity]]] = srctools.EmptyMapping)

Map information passed to FileType.ENTCLASS_FUNC functions.

mapname: str

The BSP/VMF map name, like what is passed to map in-game.

class srctools.fgd.Snippet(
name: str,
source_path: str,
source_line: int,
value: ValueT_co,
)

A part of some definition which has been given a name to be reused.

classmethod lookup(
error: Callable[[str], BaseException],
kind: str,
mapping: Mapping[str, Snippet[T]],
key: str,
) T

Locate a snippet using the specified mapping.

If not found, error is used to create the exception to raise, using kind as the snippet type.

classmethod parse(
fgd: FGD,
path: str,
tokeniser: BaseTokenizer,
) None

Parse snippet definitions in a FGD.

class srctools.fgd.HelperBBox(
bbox_min: Vec,
bbox_max: Vec,
)

Helper implementation for bbox().

class srctools.fgd.HelperBoundingBox(min: str, max: str)

Displays bounding box between two keyvalues.

classmethod parse(
args: List[str],
) Self

Parse wirebox(min, max)

export() List[str]

Produce the wirebox(min, max) arguments.

class srctools.fgd.HelperBreakableSurf

Specialized helper for func_breakable_surf.

class srctools.fgd.HelperBrushSides(key: str)

Highlights brush faces in a space-sepearated keyvalue.

class srctools.fgd.HelperCylinder(
r: float,
g: float,
b: float,
start_key: str,
start_value: str,
end_key: str | None = None,
end_value: str | None = None,
start_radius: str | None = None,
end_radius: str | None = None,
)

Helper implementation for cylinder().

Cylinder has the same sort of arguments as line(), plus radii for both positions.

classmethod parse(
args: List[str],
) Self

Parse cylinder(r g b, start key/value/radius, end key/value/radius).

export() List[str]

Produce the correct line() arguments.

class srctools.fgd.HelperDecal

Specialized helper for infodecal.

class srctools.fgd.HelperEnvSprite(mat: str | None)

Variant of iconsprite() specifically for env_sprite.

class srctools.fgd.HelperFrustum(
fov: str | float,
near_z: str | float,
far_z: str | float,
color: str | Tuple[float, float, float],
pitch_scale: str | float,
)

Helper for env_projectedtexture visuals.

classmethod parse(
args: List[str],
) Self

Parse frustum(fov, near, far, color, pitch_scale).

export() List[str]

Export back out frustrum() arguments.

class srctools.fgd.HelperHalfGridSnap

Helper implementation for halfgridsnap().

This causes the entity to snap to half a grid. This argument doesn’t use () in Valve’s files.

class srctools.fgd.HelperInherit

Helper implementation for base().

These specify the base classes for an entity def. This implementation isn’t used, the EntityDef special-cases it.

class srctools.fgd.HelperInstance

Specialized helper for func_instance.

class srctools.fgd.HelperLight

Specialized helper for omnidirectional lights.

class srctools.fgd.HelperLightSpot(
inner: str,
outer: str,
color: str,
pitch_scale: float,
)

Specialized helper for displaying spotlight previews.

classmethod parse(
args: List[str],
) Self

Parse lightcone(inner, outer, color, pitch_scale).

export() List[str]

Produce the arguments for lightcone().

class srctools.fgd.HelperLine(
r: float,
g: float,
b: float,
start_key: str,
start_value: str,
end_key: str | None = None,
end_value: str | None = None,
)

Helper implementation for line().

Line has the arguments line(r g b, start_key, start_value, end_key, end_value) It searches for the first entity where ent[start_key] == self[start_value]. If the second pair are present it does the same for those for the other line end.

classmethod parse(
args: List[str],
) Self

Parse line(r g b, start_key, start_value, end_key, end_value).

export() List[str]

Produce the correct line() arguments.

class srctools.fgd.HelperModel(model: str | None)

Helper which displays models.

If the model is not provided, the ‘model’ key is used.

overrides() Collection[HelperTypes]

Avoid some issues where other helpers break this one.

classmethod parse(
args: List[str],
) Self

Parse iconsprite(mat).

export() List[str]

Produce the arguments for iconsprite().

get_resources(
entity: EntityDef,
) Iterable[str]

studio() uses a single model.

class srctools.fgd.HelperModelLight(model: str | None)

Special model helper, with inverted pitch.

class srctools.fgd.HelperModelProp(model: str | None)

Model helper which does not affect the bounding box.

class srctools.fgd.HelperOrientedBBox(min: str, max: str)

A bounding box oriented to angles.

class srctools.fgd.HelperOrigin(key: str)

Parse the origin() helper.

class srctools.fgd.HelperOverlay

Specialized helper for env_overlay.

class srctools.fgd.HelperOverlayTransition

Specialized helper for env_overlay_transition.

class srctools.fgd.HelperRenderColor(r: float, g: float, b: float)

Helper implementation for color().

overrides() Collection[HelperTypes]

Previous ones of these are overridden by this.

classmethod parse(
args: List[str],
) Self

Parse color(R G B).

export() List[str]

Produce color(R G B).

class srctools.fgd.HelperRope(name_kv: str | None)

Specialized helper for displaying move_rope and keyframe_rope.

classmethod parse(
args: List[str],
) Self

Parse keyframe(name).

export() List[str]

Produce the arguments for keyframe().

class srctools.fgd.HelperSize(
point1: Vec,
point2: Vec,
)

Helper implementation for size().

This sets the bbox for the entity.

overrides() Collection[HelperTypes]

Additional versions of this are not available.

classmethod parse(
args: List[str],
) Self

Parse size(x1 y1 z1, x2 y2 z2).

export() List[str]

Produce (x1 y1 z1, x2 y2 z2).

class srctools.fgd.HelperSphere(
r: float,
g: float,
b: float,
size_key: str,
)

Helper implementation for sphere().

classmethod parse(
args: List[str],
) Self

Parse sphere(radius, r g b).

export() List[str]

Export the helper.

class srctools.fgd.HelperSprite(mat: str | None)

The sprite helper, for editor icons.

If the material is not provided, the ‘model’ key is used.

overrides() Collection[HelperTypes]

Specifies helpers which this makes irrelevant.

classmethod parse(
args: List[str],
) Self

Parse iconsprite(mat).

export() List[str]

Produce the arguments for iconsprite().

get_resources(
entity: EntityDef,
) Iterator[str]

iconsprite() uses a single material.

class srctools.fgd.HelperSweptPlayerHull

Draws the movement of a player-sized bounding box from A to B.

class srctools.fgd.HelperTrack

Specialized helper for path_track-style entities.

This no longer does anything.

class srctools.fgd.HelperVecLine(key: str)

A variant of line() which draws a line to the entity.

class srctools.fgd.HelperWorldText

Specialized helper for point_worldtext.

class srctools.fgd.HelperExtAppliesTo(tags: List[str] = NOTHING)

Allows specifying “tags” to indicate an entity is only used in certain games.

classmethod parse(
args: List[str],
) Self

Parse appliesto(tag1, tag2).

export() List[str]

Produce the arguments for appliesto().

class srctools.fgd.HelperExtAutoVisgroups(
path: List[str] = NOTHING,
)

Convenience for parsing, adds @AutoVisgroups to entities.

‘Auto’ is implied at the start.

classmethod parse(
args: List[str],
) Self

Parse autovis(group1, group2).

export() List[str]

Produce the arguments for autovis().

class srctools.fgd.HelperExtOrderBy(order: List[str] = NOTHING)

Reorder keyvalues. Args = names in order.

classmethod parse(
args: List[str],
) Self

Parse orderby(key1, key2).

export() List[str]

Produce the arguments for orderby().