### Install Squish Library Components with CMake Source: https://github.com/teamspen210/srctools/blob/master/src/libsquish/CMakeLists.txt This CMake snippet defines the installation rules for the 'squish' library. It specifies that the library, import libraries, and public headers should be installed into 'lib' and 'include' directories respectively. This ensures the library can be used by other projects. ```cmake INSTALL( TARGETS squish LIBRARY DESTINATION lib ARCHIVE DESTINATION lib PUBLIC_HEADER DESTINATION include ) ``` -------------------------------- ### Game Configuration and Filesystem Setup with srctools.game Source: https://context7.com/teamspen210/srctools/llms.txt Shows how to use the srctools.game module to parse a Source game's gameinfo.txt file. This allows for automatic setup of the game's filesystem search paths, enabling easy access to game assets. ```python from srctools.game import Game # Load game configuration game = Game('C:/Steam/steamapps/common/Half-Life 2/hl2') print(f"Game: {game.game_name}") print(f"App ID: {game.app_id}") # Get full filesystem chain with all searchpaths fs = game.get_filesystem() # Access any file from the game if 'materials/models/weapons/v_shotgun.vmt' in fs: with fs['materials/models/weapons/v_shotgun.vmt'].open_str() as f: print(f.read()) # Search paths are automatically set up for path in game.search_paths: print(f"Search path: {path}") ``` -------------------------------- ### Get Entity Resources with srctools.vmf Source: https://context7.com/teamspen210/srctools/llms.txt Demonstrates how to extract resources required by a Source Engine entity using the srctools.vmf module. It takes an Entity object and a game configuration (fgd) to identify and list associated resources like models and materials. ```python from srctools.vmf import Entity ent = Entity({'classname': 'prop_static', 'model': 'models/props/table.mdl'}) resources = list(ent_def.get_resources(ent, fgd)) for res in resources: print(f"Resource: {res.filename} ({res.type})") ``` -------------------------------- ### Parse Keyvalues to Specific Types with Defaults Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/keyvalues.rst Provides examples of using helper methods like `int`, `float`, `bool`, and `vec` to search for a key, parse its value to the specified type, and return a default if the key is missing or parsing fails. This simplifies type-safe data retrieval. ```python integer_value = kv.int('int_key', 0) float_value = kv.float('float_key', 0.0) boolean_value = kv.bool('bool_key', False) vector_value = kv.vec('vec_key', [0,0,0]) ``` -------------------------------- ### Locating and Writing Files Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/vpk.rst Details on how to find files within a VPK archive and how to add new files or folders. ```APIDOC ## Locating and Writing Files ### Description This section explains how to efficiently locate files within a VPK archive using various indexing methods and how to add new files or folders to an existing VPK. ### Locating Files The VPK structure organizes files by folder and extension, allowing for efficient iteration. You can locate a specific file using dictionary-like indexing: - `vpk['folders/name.ext']` - `vpk['folders', 'name.ext']` - `vpk['folders', 'name', 'ext']` Membership testing (`in`) and length checks (`len`) are also supported. If the exact filename is unknown, you can iterate through the VPK or use the following methods: ### Methods - **`VPK.filenames()`**: Returns an iterator for all filenames in the VPK. - **`VPK.folders()`**: Returns an iterator for all folders in the VPK. - **`VPK.fileinfos()`**: Returns an iterator for all `FileInfo` objects in the VPK. ### Writing Files To write to a VPK: 1. Create a new file info entry using `VPK.new_file()`. 2. Use the `FileInfo.write()` method to write data to the newly created entry. Alternatively, you can use the following convenience methods: ### Methods - **`VPK.new_file(filename, size, offset, arch_index)`**: Creates a new file entry in the VPK directory. - **`VPK.add_file(filename, data)`**: Adds a new file with the given data to the VPK. - **`VPK.add_folder(folder_path)`**: Adds a new folder to the VPK. ### Deleting Files Files can be removed from a VPK using the `del` keyword: ```python del vpk['some/filename'] ``` ``` -------------------------------- ### VPK File Access and Context Management (Python) Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/vpk.rst Demonstrates how to open, read from, and write to VPK archives using Python. It shows the use of VPK as a context manager for automatic saving and highlights immediate writes to data files versus delayed directory updates. ```python from srctools.vpk import VPK, OpenModes # Open a VPK in read/write mode with VPK('path/to/archive.vpk', OpenModes.READ_WRITE) as vpk: # Read a file file_content = vpk['path/to/file.txt'].read() # Write to a file (changes to data files are immediate) new_file_info = vpk.new_file('new/file.bin') new_file_info.write(b'binary data') # Changes to the directory are saved on exit or explicitly vpk.write_dirfile() # Explicitly save directory changes # VPK is automatically closed and changes saved if no exception occurred ``` -------------------------------- ### Adding and Deleting Files in VPK (Python) Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/vpk.rst Demonstrates how to add new files to a VPK archive and how to remove existing files using Python. It covers creating new file entries and using the `del` keyword for removal. ```python from srctools.vpk import VPK vpk = VPK('path/to/archive.vpk', mode='r+') # Open in read/write mode # Add a new file with content new_file_info = vpk.new_file('new/data.bin') new_file_info.write(b'\x01\x02\x03') # Alternatively, add a file and write content in one step vpk.add_file('another/file.txt', b'Hello, VPK!') # Delete a file if 'path/to/old_file.txt' in vpk: del vpk['path/to/old_file.txt'] vpk.write_dirfile() # Save directory changes ``` -------------------------------- ### VPK Package Management with Python Source: https://context7.com/teamspen210/srctools/llms.txt Explains how to use the VPK module for reading and writing Valve's VPK package format. It covers opening existing VPKs, listing files, reading specific file contents, checking for file existence, creating new VPKs, adding files, saving, and appending to existing VPKs. ```python from srctools.vpk import VPK # Open existing VPK (read mode) vpk = VPK('hl2/hl2_textures_dir.vpk') # List all files for file_info in vpk: print(file_info.filename) # Read specific file if 'materials/brick/brickwall001a.vmt' in vpk: file_info = vpk['materials/brick/brickwall001a.vmt'] content = file_info.read() print(content.decode('utf-8')) # Check if file exists exists = 'models/props/table.mdl' in vpk # Create new VPK new_vpk = VPK('custom_pak_dir.vpk', mode='w') # Add files new_vpk['materials/custom/mytexture.vmt'] = b'"LightmappedGeneric"\n{\n\t"$basetexture" "custom/mytexture"\n}\n' new_vpk['materials/custom/mytexture.vtf'] = open('mytexture.vtf', 'rb').read() # Save and close new_vpk.save() # Append to existing VPK append_vpk = VPK('custom_pak_dir.vpk', mode='a') append_vpk['sounds/custom/mysound.wav'] = open('mysound.wav', 'rb').read() append_vpk.save() ``` -------------------------------- ### Accessing VPK Files by Path (Python) Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/vpk.rst Illustrates various ways to access files within a VPK archive using Python. It covers direct string indexing, tuple indexing, and component-wise indexing for locating specific files. ```python from srctools.vpk import VPK vpk = VPK('path/to/archive.vpk') # Access by full path string file_data_1 = vpk['folder/subfolder/file.ext'].read() # Access by path components (folder, filename) file_data_2 = vpk['folder/subfolder', 'file.ext'].read() # Access by folder, filename, and extension file_data_3 = vpk['folder/subfolder', 'file', 'ext'].read() ``` -------------------------------- ### Verifying VPK Integrity (Python) Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/vpk.rst Shows how to verify the integrity of individual files and the entire VPK archive using Python. The `verify()` method checks file checksums, and `verify_all()` checks all files. ```python from srctools.vpk import VPK vpk = VPK('path/to/archive.vpk') # Verify a specific file file_info = vpk['some/file.dat'] if file_info.verify(): print('File integrity verified.') else: print('File integrity check failed!') # Verify all files in the VPK if vpk.verify_all(): print('All VPK files verified successfully.') else: print('VPK integrity check failed for one or more files.') ``` -------------------------------- ### Reading and Writing Keyvalues Files Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/keyvalues.rst Demonstrates how to read KeyValues files into Keyvalues objects and how to serialize Keyvalues objects back into files. ```APIDOC ## Reading and Writing Keyvalues Files ### Description Use `Keyvalues.parse` to read KeyValues files and `Keyvalues.serialise` (or `Keyvalues.serialize`) to write them back. ### Methods * `Keyvalues.parse(file_obj, filename)`: Parses a KeyValues file from the given file object and returns a `Keyvalues` object. The `filename` is used for error reporting. * `Keyvalues.serialise(file_obj)`: Serializes the `Keyvalues` object to the given file object. * `Keyvalues.serialize(file_obj)`: Alias for `serialise`. * `Keyvalues.export(file_obj)`: Exports the Keyvalues tree, typically used for line-based output. ### Example Usage ```python from srctools.keyvalues import Keyvalues # Reading a file with open('filename.txt', 'r') as read_file: kv = Keyvalues.parse(read_file, 'filename.txt') # Writing to a file with open('filename_2.txt', 'w') as write_file: kv.serialise(write_file) ``` ### Exceptions * `KeyValError`: Base exception for errors during KeyVal processing. ``` -------------------------------- ### srctools.cmdseq.write Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/cmdseq.rst Writes a CmdSeqTree object to a .wc expert compile options file in Valve's binary format. ```APIDOC ## srctools.cmdseq.write ### Description Writes a CmdSeqTree object to a .wc expert compile options file in Valve's binary format. ### Method POST (or equivalent for file writing) ### Endpoint N/A (Function call) ### Parameters #### Path Parameters - **filepath** (str) - Required - The path to the .wc file to write. - **cmdseq_tree** (CmdSeqTree) - Required - The CmdSeqTree object to write. ### Request Example ```python import srctools.cmdseq # Assuming compile_options is a CmdSeqTree object obtained from parsing or building compile_options = srctools.cmdseq.CmdSeqTree() # ... populate compile_options ... srctools.cmdseq.write('path/to/output.wc', compile_options) ``` ### Response #### Success Response (200) - None (operation is a side effect of writing to a file). #### Response Example ```json { "example": "No direct response, file is written." } ``` ``` -------------------------------- ### srctools.cmdseq.parse Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/cmdseq.rst Parses a .wc expert compile options file. Automatically detects and reads both Valve's binary format and the keyvalues format. ```APIDOC ## srctools.cmdseq.parse ### Description Parses a .wc expert compile options file. Automatically detects and reads both Valve's binary format and the keyvalues format. ### Method GET (or equivalent for file reading) ### Endpoint N/A (Function call) ### Parameters #### Path Parameters - **filepath** (str) - Required - The path to the .wc file to parse. ### Request Example ```python import srctools.cmdseq compile_options = srctools.cmdseq.parse('path/to/your/map.wc') ``` ### Response #### Success Response (200) - **compile_options** (CmdSeqTree) - An object representing the parsed compile options. #### Response Example ```json { "example": "CmdSeqTree object representing the parsed compile options" } ``` ``` -------------------------------- ### Iterating and Checking for Files in VPK (Python) Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/vpk.rst Shows how to iterate through all files within a VPK archive and how to check for the existence of a specific file using Python. It demonstrates the use of `in` operator and `len()`. ```python from srctools.vpk import VPK vpk = VPK('path/to/archive.vpk') # Check if a file exists if 'path/to/some_file.txt' in vpk: print('File exists!') # Get the total number of files num_files = len(vpk) print(f'Total files: {num_files}') # Iterate through all filenames for filename in vpk.filenames(): print(filename) # Iterate through all file infos for file_info in vpk.fileinfos(): print(f'Filename: {file_info.name}, Size: {file_info.size}') ``` -------------------------------- ### BSP Class - Initialization and Loading Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/bsp.rst Initializes and loads a BSP file. The file is loaded into memory, but only the main headers are parsed initially. BSP files cannot be created from scratch. ```APIDOC ## BSP Class ### Description Represents a compiled BSP map file, allowing for reading and writing. ### Method `__init__` ### Endpoint N/A (Class constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **filename** (str | os.PathLike[str]) - Required - The path to the BSP file to read. * **version** (Union[VERSIONS, GameVersion, None]) - Optional - Specifies the expected file version. An error is raised if the BSP's version does not match. ### Request Example ```python # Example usage (assuming srctools.bsp is imported) # bsp_map = srctools.bsp.BSP('path/to/your/map.bsp') ``` ### Response #### Success Response (200) N/A (Constructor does not return a value, but initializes the object.) #### Response Example N/A ``` -------------------------------- ### VMT Material Parsing and Creation in Python Source: https://context7.com/teamspen210/srctools/llms.txt Provides guidance on using the VMT module to parse and create Source Engine material files. It covers parsing existing VMTs, accessing shader parameters, checking parameter types, programmatically creating new materials, adding proxies, and serializing materials to a string format. ```python from srctools.vmt import Material # Parse VMT file with open('materials/brick/brickwall.vmt', 'r') as f: mat = Material.parse(f, 'brickwall.vmt') print(f"Shader: {mat.shader}") print(f"Base texture: {mat['$basetexture']}") # Access shader parameters if '$bumpmap' in mat: print(f"Normal map: {mat['$bumpmap']}") # Check parameter types from srctools.vmt import VarType param_type = VarType.from_name('$basetexture') # Returns VarType.TEXTURE # Create material programmatically new_mat = Material( shader='LightmappedGeneric', params={ '$basetexture': 'custom/mywall', '$bumpmap': 'custom/mywall_normal', '$surfaceprop': 'concrete', } ) # Add proxies from srctools import Keyvalues new_mat.proxies.append(Keyvalues('TextureScroll', [ Keyvalues('texturescrollvar', '$basetexturetransform'), Keyvalues('texturescrollrate', '0.1'), Keyvalues('texturescrollangle', '90'), ])) # Serialize to string (for writing to file) import io buffer = io.StringIO() # Note: Material serialization would require manual construction ``` -------------------------------- ### Configure Platform-Specific Build Settings (Xcode, SSE2, Altivec) Source: https://github.com/teamspen210/srctools/blob/master/src/libsquish/CMakeLists.txt This CMake snippet configures build settings based on the generator and build options. For Xcode, it sets architectures for universal binaries. For other platforms, it enables SSE2 or Altivec support based on corresponding build options and compiler flags. ```cmake IF (CMAKE_GENERATOR STREQUAL "Xcode") SET(CMAKE_OSX_ARCHITECTURES "i386;ppc") ELSE (CMAKE_GENERATOR STREQUAL "Xcode") IF (BUILD_SQUISH_WITH_SSE2 AND NOT WIN32) ADD_DEFINITIONS(-DSQUISH_USE_SSE=2 -msse2) ENDIF (BUILD_SQUISH_WITH_SSE2 AND NOT WIN32) IF (BUILD_SQUISH_WITH_ALTIVEC AND NOT WIN32) ADD_DEFINITIONS(-DSQUISH_USE_ALTIVEC=1 -maltivec) ENDIF (BUILD_SQUISH_WITH_ALTIVEC AND NOT WIN32) ENDIF (CMAKE_GENERATOR STREQUAL "Xcode") ``` -------------------------------- ### VMF Map File Parsing and Manipulation (Python) Source: https://context7.com/teamspen210/srctools/llms.txt Illustrates reading and writing Hammer VMF map files. Covers accessing worldspawn, iterating through entities, finding entities by class, creating new entities, adding outputs, creating brushes, performing wildcard searches for entities, and exporting modified map data. ```Python from srctools import VMF, Vec, Angle # Parse existing map with open('mymap.vmf', 'r') as f: vmf = VMF.parse(f) # Access worldspawn print(f"Map skybox: {vmf.spawn['skyname']}") # Iterate all entities for ent in vmf.entities: if ent['classname'] == 'info_player_start': origin = Vec.from_str(ent['origin']) print(f"Spawn point at {origin}") # Find entities by class for light in vmf.by_class.get('light', []): brightness = light['_light', '255 255 255 200'] print(f"Light: {brightness}") # Create new entity trigger = vmf.create_ent( classname='trigger_once', origin='0 0 64', targetname='my_trigger', spawnflags='1', ) # Add output from srctools.vmf import Output trigger.add_out(Output( output='OnTrigger', target='relay_start', input='Trigger', delay=0.5, )) # Create a brush (rectangular prism) prism = vmf.make_prism( Vec(-64, -64, 0), # min corner Vec(64, 64, 128), # max corner mat='tools/toolstrigger', ) trigger.solids.append(prism.solid) # Search for entities for ent in vmf.search('relay_*'): # Wildcard search by targetname print(f"Found: {ent['targetname']}") # Export modified map with open('mymap_modified.vmf', 'w') as f: vmf.export(f) ``` -------------------------------- ### Asset Dependency Tracking with srctools.packlist Source: https://context7.com/teamspen210/srctools/llms.txt Explains the functionality of the srctools.packlist module for tracking files to be packed into BSP maps. It demonstrates how to initialize a PackList, pack individual files, automatically detect dependencies from VMF entities using an FGD, and pack assets into a BSP's pakfile. ```python from srctools.packlist import PackList from srctools.game import Game from srctools.fgd import FGD from srctools import VMF, BSP # Set up packlist with game filesystem game = Game('C:/Steam/steamapps/common/Team Fortress 2/tf') fs = game.get_filesystem() packlist = PackList(fs) # Load FGD for entity resource detection fgd = FGD() # ... load FGD files ... # Pack a material (will find and pack textures, etc.) packlist.pack_file('materials/custom/mytexture.vmt') # Pack a model (will find and pack materials, physics, etc.) packlist.pack_file('models/custom/mymodel.mdl') # Auto-detect dependencies from VMF entities with open('mymap.vmf', 'r') as f: vmf = VMF.parse(f) for ent in vmf.entities: packlist.pack_from_ent(ent, fgd) # Pack into BSP bsp = BSP('maps/mymap.bsp') packlist.pack_into_zip(bsp.pakfile) bsp.save() # List what would be packed for filename, packfile in packlist.filelist.items(): if packfile.data is not None: print(f"Pack: {filename}") ``` -------------------------------- ### Miscellaneous Operations Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/vpk.rst Provides information on additional utility functions and data constants available in the module. ```APIDOC ## Miscellaneous Operations ### Description This section outlines additional utility functions and constants provided by the `srctools.vpk` module for various VPK-related tasks. ### Methods - **`VPK.extract_all(output_dir)`**: Extracts all contents of the VPK archive to the specified output directory. - **`VPK.verify_all()`**: Verifies the integrity of all files within the VPK archive. ### Data Constants - **`VPK_SIG`**: A constant representing the VPK file signature. - **`DIR_ARCH_INDEX`**: A constant representing the index for the directory archive. ### Functions - **`get_arch_filename(vpk_path, index)`**: Returns the filename for a given archive index within a VPK path. ``` -------------------------------- ### VisTree Class Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/bsp.rst Documentation for the `VisTree` class, including its attributes and methods. ```APIDOC ## VisTree Class ### Description Represents a node in the visibility tree, used for spatial partitioning of the map. ### Method N/A (Class Definition) ### Endpoint N/A (Class Definition) ### Parameters N/A ### Request Example N/A ### Response #### Success Response (200) - **plane** (Plane) - The plane defining the split at this node. - **mins** (tuple[float, float, float]) - The minimum bounds of this node's bounding box. - **maxes** (tuple[float, float, float]) - The maximum bounds of this node's bounding box. - **child_neg** (VisTree or VisLeaf) - The child node or leaf for the negative side of the plane. - **child_pos** (VisTree or VisLeaf) - The child node or leaf for the positive side of the plane. - **area_ind** (int) - The area index associated with this node. - **faces** (list[Face]) - The faces associated with this node. - **test_point(point: Vec)** - Tests if a point is inside this node. - **iter_leafs()** - Iterates over all leaf nodes within this subtree. #### Response Example ```json { "plane": { "normal": [0.0, 0.0, 1.0], "dist": 0.0 }, "mins": [-1000.0, -1000.0, -1000.0], "maxes": [1000.0, 1000.0, 1000.0], "child_neg": "", "child_pos": "", "area_ind": 0, "faces": [ // Face objects ] } ``` ``` -------------------------------- ### Configure Another Soundscape Layer in SimpleScape Source: https://github.com/teamspen210/srctools/blob/master/tests/test_sndscape/sample_scape.txt Includes another soundscape layer into the SimpleScape, specifying its name, volume range, and position. This demonstrates how to layer different soundscapes with adjustable volume and placement. ```text playsoundscape { name "samples.beach_common" volume "0.3, 0.4" position 1 } ``` -------------------------------- ### srctools.cmdseq.build_keyvalues Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/cmdseq.rst Builds a keyvalues formatted string representation of a CmdSeqTree object. ```APIDOC ## srctools.cmdseq.build_keyvalues ### Description Builds a keyvalues formatted string representation of a CmdSeqTree object. This is useful for saving compile options in a human-readable format. ### Method POST (or equivalent for building string) ### Endpoint N/A (Function call) ### Parameters #### Path Parameters - **cmdseq_tree** (CmdSeqTree) - Required - The CmdSeqTree object to convert. ### Request Example ```python import srctools.cmdseq # Assuming compile_options is a CmdSeqTree object compile_options = srctools.cmdseq.CmdSeqTree() # ... populate compile_options ... keyvalues_output = srctools.cmdseq.build_keyvalues(compile_options) print(keyvalues_output) ``` ### Response #### Success Response (200) - **keyvalues_string** (str) - A string containing the keyvalues formatted compile options. #### Response Example ```json { "example": "[Commands]\nCompile=echo Compiling map...\n" } ``` ``` -------------------------------- ### FileInfo Object Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/vpk.rst Represents a file within a VPK archive and provides methods for reading and writing its contents. ```APIDOC ## FileInfo Object ### Description The `FileInfo` object represents an individual file stored within a VPK archive. It provides read-only access to file metadata and methods to read or write the file's content. ### Attributes - **`filename`**: The name of the file. - **`dir`**: The directory path of the file within the VPK. - **`ext`**: The file extension. - **`size`**: The size of the file in bytes. - **`arch_index`**: The index of the archive file containing this file's data. - **`arch_len`**: The length of the file's data within its archive. - **`vpk`**: A reference to the parent VPK object. - **`offset`**: The offset of the file's data within its archive. - **`start_data`**: Indicates if the file data starts at the beginning of the archive. ### Methods - **`read()`**: Reads the entire content of the file from the VPK. - **`write(data)`**: Writes the provided data to the file in the VPK. This operation modifies the VPK immediately. - **`verify()`**: Verifies the integrity of the file within the VPK. ``` -------------------------------- ### Configure Playsoundscape Instance - SimpleScape Source: https://github.com/teamspen210/srctools/blob/master/tests/test_sndscape/test_roundtrip.txt Defines a soundscape instance by its name, with options to override its default position and ambient position. This allows for custom placement of pre-defined soundscapes. ```srctools playsoundscape { name "samples.graveYard" positionoverride "4" ambientpositionoverride "5" } ``` -------------------------------- ### Output Management Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/vmf.rst Documentation for managing entity outputs, including adding outputs, targeting outputs, and iterating through input connections. ```APIDOC ## Output Management ### Description This section covers the management of entity outputs, including adding new output connections, specifying target entities and parameters, and handling input parsing and export. ### Methods - **Entity.add_out(output_name, target_name, param, delay, times, only_once)** - Adds an output connection to the entity. - **Entity.output_targets()** - Returns a list of output targets for the entity. - **VMF.iter_inputs(output_name)** - Iterates through all input connections for a given output name. ### Classes #### Output Represents an output connection. - **input** (str) - The name of the input to trigger. - **target** (str) - The name of the target entity. - **output** (str) - The name of the output to fire. - **params** (str) - Parameters for the output. - **delay** (float) - Delay in seconds before firing the output. - **times** (int) - Number of times the output can fire. - **only_once** (bool) - Whether the output should only fire once. - **comma_sep** (bool) - Whether parameters are comma-separated. - **inst_in** (bool) - Whether the output is an instance input. - **inst_out** (bool) - Whether the output is an instance output. #### Methods - **parse(data)** - Parses output data. - **export()** - Exports the output data. - **as_keyvalue()** - Returns the output as a key-value string. - **combine(other)** - Combines this output with another. - **parse_name(name)** - Parses an output name string. - **exp_out()** - Exports the output. - **exp_in()** - Exports the input. - **copy()** - Creates a copy of the output. - **gen_addoutput()** - Generates the addoutput string for the output. ``` -------------------------------- ### Configure Third Soundscape Layer in SimpleScape Source: https://github.com/teamspen210/srctools/blob/master/tests/test_sndscape/sample_scape.txt Adds a third soundscape layer, 'samples.birds', to the SimpleScape configuration. It defines a specific volume range and overrides the position. This allows for fine-tuning the contribution of individual soundscape layers. ```text playsoundscape { name "samples.birds" volume "10, 11" positionoverride 6 } ``` -------------------------------- ### Configure Looping Soundscape with Specific Position - SimpleScape Source: https://github.com/teamspen210/srctools/blob/master/tests/test_sndscape/test_roundtrip.txt Sets up a looping soundscape using a specific wave file and a precise 3D position. It also defines the sound level for the audio. ```srctools playlooping { wave "npc/whispers.wav" position "0 -29.5 1928" soundlevel "SNDLVL_10dB" } ``` -------------------------------- ### Structure Tools Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/binformat.rst Functions for reading and writing structured binary data, including deferred writes. ```APIDOC ## Structure Tools ### Description Provides utilities for reading and writing structured binary data, including handling deferred writes and specific data types like vectors and null-terminated strings. ### Method N/A (Functions) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response #### Success Response (N/A) - **DeferredWrites** (class) - Manages deferred writes to a binary buffer. - **struct_read** (function) - Reads data from a binary buffer using a struct format. - **str_readvec** (function) - Reads a vector from a binary buffer. - **read_array** (function) - Reads an array from a binary buffer. - **write_array** (function) - Writes an array to a binary buffer. - **read_nullstr** (function) - Reads a null-terminated string from a binary buffer. - **read_nullstr_array** (function) - Reads an array of null-terminated strings from a binary buffer. - **read_offset_array** (function) - Reads an array of offsets from a binary buffer. #### Response Example N/A ``` -------------------------------- ### FGD Entity Definition Parsing in Python Source: https://context7.com/teamspen210/srctools/llms.txt Explains how to use the FGD module to parse Forge Game Data files, which define entity classes for Hammer. It covers parsing FGD files, accessing entity definitions, listing keyvalues, and iterating through inputs and outputs. It also shows how to use built-in engine databases for entity definitions. ```python from srctools.fgd import FGD, EntityDef # Parse FGD file fgd = FGD() with open('base.fgd', 'r') as f: fgd.parse_file(f, 'base.fgd') # Access entity definitions if 'prop_static' in fgd: ent_def = fgd['prop_static'] print(f"Entity type: {ent_def.type}") # EntityTypes.POINT or BRUSH # List keyvalues for kv_name, kv_def in ent_def.kv.items(): print(f" {kv_name}: {kv_def.type} = {kv_def.default}") # List inputs/outputs for inp_name, inp_def in ent_def.inp.items(): print(f" Input: {inp_name}") for out_name, out_def in ent_def.out.items(): print(f" Output: {out_name}") # Use built-in engine database (from HammerAddons) ent_def = EntityDef.engine_def('trigger_multiple') if ent_def: print(f"Found trigger_multiple with {len(ent_def.kv)} keyvalues") ``` -------------------------------- ### Configure Looping Sound Playback in SimpleScape Source: https://github.com/teamspen210/srctools/blob/master/tests/test_sndscape/sample_scape.txt Configures a looping sound for a SimpleScape. This includes setting the playback position, the sound file (e.g., music), attenuation, pitch range, radius, and a suppression flag. Ideal for background music or continuous ambient effects. ```text playlooping { position random wave "music/epic_music.mp3" attenuation "1.25, 1.0" pitch "PITCH_LOW, PITCH_HIGH" radius "8192.85" suppress_on_restore 1 } ``` -------------------------------- ### 3D Math Operations with Vec, Angle, Matrix (Python) Source: https://context7.com/teamspen210/srctools/llms.txt Demonstrates the usage of Vec, Angle, and Matrix classes for 3D transformations and vector math. Supports standard arithmetic operations, parsing from string formats, rotations, and immutable vector types. Includes bounding box calculation and linear interpolation. ```Python from srctools import Vec, Angle, Matrix, FrozenVec # Create vectors pos = Vec(100, 200, 300) direction = Vec(1, 0, 0) # Vector operations pos2 = pos + Vec(50, 0, 0) # Vec(150, 200, 300) scaled = pos * 2 # Vec(200, 400, 600) length = pos.mag() # Magnitude normalized = pos.norm() # Unit vector # Parse from Source Engine string format origin = Vec.from_str("128 256 64") # Rotations with angles angle = Angle(pitch=0, yaw=90, roll=0) rotated_vec = pos @ angle # Rotate vector by angle # Matrix operations for complex rotations mat = Matrix.from_angle(angle) transformed = direction @ mat # Immutable versions for dictionary keys frozen = FrozenVec(1, 2, 3) cache = {frozen: "some_value"} # Bounding box calculation points = [Vec(0, 0, 0), Vec(100, 50, 25), Vec(-20, 80, 10)] bb_min, bb_max = Vec.bbox(points) # Linear interpolation from srctools import lerp value = lerp(0.5, 0, 100, 0, 255) # Map 0-100 to 0-255, returns 127.5 ``` -------------------------------- ### Configure Playsoundscape with Volume and Position - SimpleScape Source: https://github.com/teamspen210/srctools/blob/master/tests/test_sndscape/test_roundtrip.txt Sets a specific soundscape instance with custom volume and position values. This allows fine-tuning of pre-defined soundscapes within the environment. ```srctools playsoundscape { name "samples.beach_common" volume "0.3, 0.4" position "1" } ``` -------------------------------- ### Parse and Serialize KeyValues Files Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/keyvalues.rst Demonstrates how to read a KeyValues file into a Keyvalues object using `Keyvalues.parse` and then write it back to a file using `Keyvalues.serialise`. This is the primary method for file I/O operations. ```python with open('filename.txt', 'r') as read_file: kv = Keyvalues.parse(read_file, 'filename.txt') with open('filename_2.txt', 'w') as write_file: kv.serialise(write_file) ``` -------------------------------- ### Parse Soundscape File Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/sndscape.rst Demonstrates how to read a Soundscape file. It first parses the file content into a Keyvalues tree and then into a Soundscape object. This requires the Keyvalues and Soundscape classes. ```python from srctools.keyvalues import Keyvalues from srctools.sndscape import Soundscape with open('soundscape.txt', 'r') as f: kv = Keyvalues.parse(f) soundscapes = Soundscape.parse(kv) ``` -------------------------------- ### Extracting All VPK Contents (Python) Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/vpk.rst Provides a Python code snippet for extracting all files from a VPK archive to a specified directory. This is useful for backing up or inspecting the contents of a VPK. ```python from srctools.vpk import VPK vpk = VPK('path/to/archive.vpk') # Extract all files to a destination directory vpk.extract_all('output/directory/') print('All files extracted.') ``` -------------------------------- ### Read and Write VCD and scenes.image Files Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/choreo.rst Demonstrates basic usage for reading and writing choreographed scene files in both text (.vcd) and binary (scenes.image) formats. It utilizes Tokenizer for text parsing and srctools.choreo functions for scene and image handling. ```python from srctools.choreo import * from srctools.tokenizer import Tokenizer with open('some_scene.vcd') as file: scene = Scene.parse_text(Tokenizer(file)) with open('some_scene_copy.vcd', 'w') as file: scene.export_text(file) with open('scenes.image', 'rb') as file: image = parse_scenes_image(file) with open('new_scenes.image', 'wb') as file: save_scenes_image_sync(file, image) ``` -------------------------------- ### Configure Random Sound Playback in SimpleScape Source: https://github.com/teamspen210/srctools/blob/master/tests/test_sndscape/sample_scape.txt Sets up random playback for sounds within a SimpleScape. It defines a time range, volume range, pitch range, sound level, and a list of random wave files to choose from. This is useful for ambient sounds that vary slightly. ```text playrandom { time "0.5, 0.92" volume "0.8, 1.275" pitch "50, 253" soundlevel "SNDLVL_TALKING" position 5 rndwave { wave "ambient/wind1.wav" wave "ambient/wind2.wav" wave "ambient.Windy" } } ``` -------------------------------- ### Configure Looping Soundscape - SimpleScape Source: https://github.com/teamspen210/srctools/blob/master/tests/test_sndscape/test_roundtrip.txt Defines a looping soundscape with specified wave file, playback position, pitch, sound level, and radius. The 'suppress_on_restore' parameter controls behavior when the game state changes. ```srctools playlooping { wave "music/epic_music.mp3" position random suppress_on_restore 1 pitch "95, 120" soundlevel "66, 70" radius "8192.85" } ``` -------------------------------- ### Special Methods and Miscellaneous Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/keyvalues.rst Covers special methods for representation, comparison, and other utility functions. ```APIDOC ## Special Methods and Miscellaneous ### Description Includes methods for object representation, equality checks, boolean evaluation, and conversion to other data types. ### Special Methods * `__repr__()`: Returns a string representation of the Keyvalues object. * `__str__()`: Returns a user-friendly string representation. * `__ne__(other)`: Checks for inequality with another Keyvalues object. * `__eq__(other)`: Checks for equality with another Keyvalues object. * `__add__(other)`: Concatenates children from another Keyvalues object. * `__iadd__(other)`: In-place concatenation of children. * `__bool__()`: Evaluates the truthiness of the Keyvalues object (e.g., if it has children). * `__contains__(key)`: Checks if a key exists as a direct child. * `__getitem__(key)`: Accesses a child keyvalue's value (see Searching section). * `__setitem__(key, value)`: Sets a child keyvalue's value (see Editing section). * `__delitem__(key)`: Deletes a child keyvalue (see Editing section). ### Miscellaneous Methods * `as_dict()`: Converts the Keyvalues object into a Python dictionary. * `clear()`: Removes all children from a block keyvalue. * `copy()`: Creates a deep copy of the Keyvalues object. * `edit()`: Returns an editable view of the Keyvalues object. ``` -------------------------------- ### Keyvalues (VDF) Parsing and Writing (Python) Source: https://context7.com/teamspen210/srctools/llms.txt Shows how to parse and write Valve's KeyValues1 format (VDF) using the Keyvalues class. Supports reading from files, accessing nested values with defaults, type conversion helpers (int, bool, vec), programmatic creation of Keyvalues structures, and iteration over child elements. ```Python from srctools import Keyvalues # Parse from file with open('gameinfo.txt', 'r') as f: kv = Keyvalues.parse(f, 'gameinfo.txt') # Access values game_name = kv['GameInfo']['game'] # Get string value app_id = kv['GameInfo']['FileSystem']['SteamAppId', '440'] # With default # Find nested blocks gameinfo = kv.find_key('GameInfo') filesystem = gameinfo.find_key('FileSystem') # Type conversion helpers port = kv.int('port', default=27015) enabled = kv.bool('enabled', default=False) position = kv.vec('origin', default=Vec(0, 0, 0)) # Create keyvalues programmatically config = Keyvalues('Config', [ Keyvalues('server', [ Keyvalues('hostname', 'My Server'), Keyvalues('maxplayers', '32'), Keyvalues('sv_cheats', '0'), ]), Keyvalues('client', [ Keyvalues('name', 'Player'), ]), ]) # Write to file with open('config.vdf', 'w') as f: config.serialise(f) # Iterate children for child in gameinfo: print(f"{child.real_name} = {child.value}") ``` -------------------------------- ### srctools.cmdseq.parse_keyvalues Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/cmdseq.rst Parses a .wc expert compile options file specifically from a keyvalues format. ```APIDOC ## srctools.cmdseq.parse_keyvalues ### Description Parses a .wc expert compile options file specifically from a keyvalues format. This is useful when you have the content as a string or stream. ### Method GET (or equivalent for parsing string/stream) ### Endpoint N/A (Function call) ### Parameters #### Path Parameters - **keyvalues_content** (str) - Required - The string content of the keyvalues formatted .wc file. ### Request Example ```python import srctools.cmdseq keyvalues_data = "\n[Commands]\nCompile=echo Compiling map...\n" srctools.cmdseq.parse_keyvalues(keyvalues_data) ``` ### Response #### Success Response (200) - **compile_options** (CmdSeqTree) - An object representing the parsed compile options. #### Response Example ```json { "example": "CmdSeqTree object representing the parsed compile options" } ``` ``` -------------------------------- ### VPK Archive Operations Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/vpk.rst This section details the core operations for interacting with VPK archives, including opening, closing, and managing file data. ```APIDOC ## VPK Archive Operations ### Description This section covers the fundamental operations for working with VPK archives, including how to open them in different modes, save changes, and use them as context managers for automatic saving. ### Opening and Closing VPKs can be opened in three modes, similar to regular files. Changes to the directory are only applied upon calling `write_dirfile()`, while writes to data files are immediate. The VPK can be utilized as a context manager to ensure automatic saving if no exceptions occur. ### Methods - **`VPK.load_dirfile()`**: Loads the directory file of a VPK archive. - **`VPK.write_dirfile()`**: Writes any pending changes to the VPK's directory file. ### Attributes - **`VPK.folder`**: The folder path associated with the VPK. - **`VPK.path`**: The full path to the VPK archive. - **`VPK.mode`**: The mode in which the VPK was opened (e.g., read, write). - **`VPK.version`**: The version of the VPK format. - **`VPK.file_prefix`**: The prefix used for data files within the VPK. - **`VPK.dir_limit`**: The maximum size limit for the directory file. - **`VPK.footer_data`**: Any additional data stored in the VPK footer. ``` -------------------------------- ### VMF Constants and Utility Functions Source: https://github.com/teamspen210/srctools/blob/master/docs/source/modules/vmf.rst Lists various constants and utility functions available within the srctools.vmf module. ```APIDOC ## VMF Constants and Utility Functions ### Description This section lists various constants and utility functions provided by the `srctools.vmf` module for working with VMF files. ### Constants - **CURRENT_HAMMER_BUILD** (int) - The current Hammer build number. - **CURRENT_HAMMER_VERSION** (str) - The current Hammer version string. - **SEP** (str) - Separator string. ### Classes - **Axis** - **Camera** - **EntityGroup** - **VisGroup** ### Utility Functions - **overlay_bounds(overlay_data)** - **make_overlay(data)** - **localise_overlay(overlay_data)** ### Methods - **VMF.create_visgroup()** - **VMF.iter_wbrushes()** - **VMF.iter_wfaces()** - **VMF.cameras()** - **VMF.vis_tree()** - **VMF.groups()** - **VMF.active_cam()** - **VMF.quickhide_count()** ### Camera Methods - **Camera.targ_ent** - **Camera.is_active** - **Camera.set_active()** - **Camera.set_inactive_all()** - **Camera.parse(data)** - **Camera.copy()** - **Camera.remove()** - **Camera.export()** - **Camera.pos** - **Camera.target** - **Camera.map** ### EntityGroup Methods - **EntityGroup.parse(data)** - **EntityGroup.copy()** - **EntityGroup.export()** - **EntityGroup.auto_shown** - **EntityGroup.color** - **EntityGroup.shown** - **EntityGroup.vmf** ### VisGroup Methods - **VisGroup.parse(data)** - **VisGroup.export()** - **VisGroup.set_visible(visible)** - **VisGroup.child_ents()** - **VisGroup.child_solids()** - **VisGroup.copy()** - **VisGroup.child_groups()** - **VisGroup.color** - **VisGroup.name** - **VisGroup.vmf** ```